Item 1: a unit is bound to the session that works on it; sisi unit continue | park | resume; stale_hours; contract init names the three ways on. done / next: item 2 (the before-tool refusal)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2ecbfea7e9
commit
275f0b43b2
7 files changed
+1130
-9
No files matched your search
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"note": "Word lists for the before-tool guard (sisi/unitguard.py). Data, so a host or a project can be adapted without code.",
|
||||||
|
"edit_tools": ["Edit", "Write", "MultiEdit", "NotebookEdit"],
|
||||||
|
"edit_name_words": ["edit", "write", "create", "delete", "move", "rename", "patch", "apply", "insert"],
|
||||||
|
"delegation_tools": ["Agent", "Task"],
|
||||||
|
"build_kinds": ["impl", "impl-multi", "edit", "tests", "debug"],
|
||||||
|
"build_words": ["change", "changing", "fix", "fixing", "implement", "implementing", "write", "writing", "edit", "editing",
|
||||||
|
"modify", "modifying", "refactor", "rewrite", "patch", "add a", "add the", "build", "create", "update",
|
||||||
|
"rename", "remove", "delete", "code"],
|
||||||
|
"read_only_phrases": ["read-only", "read only", "do not modify", "do not change", "do not edit", "do not write",
|
||||||
|
"don't modify", "don't change", "don't edit", "without changing", "without modifying",
|
||||||
|
"no changes", "report only", "only report", "do not create"],
|
||||||
|
"self_refs": ["me", "myself", "i", "my", "own", "self", "yourself", "the author", "author", "this session", "same session",
|
||||||
|
"the agent", "the implementer"],
|
||||||
|
"ignore_changed": ["**/__pycache__/**", "**/*.pyc", "**/.pytest_cache/**", "**/.mypy_cache/**", "**/.ruff_cache/**",
|
||||||
|
"**/node_modules/**", ".git/**"]
|
||||||
|
}
|
||||||
+6
-4
@@ -89,9 +89,11 @@ def independent_evidence(project, c, results, now=None):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def missing(profile, c, project, results=None, errors=None, deep_state=None, now=None):
|
def missing(profile, c, project, results=None, errors=None, deep_state=None, now=None, before_build=False):
|
||||||
"""[(what is missing, how to supply it)] for this profile. `c` is None when no contract is open.
|
"""[(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."""
|
`errors` are the contract's validation errors. Nothing is asked that the table does not require.
|
||||||
|
`before_build` asks only what must exist before building starts: independent evidence, the deep
|
||||||
|
checks and the retro belong to the end of the work."""
|
||||||
req = requirements(profile)
|
req = requirements(profile)
|
||||||
out = []
|
out = []
|
||||||
if not req.get("contract"):
|
if not req.get("contract"):
|
||||||
@@ -137,11 +139,11 @@ def missing(profile, c, project, results=None, errors=None, deep_state=None, now
|
|||||||
or not [a for a in ap.get("alternatives") or [] if not C.is_placeholder(a)]:
|
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",
|
out.append(("the approach: what you chose, why, and an alternative you rejected",
|
||||||
'"approach": {"chosen", "why", "alternatives": [...]}'))
|
'"approach": {"chosen", "why", "alternatives": [...]}'))
|
||||||
if req.get("independent_evidence") and not independent_evidence(project, c, results, now):
|
if req.get("independent_evidence") and not before_build and not independent_evidence(project, c, results, now):
|
||||||
out.append(("independent evidence that someone or something else checked this",
|
out.append(("independent evidence that someone or something else checked this",
|
||||||
"a reviewer's judged result (`sisi delegate judge --type review --outcome accepted "
|
"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>\""))
|
"--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"):
|
if req.get("all_checks") and not before_build 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)",
|
out.append(("every check, deep ones included, passing on this tree (release)",
|
||||||
"`sisi verify --deep --background`, then `sisi verify --state`"))
|
"`sisi verify --deep --background`, then `sisi verify --state`"))
|
||||||
return out
|
return out
|
||||||
|
|||||||
+12
-3
@@ -26,9 +26,11 @@ def cmd_contract(args):
|
|||||||
old = None
|
old = None
|
||||||
from . import unit as _U
|
from . import unit as _U
|
||||||
if not _U.is_closed(old):
|
if not _U.is_closed(old):
|
||||||
print("sisi: %s already exists and the unit %s is still open. Close it first with "
|
print("sisi: %s already exists and the unit %s (%s) is still open. Three ways on: "
|
||||||
"`sisi unit close`, or record why it stopped with "
|
"`sisi unit continue` if it is this work; `sisi unit park \"<why>\"` to set it aside, "
|
||||||
"`sisi unit close --abandon \"<reason>\"`." % (p, (old or {}).get("id", "?")))
|
"kept, and start new work; or `sisi unit close --abandon \"<reason>\"` if it was dropped. "
|
||||||
|
"Then `sisi contract init` again for new work."
|
||||||
|
% (p, (old or {}).get("id", "?"), ((old or {}).get("goal") or "no goal")[:80]))
|
||||||
return 1
|
return 1
|
||||||
# A closed unit is replaced. Its archive should already exist; if a hand-edited
|
# A closed unit is replaced. Its archive should already exist; if a hand-edited
|
||||||
# contract claims closed with none, archive it now so nothing is ever lost.
|
# contract claims closed with none, archive it now so nothing is ever lost.
|
||||||
@@ -50,6 +52,13 @@ def cmd_contract(args):
|
|||||||
json.dump(skel, f, indent=2)
|
json.dump(skel, f, indent=2)
|
||||||
f.write("\n")
|
f.write("\n")
|
||||||
trust.add(os.getcwd())
|
trust.add(os.getcwd())
|
||||||
|
try:
|
||||||
|
from . import unitguard as _G
|
||||||
|
_sid = _G.cli_session()
|
||||||
|
if _sid:
|
||||||
|
_G.bind(_sid, project, skel, "init")
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("contract-init-bind", e)
|
||||||
print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command "
|
print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command "
|
||||||
"(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and "
|
"(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and "
|
||||||
"the end-of-turn gate ignores it." % p)
|
"the end-of-turn gate ignores it." % p)
|
||||||
|
|||||||
@@ -366,6 +366,7 @@ def open_units(cwd=None):
|
|||||||
c = C.load(p) if p else None
|
c = C.load(p) if p else None
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
return out
|
return out
|
||||||
|
out += _parked_rows(cwd, C.project_dir(p) if p else None)
|
||||||
if not isinstance(c, dict) or not c.get("id") or c.get("status") == "closed" or C.is_unedited_skeleton(c):
|
if not isinstance(c, dict) or not c.get("id") or c.get("status") == "closed" or C.is_unedited_skeleton(c):
|
||||||
return out
|
return out
|
||||||
project = C.project_dir(p)
|
project = C.project_dir(p)
|
||||||
@@ -382,10 +383,33 @@ def open_units(cwd=None):
|
|||||||
row["lowered"] = "declared %s below the floor %s: %s" % (rk.get("profile"), floor, rk.get("why"))
|
row["lowered"] = "declared %s below the floor %s: %s" % (rk.get("profile"), floor, rk.get("why"))
|
||||||
if c.get("unverified"):
|
if c.get("unverified"):
|
||||||
row["unverified"] = "; ".join(c["unverified"].get("why") or [])
|
row["unverified"] = "; ".join(c["unverified"].get("why") or [])
|
||||||
|
row["refusals"] = _refusal_count(project, c)
|
||||||
out.append(row)
|
out.append(row)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _refusal_count(project, c):
|
||||||
|
"""How many times the before-tool guard refused building steps for this unit (rule 3)."""
|
||||||
|
try:
|
||||||
|
from . import unitguard
|
||||||
|
return len(unitguard.refusals_for(project, c.get("id"), c.get("started")))
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("status-refusals", e)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _parked_rows(cwd, project):
|
||||||
|
"""Units set aside with `sisi unit park`, as display rows: how long ago, why, what each still owes."""
|
||||||
|
try:
|
||||||
|
from . import gitutil, unit as U
|
||||||
|
project = project or gitutil.root(cwd or os.getcwd()) or os.path.abspath(cwd or os.getcwd())
|
||||||
|
return [{"id": x["id"], "status": "parked", "age": _age(x.get("ts")), "goal": x.get("goal") or "",
|
||||||
|
"why": x.get("why"), "owes": [tuple(o) for o in x.get("owes") or []]} for x in U.list_parked(project)]
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("status-parked", e)
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
def _lowered_note(u):
|
def _lowered_note(u):
|
||||||
rk = u.get("risk") or {}
|
rk = u.get("risk") or {}
|
||||||
if not rk.get("lowered"):
|
if not rk.get("lowered"):
|
||||||
@@ -403,10 +427,17 @@ def _basis_note(r):
|
|||||||
def format_open(rows):
|
def format_open(rows):
|
||||||
lines = []
|
lines = []
|
||||||
for r in rows:
|
for r in rows:
|
||||||
|
if r["status"] == "parked":
|
||||||
|
lines.append("parked %-24s %s ago %s" % (r["id"], r["age"], r["goal"][:60]))
|
||||||
|
lines.append(" set aside: %s; owes: %s" % (r.get("why") or "?",
|
||||||
|
", ".join("%s (%s)" % tuple(o) for o in r.get("owes") or []) or "nothing outstanding"))
|
||||||
|
continue
|
||||||
if r["status"] == "paused":
|
if r["status"] == "paused":
|
||||||
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")))
|
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:
|
else:
|
||||||
lines.append("open %-24s age %s%s %s" % (r["id"], r["age"], _basis_note(r), r["goal"][:80]))
|
lines.append("open %-24s age %s%s %s" % (r["id"], r["age"], _basis_note(r), r["goal"][:80]))
|
||||||
|
if r.get("refusals"):
|
||||||
|
lines.append(" the guard refused %d building step(s) before a valid unit stood behind them" % r["refusals"])
|
||||||
if r.get("lowered"):
|
if r.get("lowered"):
|
||||||
lines.append(" lowered: " + r["lowered"])
|
lines.append(" lowered: " + r["lowered"])
|
||||||
if r.get("unverified"):
|
if r.get("unverified"):
|
||||||
|
|||||||
+137
-2
@@ -39,10 +39,47 @@ def list_archives(project):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parked_dir(project):
|
||||||
|
return os.path.join(project, ".sisi", "parked")
|
||||||
|
|
||||||
|
|
||||||
|
def list_parked(project):
|
||||||
|
"""The units set aside in this project: [{id, goal, ts, why, owes, session, path, contract}]."""
|
||||||
|
d = parked_dir(project)
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
names = sorted(os.listdir(d))
|
||||||
|
except OSError:
|
||||||
|
return out
|
||||||
|
for n in names:
|
||||||
|
if not n.endswith(".json"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with open(os.path.join(d, n), encoding="utf-8") as f:
|
||||||
|
rec = json.load(f)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
continue
|
||||||
|
c = rec.get("contract") if isinstance(rec, dict) else None
|
||||||
|
pk = rec.get("parked") if isinstance(rec.get("parked"), dict) else {}
|
||||||
|
if isinstance(c, dict) and c.get("id"):
|
||||||
|
out.append({"id": c["id"], "goal": c.get("goal") or "", "ts": pk.get("ts"), "why": pk.get("why"),
|
||||||
|
"owes": pk.get("owes") or [], "session": pk.get("session"),
|
||||||
|
"path": os.path.join(d, n), "contract": c, "started": c.get("started")})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def owed_checks(c, project):
|
||||||
|
"""What the unit still owes: [(check id, status)] of its checks and invariants that have not passed."""
|
||||||
|
rows = _unit_results(c, project, c.get("started"))
|
||||||
|
return [(r["id"], r["status"]) for r in latest_results(c, rows)
|
||||||
|
if r["item"] in ("check", "invariant") and r["status"] != "passed" and not _justified_by_selection(r)]
|
||||||
|
|
||||||
|
|
||||||
def fresh_id(base, project):
|
def fresh_id(base, project):
|
||||||
"""A unit id not already used by an archived or summarised unit in this project."""
|
"""A unit id not already used by an archived or summarised unit in this project."""
|
||||||
used = {r.get("id") for r in list_archives(project)}
|
used = {r.get("id") for r in list_archives(project)}
|
||||||
used |= {r.get("id") for r in store.read("units") if isinstance(r, dict) and r.get("project") == project}
|
used |= {r.get("id") for r in store.read("units") if isinstance(r, dict) and r.get("project") == project}
|
||||||
|
used |= {r.get("id") for r in list_parked(project)} # a parked unit still owns its id
|
||||||
if base not in used:
|
if base not in used:
|
||||||
return base
|
return base
|
||||||
n = 2
|
n = 2
|
||||||
@@ -759,6 +796,97 @@ def cmd_unit(args, cwd=None, out=print):
|
|||||||
if rec.get("deferred_checks"):
|
if rec.get("deferred_checks"):
|
||||||
out("deferred checks: %s" % ", ".join(rec["deferred_checks"]))
|
out("deferred checks: %s" % ", ".join(rec["deferred_checks"]))
|
||||||
return 0 if ok else 1
|
return 0 if ok else 1
|
||||||
|
if sub == "continue":
|
||||||
|
from . import unitguard as G
|
||||||
|
c, p, project = _open_contract(cwd, out)
|
||||||
|
if c is None:
|
||||||
|
return 2
|
||||||
|
if is_closed(c):
|
||||||
|
out("sisi: unit %s is closed; start new work with `sisi contract init`" % c.get("id"))
|
||||||
|
return 1
|
||||||
|
sid = G.cli_session()
|
||||||
|
if not sid:
|
||||||
|
out("sisi: cannot tell which session this is (SISI_SESSION_ID is not set and no session hook was seen); "
|
||||||
|
"run it from the agent's own shell")
|
||||||
|
return 1
|
||||||
|
G.bind(sid, project, c, "continue")
|
||||||
|
owed = owed_checks(c, project)
|
||||||
|
started, basis = start_of(c, p)
|
||||||
|
out("continuing unit %s: %s" % (c.get("id"), c.get("goal") or ""))
|
||||||
|
out("started %s%s; last activity %s" % (G.age_text(harvest.epoch(started) if started else None),
|
||||||
|
" (inferred)" if basis == "inferred" else "", G.age_text(G.last_activity(project, c))))
|
||||||
|
out("owes: %s" % (", ".join("%s (%s)" % x for x in owed) if owed else "no check outstanding"))
|
||||||
|
out("this session is now bound to the unit; it must be continued again after %g hours without activity"
|
||||||
|
% (G.stale_seconds() / 3600.0))
|
||||||
|
return 0
|
||||||
|
if sub == "park":
|
||||||
|
from . import unitguard as G
|
||||||
|
why = " ".join(args[1:]).strip()
|
||||||
|
if not why:
|
||||||
|
out('usage: sisi unit park "<why this work is set aside>"')
|
||||||
|
return 1
|
||||||
|
c, p, project = _open_contract(cwd, out)
|
||||||
|
if c is None:
|
||||||
|
return 2
|
||||||
|
if is_closed(c):
|
||||||
|
out("sisi: unit %s is closed; there is nothing to park" % c.get("id"))
|
||||||
|
return 1
|
||||||
|
owed = owed_checks(c, project)
|
||||||
|
d = parked_dir(project)
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
target = os.path.join(d, "%s.json" % store.safe_id(c["id"]))
|
||||||
|
rec = {"parked": {"ts": store.now(), "why": why, "session": G.cli_session(), "owes": [list(x) for x in owed]},
|
||||||
|
"contract": c}
|
||||||
|
tmp = "%s.tmp%d" % (target, os.getpid())
|
||||||
|
with open(tmp, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(rec, f, indent=2)
|
||||||
|
f.write("\n")
|
||||||
|
os.replace(tmp, target)
|
||||||
|
try:
|
||||||
|
os.unlink(p)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
out("parked unit %s: %s (kept in %s; it owes: %s). Bring it back with `sisi unit resume %s` when no unit is open."
|
||||||
|
% (c["id"], why, target, ", ".join("%s (%s)" % x for x in owed) or "nothing outstanding", c["id"]))
|
||||||
|
return 0
|
||||||
|
if sub == "resume":
|
||||||
|
from . import unitguard as G
|
||||||
|
if len(args) < 2:
|
||||||
|
out("usage: sisi unit resume ID (`sisi unit list` shows the parked units)")
|
||||||
|
return 1
|
||||||
|
uid = args[1]
|
||||||
|
p = C.find(cwd)
|
||||||
|
project = C.project_dir(p) if p else (gitutil.root(cwd) or os.path.abspath(cwd))
|
||||||
|
cur = None
|
||||||
|
if p:
|
||||||
|
try:
|
||||||
|
cur = C.load(p)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
cur = None
|
||||||
|
if isinstance(cur, dict) and not is_closed(cur):
|
||||||
|
out("sisi: unit %s is open; set it aside first with `sisi unit park \"<why>\"` or close it with `sisi unit close`"
|
||||||
|
% cur.get("id"))
|
||||||
|
return 1
|
||||||
|
hit = next((x for x in list_parked(project) if x["id"] == uid), None)
|
||||||
|
if hit is None:
|
||||||
|
out("sisi: no parked unit %r here (`sisi unit list` shows them)" % uid)
|
||||||
|
return 1
|
||||||
|
c = hit["contract"]
|
||||||
|
if c.get("status") == "paused":
|
||||||
|
c["status"] = "open"
|
||||||
|
cp = os.path.join(project, C.REL)
|
||||||
|
C.save(cp, c)
|
||||||
|
try:
|
||||||
|
os.unlink(hit["path"])
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
sid = G.cli_session()
|
||||||
|
if sid:
|
||||||
|
G.bind(sid, project, c, "resume")
|
||||||
|
else:
|
||||||
|
G.touch(project, c)
|
||||||
|
out("resumed unit %s: %s" % (c["id"], c.get("goal") or ""))
|
||||||
|
return 0
|
||||||
if sub == "pause":
|
if sub == "pause":
|
||||||
what = " ".join(args[1:]).strip()
|
what = " ".join(args[1:]).strip()
|
||||||
if not what:
|
if not what:
|
||||||
@@ -822,10 +950,17 @@ def cmd_unit(args, cwd=None, out=print):
|
|||||||
rows.append((rec.get("ended") or "", rec.get("id"), rec.get("delivery_status"), rec.get("goal") or ""))
|
rows.append((rec.get("ended") or "", rec.get("id"), rec.get("delivery_status"), rec.get("goal") or ""))
|
||||||
if c is not None and not is_closed(c):
|
if c is not None and not is_closed(c):
|
||||||
out("open %-24s %s" % (c.get("id"), c.get("goal") or ""))
|
out("open %-24s %s" % (c.get("id"), c.get("goal") or ""))
|
||||||
|
if project:
|
||||||
|
from . import unitguard as G
|
||||||
|
for x in list_parked(project):
|
||||||
|
out("parked %-24s %s (parked %s: %s; owes: %s)" % (
|
||||||
|
x["id"], x["goal"], G.age_text(harvest.epoch(x["ts"]) if x.get("ts") else None), x.get("why") or "",
|
||||||
|
", ".join("%s (%s)" % tuple(o) for o in x["owes"]) or "nothing outstanding"))
|
||||||
for ended, uid, status, goal in sorted(rows, reverse=True):
|
for ended, uid, status, goal in sorted(rows, reverse=True):
|
||||||
out("%-8s %-24s %-24s %s" % (str(ended)[:10], uid, status, goal))
|
out("%-8s %-24s %-24s %s" % (str(ended)[:10], uid, status, goal))
|
||||||
if c is None and not rows:
|
if c is None and not rows and not (project and list_parked(project)):
|
||||||
out("no units in this project yet")
|
out("no units in this project yet")
|
||||||
return 0
|
return 0
|
||||||
out("usage: sisi unit close [--abandon \"<reason>\"] | pause \"<what it waits for>\" | show [ID] | list")
|
out("usage: sisi unit close [--abandon \"<reason>\"] | pause \"<what it waits for>\" | continue | "
|
||||||
|
"park \"<why>\" | resume ID | show [ID] | list")
|
||||||
return 1
|
return 1
|
||||||
@@ -0,0 +1,694 @@
|
|||||||
|
"""The contract comes before the work: a unit is bound to the session that works on it, and the
|
||||||
|
before-tool hook refuses the first building step that has no valid unit behind it (rule 3).
|
||||||
|
|
||||||
|
What makes a unit valid for building, in this order:
|
||||||
|
- it is open (not closed), and this session opened it (`sisi contract init`) or said it continues it
|
||||||
|
(`sisi unit continue`): the binding lives in the session record, never in the contract file, so a
|
||||||
|
unit left by another session is foreign until it is continued, parked or closed;
|
||||||
|
- it is not stale: its last activity (a verification run, an allowed edit, a continue) is younger
|
||||||
|
than `unit.stale_hours`;
|
||||||
|
- `sisi contract check` passes, no check still carries the skeleton's placeholder, and the contract
|
||||||
|
carries what the risk profile of the work requires BEFORE building (canon/risk.json: for
|
||||||
|
integration and above the requirement list, the risk note and the approach; independent
|
||||||
|
evidence and the retro are asked at the end, never here).
|
||||||
|
|
||||||
|
The profile is the risk floor of the target path together with the paths this session already
|
||||||
|
changed since its last valid unit (`risk.assess`). A trivial change is never refused. Writes under
|
||||||
|
.sisi/ and outside the project are never refused. Worker and subagent sessions are never refused:
|
||||||
|
their parent owns the unit. Every refusal says what is missing and names the command that resolves
|
||||||
|
it, and is stored (what, when) so the unit's record and `sisi status` can count them. Any error in
|
||||||
|
here lets the call through.
|
||||||
|
|
||||||
|
Entry points for sisi/watch.py: `before(payload)` (True when it refused and printed the host's
|
||||||
|
refusal) and `after(payload)`. For the gate and `sisi unit pause`: `bound_fresh`, `verdict`.
|
||||||
|
"""
|
||||||
|
import fnmatch, hashlib, json, os, re, shlex, sys, time
|
||||||
|
|
||||||
|
from . import assure, contract as C, gitutil, paths as P, risk, store, trust
|
||||||
|
|
||||||
|
CLAIM_RE = re.compile(r"\bsisi\b[^\n;&|]*?\b(?:contract\s+init|unit\s+(?:continue|resume|park))\b")
|
||||||
|
MAX_LINES = 12
|
||||||
|
_DATA = {}
|
||||||
|
|
||||||
|
|
||||||
|
def data():
|
||||||
|
"""canon/guard.json (word lists), read once per process."""
|
||||||
|
if not _DATA:
|
||||||
|
try:
|
||||||
|
with open(P.canon("guard.json"), encoding="utf-8") as f:
|
||||||
|
_DATA.update(json.load(f))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
_DATA["_missing"] = True
|
||||||
|
return _DATA
|
||||||
|
|
||||||
|
|
||||||
|
def _list(name):
|
||||||
|
v = data().get(name)
|
||||||
|
return [x for x in v if isinstance(x, str)] if isinstance(v, list) else []
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- who is asking
|
||||||
|
|
||||||
|
def _claim_file():
|
||||||
|
return os.path.join(P.state(), "unitguard-claim.json")
|
||||||
|
|
||||||
|
|
||||||
|
def note_claim(sid, cwd):
|
||||||
|
"""The before-hook saw this session about to run `sisi contract init|unit continue|...`: remember which
|
||||||
|
session it was, for a command line whose environment does not carry the session id."""
|
||||||
|
try:
|
||||||
|
os.makedirs(P.state(), exist_ok=True)
|
||||||
|
tmp = _claim_file() + ".tmp%d" % os.getpid()
|
||||||
|
with open(tmp, "w", encoding="utf-8") as f:
|
||||||
|
json.dump({"sid": sid, "cwd": cwd, "ts": time.time()}, f)
|
||||||
|
os.replace(tmp, _claim_file())
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def cli_session():
|
||||||
|
"""The session a `sisi` command line belongs to: the id the session-start hook exported, else the
|
||||||
|
session the before-hook saw start this command a moment ago. None when neither is known."""
|
||||||
|
sid = os.environ.get("SISI_SESSION_ID")
|
||||||
|
if sid:
|
||||||
|
return sid
|
||||||
|
try:
|
||||||
|
with open(_claim_file(), encoding="utf-8") as f:
|
||||||
|
d = json.load(f)
|
||||||
|
if time.time() - float(d.get("ts", 0)) < 120 and isinstance(d.get("sid"), str):
|
||||||
|
return d["sid"]
|
||||||
|
except (OSError, ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- unit identity, binding, activity
|
||||||
|
|
||||||
|
def unit_key(project, c):
|
||||||
|
return "%s|%s|%s" % (os.path.realpath(project), c.get("id"), c.get("started") or "")
|
||||||
|
|
||||||
|
|
||||||
|
def _act_path(key):
|
||||||
|
return os.path.join(P.state(), "unitguard", hashlib.sha1(key.encode()).hexdigest()[:16] + ".json")
|
||||||
|
|
||||||
|
|
||||||
|
def _load(path):
|
||||||
|
try:
|
||||||
|
with open(path, encoding="utf-8") as f:
|
||||||
|
d = json.load(f)
|
||||||
|
return d if isinstance(d, dict) else {}
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _save(path, obj):
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
tmp = path + ".tmp%d" % os.getpid()
|
||||||
|
with open(tmp, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(obj, f)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
|
||||||
|
|
||||||
|
def touch(project, c, model=None, throttle=0.0):
|
||||||
|
"""This unit had activity just now. `throttle` skips the write when the last one is that recent."""
|
||||||
|
key = unit_key(project, c)
|
||||||
|
p = _act_path(key)
|
||||||
|
d = _load(p)
|
||||||
|
now = time.time()
|
||||||
|
if throttle and now - float(d.get("last", 0) or 0) < throttle and not model:
|
||||||
|
return
|
||||||
|
d.update(project=os.path.realpath(project), id=c.get("id"), started=c.get("started"), last=now)
|
||||||
|
if model:
|
||||||
|
ms = d.setdefault("models", [])
|
||||||
|
if model not in ms:
|
||||||
|
ms.append(model)
|
||||||
|
_save(p, d)
|
||||||
|
|
||||||
|
|
||||||
|
def author_models(project, c):
|
||||||
|
"""The models of the sessions that bound themselves to this unit: who wrote the work."""
|
||||||
|
return [m for m in _load(_act_path(unit_key(project, c))).get("models", []) if isinstance(m, str)]
|
||||||
|
|
||||||
|
|
||||||
|
def bind(sid, project, c, how):
|
||||||
|
"""This session now works on this unit: it opened it, continued it or resumed it."""
|
||||||
|
sess = store.load_session(sid)
|
||||||
|
sess.setdefault("session_id", sid)
|
||||||
|
if not (sess.get("started") or sess.get("first_seen")):
|
||||||
|
sess["first_seen"] = store.now()
|
||||||
|
sess.setdefault("unit_bound", {})[os.path.realpath(project)] = {
|
||||||
|
"id": c.get("id"), "started": c.get("started"), "how": how, "ts": store.now()}
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
touch(project, c, model=sess.get("model") if isinstance(sess.get("model"), str) else None)
|
||||||
|
|
||||||
|
|
||||||
|
def is_bound(sess, project, c):
|
||||||
|
b = (sess.get("unit_bound") or {}).get(os.path.realpath(project))
|
||||||
|
return isinstance(b, dict) and b.get("id") == c.get("id") and (b.get("started") or None) == (c.get("started") or None)
|
||||||
|
|
||||||
|
|
||||||
|
def stale_seconds():
|
||||||
|
try:
|
||||||
|
h = float(((store.config().get("unit") or {}).get("stale_hours", 12)))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
h = 12.0
|
||||||
|
return max(0.0, h) * 3600.0
|
||||||
|
|
||||||
|
|
||||||
|
def _epoch(iso):
|
||||||
|
try:
|
||||||
|
return time.mktime(time.strptime(iso[:19], "%Y-%m-%dT%H:%M:%S")) - time.timezone
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _last_result_ts(project, uid):
|
||||||
|
"""Newest verification result recorded for this unit: only the tail of the results file is read."""
|
||||||
|
try:
|
||||||
|
p = store.file_path("results")
|
||||||
|
with open(p, "rb") as f:
|
||||||
|
f.seek(0, 2)
|
||||||
|
size = f.tell()
|
||||||
|
f.seek(max(0, size - 200000))
|
||||||
|
tail = f.read().decode("utf-8", "replace").splitlines()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
for line in reversed(tail):
|
||||||
|
if '"%s"' % uid not in line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
r = json.loads(line)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if isinstance(r, dict) and r.get("contract") == uid and r.get("project") == project:
|
||||||
|
return _epoch(r.get("ts"))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def last_activity(project, c):
|
||||||
|
"""Epoch of the unit's last activity: a continue or allowed edit, a verification run, or its start."""
|
||||||
|
cands = [_epoch(c.get("started"))]
|
||||||
|
cands.append(_load(_act_path(unit_key(project, c))).get("last"))
|
||||||
|
cands.append(_last_result_ts(project, c.get("id")))
|
||||||
|
cands = [x for x in cands if isinstance(x, (int, float))]
|
||||||
|
return max(cands) if cands else None
|
||||||
|
|
||||||
|
|
||||||
|
def age_text(epoch):
|
||||||
|
if not epoch:
|
||||||
|
return "an unknown time"
|
||||||
|
s = max(0, time.time() - epoch)
|
||||||
|
if s < 90:
|
||||||
|
return "just now"
|
||||||
|
if s < 5400:
|
||||||
|
return "%d minutes ago" % round(s / 60)
|
||||||
|
if s < 36 * 3600:
|
||||||
|
return "%d hours ago" % round(s / 3600)
|
||||||
|
return "%d days ago" % round(s / 86400)
|
||||||
|
|
||||||
|
|
||||||
|
def open_unit(cwd):
|
||||||
|
"""(contract, path, project) of the open unit (not closed) found from cwd, else (None, None, None)."""
|
||||||
|
p = C.find(cwd)
|
||||||
|
if not p:
|
||||||
|
return None, None, None
|
||||||
|
try:
|
||||||
|
c = C.load(p)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None, None, None
|
||||||
|
if not isinstance(c, dict) or c.get("status") == "closed":
|
||||||
|
return None, None, None
|
||||||
|
return c, p, C.project_dir(p)
|
||||||
|
|
||||||
|
|
||||||
|
def bound_fresh(sess, project, c):
|
||||||
|
"""('ok'|'foreign'|'stale', last activity epoch) for this session and the open unit."""
|
||||||
|
last = last_activity(project, c)
|
||||||
|
if not is_bound(sess, project, c):
|
||||||
|
return "foreign", last
|
||||||
|
if last is not None and time.time() - last > stale_seconds():
|
||||||
|
return "stale", last
|
||||||
|
return "ok", last
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- what the work is, how risky
|
||||||
|
|
||||||
|
def _ignored(rel):
|
||||||
|
p = rel.replace(os.sep, "/").lower()
|
||||||
|
return any(fnmatch.fnmatchcase(p, g.lower()) or (g.startswith("**/") and fnmatch.fnmatchcase(p, g[3:].lower()))
|
||||||
|
or (g.endswith("/**") and p.startswith(g[:-2].lower())) for g in _list("ignore_changed"))
|
||||||
|
|
||||||
|
|
||||||
|
def _rel_in_project(path, root, cwd):
|
||||||
|
"""The path relative to the project root, or None when it lies outside it."""
|
||||||
|
ap = path if os.path.isabs(path) else os.path.join(cwd, path)
|
||||||
|
ap = os.path.normpath(ap)
|
||||||
|
real_root = os.path.realpath(root)
|
||||||
|
d, b = os.path.split(ap)
|
||||||
|
rp = os.path.join(os.path.realpath(d), b)
|
||||||
|
if rp == real_root or not rp.startswith(real_root + os.sep):
|
||||||
|
return None
|
||||||
|
return os.path.relpath(rp, real_root)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_sisi(rel):
|
||||||
|
r = rel.replace(os.sep, "/")
|
||||||
|
return r == ".sisi" or r.startswith(".sisi/")
|
||||||
|
|
||||||
|
|
||||||
|
def floor_of(rels, project):
|
||||||
|
prof, reasons = risk.assess([r for r in rels if r], patterns=risk.load_patterns(project))
|
||||||
|
return prof, reasons
|
||||||
|
|
||||||
|
|
||||||
|
def session_paths(sess):
|
||||||
|
"""Paths this session changed (and nothing covered yet) since its last valid unit."""
|
||||||
|
return [p for p in (sess.get("ug_paths") or []) if isinstance(p, str)]
|
||||||
|
|
||||||
|
|
||||||
|
def _absorb(sess, root):
|
||||||
|
"""Fold the paths the after-tool snapshot attributed to this session into the guard's own list, once."""
|
||||||
|
since = [p for p in (sess.get("attr_since_pass") or []) if isinstance(p, str) and not p.startswith("*")]
|
||||||
|
covered = set(sess.get("ug_covered") or [])
|
||||||
|
sess["ug_covered"] = [p for p in covered if p in since] # settled stops empty attr_since_pass: forget
|
||||||
|
have = sess.setdefault("ug_paths", [])
|
||||||
|
new = False
|
||||||
|
for p in since:
|
||||||
|
rel = p
|
||||||
|
if os.path.isabs(p):
|
||||||
|
rel = _rel_in_project(p, root, root)
|
||||||
|
if rel is None:
|
||||||
|
continue
|
||||||
|
if p in covered or rel in have or _is_sisi(rel) or _ignored(rel):
|
||||||
|
continue
|
||||||
|
have.append(rel)
|
||||||
|
new = True
|
||||||
|
return new
|
||||||
|
|
||||||
|
|
||||||
|
def _cover(sess):
|
||||||
|
"""A valid unit stands behind everything changed so far."""
|
||||||
|
sess["ug_covered"] = [p for p in (sess.get("attr_since_pass") or []) if isinstance(p, str) and not p.startswith("*")]
|
||||||
|
sess["ug_paths"] = []
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- the verdict
|
||||||
|
|
||||||
|
def _problems(profile, c, project, info):
|
||||||
|
"""[(what is missing, how to supply it)] before building at this profile."""
|
||||||
|
errs = C.validate(c)
|
||||||
|
out = []
|
||||||
|
if C.is_unedited_skeleton(c) or any(isinstance(x, dict) and x.get("cmd") == C.PLACEHOLDER_CMD
|
||||||
|
for x in (c.get("checks") or [])):
|
||||||
|
out.append(("a check still carries the skeleton's placeholder command",
|
||||||
|
"replace it with a command that can fail, or delete the placeholder check (`sisi contract check`)"))
|
||||||
|
errs = [e for e in errs if "placeholder" not in e.lower()]
|
||||||
|
if C.is_placeholder(c.get("goal")):
|
||||||
|
out.append(("the goal in the person's words", 'set "goal" to one sentence naming the outcome wanted'))
|
||||||
|
if info.get("refused"):
|
||||||
|
out.append(("risk.profile %r is below the floor %r and gives no reason" % (info.get("declared"), info.get("floor")),
|
||||||
|
'raise it, or add "risk": {"why": "<why the floor is too high>"}'))
|
||||||
|
out += assure.missing(profile, c, project, None, errs, None, before_build=True)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def verdict(sid, sess, cwd, floor, c=None, path=None, project=None):
|
||||||
|
"""What stands between this session and building a change of this floor.
|
||||||
|
{"state": none|foreign|stale|invalid|ok, "problems": [(what, how)], "unit": contract|None, "profile": ...}"""
|
||||||
|
if c is None:
|
||||||
|
c, path, project = open_unit(cwd)
|
||||||
|
if c is None:
|
||||||
|
prof = floor if floor != "trivial" else "isolated"
|
||||||
|
return {"state": "none", "problems": [], "unit": None, "profile": prof, "last": None, "project": project}
|
||||||
|
state, last = bound_fresh(sess, project, c)
|
||||||
|
profile, info = assure.effective_profile(floor if floor != "trivial" else "isolated", c)
|
||||||
|
v = {"state": state, "problems": [], "unit": c, "profile": profile, "last": last, "project": project, "info": info}
|
||||||
|
if state != "ok":
|
||||||
|
return v
|
||||||
|
v["problems"] = _problems(profile, c, project, info)
|
||||||
|
if v["problems"]:
|
||||||
|
v["state"] = "invalid"
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- the message
|
||||||
|
|
||||||
|
def _how_on(c, state, last):
|
||||||
|
uid = c.get("id") or "?"
|
||||||
|
goal = " ".join(str(c.get("goal") or "").split())[:90]
|
||||||
|
when = age_text(last)
|
||||||
|
if state == "stale":
|
||||||
|
head = 'Unit %s ("%s") has had no activity since %s, so this session must say it continues it.' % (uid, goal, when)
|
||||||
|
else:
|
||||||
|
head = 'Unit %s ("%s", last active %s) was not opened or continued by this session.' % (uid, goal, when)
|
||||||
|
return [head,
|
||||||
|
"Three ways on: `sisi unit continue` (it is this work), `sisi unit park \"<why>\"` (set it aside, kept),",
|
||||||
|
"or `sisi unit close --abandon \"<why>\"`; for new work then run `sisi contract init`, replace its placeholder",
|
||||||
|
"check with one that can fail, and fill what the profile needs."]
|
||||||
|
|
||||||
|
|
||||||
|
def _profile_needs(profile):
|
||||||
|
req = assure.requirements(profile)
|
||||||
|
names = [n for k, n in (("covers", "what each check covers"), ("invariants", "invariants"),
|
||||||
|
("requirement_model", "the requirement list"), ("risk_note", "the risk note"),
|
||||||
|
("approach", "the approach")) if req.get(k)]
|
||||||
|
return ", ".join(names)
|
||||||
|
|
||||||
|
|
||||||
|
def refusal_text(v, what, floor_reasons=None):
|
||||||
|
profile = v["profile"]
|
||||||
|
lines = ["sisi refused: %s; that is a %s change and there is no valid unit for this work (rule 3: the contract comes first)."
|
||||||
|
% (what, profile)]
|
||||||
|
c = v.get("unit")
|
||||||
|
if v["state"] == "none":
|
||||||
|
lines += ["Missing: a unit for this work -> `sisi contract init`, then write at least one check that can fail,",
|
||||||
|
"replacing the placeholder, and set the goal in the person's words."]
|
||||||
|
need = _profile_needs(profile)
|
||||||
|
if need:
|
||||||
|
lines.append("At %s the contract also needs: %s (`sisi contract check` lists what is missing)." % (profile, need))
|
||||||
|
elif v["state"] in ("foreign", "stale"):
|
||||||
|
lines += _how_on(c, v["state"], v.get("last"))
|
||||||
|
else:
|
||||||
|
lines.append("Unit %s is yours but not ready to build on. Missing:" % c.get("id"))
|
||||||
|
lines += ["- %s -> %s" % (a, b) for a, b in v["problems"]]
|
||||||
|
lines.append("Then retry the call.")
|
||||||
|
return assure.fit(lines, MAX_LINES)
|
||||||
|
|
||||||
|
|
||||||
|
def unit_line(v):
|
||||||
|
"""One phrase for the refusal record: what state the unit was in."""
|
||||||
|
return v["state"] + ((": " + "; ".join(a for a, _ in v["problems"][:3])) if v.get("problems") else "")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- the record of refusals
|
||||||
|
|
||||||
|
REFUSALS = "refusals.jsonl"
|
||||||
|
|
||||||
|
|
||||||
|
def record_refusal(sid, project, what, v, sess=None, tool=None):
|
||||||
|
"""Store one refusal: what was refused and when. `unit` is the unit this session is bound to (None when
|
||||||
|
none); `open_unit` is whatever unit was open."""
|
||||||
|
c = v.get("unit")
|
||||||
|
bound = None
|
||||||
|
if isinstance(c, dict) and is_bound(sess or {}, project, c):
|
||||||
|
bound = c.get("id")
|
||||||
|
try:
|
||||||
|
store.append(REFUSALS, {"ts": store.now(), "session": sid, "project": os.path.realpath(project), "what": what,
|
||||||
|
"tool": tool, "state": v["state"], "unit": bound,
|
||||||
|
"unit_started": c.get("started") if bound else None,
|
||||||
|
"open_unit": c.get("id") if isinstance(c, dict) else None,
|
||||||
|
"why": unit_line(v)[:300]})
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("unitguard-record", e)
|
||||||
|
|
||||||
|
|
||||||
|
def refusals_for(project, uid=None, started=None):
|
||||||
|
"""The stored refusals of one unit (its id and start), or, with uid None, of no unit at all."""
|
||||||
|
rp = os.path.realpath(project)
|
||||||
|
out = []
|
||||||
|
for r in store.read(REFUSALS):
|
||||||
|
if not isinstance(r, dict) or r.get("project") != rp:
|
||||||
|
continue
|
||||||
|
if uid is None:
|
||||||
|
if r.get("unit") is None:
|
||||||
|
out.append(r)
|
||||||
|
elif r.get("unit") == uid and (started is None or r.get("unit_started") in (None, started)):
|
||||||
|
out.append(r)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- what a tool call would change
|
||||||
|
|
||||||
|
def _norm_lines(cmd):
|
||||||
|
"""The command without heredoc bodies (their text is data, not commands)."""
|
||||||
|
out, skip = [], None
|
||||||
|
for line in str(cmd).split("\n"):
|
||||||
|
if skip is not None:
|
||||||
|
if line.strip() == skip:
|
||||||
|
skip = None
|
||||||
|
continue
|
||||||
|
out.append(line)
|
||||||
|
m = re.search(r"<<-?\s*['\"]?(\w+)['\"]?", line)
|
||||||
|
if m:
|
||||||
|
skip = m.group(1)
|
||||||
|
return "\n".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def shell_targets(cmd, cwd):
|
||||||
|
"""Best-effort paths a shell command writes: redirects, tee, sed/perl -i, cp/mv/install/ln, rm/touch/mkdir, dd of=.
|
||||||
|
What cannot be told from the text (an interpreter, a script) is left to the after-tool snapshot."""
|
||||||
|
try:
|
||||||
|
lex = shlex.shlex(_norm_lines(cmd), posix=True, punctuation_chars=True)
|
||||||
|
lex.whitespace_split = True
|
||||||
|
toks = list(lex)
|
||||||
|
except ValueError:
|
||||||
|
return []
|
||||||
|
segs, cur = [], []
|
||||||
|
for t in toks:
|
||||||
|
if t in (";", "&", "|", "&&", "||"):
|
||||||
|
segs.append(cur)
|
||||||
|
cur = []
|
||||||
|
else:
|
||||||
|
cur.append(t)
|
||||||
|
segs.append(cur)
|
||||||
|
out = []
|
||||||
|
|
||||||
|
def add(x):
|
||||||
|
if x and not x.startswith(("&", "-", "/dev/")) and x not in out:
|
||||||
|
out.append(x)
|
||||||
|
for seg in segs:
|
||||||
|
i = 0
|
||||||
|
while i < len(seg):
|
||||||
|
t = seg[i]
|
||||||
|
if re.fullmatch(r"\d*>>?", t) or t in (">>", ">", ">|") or re.fullmatch(r"&>>?", t):
|
||||||
|
if i + 1 < len(seg):
|
||||||
|
add(seg[i + 1])
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
i += 1
|
||||||
|
words = [w for w in seg if w and not re.fullmatch(r"\d*(>>?|<<?|>\||&>>?)", w)]
|
||||||
|
k = 0
|
||||||
|
while k < len(words) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[k]) or words[k] in ("sudo", "command", "exec", "time", "nice")):
|
||||||
|
k += 1
|
||||||
|
if k >= len(words):
|
||||||
|
continue
|
||||||
|
prog, rest = os.path.basename(words[k]), words[k + 1:]
|
||||||
|
args = [a for a in rest if not a.startswith("-")]
|
||||||
|
if prog == "tee":
|
||||||
|
for a in args:
|
||||||
|
add(a)
|
||||||
|
elif prog in ("sed", "perl") and any(re.match(r"^-[a-zA-Z]*i", a) for a in rest if a.startswith("-")):
|
||||||
|
for a in (args[1:] if prog == "sed" and not any(a in ("-e", "-f") for a in rest) else args):
|
||||||
|
add(a)
|
||||||
|
elif prog in ("cp", "install", "ln", "mv", "rm", "touch", "mkdir", "rmdir"):
|
||||||
|
for a in (args if prog in ("mv", "rm", "touch", "mkdir", "rmdir") else args[-1:]):
|
||||||
|
add(a)
|
||||||
|
elif prog == "dd":
|
||||||
|
for a in rest:
|
||||||
|
if a.startswith("of="):
|
||||||
|
add(a[3:])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _is_sisi_command(cmd):
|
||||||
|
"""Every command of the line is sisi itself: it writes only personal data and the unit's own files."""
|
||||||
|
try:
|
||||||
|
lex = shlex.shlex(_norm_lines(cmd), posix=True, punctuation_chars=True)
|
||||||
|
lex.whitespace_split = True
|
||||||
|
toks = list(lex)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
segs, cur = [], []
|
||||||
|
for t in toks:
|
||||||
|
if t in (";", "&", "|", "&&", "||"):
|
||||||
|
segs.append(cur)
|
||||||
|
cur = []
|
||||||
|
else:
|
||||||
|
cur.append(t)
|
||||||
|
segs.append(cur)
|
||||||
|
segs = [s for s in segs if s]
|
||||||
|
return bool(segs) and all(os.path.basename(s[0]) == "sisi" for s in segs)
|
||||||
|
|
||||||
|
|
||||||
|
def classify(tool, payload, cmd):
|
||||||
|
"""'edit' (a file-editing tool), 'shell', 'delegate' (spawns a worker) or None."""
|
||||||
|
from . import watch
|
||||||
|
t = tool or ""
|
||||||
|
if t in _list("edit_tools") or any(w in t.lower() for w in _list("edit_name_words")):
|
||||||
|
return "edit"
|
||||||
|
if t in _list("delegation_tools"):
|
||||||
|
return "delegate"
|
||||||
|
if watch.is_shell(t, cmd):
|
||||||
|
return "shell"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _brief_text(payload):
|
||||||
|
inp = payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
|
||||||
|
return " ".join(str(inp.get(k) or "") for k in ("description", "prompt", "task", "message")).lower()
|
||||||
|
|
||||||
|
|
||||||
|
def routed_kind(sess, payload):
|
||||||
|
"""The kind of work a delegation was routed as (impl, review, search, ...), or None when no routing
|
||||||
|
decision is recorded for it. The one place that reads the routing record."""
|
||||||
|
r = sess.get("route") if isinstance(sess.get("route"), dict) else None
|
||||||
|
k = r.get("kind") if r else None
|
||||||
|
return k if isinstance(k, str) and k else None
|
||||||
|
|
||||||
|
|
||||||
|
def is_building_delegation(sess, payload):
|
||||||
|
kind = routed_kind(sess, payload)
|
||||||
|
if kind:
|
||||||
|
return kind in _list("build_kinds")
|
||||||
|
text = _brief_text(payload)
|
||||||
|
if any(ph in text for ph in _list("read_only_phrases")):
|
||||||
|
return False
|
||||||
|
return any(re.search(r"\b" + re.escape(w), text) for w in _list("build_words"))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- the hooks
|
||||||
|
|
||||||
|
def _deny(msg):
|
||||||
|
sys.stdout.write(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
||||||
|
"permissionDecisionReason": msg}}) + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def _is_contract_target(rel):
|
||||||
|
return rel.replace(os.sep, "/") == ".sisi/contract.json"
|
||||||
|
|
||||||
|
|
||||||
|
def before(payload):
|
||||||
|
"""True when this call was refused (the refusal is printed in the host's shape and the call must not run)."""
|
||||||
|
try:
|
||||||
|
return _before(payload)
|
||||||
|
except Exception as e: # fail open: a tool call is never held up by an error in here
|
||||||
|
store.log_error("unitguard-before", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _before(payload):
|
||||||
|
from . import attribution, watch, workers
|
||||||
|
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
||||||
|
kind = classify(tool, payload, cmd)
|
||||||
|
if kind is None:
|
||||||
|
return False
|
||||||
|
if not store.config()["gate"].get("enabled", True) or workers.is_subagent_payload(payload):
|
||||||
|
return False
|
||||||
|
sid = sid or "cwd-" + cwd
|
||||||
|
if kind == "shell":
|
||||||
|
if CLAIM_RE.search(cmd or ""):
|
||||||
|
note_claim(sid, cwd)
|
||||||
|
if watch._may_write(cmd) is False or _is_sisi_command(cmd):
|
||||||
|
return False
|
||||||
|
sess = store.load_session(sid)
|
||||||
|
if sess.get("subagent"):
|
||||||
|
return False
|
||||||
|
top = gitutil.root(cwd)
|
||||||
|
if top is None:
|
||||||
|
return False # nothing to measure outside a repository
|
||||||
|
rels, outside = [], False
|
||||||
|
if kind == "edit":
|
||||||
|
files = attribution._input_files(payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {})
|
||||||
|
if not files:
|
||||||
|
return False
|
||||||
|
targets = files
|
||||||
|
elif kind == "shell":
|
||||||
|
targets = shell_targets(cmd, cwd)
|
||||||
|
else:
|
||||||
|
targets = []
|
||||||
|
for f in targets:
|
||||||
|
r = _rel_in_project(f, top, cwd)
|
||||||
|
if r is None:
|
||||||
|
outside = True
|
||||||
|
else:
|
||||||
|
rels.append(r)
|
||||||
|
if kind == "delegate" and not is_building_delegation(sess, payload):
|
||||||
|
return False
|
||||||
|
if kind == "edit" and not rels:
|
||||||
|
return False # only outside the project
|
||||||
|
c, cpath, project = open_unit(cwd)
|
||||||
|
project = project or top
|
||||||
|
if any(_is_contract_target(r) for r in rels):
|
||||||
|
return _guard_contract_write(sid, sess, c, project, cwd, kind)
|
||||||
|
rels = [r for r in rels if not _is_sisi(r) and not _ignored(r)]
|
||||||
|
changed = _absorb(sess, top)
|
||||||
|
paths_all = list(dict.fromkeys(rels + session_paths(sess)))
|
||||||
|
if kind != "delegate" and not paths_all:
|
||||||
|
if changed:
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
return False
|
||||||
|
floor, _reasons = floor_of(paths_all, project) if paths_all else ("trivial", [])
|
||||||
|
if kind != "delegate" and floor == "trivial":
|
||||||
|
have = sess.setdefault("ug_paths", [])
|
||||||
|
for r in rels:
|
||||||
|
if r not in have:
|
||||||
|
have.append(r)
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
return False
|
||||||
|
v = verdict(sid, sess, cwd, floor, c, cpath, project)
|
||||||
|
if v["state"] == "ok":
|
||||||
|
_cover(sess)
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
touch(project, c, throttle=60.0)
|
||||||
|
return False
|
||||||
|
if kind == "delegate":
|
||||||
|
what = "delegating this work to a worker"
|
||||||
|
else:
|
||||||
|
shown = (rels[0] if rels else paths_all[0])
|
||||||
|
what = ("this call would change `%s`" % shown) if rels else ("earlier changes (`%s`) were made with no unit" % paths_all[0])
|
||||||
|
msg = refusal_text(v, what)
|
||||||
|
if kind == "delegate":
|
||||||
|
msg = msg.replace("Then retry the call.", "The contract is where the worker's brief takes its acceptance from. Then retry.")
|
||||||
|
record_refusal(sid, project, what, v, sess, tool)
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
_deny(msg)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _guard_contract_write(sid, sess, c, project, cwd, kind):
|
||||||
|
"""A write to the contract file itself. With a unit open that this session does not hold, that would
|
||||||
|
overwrite another piece of work's record: refused, with the three ways on. With no unit open it is how a
|
||||||
|
new contract is written, and the session is bound to it afterwards."""
|
||||||
|
if c is None:
|
||||||
|
sess["ug_will_bind"] = os.path.realpath(project)
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
return False
|
||||||
|
state, last = bound_fresh(sess, project, c)
|
||||||
|
if state == "ok":
|
||||||
|
return False
|
||||||
|
v = {"state": state, "problems": [], "unit": c, "profile": "isolated", "last": last, "project": project}
|
||||||
|
what = "this call would rewrite the contract of unit %s" % c.get("id")
|
||||||
|
msg = assure.fit(["sisi refused: %s, which this session has not opened or continued." % what] + _how_on(c, state, last)
|
||||||
|
+ ["Then retry the call."], MAX_LINES)
|
||||||
|
record_refusal(sid, project, what, v, sess, "contract-write")
|
||||||
|
_deny(msg)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def after(payload):
|
||||||
|
try:
|
||||||
|
_after(payload)
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("unitguard-after", e)
|
||||||
|
|
||||||
|
|
||||||
|
def _after(payload):
|
||||||
|
from . import watch
|
||||||
|
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
||||||
|
sid = sid or "cwd-" + cwd
|
||||||
|
sess = store.load_session(sid)
|
||||||
|
if not sess:
|
||||||
|
return
|
||||||
|
dirty = False
|
||||||
|
top = gitutil.root(cwd)
|
||||||
|
if sess.get("ug_will_bind"):
|
||||||
|
project = sess.pop("ug_will_bind")
|
||||||
|
dirty = True
|
||||||
|
c, _p, proj = open_unit(project)
|
||||||
|
if c is not None:
|
||||||
|
bind(sid, proj, c, "wrote")
|
||||||
|
sess = store.load_session(sid)
|
||||||
|
if top and classify(tool, payload, cmd) == "shell" and not sess.get("subagent"):
|
||||||
|
dirty = _absorb(sess, top) or dirty # a change the before-hook could not see: the next counted call answers for it
|
||||||
|
if dirty:
|
||||||
|
store.save_session(sid, sess)
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
"""Rule 3 as a mechanism: a unit is bound to the session that works on it, the first building step is
|
||||||
|
refused without a valid unit for THIS work, pause cannot skip the contract, the gate judges only the unit
|
||||||
|
a session holds, and nobody is their own independent evidence.
|
||||||
|
|
||||||
|
Requirement ids (docs/spec/requirements.json): R-9-1 (the lifecycle is followed), R-10.1-1 (a unit is one
|
||||||
|
piece of work, not a leftover), R-10.2-1 (the unit's durable record), R-10.3-1 (closing and pausing
|
||||||
|
cannot skip what the unit owes), R-5.3-1 and R-5.3-4 (the profile's row is enforced, the floor wins),
|
||||||
|
R-13.3-4 (independent evaluation is independent of the implementer), R-14.2-1 (stay inside the lines).
|
||||||
|
The abuse cases are written from the side of an agent that wants to skip."""
|
||||||
|
import contextlib, io, json, os, subprocess, sys, time, unittest
|
||||||
|
from unittest import mock
|
||||||
|
from support import *
|
||||||
|
from sisi import assure, contract as C, gate, gitutil, store, unit as U, unitguard as G, watch
|
||||||
|
|
||||||
|
SRC = "src/app.py"
|
||||||
|
|
||||||
|
|
||||||
|
def real(id, cmd="test -f src/app.py", **kw):
|
||||||
|
return dict(check(id, cmd), covers="the source file is missing", **kw)
|
||||||
|
|
||||||
|
|
||||||
|
def good_contract(goal="make the app greet", profile="isolated", **over):
|
||||||
|
c = {"id": "work", "parent": None, "goal": goal, "scope": {"in": [], "out": []},
|
||||||
|
"requirements": [], "risk": {"profile": profile}, "checks": [real("c1")], "invariants": [],
|
||||||
|
"assumptions": [], "questions": [], "deferred": [], "limitations": [], "plan": [], "approach": None,
|
||||||
|
"status": "open", "started": store.now(), "pauses": [], "deviations": []}
|
||||||
|
c.update(over)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def full_contract(**over):
|
||||||
|
"""Carries everything an integration-or-higher unit needs before building."""
|
||||||
|
c = good_contract(profile="integration")
|
||||||
|
c.update(requirements=[{"id": "r1", "kind": "explicit", "text": "the app greets by name", "decision": "now"}],
|
||||||
|
invariants=[dict(check("inv", "test -f README.md"), claim="the readme stays", covers="readme deleted")],
|
||||||
|
approach={"chosen": "change the greeting function", "why": "the smallest change",
|
||||||
|
"alternatives": ["a template engine: more moving parts"]})
|
||||||
|
c["risk"] = {"profile": "integration", "blast_radius": "only the greeting; nothing else reads it",
|
||||||
|
"rollback": "git revert the commit"}
|
||||||
|
c.update(over)
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
class GuardCase(SisiCase):
|
||||||
|
sid = "me"
|
||||||
|
model = "model-a"
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.git_init()
|
||||||
|
self.put("README.md", "# app\n")
|
||||||
|
self.put(SRC, "def greet():\n return 'hi'\n")
|
||||||
|
self.git_commit()
|
||||||
|
self.contract_path = os.path.join(self.proj, C.REL)
|
||||||
|
|
||||||
|
# ----- project helpers
|
||||||
|
def put(self, rel, text="x\n"):
|
||||||
|
p = os.path.join(self.proj, rel)
|
||||||
|
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||||
|
with open(p, "w") as f:
|
||||||
|
f.write(text)
|
||||||
|
return p
|
||||||
|
|
||||||
|
def git_commit(self):
|
||||||
|
subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True)
|
||||||
|
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "c"], cwd=self.proj, check=True)
|
||||||
|
|
||||||
|
def tick(self, sid=None, model=None, **extra):
|
||||||
|
"""The session-start hook for this session."""
|
||||||
|
self.sisi("tick", stdin=json.dumps(dict({"session_id": sid or self.sid, "cwd": self.proj, "source": "startup",
|
||||||
|
"model": model or self.model}, **extra)))
|
||||||
|
|
||||||
|
def open_unit(self, c=None, bind=True, sid=None):
|
||||||
|
self.write_contract(c or good_contract())
|
||||||
|
c = C.load(self.contract_path)
|
||||||
|
if bind:
|
||||||
|
G.bind(sid or self.sid, self.proj, c, "init")
|
||||||
|
return c
|
||||||
|
|
||||||
|
# ----- the hook
|
||||||
|
def payload(self, tool, inp, sid=None, **extra):
|
||||||
|
return dict({"session_id": sid or self.sid, "cwd": self.proj, "hook_event_name": "PreToolUse",
|
||||||
|
"tool_name": tool, "tool_input": inp}, **extra)
|
||||||
|
|
||||||
|
def before(self, tool, inp, sid=None, **extra):
|
||||||
|
"""Run the before-tool guard as the hook would. Returns the refusal text, or None when the call goes through."""
|
||||||
|
out = io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(out):
|
||||||
|
refused = G.before(self.payload(tool, inp, sid, **extra))
|
||||||
|
if not refused:
|
||||||
|
self.assertEqual(out.getvalue(), "")
|
||||||
|
return None
|
||||||
|
d = json.loads(out.getvalue())["hookSpecificOutput"]
|
||||||
|
self.assertEqual((d["hookEventName"], d["permissionDecision"]), ("PreToolUse", "deny"))
|
||||||
|
return d["permissionDecisionReason"]
|
||||||
|
|
||||||
|
def edit(self, rel=SRC, **kw):
|
||||||
|
return self.before("Edit", {"file_path": os.path.join(self.proj, rel), "old_string": "a", "new_string": "b"}, **kw)
|
||||||
|
|
||||||
|
def bash(self, cmd, **kw):
|
||||||
|
return self.before("Bash", {"command": cmd}, **kw)
|
||||||
|
|
||||||
|
def refusals(self):
|
||||||
|
return store.read(G.REFUSALS)
|
||||||
|
|
||||||
|
def age_unit(self, c, ago_s, sid=None):
|
||||||
|
"""The unit was started and last active `ago_s` seconds ago; the session is (still) bound to it."""
|
||||||
|
c["started"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - ago_s))
|
||||||
|
C.save(self.contract_path, c)
|
||||||
|
G.bind(sid or self.sid, self.proj, c, "init")
|
||||||
|
G._save(G._act_path(G.unit_key(self.proj, c)), {"project": os.path.realpath(self.proj), "id": c["id"],
|
||||||
|
"started": c.get("started"), "last": time.time() - ago_s})
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
class BindingTests(GuardCase):
|
||||||
|
"""Item 1: a unit is bound to the session that works on it (R-10.1-1)."""
|
||||||
|
|
||||||
|
def init(self, sid="me", goal="make the app greet"):
|
||||||
|
r = self.sisi("contract", "init", "--goal", goal, env={"SISI_SESSION_ID": sid})
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
return C.load(self.contract_path)
|
||||||
|
|
||||||
|
def test_the_session_that_opens_a_unit_is_bound_to_it_and_another_is_not(self):
|
||||||
|
c = self.init("me")
|
||||||
|
self.assertTrue(G.is_bound(store.load_session("me"), self.proj, c))
|
||||||
|
self.assertFalse(G.is_bound(store.load_session("other"), self.proj, c))
|
||||||
|
|
||||||
|
def test_continue_binds_the_session_and_says_the_goal_the_age_and_what_is_owed(self):
|
||||||
|
c = good_contract(goal="reshape the greeting")
|
||||||
|
c["started"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 3 * 86400))
|
||||||
|
self.write_contract(c)
|
||||||
|
self.assertFalse(G.is_bound(store.load_session("other"), self.proj, C.load(self.contract_path)))
|
||||||
|
r = self.sisi("unit", "continue", env={"SISI_SESSION_ID": "other"})
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.assertIn("reshape the greeting", r.stdout)
|
||||||
|
self.assertIn("3 days ago", r.stdout)
|
||||||
|
self.assertIn("c1 (not-run)", r.stdout)
|
||||||
|
self.assertTrue(G.is_bound(store.load_session("other"), self.proj, C.load(self.contract_path)))
|
||||||
|
|
||||||
|
def test_continue_without_a_unit_or_on_a_closed_one_is_refused(self):
|
||||||
|
self.assertNotEqual(self.sisi("unit", "continue", env={"SISI_SESSION_ID": "s"}).returncode, 0)
|
||||||
|
self.write_contract(good_contract(status="closed"))
|
||||||
|
r = self.sisi("unit", "continue", env={"SISI_SESSION_ID": "s"})
|
||||||
|
self.assertNotEqual(r.returncode, 0)
|
||||||
|
self.assertIn("closed", r.stdout)
|
||||||
|
|
||||||
|
def test_a_unit_with_no_activity_for_stale_hours_needs_continue_again(self):
|
||||||
|
c = self.init("me")
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "ok")
|
||||||
|
self.age_unit(c, 13 * 3600, "me")
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "stale")
|
||||||
|
r = self.sisi("unit", "continue", env={"SISI_SESSION_ID": "me"})
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout)
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "ok")
|
||||||
|
|
||||||
|
def test_stale_hours_is_configurable(self):
|
||||||
|
c = self.age_unit(self.init("me"), 2 * 3600, "me")
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "ok") # the default is 12 hours
|
||||||
|
os.makedirs(self.data, exist_ok=True)
|
||||||
|
with open(os.path.join(self.data, "config.json"), "w") as f:
|
||||||
|
json.dump({"unit": {"stale_hours": 1}}, f)
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "stale")
|
||||||
|
|
||||||
|
def test_a_verification_run_counts_as_activity(self):
|
||||||
|
c = self.age_unit(self.init("me"), 30 * 3600, "me")
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "stale")
|
||||||
|
store.append("results", {"ts": store.now(), "contract": c["id"], "project": self.proj, "check": "c1",
|
||||||
|
"item": "check", "status": "passed", "run": "r1"})
|
||||||
|
self.assertEqual(G.bound_fresh(store.load_session("me"), self.proj, c)[0], "ok")
|
||||||
|
|
||||||
|
def test_contract_init_on_an_open_unit_names_all_three_ways_on(self):
|
||||||
|
self.init("me")
|
||||||
|
r = self.sisi("contract", "init", env={"SISI_SESSION_ID": "me"})
|
||||||
|
self.assertEqual(r.returncode, 1)
|
||||||
|
for way in ("sisi unit continue", "sisi unit park", "sisi unit close --abandon"):
|
||||||
|
self.assertIn(way, r.stdout)
|
||||||
|
self.assertEqual(C.load(self.contract_path)["goal"], "make the app greet") # the old unit is untouched
|
||||||
|
|
||||||
|
def test_park_sets_the_unit_aside_keeping_its_contract_and_what_it_owes(self):
|
||||||
|
c = self.init("me")
|
||||||
|
r = self.sisi("unit", "park", "the owner asked for something else first", env={"SISI_SESSION_ID": "me"})
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.assertFalse(os.path.exists(self.contract_path))
|
||||||
|
with open(os.path.join(self.proj, ".sisi", "parked", "proj.json")) as f:
|
||||||
|
rec = json.load(f)
|
||||||
|
self.assertEqual(rec["contract"]["goal"], c["goal"])
|
||||||
|
self.assertEqual(rec["parked"]["why"], "the owner asked for something else first")
|
||||||
|
self.assertEqual(rec["parked"]["owes"], [["c1", "not-run"], ["deep-example", "not-run"]])
|
||||||
|
self.assertIn("c1", r.stdout)
|
||||||
|
|
||||||
|
def test_park_needs_a_reason_and_an_open_unit(self):
|
||||||
|
self.assertNotEqual(self.sisi("unit", "park", "why").returncode, 0)
|
||||||
|
self.init("me")
|
||||||
|
self.assertEqual(self.sisi("unit", "park").returncode, 1)
|
||||||
|
self.assertTrue(os.path.exists(self.contract_path))
|
||||||
|
|
||||||
|
def test_status_and_unit_list_show_a_parked_unit_with_its_age_and_what_it_owes(self):
|
||||||
|
self.init("me")
|
||||||
|
self.sisi("unit", "park", "waiting for the owner", env={"SISI_SESSION_ID": "me"})
|
||||||
|
st = self.sisi("status").stdout
|
||||||
|
self.assertIn("parked", st)
|
||||||
|
self.assertIn("proj", st)
|
||||||
|
self.assertIn("waiting for the owner", st)
|
||||||
|
self.assertIn("c1 (not-run)", st)
|
||||||
|
ls = self.sisi("unit", "list").stdout
|
||||||
|
self.assertIn("parked", ls)
|
||||||
|
self.assertIn("c1 (not-run)", ls)
|
||||||
|
|
||||||
|
def test_resume_brings_a_parked_unit_back_when_no_unit_is_open_and_binds_the_session(self):
|
||||||
|
self.init("me")
|
||||||
|
self.sisi("unit", "park", "later", env={"SISI_SESSION_ID": "me"})
|
||||||
|
self.init("me", goal="other work") # new work while the first is parked: it gets its own id
|
||||||
|
self.assertNotEqual(C.load(self.contract_path)["id"], "proj")
|
||||||
|
r = self.sisi("unit", "resume", "proj", env={"SISI_SESSION_ID": "me"})
|
||||||
|
self.assertEqual(r.returncode, 1, "a unit is open: resume must wait")
|
||||||
|
self.assertIn("sisi unit park", r.stdout)
|
||||||
|
self.sisi("unit", "close", "--abandon", "dropped", env={"SISI_SESSION_ID": "me"})
|
||||||
|
r = self.sisi("unit", "resume", "proj", env={"SISI_SESSION_ID": "third"})
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
c = C.load(self.contract_path)
|
||||||
|
self.assertEqual((c["id"], c["goal"]), ("proj", "make the app greet"))
|
||||||
|
self.assertTrue(G.is_bound(store.load_session("third"), self.proj, c))
|
||||||
|
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "parked", "proj.json")))
|
||||||
|
|
||||||
|
def test_resume_of_an_unknown_id_says_so(self):
|
||||||
|
r = self.sisi("unit", "resume", "nope")
|
||||||
|
self.assertEqual(r.returncode, 1)
|
||||||
|
self.assertIn("no parked unit", r.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user