# Conflicts: # tests/test_core.py
This commit is contained in:
commit
058d6e3e56
10 files changed
+295
-91
No files matched your search
+1
-1
@@ -12,7 +12,7 @@ Before and after the work
|
||||
|
||||
The learning loop
|
||||
sisi retro what happened in this piece of work, to set against the objective
|
||||
sisi retro --gap G --cause C --improve I --term T --problem N|"..." [--scope user]
|
||||
sisi retro --gap G --cause C --improve I --term T --problem N|"..." --level core|user|project
|
||||
record the gap and problem; the improvement is a rule at once
|
||||
sisi retro --no-gap TEXT --term T --better B | --later TEXT
|
||||
nothing fell short; or the work is not finished yet
|
||||
|
||||
+3
-3
@@ -12,7 +12,7 @@ DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call
|
||||
|
||||
METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your workers and `sisi pick routine|ordinary|hard` "
|
||||
"chooses one; if doing this yourself costs less than briefing it, say why with `sisi direct \"<reason>\"` (%d more).")
|
||||
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"<gap>\" --cause \"<cause>\" --improve \"<rule>\" --term <term> --problem N|\"<name>\"` "
|
||||
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"<gap>\" --cause \"<cause>\" --improve \"<rule>\" --term <term> --problem N|\"<name>\" --level core|user|project` "
|
||||
"or `sisi retro --no-gap \"<evidence>\" --term <term> --better \"<what would score better>\"` (or pause: `sisi retro --later \"<what it waits for>\"`).")
|
||||
NODONE = "sisi: no done is recorded yet. Define what the person wants and what comes next now: `sisi done --goal \"<their goal>\" --check \"<a check that can fail>\" [--check ...] --next \"<what comes next and what you do about it>\"`."
|
||||
NOPICK = ("sisi: this delegation went to a worker the wheel did not give you (recorded so `sisi judge` still works). Use `sisi pick routine|ordinary|hard` next time "
|
||||
@@ -21,7 +21,7 @@ NOLOOK = ("sisi: this brief asks for something the person will look at but state
|
||||
"Choose it with the person from previews and put it in the brief, or add a line 'Look: <the existing design it follows>'.")
|
||||
UNKNOWN = "sisi: the worker you named is not in the models table (recorded so `sisi judge` still works), so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), and use `sisi pick` next time."
|
||||
NOSHELL = "sisi: do not shell out to a worker; start it with the host's delegation tool next time."
|
||||
FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term> --problem N|\"<name>\"` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term> --problem N|\"<name>\" --level core|user|project` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
OPEN = "sisi: these checks have no verdict yet: %s. Give each one: `sisi done --pass N \"<evidence>\"` or `sisi done --fail N \"<why>\"` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
LATE = "%s was started %s and has not reported. Check it: if still running, let it finish (this reminder is shown once); if dead or unwanted, cancel it and run `sisi judge WORKER bad \"<why>\"`; if it reported, run `sisi judge WORKER good|bad \"<why>\"`."
|
||||
|
||||
@@ -119,7 +119,7 @@ def tick(p):
|
||||
store.append(env, "export SISI_SESSION_ID=%s" % sid, once=True) # so `sisi retro` knows its session
|
||||
if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")):
|
||||
rules.build_rulebook()
|
||||
(text := "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text)
|
||||
(text := "\n".join(x for x in (rules.project_text(cwd), rules.core_note(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
+12
-8
@@ -6,7 +6,7 @@ from . import rules, store
|
||||
DONE_USAGE = """usage: sisi done --goal "<the goal in their words, 5+ words>" --check "<a check that can fail, 4+ words>" [--check ...] \\
|
||||
--next "<what they will need next and what you do about it: now, room, follow-up or drop; 4+ words>"
|
||||
sisi done --pass N "<evidence>" | --fail N "<why>" sisi done: show it"""
|
||||
FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--term", "--better", "--problem")
|
||||
FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--level", "--term", "--better", "--problem")
|
||||
TERMS = {"value": "what the person wanted", "evidence": "verified by checks that fit the risk", "time": "elapsed time",
|
||||
"cost": "compute and tool cost", "attention": "the person's attention", "learning": "getting better at the next piece of work"}
|
||||
TERM_HELP = "--term is one of: %s." % ", ".join(TERMS)
|
||||
@@ -14,8 +14,8 @@ clean = store.clean
|
||||
USAGE = """Record one of these:
|
||||
sisi retro --gap "<where the work fell short of the objective, with the evidence>" \\
|
||||
--cause "<the root cause>" \\
|
||||
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." [--scope user]
|
||||
Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: in this project, or with --scope user in all your work.
|
||||
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." --level core|user|project
|
||||
Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: --level project: this git repo only; user: all your work; core: queued for the sisi product (never loaded). --scope works as --level.
|
||||
sisi retro --no-gap "<what shows the work met the objective>" --term TERM \\
|
||||
--better "<one concrete thing that would have scored better on that term, 5+ words>"
|
||||
TERM is where the work fell short, or could most have scored better: %s.
|
||||
@@ -210,9 +210,9 @@ def run(args, cwd=None):
|
||||
if not args:
|
||||
return report(sid, cwd) or 0
|
||||
opt = _options(args)
|
||||
scope, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "term", "better", "problem")]
|
||||
scope = scope or rules.PROJECT
|
||||
kind = (None if not opt or scope not in (rules.USER, rules.PROJECT)
|
||||
scope, level, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "level", "term", "better", "problem")]
|
||||
scope = level or scope
|
||||
kind = (None if not opt or (scope is not None and scope not in (rules.CORE, rules.USER, rules.PROJECT))
|
||||
else "later" if set(opt) == {"later"} and _words(opt, "later", 3)
|
||||
else "no-gap" if set(opt) == {"no-gap"} and _words(opt, "no-gap", 5)
|
||||
else "gap" if set(opt) == {"gap", "cause", "improve"} and all(_words(opt, k, 4) for k in opt) else None)
|
||||
@@ -221,6 +221,9 @@ def run(args, cwd=None):
|
||||
print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most "
|
||||
"400 characters).\n" + USAGE)
|
||||
return 1
|
||||
if kind == "gap" and (why := rules.refuse_level(scope, cwd, "sisi retro --gap ...")):
|
||||
print("sisi retro: " + why)
|
||||
return 1
|
||||
if kind != "gap" and problem is not None:
|
||||
print("sisi retro: --problem goes only with --gap.")
|
||||
return 1
|
||||
@@ -270,8 +273,9 @@ def run(args, cwd=None):
|
||||
print("opened problem %d '%s'." % (prob["num"], prob["name"]))
|
||||
try:
|
||||
added, warn = rules.add(opt["improve"], scope, "retro", cwd)
|
||||
print(warn or "recorded. In force from the next session%s: %s" % (
|
||||
" in every project" if scope == rules.USER else " in this project", added))
|
||||
print(warn or ("recorded. In force from the next session%s: %s" % (
|
||||
" in every project" if scope == rules.USER else " in this project", added) if scope != rules.CORE else "recorded, queued for the product: %s" % added))
|
||||
print(rules.filed(scope, opt["improve"], cwd))
|
||||
except OSError as e:
|
||||
print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e))
|
||||
if misses >= 2:
|
||||
|
||||
+113
-26
@@ -6,7 +6,9 @@ Now and then a cheap worker audits and organizes them. Store changes are committ
|
||||
import contextlib, hashlib, json, os, re, time
|
||||
from . import store
|
||||
|
||||
USER, PROJECT = "user", "project"
|
||||
USER, PROJECT, CORE = "user", "project", "core"
|
||||
LEVELS = """The three levels: core = the sisi product itself, for every sisi user anywhere, nothing personal (queued for its maintainers, never loaded);
|
||||
user = how this person works across all projects, their machine, accounts, providers; project = this one git repo only (its .sisi/rules.md)."""
|
||||
OWNER = re.compile(r"\[owner\b[^\]]*\]")
|
||||
_owner, _retro = lambda l: bool(OWNER.search(l)), lambda ls: [l for l in ls if not _owner(l)]
|
||||
_snap = lambda u, p: hashlib.sha1(("\n".join(u) + "\0" + "\n".join(p)).encode()).hexdigest()[:16]
|
||||
@@ -30,8 +32,11 @@ Rewrite both lists so they serve that objective best:
|
||||
- Merge rules that say the same thing. Drop fragments, rules that are stale or contradicted by a later one,
|
||||
and rules too specific to come up again.
|
||||
- Word each rule as a direct instruction with its reason, on one line, standing on its own.
|
||||
- A rule seen in more than one project, or about how the person wants to be worked with, belongs in the
|
||||
first list. A rule about this project's own code belongs in the second.
|
||||
- Audit where each rule is filed. %(levels)s Move a rule that sits at the wrong level, in either direction,
|
||||
with its words byte-identical: a user line about one project goes to `## project` (this one; if it names another
|
||||
project leave it and flag it); a project line that applies to all the person's work goes to `## user`; a line
|
||||
that applies to every sisi user goes under `## core` (a queue for the product's maintainers). [owner ...] lines
|
||||
may move between levels too, never reworded.
|
||||
- Lines marked [owner ...] are the person's own words: copy every one of them verbatim, unchanged by even
|
||||
one character (you may reorder them). Only the other lines ([retro ...], [agent ...]) may be merged, reworded or dropped.
|
||||
- Flag, but do not change, any [owner ...] line whose text does not read as the person's own words (a paraphrase, an
|
||||
@@ -48,6 +53,8 @@ Answer with exactly this shape and nothing else:
|
||||
- ...
|
||||
## project
|
||||
- ...
|
||||
## core
|
||||
- ... (only lines moved to the product queue)
|
||||
## drops
|
||||
- <old rule> | #<N or -> | <reason> (optional; only if any non-owner rules were dropped)
|
||||
## flags
|
||||
@@ -70,7 +77,31 @@ Answer with exactly this shape and nothing else:
|
||||
def path(scope, cwd=None):
|
||||
"""Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept."""
|
||||
top, inside = store.root(cwd) if scope == PROJECT else ("", False)
|
||||
return store.data("rules", "user.md") if scope == USER else "" if inside else os.path.join(top, ".sisi", "rules.md")
|
||||
return store.data("rules", scope + ".md") if scope in (USER, CORE) else "" if inside else os.path.join(top, ".sisi", "rules.md")
|
||||
|
||||
|
||||
def has_project(cwd=None):
|
||||
"""True inside a git repository whose root is not the home folder: the only place a project list may be written."""
|
||||
top, inside = store.root(cwd)
|
||||
return not inside and os.path.lexists(os.path.join(top, ".git")) and os.path.realpath(top) != os.path.realpath(store.HOME)
|
||||
|
||||
|
||||
def refuse_level(level, cwd, cmd):
|
||||
"""Why a rule may not be filed at this level (with the command to rerun), or ""."""
|
||||
if level not in (CORE, USER, PROJECT):
|
||||
return "name the level of this rule. %s\nRerun with --level core|user|project, e.g. `%s --level user ...`." % (LEVELS, cmd)
|
||||
return "no project here (not inside a git repository, or it is the home folder), use user: `%s --level user ...`." % cmd if level == PROJECT and not has_project(cwd) else ""
|
||||
|
||||
|
||||
def filed(level, text, cwd):
|
||||
return 'filed as %s rule in %s. Wrong level? sisi rules move "%s" core|user|project' % (level, path(level, cwd), " ".join(text.split()[:5]))
|
||||
|
||||
|
||||
def core_note(cwd):
|
||||
"""At session start in the sisi repo itself: how many rules wait in the product queue."""
|
||||
top = store.project_root(cwd)
|
||||
n = len(lines(path(CORE))) if all(os.path.isfile(os.path.join(top, *f)) for f in (("canon", "core.md"), ("sisi", "rules.py"))) else 0
|
||||
return "sisi: %d rule%s proposed for the product: add each to canon/core.md or move it (sisi rules move)." % (n, "" if n == 1 else "s") if n else ""
|
||||
|
||||
|
||||
def _legacy(cwd=None):
|
||||
@@ -186,13 +217,16 @@ def _commit(msg, *paths, snap=None, put=None):
|
||||
raise OSError("store git commit failed (%s)" % store.GIT_ERROR)
|
||||
|
||||
|
||||
def add(text, scope, source, cwd=None, log=None, means=""):
|
||||
def add(text, scope, source, cwd=None, log=None, means="", raw=None):
|
||||
"""Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written."""
|
||||
if scope == PROJECT and not has_project(cwd):
|
||||
raise OSError("no project here, use user")
|
||||
line, *more = ["- %s [%s %s]" % (" ".join(str(t).split()), src, time.strftime("%Y-%m-%d")) for t, src in ((text, source), (means, "agent reading")) if t] # one commit holds both
|
||||
line, more = (raw, []) if raw else (line, more)
|
||||
dest = path(scope, cwd)
|
||||
scope == PROJECT and not dest and _check_writable(dest)
|
||||
with store.lock(dest if scope == PROJECT else "user"):
|
||||
if scope == USER:
|
||||
if scope != PROJECT:
|
||||
[store.append(dest, l) for l in [line, *more]]
|
||||
else:
|
||||
_check_writable(dest)
|
||||
@@ -204,7 +238,7 @@ def add(text, scope, source, cwd=None, log=None, means=""):
|
||||
note(dest)
|
||||
try:
|
||||
log and store.append(*log)
|
||||
extra = ([dest] if scope == USER else []) + ([log[0]] if log else [])
|
||||
extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else [])
|
||||
_commit("rule added (%s, %s)" % (scope, source), *extra, snap=(dest, before, after) if scope == PROJECT else None)
|
||||
warn = ""
|
||||
except OSError as e:
|
||||
@@ -275,8 +309,9 @@ def due(cwd, claim=False):
|
||||
ls, k = _retro(scope_lines(scope, cwd, migrate=False)), _mark_key(scope, cwd)
|
||||
prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0))
|
||||
over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]
|
||||
if not active(cl, k) and (over or len(ls) - prev >= cfg["organize_after"]):
|
||||
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev))))
|
||||
audit = scope == USER and has_project(cwd) and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"]
|
||||
if not active(cl, k) and (over or audit or len(ls) - prev >= cfg["organize_after"]):
|
||||
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev) if len(ls) - prev >= cfg["organize_after"] else "time to audit their levels")))
|
||||
if not need:
|
||||
return ""
|
||||
if claim:
|
||||
@@ -328,7 +363,7 @@ def organize_brief(cwd):
|
||||
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
|
||||
store.write(store.data("locks", "organize.json"), json.dumps(cl))
|
||||
return ORGANIZE % {
|
||||
"name": os.path.basename(store.project_root(cwd)), "objective": objective(),
|
||||
"name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "objective": objective(),
|
||||
"lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
|
||||
"flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)",
|
||||
"user": "\n".join(u) or "(none)", "project": "\n".join(p) or "(none)",
|
||||
@@ -339,10 +374,10 @@ def organize_brief(cwd):
|
||||
def organize_record(answer_file, cwd):
|
||||
"""Replace both lists with the worker's answer. Returns why not, or None when it is done."""
|
||||
cfg = store.config()
|
||||
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project)[ \t]*|## [^\n]*)$", store.read(answer_file))
|
||||
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file))
|
||||
got, flags, drops = {}, "", {}
|
||||
for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)):
|
||||
if re.fullmatch(r"## (user|project)[ \t]*", h):
|
||||
if re.fullmatch(r"## (user|project|core)[ \t]*", h):
|
||||
got[h[3:].strip()] = [l.rstrip() for l in chunk.splitlines() if l.startswith("- ")]
|
||||
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
|
||||
flags += chunk
|
||||
@@ -350,6 +385,7 @@ def organize_record(answer_file, cwd):
|
||||
for l in chunk.splitlines():
|
||||
if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]):
|
||||
drops.setdefault(rk, (m[2], why))
|
||||
core = got.pop(CORE, [])
|
||||
if set(got) != {USER, PROJECT}:
|
||||
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
|
||||
for scope, ls in got.items():
|
||||
@@ -357,7 +393,9 @@ def organize_record(answer_file, cwd):
|
||||
if len(r) > cfg["rules_lines"] or sum(map(len, r)) > cfg["rules_chars"]:
|
||||
return "the %s list is over the budget of %d lines and %d characters (it has %d and %d)" % (
|
||||
scope, cfg["rules_lines"], cfg["rules_chars"], len(r), sum(map(len, r)))
|
||||
up, pp = path(USER), path(PROJECT, cwd)
|
||||
up, pp, cp = path(USER), path(PROJECT, cwd), path(CORE)
|
||||
if not has_project(cwd):
|
||||
return "no project here, so there is no project list to organize; run it from inside a git project"
|
||||
if not pp or os.path.islink(os.path.dirname(pp)):
|
||||
return _migrate(cwd)[1].removeprefix("sisi: ")
|
||||
with store.lock(pp):
|
||||
@@ -367,10 +405,10 @@ def organize_record(answer_file, cwd):
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
|
||||
if (want := _organized(("locks", "organize.json")).get("snap:" + _mark_key(PROJECT, cwd))) and _snap(had[USER], had[PROJECT]) != want:
|
||||
return "the rules changed since `sisi rules organize` ran; run `sisi rules organize` again"
|
||||
for scope in (USER, PROJECT):
|
||||
if miss := [l for l in had[scope] if _owner(l) and got[scope].count(l) < had[scope].count(l)]:
|
||||
return "owner rule missing or changed (%s): %s" % (scope, miss[0])
|
||||
kept = list(got[USER]) + list(got[PROJECT])
|
||||
every = got[USER] + got[PROJECT] + core # an owner line may change level, never a word
|
||||
if miss := [l for l in had[USER] + had[PROJECT] if _owner(l) and every.count(l) < (had[USER] + had[PROJECT]).count(l)]:
|
||||
return "owner rule missing or changed: %s" % miss[0]
|
||||
kept = every[:]
|
||||
dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)]
|
||||
from . import retro
|
||||
nprobs = len(retro._problems()) if dropped else 0
|
||||
@@ -391,12 +429,13 @@ def organize_record(answer_file, cwd):
|
||||
utext = "".join(l + "\n" for l in got[USER])
|
||||
try:
|
||||
seen = _organized()
|
||||
seen["retros"] = len(store.read(store.data("retro.jsonl")).splitlines())
|
||||
seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))})
|
||||
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
|
||||
dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
for r, pn, why in recs:
|
||||
store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True))
|
||||
_commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, store.data("rules", "organized.json"): json.dumps(seen)})
|
||||
_commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, **({cp: "".join(l + "\n" for l in dict.fromkeys(lines(cp) + core))} if core else {}), store.data("rules", "organized.json"): json.dumps(seen)})
|
||||
except OSError as e:
|
||||
(wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook()
|
||||
if not wrote and not wrote_u:
|
||||
@@ -417,7 +456,7 @@ def organize_record(answer_file, cwd):
|
||||
|
||||
def revert():
|
||||
"""Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left."""
|
||||
files = ("rules/user.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS)
|
||||
files = ("rules/user.md", "rules/core.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS)
|
||||
advice = " (edit by hand or restore with git)"
|
||||
if os.path.isdir(os.path.join(store.DATA, ".git")) and store.git(["status", "--porcelain", "--", *files], store.DATA)[1].strip():
|
||||
return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice
|
||||
@@ -478,15 +517,53 @@ def run(args, cwd=None):
|
||||
return 0
|
||||
if args[0] == "organize" and len(args) == 3 and args[1] == "--record":
|
||||
why = organize_record(args[2], cwd)
|
||||
elif args[:1] == ["move"]:
|
||||
why = move(args[1:], cwd)
|
||||
elif args == ["revert"]:
|
||||
why = revert()
|
||||
else:
|
||||
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules revert"
|
||||
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules move \"<start of a rule>\" core|user|project [--project PATH] | sisi rules revert"
|
||||
if why:
|
||||
print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why)
|
||||
return 1 if why else 0
|
||||
|
||||
|
||||
def move(args, cwd):
|
||||
"""`sisi rules move "<start of a rule line>" LEVEL [--project PATH]`: one line, verbatim, to another level. Returns why not, or None."""
|
||||
top = None
|
||||
if "--project" in args:
|
||||
i = args.index("--project")
|
||||
top, args = os.path.abspath((args[i + 1:i + 2] or [""])[0]), args[:i] + args[i + 2:]
|
||||
if not has_project(top) or os.path.realpath(store.root(top)[0]) != os.path.realpath(top):
|
||||
return "--project needs the folder of a git repository (its root)"
|
||||
if len(args) != 2 or args[1] not in (CORE, USER, PROJECT):
|
||||
return 'usage: sisi rules move "<start of a rule line>" core|user|project [--project PATH]'
|
||||
start, to = args[0].strip().removeprefix("- ").strip(), args[1]
|
||||
homes = [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in dict.fromkeys(c for c in (cwd if has_project(cwd) else None, top) if c)]
|
||||
hits = [(lv, c, l) for lv, c in homes for l in dict.fromkeys(scope_lines(lv, c, migrate=False) if lv == PROJECT else lines(path(lv))) if l[2:].startswith(start)] if start else []
|
||||
if len(hits) != 1:
|
||||
return "no rule line starts with that" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for lv, _, l in hits)
|
||||
lv, c, line = hits[0]
|
||||
to_cwd = top or cwd
|
||||
if path(lv, c) == path(to, to_cwd):
|
||||
return "that rule is already a %s rule" % to
|
||||
if why := refuse_level(to, to_cwd, "sisi rules move"):
|
||||
return why.split(": `")[0]
|
||||
add(line, to, "move", to_cwd, raw=line)
|
||||
src = path(lv, c)
|
||||
with store.lock(src if lv == PROJECT else "user"):
|
||||
keep = (_text(src) or "").splitlines(True)
|
||||
keep.remove(next(x for x in keep if x.rstrip("\r\n") == line))
|
||||
if lv == PROJECT:
|
||||
_check_writable(src)
|
||||
store.write(src, "".join(keep))
|
||||
else:
|
||||
_commit("rule moved (%s to %s)" % (lv, to), put={src: "".join(keep)})
|
||||
lv == USER and build_rulebook()
|
||||
print("moved to %s: %s" % (to, line))
|
||||
return None
|
||||
|
||||
|
||||
_norm = lambda t: " ".join(re.sub(r"[\W_]+", " ", t.lower()).split())
|
||||
|
||||
|
||||
@@ -501,14 +578,23 @@ def _said(words, cwd):
|
||||
|
||||
|
||||
def learn(args, cwd=None):
|
||||
"""`sisi learn [--project] "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
|
||||
"""`sisi learn --level core|user|project "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
|
||||
owner tag only when the words are found in the person's recent messages, else the agent's own tag."""
|
||||
i = args.index("--means") if "--means" in args else len(args)
|
||||
args, means = list(args[:i]), " ".join(args[i + 1:])
|
||||
scope = PROJECT if "--project" in args else USER
|
||||
text = " ".join(a for a in args if a != "--project").strip()
|
||||
if len(text.split()) < 3 or (means and len(means.split()) < 3):
|
||||
print('usage: sisi learn [--project] "<what the person said, in their words>" [--means "<how I will apply it>"]')
|
||||
scope, words, i = PROJECT if "--project" in args else None, [], 0
|
||||
while i < len(args):
|
||||
if args[i] in ("--level", "--scope") and i + 1 < len(args):
|
||||
scope, i = args[i + 1], i + 2
|
||||
else:
|
||||
words += [args[i]] * (args[i] != "--project")
|
||||
i += 1
|
||||
text = " ".join(words).strip()
|
||||
if len(text.split()) < 3 or (means and len(means.split()) < 3) or any(w.startswith("--") for w in words):
|
||||
print('usage: sisi learn --level core|user|project "<what the person said, in their words>" [--means "<how I will apply it>"]')
|
||||
return 1
|
||||
if why := refuse_level(scope, cwd, 'sisi learn'):
|
||||
print("sisi learn: " + why)
|
||||
return 1
|
||||
heard = _said(text, cwd)
|
||||
log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
|
||||
@@ -518,5 +604,6 @@ def learn(args, cwd=None):
|
||||
print("sisi learn: could not write %s (%s). Nothing was changed, and your words were not kept." % (path(scope, cwd) or cwd or os.getcwd(), e))
|
||||
return 1
|
||||
heard or print("sisi learn: these words were not found in the person's recent messages, so the rule carries the weaker tag [agent, attributed to owner]; a later owner statement or a measurement overrides it.")
|
||||
print(warn or "in force from the next session: %s" % line)
|
||||
print(warn or ("in force from the next session: %s" if scope != CORE else "queued for the product, not in force: %s") % line)
|
||||
print(filed(scope, text, cwd))
|
||||
return 0
|
||||
+1
-1
@@ -24,7 +24,7 @@ GIT_ERROR = "" # why the last git call that failed did: the first line of its s
|
||||
|
||||
# Every setting there is. The person overrides one under "core" in config.json in their store.
|
||||
DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8,
|
||||
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False,
|
||||
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 7, "shell_workers": False,
|
||||
"worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8}
|
||||
|
||||
def config():
|
||||
|
||||
Reference in new issue
Block a user