Learning loop rebuild: record store, retro, cycle, earned scope

This commit is contained in:
swaits committed 2026-11-23 11:02:37 -07:00
1 parent d357fe0004
commit 553b397ad0
11 files changed
+1328 -5160

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
{
"rules": ["know-done", "strongest-check", "finish-by-verifying", "retro-every-time"],
"note": "Non-negotiable rules: a learning cycle must never replace or disable these. They carry verification before done, truthful reporting, and this governance itself. Changing them is product work by the owner, never a cycle."
}
+23 -51
View File
@@ -37,37 +37,22 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT
learned changes to rules, verifiers and recipes; each one a commit in your personal repo
sisi audit inventory of standing instructions per tool
sisi retro --scope core|user|project --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" --pattern "the general failure of thinking, one line" [--pattern-id N] [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"]
(or --json - with the same keys on stdin)
end of every piece of work: HOW it could have gone better; --when (at least
5 terms, synonyms included) is how a later agent with different words finds it;
--pattern is required (one line that would apply to unrelated
work; `sisi retro patterns` lists existing ones to reuse);
--short (at most 140 characters) and --topic (at most 30) are optional: when
omitted, the next learning round writes them
aims: level (the human could have worked at a higher level), verified (a stronger check was
possible), hands-off (the human was interrupted more than needed), intent (the result was not
what they meant), speed (it took longer than it had to)
sisi lessons [filters] | show ID | digest [--all] | set ID --status S | apply ID | export [FILE] | import FILE
the shared lessons from retros (--aim --kind --status --repo --top --json);
digest prints a short plain-language summary grouped by topic, for the human
sisi backlog tool lessons: changes to sisi itself, most seen first
sisi cycle [due|apply FILE|check FILE|--dry-run FILE|revert [ID]|status|help|--now]
consolidate lessons into rules, entries and enforced checks (no
scheduler: due-ness is a counter checked during normal use);
with no argument, or with --now, it prints the brief on demand even
when none is due; check/--dry-run prints what would change, changing
nothing; help prints the full cycle file format
sisi improve is it getting better? lessons, recurrence, send-backs, time, rulebook size
sisi retro print the unit's record and what stands out in it
sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID]
record one finding; promote also needs --change, --mechanism,
--expect and --validate; record needs --limits; drop needs --why-not
sisi lessons [--json] | show ID the learning records and their statuses
sisi cycle [due|apply FILE|check FILE|revert [ID]|help]
turn proposed learnings into mechanisms (no scheduler:
due-ness is a counter); apply validates and replays before
promoting; help prints the cycle file format
sisi approve [ID --yes|--no] decide a consequential learning change a cycle parked
sisi note TEXT (older; prefer retro) record something that went wrong
sisi propose TEXT (older; prefer retro) suggest a rule change
sisi learn --scope core|user|project TEXT
record a human-stated preference; it takes effect at once.
--scope is required, by two questions: (a) does it apply to
all projects where sisi may be used? (b) would it be useful
to every user who installs sisi? Both yes: core (in force
for you, queued for the product). (a) only: user (your
standing principles). Neither: project (handed over to it)
sisi learn [--scope user|project] TEXT
record an owner statement; it takes effect at once and
`sisi oracle` prints it. Scope for other learnings is
earned by evidence, never claimed
sisi design the owner's standing principles and the design questions to
answer in a contract's design section before sizeable work
(implies, provided, alternatives, chosen, objections, challenge)
@@ -146,8 +131,8 @@ def cmd_contract(args):
except Exception:
pass
try:
from . import retro
block = retro.delivery_block(goal or "", "contract-init", extra="contract checks verified")
from . import learning as _L
block = _L.delivery_text(os.getcwd(), goal or "")
if block:
print(block)
except Exception:
@@ -232,18 +217,13 @@ def cmd_oracle():
def _status_retro():
try:
from . import retro
st = retro.stats()
from . import learning as _L
rows = _L.load_learnings()
print("learnings : %d total, %d proposed, %d promoted (`sisi status --learning` for the report)"
% (len(rows), sum(1 for r in rows if r.get("status") == "proposed"),
sum(1 for r in rows if r.get("status") in ("promoted", "monitored"))))
except Exception:
return
print("lessons : %d total, %d open, %d applied; %d occurrences in the last 7 days"
% (st["total"], st["open"], st["applied"], st["occ7"]))
w = st["sessions_with_work"]
print("retros : %s of sessions with real work recorded one (%d of %d)"
% ("%.0f%%" % (100 * st["sessions_with_retro"] / w) if w else "n/a", st["sessions_with_retro"], w))
for t in st["top"]:
from . import retro as _R
print(" active #%-4d x%-3d %s" % (t["id"], t["count"], _R.heading_text(t, 90)))
def _status_contracts(res):
@@ -309,11 +289,6 @@ def cmd_status():
except Exception:
pass
_status_retro()
try:
from . import cycle
print(cycle.improve_line())
except Exception:
pass
_status_contracts(res)
from . import verifiers
vs = [e for e in verifiers.load_verifiers() if e["header"]]
@@ -474,15 +449,12 @@ def main(argv):
if cmd == "lessons":
from . import retro
return retro.cmd_lessons(args)
if cmd == "backlog":
from . import retro
return retro.cmd_backlog(args)
if cmd == "cycle":
from . import cycle
return cycle.cmd_cycle(args)
if cmd == "improve":
if cmd == "approve":
from . import cycle
return cycle.cmd_improve(args)
return cycle.cmd_approve(args)
if cmd == "oracle":
return cmd_oracle()
if cmd == "design":
+484 -1975
View File
File diff suppressed because it is too large. Load diff
+28 -849
View File
@@ -1,861 +1,40 @@
"""Whole-document edits: the things agents read are documents, and a learning round ends by
rewriting them as documents -- not by appending one more dated bullet.
"""Rulebook structure and budget checks. The per-lesson trace regime is gone.
Documents: the rulebook (doc `rulebook`), each recipe (`recipe:<id>`) and each technique entry
(`verifier:<id>`). A folded lesson ends up as part of the document's own text, in the section
where it belongs. The personal version of a recipe or technique lives in the overlay and
shadows the product's; the overlay records the product text's hash it was derived from
(`overlay.bases()`), and when the product later changes the next brief lists the document as
needing a re-merge -- never silently keeping a stale copy, never silently dropping additions.
Nothing may be lost: a rewrite in a cycle file gives, for every lesson folded into the
document, the exact fragment of the new text that carries it (or that it moved, merged, or was
retired under the usual retirement rule). The trace map lives beside the document in
`overlay/traces/`, never in the text agents load. `sisi lessons show ID`, `sisi rule N` and
`sisi done ID --trace` print where a lesson lives.
Structure is checked mechanically (see `structure_problems`): budgets, headings and Why,
the library lint, the house width after wrapping, run-on bullets, and dated journal bullets.
Kept: what a cycle needs to prove about rule text — every rule keeps an id and a Why,
and the rendered rulebook stays inside its line and character budgets.
"""
import json, os, re, tempfile, textwrap
from . import overlay, paths
EDITORIAL_STANDARD = [
"one instruction per bullet or sentence;",
"most important and most often violated first;",
"related instructions grouped under one heading;",
"no duplicates or near-duplicates;",
"imperative, concrete, plain words;",
"each rule keeps its reason (its Why);",
"exceptions next to the instruction they qualify;",
"nothing that is history or narrative (that lives in the lesson's own record).",
]
DEFAULT_REVIEW_ROUNDS = 10 # a document with no whole-document review for this many rounds is listed
DEFAULT_MAX_BULLET_CHARS = 650
DATED_BULLET = re.compile(r"^\s*[-*]\s+\d{4}-\d{2}-\d{2}\s*:")
MORE_LINE = re.compile(r"^More: `sisi rule \d+`.*$")
from . import overlay
def _cfg(key, default):
class DocumentError(Exception):
pass
def check_rule_text(text, rid=None):
"""Parse and check one rule; returns the parsed rule or raises DocumentError."""
try:
v = (paths.personal_config().get("cycle") or {}).get(key)
return int(v) if v is not None else default
except Exception:
return default
def review_every_rounds():
return _cfg("review_every_rounds", DEFAULT_REVIEW_ROUNDS)
def max_bullet_chars():
return _cfg("max_bullet_chars", DEFAULT_MAX_BULLET_CHARS)
def doc_key(kind, id):
if kind == "rulebook":
return "rulebook"
if kind == "oracle":
return "oracle"
return "%s:%s" % (kind, id)
def parse_doc_key(key):
if key == "rulebook":
return "rulebook", "rulebook"
if key in ("oracle", "oracle:oracle"):
return "oracle", "oracle"
if isinstance(key, str) and ":" in key:
kind, _, id = key.partition(":")
if kind in ("recipe", "verifier") and id:
return kind, id
return None, None
# ---- trace maps and review bookkeeping (overlay/traces/) --------------------
def _trace_rel(kind, id):
return "traces/%s.json" % doc_key(kind, id).replace(":", "-")
def load_trace(kind, id):
try:
with open(paths.overlay_dir(_trace_rel(kind, id)), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def trace_entries(kind, id):
e = load_trace(kind, id).get("entries")
return e if isinstance(e, dict) else {}
def all_traces():
"""{doc_key: entries} for every trace map on disk."""
out = {}
d = paths.overlay_dir("traces")
try:
names = sorted(os.listdir(d))
except OSError:
return out
for n in names:
if not n.endswith(".json") or n == "reviews.json":
continue
try:
with open(os.path.join(d, n), encoding="utf-8") as f:
rec = json.load(f)
if isinstance(rec, dict) and rec.get("doc"):
out[rec["doc"]] = rec.get("entries") or {}
except (OSError, ValueError):
continue
return out
r = overlay.parse_rule_file(text, rid)
except Exception as e:
raise DocumentError("rule text does not parse: %s" % e)
body = r.get("body") or r.get("text") or ""
if "Why" not in body and "why" not in body.split(":", 1)[0].lower():
raise DocumentError("rule %r has no Why paragraph" % r.get("id"))
return r
def traces_for_lesson(lesson_id):
"""[(doc_key, entry)] -- every trace map that says where this lesson lives."""
out = []
for key, entries in sorted(all_traces().items()):
e = entries.get(str(lesson_id))
if isinstance(e, dict):
out.append((key, e))
return out
return [] # the per-lesson trace regime is retired; provenance lives on the learning record
def load_reviews():
try:
with open(paths.overlay_dir("traces", "reviews.json"), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def trace_lines(kind, entry_id):
return []
def _save_reviews(reviews):
overlay._write("traces/reviews.json", json.dumps(reviews, indent=1, sort_keys=True) + "\n")
def next_round_number():
from . import cycle
return len(cycle.cycle_records()) + 1
# ---- what a document currently says, and which lessons are folded into it ----
def effective_text(kind, id):
if kind == "rulebook":
return overlay.render()
if kind == "oracle":
from . import principles
return principles.oracle_text()
from . import verifiers as V
entries = V.load_recipes() if kind == "recipe" else V.load_verifiers()
for e in entries:
if e["id"] == id:
try:
with open(e["path"], encoding="utf-8") as f:
return f.read()
except OSError:
return ""
return ""
def _notes_lesson_ids(entry_id):
from . import retro
ids = []
try:
with open(os.path.join(paths.notes_dir(), entry_id + ".md"), encoding="utf-8") as f:
for line in f:
p = retro._parse_bullet(line)
if p:
ids.append(p[2])
except OSError:
pass
return ids
def folded_lesson_ids(con, kind, id):
"""Lessons folded into this document: by the lessons table, by its field-note bullets,
and by an existing trace map. Superseded lessons are history and do not count."""
ids = set()
try:
for r in con.execute("SELECT id, folded_into, status FROM lessons"):
if r[2] == "superseded":
continue
targets = [t.strip() for t in str(r[1] or "").split(",") if t.strip()]
if kind == "rulebook":
hit = any(t.startswith("rule:") or t == "rulebook" for t in targets)
else:
hit = id in targets
if hit:
ids.add(r[0])
except Exception:
pass
if kind != "rulebook":
ids.update(_notes_lesson_ids(id))
for k in trace_entries(kind, id):
try:
ids.add(int(k))
except ValueError:
pass
key = doc_key(kind, id)
for _src, entries in all_traces().items():
for lid_s, t in entries.items():
if isinstance(t, dict) and t.get("disposition") == "moved" and t.get("to") == key:
try:
ids.add(int(lid_s))
except ValueError:
pass
return sorted(ids)
def _personal_exists(kind, id):
return bool(overlay._overlay_entry_paths(kind, id))
def _stale_reason(kind, id):
if kind == "rulebook" or not _personal_exists(kind, id):
return None
cur = overlay.base_hash(kind, id)
if cur is None:
return None # a personal addition: there is no product text to drift from
recorded = overlay.bases().get("%s:%s" % (kind, id))
if recorded != cur:
return ("the product text changed since the personal copy was made: needs a re-merge "
"(keep the personal additions, take in the product's changes)")
return None
def required_documents(con):
"""Documents the next round must rewrite or mark reviewed: field notes not yet integrated,
a stale personal copy, or no whole-document review for the configured number of rounds.
Returns [{doc, kind, id, reasons, lessons}] -- lessons are the unintegrated ones."""
from . import cycle, verifiers as V
reviews = load_reviews()
rounds = len(cycle.cycle_records())
every = review_every_rounds()
cands = [("rulebook", "rulebook"), ("oracle", "oracle")]
cands += [("recipe", e["id"]) for e in V.load_recipes() if e["header"]]
cands += [("verifier", e["id"]) for e in V.load_verifiers() if e["header"]]
out = []
for kind, id in cands:
key = doc_key(kind, id)
if kind == "oracle":
from . import principles as _pr
recs = _pr.statements()
if not recs:
continue
file_text = _pr._oracle_file_text() or ""
entries = trace_entries(kind, id)
traced_texts = {e.get("statement") for e in entries.values() if isinstance(e, dict)}
missing = [r for r in recs if r["text"] not in traced_texts or r["text"] not in file_text]
reasons = []
if missing:
reasons.append("standing principles not yet integrated and traced into the "
"oracle document (they are in force; this round owns the document)")
last = int((reviews.get(key) or {}).get("round") or 0)
if rounds >= every and rounds - last >= every:
reasons.append("no whole-document review for %d rounds" % (rounds - last))
if reasons:
out.append({"doc": key, "kind": kind, "id": id, "reasons": reasons,
"lessons": [], "statements": [r["text"] for r in missing]})
continue
folded = folded_lesson_ids(con, kind, id)
traced = {int(k) for k in trace_entries(kind, id) if str(k).isdigit()}
covered = set((reviews.get(key) or {}).get("covered") or [])
unintegrated = [i for i in folded if i not in traced and i not in covered]
reasons = []
if unintegrated:
reasons.append("appended field notes not yet integrated into the document's own text"
if kind != "rulebook" else
"lessons folded into rules are not yet traced to the text that carries them")
stale = _stale_reason(kind, id)
if stale:
reasons.append(stale)
eligible = kind == "rulebook" or bool(folded) or bool(traced) or _personal_exists(kind, id)
last = int((reviews.get(key) or {}).get("round") or 0)
if eligible and rounds >= every and rounds - last >= every:
reasons.append("no whole-document review for %d rounds" % (rounds - last))
if reasons:
out.append({"doc": key, "kind": kind, "id": id, "reasons": reasons,
"lessons": unintegrated})
return out
# ---- structure checks ---------------------------------------------------------
def _bullets(text):
"""Joined bullet texts (a bullet plus its indented continuation lines)."""
out, cur = [], None
for line in text.split("\n"):
if re.match(r"^\s*[-*]\s+", line):
if cur is not None:
out.append(cur)
cur = line.strip()
elif cur is not None and line.startswith(" ") and line.strip():
cur += " " + line.strip()
elif cur is not None:
out.append(cur)
cur = None
if cur is not None:
out.append(cur)
return out
def _sentence_count(text):
t = re.sub(r"`[^`]*`", " ", text) # code spans are not prose
t = re.sub(r"https?://\S+", " ", t)
return len(re.findall(r"[.!?]+(?=\s+[A-Z0-9\"']|\s*$)", t))
def wrap_text(text, width=overlay.HOUSE_WIDTH):
"""Wrap prose paragraphs and bullets to the house width. Front matter, code fences,
indented code, tables and headings are left alone."""
lines = text.split("\n")
out, i, fence, front = [], 0, False, bool(lines and lines[0].strip() == "---")
while i < len(lines):
line = lines[i]
if front:
out.append(line)
if i > 0 and line.strip() == "---":
front = False
i += 1
continue
if line.strip().startswith("```"):
fence = not fence
out.append(line); i += 1; continue
if fence or not line.strip() or line.startswith((" ", "\t", "|", "#")):
out.append(line); i += 1; continue
m = re.match(r"^(\s*)([-*]|\d+\.)\s+(.*)$", line)
if m:
indent, marker, rest = m.groups()
parts = [rest]
i += 1
while i < len(lines) and lines[i].startswith(" ") and lines[i].strip() \
and not re.match(r"^\s*[-*]\s+", lines[i]):
parts.append(lines[i].strip()); i += 1
joined = " ".join(parts)
sub = indent + " " * (len(marker) + 1)
wrapped = textwrap.wrap(joined, width=width, initial_indent="%s%s " % (indent, marker),
subsequent_indent=sub, break_long_words=False,
break_on_hyphens=False)
out.extend(wrapped or ["%s%s " % (indent, marker)])
continue
parts = [line.strip()]
i += 1
while i < len(lines) and lines[i].strip() and not lines[i].startswith((" ", "\t", "|", "#")) \
and not re.match(r"^\s*([-*]|\d+\.)\s+", lines[i]) \
and not lines[i].strip().startswith("```"):
parts.append(lines[i].strip()); i += 1
out.extend(textwrap.wrap(" ".join(parts), width=width, break_long_words=False,
break_on_hyphens=False) or [""])
return "\n".join(out)
def _long_line_problems(text):
wrapped = wrap_text(text)
out, fence, front = [], False, wrapped.startswith("---")
for n, line in enumerate(wrapped.split("\n"), 1):
if front:
if n > 1 and line.strip() == "---":
front = False
continue
if line.strip().startswith("```"):
fence = not fence
continue
if fence or line.startswith((" ", "\t", "|")):
continue
if len(line) > overlay.HOUSE_WIDTH:
out.append("line %d is %d characters after wrapping (house width %d)"
% (n, len(line), overlay.HOUSE_WIDTH))
return out
def _entry_lint_problems(kind, text, doc_id):
"""The library lint for one candidate entry, mirroring `verifiers.lint()`."""
from . import contract as C, verifiers as V
tmp = tempfile.NamedTemporaryFile("w", suffix=".md", prefix=(doc_id or "entry") + "-",
delete=False, encoding="utf-8")
try:
tmp.write(text); tmp.close()
# parse under the entry's own file name so the id-equals-stem check means something
named = os.path.join(os.path.dirname(tmp.name), (doc_id or "entry") + ".md")
os.replace(tmp.name, named)
e = V.parse(named)
finally:
for p in (tmp.name, os.path.join(os.path.dirname(tmp.name), (doc_id or "entry") + ".md")):
try:
os.unlink(p)
except OSError:
pass
out = list(e["problems"])
h = e["header"]
if not h:
return out or ["no header block"]
keys, heads = (V.V_KEYS, V.V_HEADINGS) if kind == "verifier" else (V.D_KEYS, V.D_HEADINGS)
for k in keys:
if k not in h or (not h[k] and k != "detect"):
out.append("missing or empty %r" % k)
if doc_id and h.get("id") and h["id"] != doc_id:
out.append("header id %r must equal the document id %r" % (h["id"], doc_id))
for m in V._missing_headings(e["body"], heads):
out.append("body lacks the heading %r" % m)
if kind == "verifier":
if not re.fullmatch(r"[1-6]", h.get("rung", "")):
out.append("rung must be an integer 1-6")
if h.get("section") and h["section"] not in V.SECTIONS:
out.append("unknown section %r" % h["section"])
if h.get("cost") and h["cost"] not in V.COSTS:
out.append("cost must be one of %s" % ", ".join(V.COSTS))
if h.get("ran_here") and h["ran_here"] not in ("yes", "no"):
out.append("ran_here must be yes or no")
for k in V._list(h.get("kinds")):
if k != "any" and k not in C.KINDS:
out.append("unknown kind %r" % k)
else:
known = {x["id"] for x in V.load_verifiers()} | set(overlay.disabled("verifier"))
fake = dict(e, body=e["body"])
for i in dict.fromkeys(V.cited_ids(fake)):
if i not in known:
out.append("Checks cites unknown verifier id %r" % i)
return out
def rulebook_problems(text):
out = []
pre, rules = overlay.parse_rules(text)
headings = [l for l in text.split("\n") if l.startswith("## ")]
if len(headings) != len(rules):
out.append("the rulebook text does not parse into rules")
seen = set()
for line, r in zip(headings, rules):
if not overlay.ID_TAIL.search(line):
out.append("rule heading %r lacks its {#id}" % line[:60])
if r["id"] in seen:
out.append("duplicate rule id %r" % r["id"])
seen.add(r["id"])
if not any(p.lstrip().startswith("Why:") for p in r["body"].split("\n\n")):
out.append("rule %s lacks its Why paragraph" % r["id"])
cand = candidate_render(pre, rules)
lines, chars = overlay.size(cand)
if lines > overlay.MAX_LINES or chars > overlay.MAX_CHARS:
out.append("the rulebook would be %d lines and %d characters; the budgets are %d lines "
"and %d characters" % (lines, chars, overlay.MAX_LINES, overlay.MAX_CHARS))
for n in range(1, len(rules) + 1):
if overlay.more_line(n) not in cand:
out.append("rule %d lacks its generated `More: sisi rule %d` line" % (n, n))
return out
def candidate_render(pre, rules):
try:
head = overlay.render().splitlines()[0]
except Exception:
head = "<!-- candidate rulebook -->"
parts = [head]
if (pre or "").strip():
parts.append(pre)
for n, r in enumerate(rules, 1):
body = "\n".join(l for l in r["body"].split("\n") if not MORE_LINE.match(l.strip()))
parts.append("## %d. %s {#%s}\n\n%s\n%s" % (n, r["title"], r["id"], body.strip("\n"),
overlay.more_line(n)))
return "\n\n".join(parts) + "\n"
def structure_problems(kind, text, doc_id=None):
"""Mechanical refusals for a rewritten document. Empty means the structure is acceptable.
The bullet test is deliberately simple: one bullet, once it passes the configured length
(default %d characters), may not end more than one sentence.""" % DEFAULT_MAX_BULLET_CHARS
out = []
for n, line in enumerate(text.split("\n"), 1):
if DATED_BULLET.match(line):
out.append("line %d is a dated journal-style bullet; integrate it into the "
"document's own text instead" % n)
limit = max_bullet_chars()
for b in _bullets(text):
if len(b) > limit and _sentence_count(b) > 1:
out.append("a bullet of %d characters holds %d sentences; one instruction per "
"bullet (limit %d characters): %r" % (len(b), _sentence_count(b), limit, b[:60]))
out.extend(_long_line_problems(text))
if kind == "oracle" and not (text or "").lstrip().startswith("# "):
out.append("the oracle document must start with a `# title` heading")
if kind == "rulebook":
out.extend(rulebook_problems(text))
elif kind in ("recipe", "verifier"):
out.extend(_entry_lint_problems(kind, text, doc_id))
return out
def _norm(s):
return " ".join(str(s or "").split())
def _fragment_in(fragment, text):
return bool(fragment) and _norm(fragment) in _norm(text)
# ---- validation of a cycle file's documents part ------------------------------
def _retirement_ok(con, lid):
from . import retro
r = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()
if not r:
return "no such lesson"
if not r["folded_into"]:
return "it is not folded anywhere yet"
if retro.shown_count(con, lid) < retro.RETIRE_SHOWS:
return "it has been shown %d times (retirement needs %d quiet showings)" % (
retro.shown_count(con, lid), retro.RETIRE_SHOWS)
if retro.recurrences_after_shown(con, r):
return "it still recurs after being shown"
return None
def validate_documents(doc, con, required=None):
errs = []
entries = doc.get("documents") or []
if not isinstance(entries, list):
return ["documents must be a list"]
by_doc = {}
for e in entries:
if not isinstance(e, dict) or not e.get("doc"):
errs.append("each documents entry needs a doc (\"rulebook\", \"oracle\", \"recipe:<id>\" or \"verifier:<id>\"): %r" % (e,))
continue
kind, id = parse_doc_key(e["doc"])
if kind is None:
errs.append("documents entry %r: doc must be \"rulebook\", \"oracle\", \"recipe:<id>\" or \"verifier:<id>\"" % e["doc"])
continue
if kind != "rulebook" and not effective_text(kind, id):
errs.append("document %s: no such %s" % (e["doc"], kind))
continue
by_doc[e["doc"]] = e
if required is None:
required = required_documents(con)
# an oracle whose only unintegrated statements this same file scopes to their project
# needs no rewrite: they leave the global store in this round
_to_project = {e.get("text") for e in doc.get("learn") or []
if isinstance(e, dict) and e.get("scope") == "project"}
if _to_project:
required = [r for r in required
if not (r.get("doc") == "oracle" and r.get("statements")
and all(t in _to_project for t in r["statements"]))]
for req in required:
if req["doc"] not in by_doc:
errs.append("document %s: missing whole-document entry - the brief listed it (%s); add a "
"documents entry {\"doc\": %r, \"action\": \"rewrite\", \"text\": ..., \"trace\": [...]} "
"or {\"doc\": %r, \"action\": \"reviewed\", \"reason\": \"...\"}"
% (req["doc"], "; ".join(req["reasons"]), req["doc"], req["doc"]))
# lessons this same file folds into a document also need a trace entry in its rewrite
extra_folded = {}
for e in doc.get("notes") or []:
if not isinstance(e, dict) or not isinstance(e.get("lesson"), int):
continue
intos = e.get("into")
intos = intos if isinstance(intos, list) else ([intos] if intos else [])
if e.get("action") == "fold-into-entry":
from . import verifiers as V
rids = {x["id"] for x in V.load_recipes() if x["header"]}
for into in intos:
key = doc_key("recipe" if into in rids else "verifier", into)
extra_folded.setdefault(key, set()).add(e["lesson"])
elif e.get("action") == "fold-into-rule":
extra_folded.setdefault("rulebook", set()).add(e["lesson"])
new_texts = {k: e.get("text") or "" for k, e in by_doc.items() if e.get("action") == "rewrite"}
for key, e in sorted(by_doc.items()):
kind, id = parse_doc_key(key)
act = e.get("action")
if act not in ("rewrite", "reviewed"):
errs.append("document %s: action must be rewrite or reviewed" % key)
continue
if act == "reviewed":
if not str(e.get("reason") or "").strip():
errs.append("document %s: reviewed needs a one-line reason why its structure is already right" % key)
continue
text = e.get("text")
if not str(text or "").strip():
errs.append("document %s: rewrite needs text (the full new document)" % key)
continue
for p in structure_problems(kind, text, None if kind == "rulebook" else id):
errs.append("document %s: %s" % (key, p))
needed = set(folded_lesson_ids(con, kind, id)) | extra_folded.get(key, set())
trace = e.get("trace") or []
if not isinstance(trace, list):
errs.append("document %s: trace must be a list" % key)
trace = []
seen = {}
for t in trace:
if isinstance(t, dict) and isinstance(t.get("lesson"), int):
seen[t["lesson"]] = t
for lid in sorted(needed - set(seen)):
errs.append("lesson #%d: no trace entry in the rewrite of %s - give the exact fragment "
"of the new text that carries it, or a moved/merged/retired disposition" % (lid, key))
for lid, t in sorted(seen.items()):
disp = t.get("disposition") or "carried"
frag = t.get("fragment")
if disp == "carried":
if not _fragment_in(frag, text):
errs.append("lesson #%d: its fragment %r does not occur in the new text of %s"
% (lid, str(frag)[:60], key))
elif disp == "merged":
other = t.get("merged_with")
if not isinstance(other, int) or other == lid:
errs.append("lesson #%d: merged needs merged_with naming a different lesson" % lid)
elif not _fragment_in(frag, text):
errs.append("lesson #%d: its merged fragment %r does not occur in the new text of %s"
% (lid, str(frag)[:60], key))
elif other in seen and _norm(seen[other].get("fragment")) != _norm(frag):
errs.append("lesson #%d: merged with #%d but their fragments differ; both ids must "
"point at the same fragment" % (lid, other))
elif disp == "moved":
to_kind, to_id = parse_doc_key(t.get("to") or "")
if to_kind is None:
errs.append("lesson #%d: moved needs \"to\" naming the document it moved to" % lid)
else:
target_text = new_texts.get(t["to"]) or effective_text(to_kind, to_id)
if not _fragment_in(frag, target_text):
errs.append("lesson #%d: its fragment %r does not occur in %s, where it is said to live now"
% (lid, str(frag)[:60], t["to"]))
elif disp == "retired":
if not str(t.get("reason") or "").strip():
errs.append("lesson #%d: retired needs a reason" % lid)
else:
why_not = _retirement_ok(con, lid)
if why_not:
errs.append("lesson #%d: cannot retire it in a rewrite: %s" % (lid, why_not))
else:
errs.append("lesson #%d: disposition must be carried, moved, merged or retired" % lid)
if kind == "oracle":
from . import principles as _pr
stmt_seen = {t["statement"]: t for t in trace
if isinstance(t, dict) and isinstance(t.get("statement"), str)}
for rec in _pr.statements():
t = stmt_seen.get(rec["text"])
if t is None:
errs.append("principle %r: no trace entry in the rewrite of oracle - give the "
"exact fragment of the new text that carries it (every statement "
"must be traced)" % rec["text"][:60])
elif not _fragment_in(t.get("fragment"), text):
errs.append("principle %r: its fragment %r does not occur in the new oracle text"
% (rec["text"][:60], str(t.get("fragment"))[:60]))
if kind == "rulebook":
_pre, new_rules = overlay.parse_rules(text)
new_ids = [r["id"] for r in new_rules]
merges = {}
for m in e.get("rule_merges") or []:
if isinstance(m, dict) and m.get("from") and m.get("into"):
merges[m["from"]] = m["into"]
_p2, eff = overlay.effective()
for r in eff:
if r["id"] not in new_ids and r["id"] not in merges:
errs.append("rule %s: every existing rule id must survive a rulebook rewrite or be "
"merged into another id (rule_merges)" % r["id"])
for frm, into in sorted(merges.items()):
if into not in new_ids:
errs.append("rule %s: merged into %s, which is not in the new rulebook" % (frm, into))
order = doc.get("rule_order")
if order is not None:
_pre, eff = overlay.effective()
want = {r["id"] for r in eff} - set(doc.get("disable_rules") or [])
want |= {e.get("id") for e in doc.get("rules") or []
if isinstance(e, dict) and e.get("action") == "add"}
rb = by_doc.get("rulebook") or {}
if rb.get("action") == "rewrite" and rb.get("text"):
_p3, new_rules = overlay.parse_rules(rb["text"])
want = {r["id"] for r in new_rules}
if not isinstance(order, list) or set(order) != want or len(order) != len(set(order)):
errs.append("rule_order must name every rule id exactly once (missing: %s; unknown: %s)"
% (", ".join(sorted(want - set(order if isinstance(order, list) else []))) or "-",
", ".join(sorted(set(order if isinstance(order, list) else []) - want)) or "-"))
return errs
def candidate_rulebook(doc):
"""The rulebook text a cycle file would produce, or None when it does not touch the
rulebook as a document or its order (the older per-rule prediction then applies)."""
entries = {e.get("doc"): e for e in doc.get("documents") or [] if isinstance(e, dict)}
rb = entries.get("rulebook") or {}
if rb.get("action") == "rewrite" and rb.get("text"):
pre, rules = overlay.parse_rules(rb["text"])
if isinstance(doc.get("rule_order"), list):
rank = {id: i for i, id in enumerate(doc["rule_order"])}
rules = sorted(rules, key=lambda r: rank.get(r["id"], len(rank)))
return candidate_render(pre, rules)
if isinstance(doc.get("rule_order"), list):
pre, eff = overlay.effective()
by_id = {r["id"]: r for r in eff}
for rid in doc.get("disable_rules") or []:
by_id.pop(rid, None)
for e in doc.get("rules") or []:
if isinstance(e, dict) and e.get("id"):
by_id[e["id"]] = {"id": e["id"], "title": e.get("title") or e["id"],
"body": overlay.wrap_rule_body(e.get("body") or "")}
rules = [by_id[i] for i in doc["rule_order"] if i in by_id]
rules += [r for i, r in by_id.items() if i not in doc["rule_order"]]
return candidate_render(pre, rules)
return None
# ---- applying a validated cycle file's documents part -------------------------
def _drop_note_bullets(entry_id, lesson_ids):
from . import retro
p = os.path.join(paths.notes_dir(), entry_id + ".md")
try:
with open(p, encoding="utf-8") as f:
lines = f.read().splitlines(True)
except OSError:
return
keep = []
for line in lines:
parsed = retro._parse_bullet(line)
if parsed and parsed[2] in lesson_ids:
continue
keep.append(line)
if not any(retro._parse_bullet(l) for l in keep):
try:
os.unlink(p)
except OSError:
pass
elif keep != lines:
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
f.write("".join(keep))
os.replace(tmp, p)
def _record_review(reviews, key, con, kind, id, action):
reviews[key] = {"round": next_round_number(), "action": action,
"covered": folded_lesson_ids(con, kind, id)}
def apply_documents(doc, con, touched):
"""Write rewrites, trace maps, reviews and rule order. Caller holds the personal-data
lock and has already validated. Returns {doc_key: [lesson ids]} for rewritten documents."""
from . import store
reviews = load_reviews()
changed = {}
for e in doc.get("documents") or []:
if not isinstance(e, dict):
continue
kind, id = parse_doc_key(e.get("doc") or "")
if kind is None:
continue
key = e["doc"]
if e.get("action") == "reviewed":
_record_review(reviews, key, con, kind, id, "reviewed")
continue
if e.get("action") != "rewrite":
continue
text = e["text"] if e["text"].endswith("\n") else e["text"] + "\n"
trace = {t["lesson"]: t for t in e.get("trace") or []
if isinstance(t, dict) and isinstance(t.get("lesson"), int)}
if kind == "rulebook":
_apply_rulebook(e, text, con, touched)
elif kind == "oracle":
from . import principles as _pr
p = _pr.oracle_path()
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
os.replace(tmp, p)
for t in e.get("trace") or []:
if isinstance(t, dict) and isinstance(t.get("statement"), str):
entries = trace_entries(kind, id)
entries[t["statement"]] = {"statement": t["statement"],
"fragment": t.get("fragment"),
"disposition": t.get("disposition") or "carried"}
rec = {"doc": key, "kind": kind, "id": id, "base_hash": None, "entries": entries}
overlay._write(_trace_rel(kind, id), json.dumps(rec, indent=1, sort_keys=True) + "\n")
_record_review(reviews, key, con, kind, id, "rewrite")
changed[key] = []
continue
else:
_id, rel, mine = overlay._put_entry(kind, text, id, True)
for p in mine:
overlay._remove(p)
overlay._write(rel, text)
overlay._set_base(kind, id, overlay.base_hash(kind, id))
if trace:
_drop_note_bullets(id, set(trace))
entries = trace_entries(kind, id)
for lid, t in trace.items():
touched.add(lid)
disp = t.get("disposition") or "carried"
entries[str(lid)] = {"fragment": t.get("fragment"), "disposition": disp,
"to": t.get("to"), "merged_with": t.get("merged_with"),
"reason": t.get("reason")}
if disp == "moved":
to_kind, to_id = parse_doc_key(t.get("to") or "")
folded = "rule:%s" % to_id if to_kind == "rulebook" else to_id
if to_kind == "rulebook":
# the fragment lives in one rule; keep the lesson pointing at the rulebook
folded = "rulebook"
con.execute("UPDATE lessons SET folded_into=? WHERE id=?", (folded, lid))
elif disp == "retired":
con.execute("UPDATE lessons SET status='retired', needs_cycle=0 WHERE id=?", (lid,))
rec = {"doc": key, "kind": kind, "id": id,
"base_hash": overlay.base_hash(kind, id) if kind != "rulebook" else None,
"entries": entries}
if kind == "rulebook" and e.get("rule_merges"):
rec["rule_merges"] = {m["from"]: m["into"] for m in e["rule_merges"]
if isinstance(m, dict) and m.get("from")}
overlay._write(_trace_rel(kind, id), json.dumps(rec, indent=1, sort_keys=True) + "\n")
_record_review(reviews, key, con, kind, id, "rewrite")
changed[key] = sorted(trace)
if isinstance(doc.get("rule_order"), list):
overlay._set_lines("rules/full-order.txt", list(doc["rule_order"]))
if reviews != load_reviews() or changed:
_save_reviews(reviews)
return changed
def _apply_rulebook(e, text, con, touched):
pre, rules = overlay.parse_rules(text)
base = {r["id"]: r for r in overlay.base_rules()[1]}
merges = {m["from"]: m["into"] for m in e.get("rule_merges") or []
if isinstance(m, dict) and m.get("from") and m.get("into")}
for r in rules:
body = overlay.wrap_rule_body("\n".join(
l for l in r["body"].split("\n") if not MORE_LINE.match(l.strip())))
cand = {"id": r["id"], "title": r["title"], "body": body}
b = base.get(r["id"])
rel = "rules/%s.md" % r["id"]
if b and b["title"] == cand["title"] and overlay.wrap_rule_body(b["body"]) == body:
overlay._remove(paths.overlay_dir(rel)) # back to the product text: no personal copy
overlay._set_base("rule", r["id"], None)
else:
overlay._write(rel, overlay.rule_text(cand))
if b:
overlay._set_base("rule", r["id"], overlay.base_hash("rule", r["id"]))
if merges:
off = overlay.disabled("rule")
overlay._set_lines("rules/disabled.txt", off + [x for x in merges if x not in off])
for frm, into in merges.items():
overlay._remove(paths.overlay_dir("rules/%s.md" % frm))
for row in con.execute("SELECT id, folded_into FROM lessons WHERE folded_into LIKE ?",
("%" + "rule:" + frm + "%",)):
touched.add(row[0])
new = ",".join("rule:" + into if t.strip() == "rule:" + frm else t.strip()
for t in str(row[1]).split(","))
con.execute("UPDATE lessons SET folded_into=? WHERE id=?", (new, row[0]))
overlay._set_lines("rules/full-order.txt", [r["id"] for r in rules])
def trace_lines(kind, id):
"""Plain lines for `sisi done ID --trace` and friends: where each lesson lives."""
entries = trace_entries(kind, id)
if not entries:
return ["no whole-document rewrite has traced lessons into %s yet" % doc_key(kind, id)]
out = ["where each lesson lives in %s (trace map, not part of the text agents load):"
% doc_key(kind, id)]
for lid_s in sorted(entries, key=lambda s: int(s) if str(s).isdigit() else 0):
t = entries[lid_s]
disp = t.get("disposition") or "carried"
if disp == "moved":
out.append(" #%s moved to %s as %r" % (lid_s, t.get("to"), t.get("fragment")))
elif disp == "merged":
out.append(" #%s merged with #%s as %r" % (lid_s, t.get("merged_with"), t.get("fragment")))
elif disp == "retired":
out.append(" #%s retired: %s" % (lid_s, t.get("reason")))
else:
out.append(" #%s lives as %r" % (lid_s, t.get("fragment")))
return out
def check_budgets(rendered=None):
"""(ok, message) for the rendered rulebook against the overlay budgets."""
rendered = overlay.render() if rendered is None else rendered
s = overlay.size(rendered)
if s["lines"] > overlay.MAX_LINES or s["chars"] > overlay.MAX_CHARS:
return False, ("rulebook over budget: %d lines (max %d), %d chars (max %d)"
% (s["lines"], overlay.MAX_LINES, s["chars"], overlay.MAX_CHARS))
return True, "%d lines, %d chars, inside budget" % (s["lines"], s["chars"])
+398
View File
@@ -0,0 +1,398 @@
"""Learning records: the single store behind retro, cycle, learn/oracle and monitoring.
One store: learnings.jsonl in the user store (one JSON object per learning, rewritten
atomically; git in the user store is the history). Findings of a retro live in
findings.jsonl. Showings are never recorded as evidence. See docs/learning.md.
"""
import hashlib, json, os, re, subprocess, time
from . import paths, pdata
STATUSES = ("observed", "analyzed", "proposed", "implemented", "validated",
"promoted", "monitored", "revised", "reverted", "rejected")
MECHANISMS = ("policy", "orchestration", "skill", "tool", "infrastructure",
"verification", "knowledge", "benchmark")
IMPACTS = ("value", "correctness", "time", "cost", "attention")
SCOPES = ("organization", "user", "project", "task-class")
GENERIC = re.compile(r"^\s*(nothing|none|n/?a|be more careful|write better tests|"
r"use cheaper models|do better|all good|no issues?)\W*$", re.I)
STOP = set("the a an and or of to in is was were be been it its this that with for on at by as not no do does did when then than from we i".split())
class LearningError(Exception):
pass
def now():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def project_key(cwd):
"""Stable project identity: the git root (main repo for linked worktrees), else the dir."""
try:
from . import groundtruth
root, _vcs = groundtruth.main_repo_of(cwd)
if root:
return os.path.realpath(root)
except Exception:
pass
try:
out = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=cwd,
capture_output=True, text=True, timeout=10)
if out.returncode == 0 and out.stdout.strip():
return os.path.realpath(out.stdout.strip())
except (OSError, subprocess.SubprocessError):
pass
return os.path.realpath(cwd)
def unit_id(project=None):
"""Seam with the work-unit worker: the id in .sisi/contract.json, else a session fallback."""
project = project or os.getcwd()
try:
with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f:
c = json.load(f)
if isinstance(c, dict) and c.get("id"):
return str(c["id"])
except (OSError, ValueError):
pass
return "session:" + (os.environ.get("SISI_SESSION_ID") or
hashlib.sha1(os.path.realpath(project).encode()).hexdigest()[:12])
def is_subagent_session():
return os.environ.get("SISI_SUBAGENT") == "1" or os.environ.get("SISI_AGENT_DEPTH", "") not in ("", "0")
# ---- store io -----------------------------------------------------------------
def learnings_path():
return paths.data_file("learnings.jsonl")
def findings_path():
return paths.data_file("findings.jsonl")
def pending_path():
return paths.data_file("pending.json")
def load_learnings():
out = []
try:
with open(learnings_path(), encoding="utf-8") as f:
for line in f:
if line.strip():
d = json.loads(line)
if isinstance(d, dict) and d.get("id"):
out.append(d)
except OSError:
pass
return out
def save_learnings(rows, msg):
pdata.ensure()
text = "".join(json.dumps(r, sort_keys=True) + "\n" for r in rows)
pdata.write_text("learnings.jsonl", text)
pdata.commit(msg, ["learnings.jsonl"])
def store_base(rows=None):
rows = load_learnings() if rows is None else rows
h = hashlib.sha256()
for r in rows:
h.update(json.dumps(r, sort_keys=True).encode())
h.update(b"\n")
return h.hexdigest()[:16]
def load_findings():
out = []
try:
with open(findings_path(), encoding="utf-8") as f:
for line in f:
if line.strip():
d = json.loads(line)
if isinstance(d, dict):
out.append(d)
except OSError:
pass
return out
def append_finding(f, msg="retro: finding"):
pdata.ensure()
old = pdata.read_text("findings.jsonl", "") or ""
pdata.write_text("findings.jsonl", old + json.dumps(f, sort_keys=True) + "\n")
pdata.commit(msg, ["findings.jsonl"])
def next_id(rows):
n = 0
for r in rows:
m = re.match(r"L-(\d+)$", str(r.get("id", "")))
if m:
n = max(n, int(m.group(1)))
return "L-%04d" % (n + 1)
def get(rows, lid):
for r in rows:
if r.get("id") == lid:
return r
return None
# ---- derived text (the tool derives search terms, topics, short lines) ---------
def stems(text):
out = set()
for w in re.findall(r"[a-z0-9]{3,}", (text or "").lower()):
if w in STOP:
continue
for suf in ("ing", "edly", "ed", "es", "s"):
if w.endswith(suf) and len(w) - len(suf) >= 3:
w = w[: -len(suf)]
break
out.add(w)
return out
def derive_terms(*texts):
return sorted(set().union(*[stems(t) for t in texts]))[:24]
def derive_title(text, limit=90):
t = " ".join((text or "").split())
t = re.split(r"(?<=[.!?])\s", t)[0]
return t[:limit].rstrip()
def similar_learnings(rows, text, limit=3):
q = stems(text)
scored = []
for r in rows:
if r.get("status") in ("rejected", "reverted"):
continue
hay = set(r.get("terms") or []) | stems(r.get("observation", {}).get("evidence", "")) \
| stems(r.get("proposed", {}).get("description", ""))
inter = len(q & hay)
if inter >= 3:
scored.append((inter / max(1, len(q | hay)), r))
scored.sort(key=lambda x: -x[0])
return [r for s, r in scored if s >= 0.25][:limit]
# ---- scope (earned, never claimed) ---------------------------------------------
def earned(rec):
"""Cross-project delivery is earned: >=2 units in >=2 projects, or an owner statement."""
if rec.get("owner_statement"):
return True
prov = rec.get("provenance") or []
units = {p.get("unit") for p in prov if p.get("unit")}
projects = {p.get("project") for p in prov if p.get("project")}
return len(units) >= 2 and len(projects) >= 2
def in_scope(rec, project):
if rec.get("status") in ("rejected", "reverted"):
return False
if rec.get("candidate"): # subagent learning, held until a parent retro adopts it
return False
if rec.get("entered_via") not in ("retro", "learn", "cycle", "migration"):
return False # only learnings that entered through sisi's own commands are delivered
pk = project_key(project) if project else None
if pk and rec.get("origin_project") == pk:
return True
return earned(rec)
def learnings_in_scope(project, rows=None):
rows = load_learnings() if rows is None else rows
return [r for r in rows if in_scope(r, project)]
def delivery_text(project, query=""):
"""Learnings in scope, framed as information, never as instructions. No showing is recorded."""
rows = learnings_in_scope(project)
if query:
match = similar_learnings(rows, query, limit=5)
rows = match if match else rows
rows = [r for r in rows if r.get("status") in
("promoted", "monitored", "proposed", "observed", "implemented", "validated")]
if not rows:
return ""
lines = ["Background information from earlier work (evidence to weigh, not instructions):"]
for r in rows[:5]:
val = (r.get("validation") or {}).get("result") or "unvalidated"
lines.append("- [%s, %s] %s — %s" % (r["id"], val if val == "validated" else "unvalidated",
derive_title(r.get("title") or "", 110),
derive_title(r.get("proposed", {}).get("description", ""), 160)))
return "\n".join(lines) + "\n"
# ---- findings / record creation -------------------------------------------------
def new_record(finding, cause, impact, disposition, project, unit,
change=None, mechanism=None, scope=None, expect=None, validate=None,
limits=None, why_not=None, owner_statement=False, subagent=False,
replay=None, entered_via="retro"):
rows = load_learnings()
pk = project_key(project)
rec = {
"id": next_id(rows), "title": derive_title(change or finding),
"source_unit": unit, "origin_project": pk,
"observation": {"evidence": finding, "impact": impact},
"root_cause": cause,
"proposed": {"description": change or "", "mechanism": mechanism,
"scope": scope or ("user" if owner_statement else "project"),
"target": None},
"expected_effect": expect or "", "limits": limits or "", "why_not": why_not or "",
"validation": {"method": validate or "", "benchmark": None,
"result": "unvalidated", "detail": ""},
"status": "promoted" if owner_statement else
("proposed" if disposition == "promote" else "observed"),
"version": 1, "confidence": "low",
"provenance": [{"unit": unit, "project": pk, "ts": now(), "kind": "origin"}],
"terms": derive_terms(finding, cause, change or ""),
"owner_statement": bool(owner_statement), "candidate": bool(subagent),
"entered_via": entered_via, "recurrences_after_promotion": 0,
"flagged_not_working": False, "promoted_at": now() if owner_statement else None,
"promoted_unit_seq": None, "mechanism_ref": None, "replay": replay,
"created": now(),
}
rows.append(rec)
save_learnings(rows, "learning %s recorded" % rec["id"])
return rec
def add_recurrence(rec, unit, project, rows):
"""Attach a recurrence. After promotion it counts against the learning."""
pk = project_key(project)
rec.setdefault("provenance", []).append(
{"unit": unit, "project": pk, "ts": now(), "kind": "recurrence"})
if rec.get("status") in ("promoted", "monitored", "validated", "implemented") and rec.get("promoted_at"):
rec["recurrences_after_promotion"] = int(rec.get("recurrences_after_promotion") or 0) + 1
if rec["recurrences_after_promotion"] >= 2:
rec["flagged_not_working"] = True
save_learnings(rows, "learning %s recurrence" % rec["id"])
return rec
def findings_for_unit(project, uid):
"""Seam for the unit record: the findings recorded for one unit in one project."""
pk = project_key(project)
return [f for f in load_findings() if f.get("unit") == uid and f.get("project") == pk]
def units_seen():
"""Closed-unit summary lines from the unit worker's store, when it exists."""
out = []
try:
with open(paths.data_file("units.jsonl"), encoding="utf-8") as f:
for line in f:
if line.strip():
out.append(json.loads(line))
except (OSError, ValueError):
pass
return out
def unit_seq():
return len(units_seen())
# ---- monitoring -----------------------------------------------------------------
def flagged(rows=None):
rows = load_learnings() if rows is None else rows
return [r for r in rows if r.get("flagged_not_working") and r.get("status") not in ("revised", "reverted", "rejected")]
def learning_report():
"""Seam for `sisi status --learning`. No claim of improvement from counts of records."""
rows = load_learnings()
findings = load_findings()
units = units_seen()
lines = ["Learning loop (recorded facts; no improvement is claimed from counts):",
"learnings: %d findings: %d closed units known: %d"
% (len(rows), len(findings), len(units))]
promoted = [r for r in rows if r.get("status") in ("promoted", "monitored") and not r.get("owner_statement")]
if promoted:
lines.append("promoted learnings:")
holding = 0
relevant = 0
for r in promoted:
since = None
if r.get("promoted_unit_seq") is not None:
since = len(units) - int(r["promoted_unit_seq"])
else:
since = sum(1 for u in units if str(u.get("ts", "")) >= str(r.get("promoted_at") or ""))
rec = int(r.get("recurrences_after_promotion") or 0)
val = (r.get("validation") or {}).get("result") or "unvalidated"
if r.get("flagged_not_working"):
verdict = "not working (flagged: next cycle must revise or revert)"
elif since >= 5 and rec == 0:
verdict = "holding"
elif rec:
verdict = "recurred, watching"
else:
verdict = "too few units to judge"
if since >= 5:
relevant += 1
if rec == 0:
holding += 1
lines.append("- %s: %d unit(s) since promotion, %d recurrence(s), %s — %s"
% (r["id"], since, rec, val if val == "validated" else "unvalidated", verdict))
if relevant < 5:
lines.append("realization rate: too few (fewer than five promoted learnings have "
"five relevant units; no rate is claimed)")
else:
lines.append("realization rate: %d of %d promoted learnings holding with no recurrence "
"over at least five units" % (holding, relevant))
fl = flagged(rows)
if fl:
lines.append("flagged not working: " + ", ".join(r["id"] for r in fl))
pend = load_pending()
if pend:
lines.append("waiting for the owner's decision: %d change(s) (`sisi approve ID --yes|--no`)"
% len(pend))
tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool"
and r.get("status") not in ("rejected", "reverted")]
if tool:
lines.append("tool backlog (changes to sisi itself):")
for r in tool[:8]:
lines.append("- %s: %s" % (r["id"], derive_title(r["title"], 110)))
return "\n".join(lines) + "\n"
# ---- pending approvals -----------------------------------------------------------
def load_pending():
try:
with open(pending_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, list) else []
except (OSError, ValueError):
return []
def save_pending(items, msg="pending decision updated"):
pdata.ensure()
pdata.write_text("pending.json", json.dumps(items, indent=2, sort_keys=True) + "\n")
pdata.commit(msg, ["pending.json"])
def pending_notice():
n = len(load_pending())
return "sisi: %d learning change(s) wait for your decision (`sisi approve`)." % n if n else ""
# ---- owner statements (one path: learn writes, oracle prints) ---------------------
def owner_statements(rows=None):
rows = load_learnings() if rows is None else rows
return [r for r in rows if r.get("owner_statement") and r.get("status") not in ("rejected", "reverted")]
+111 -17
View File
@@ -99,7 +99,6 @@ def _merge_retro_db(src, dst):
b.row_factory = sqlite3.Row
added = 0
try:
from . import retro
key = lambda r: (r["aim"], r["change_kind"], r["target"], r["change"])
have = {key(r): r["id"] for r in b.execute("SELECT * FROM lessons")}
for r in a.execute("SELECT * FROM lessons ORDER BY id"):
@@ -107,7 +106,7 @@ def _merge_retro_db(src, dst):
lid = have[key(r)]
else:
bcols = [x[1] for x in b.execute("PRAGMA table_info(lessons)")]
cols = [c for c in retro.LESSON_COLS if c != "id" and c in bcols]
cols = [c for c in bcols if c != "id"] # legacy schema, read from the db itself
cur = b.execute("INSERT INTO lessons(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))),
[r[c] if c in r.keys() else None for c in cols])
lid = cur.lastrowid
@@ -117,7 +116,8 @@ def _merge_retro_db(src, dst):
if b.execute("SELECT 1 FROM occurrences WHERE lesson_id=? AND ts=? AND session IS ? AND moment=?",
(lid, o["ts"], o["session"], o["moment"])).fetchone():
continue
cols = [c for c in retro.OCC_COLS if c not in ("id", "lesson_id")]
ocols = [x[1] for x in b.execute("PRAGMA table_info(occurrences)")]
cols = [c for c in ocols if c not in ("id", "lesson_id")]
b.execute("INSERT INTO occurrences(lesson_id,%s) VALUES(?,%s)" % (",".join(cols), ",".join("?" * len(cols))),
[lid] + [o[c] if c in o.keys() else None for c in cols])
b.commit()
@@ -239,17 +239,118 @@ def run():
_union_lines(src, paths.data_file(name))
os.unlink(src)
notes.append("%s moved" % name)
try:
from . import retro
retro.export_jsonl()
except Exception as e:
store.log_error("migrate-export", e)
notes.append("lessons dump failed: %r" % e)
pdata.commit("migrate: move personal data out of the product and the state folder", strict=True)
notes += pdata.upgrade()
notes += migrate_learnings()
return notes
def migrate_learnings():
"""Old lesson store -> learning records. Idempotent, with a backup first, lossless.
lessons.jsonl mixed lesson rows with occurrence and impression rows. Lessons become
learning records with honest statuses (folded into prose is `implemented`, always
unvalidated; nothing becomes `validated`); occurrences become provenance; impressions
(sisi's own showings) are dropped, never evidence. learn.jsonl owner statements become
owner-statement records in the same store. Returns notes with before/after counts.
"""
from . import learning as L
if os.path.exists(L.learnings_path()):
return []
src = paths.data_file("lessons.jsonl")
learn_src = paths.data_file("learn.jsonl")
if not os.path.exists(src) and not os.path.exists(learn_src) \
and not os.path.exists(paths.data_file("retro.db")):
return []
bdir = snapshot("learning-migration")
lessons, occs, impressions = {}, {}, 0
if os.path.exists(src):
with open(src, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
try:
r = json.loads(line)
except ValueError:
continue
t = r.get("t")
if t == "lesson":
lessons[r.get("id")] = r
elif t == "occurrence":
occs.setdefault(r.get("lesson_id"), []).append(r)
elif t == "impression":
impressions += 1
rows = []
for lid in sorted(lessons, key=lambda x: (x is None, x)):
old = lessons[lid]
prov = []
for o in occs.get(lid, []):
prov.append({"unit": "session:%s" % (o.get("session") or o.get("id")),
"project": o.get("repo") or o.get("cwd") or old.get("project") or "",
"ts": o.get("ts") or "", "kind": "occurrence"})
origin = old.get("project") or (prov[0]["project"] if prov else "")
if not prov:
prov = [{"unit": "legacy:%s" % lid, "project": origin, "ts": old.get("created") or "",
"kind": "origin"}]
status = {"applied": "implemented", "retired": "reverted"}.get(old.get("status"), "observed")
kind = old.get("change_kind")
rows.append({
"id": "L-%04d" % (len(rows) + 1), "legacy_id": lid,
"title": L.derive_title(old.get("short") or old.get("change") or old.get("moment") or ""),
"source_unit": prov[0]["unit"], "origin_project": origin,
"observation": {"evidence": old.get("moment") or "", "impact": "correctness"},
"root_cause": old.get("cause") or "",
"proposed": {"description": old.get("change") or "",
"mechanism": "tool" if kind == "tool" else ("verification" if kind in ("check", "test") else "policy"),
"scope": "project", "target": old.get("target")},
"expected_effect": "", "limits": "", "why_not": "",
"validation": {"method": "", "benchmark": None, "result": "unvalidated",
"detail": "migrated from the old lesson store; never replay-validated"},
"status": status, "version": 1, "confidence": "low", "provenance": prov,
"terms": L.derive_terms(old.get("moment") or "", old.get("cause") or "", old.get("change") or ""),
"owner_statement": False, "candidate": False, "entered_via": "migration",
"recurrences_after_promotion": 0, "flagged_not_working": False,
"promoted_at": None, "promoted_unit_seq": None, "mechanism_ref": old.get("folded_into"),
"replay": None, "created": old.get("created") or L.now()})
statements = 0
if os.path.exists(learn_src):
with open(learn_src, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
try:
r = json.loads(line)
except ValueError:
continue
text = r.get("text") or r.get("statement") or ""
if not text:
continue
statements += 1
rows.append({
"id": "L-%04d" % (len(rows) + 1), "title": L.derive_title(text),
"source_unit": "owner", "origin_project": r.get("cwd") or "",
"observation": {"evidence": text, "impact": "value"},
"root_cause": "owner statement",
"proposed": {"description": text, "mechanism": "knowledge",
"scope": "user", "target": None},
"expected_effect": "the agent acts on this statement", "limits": "", "why_not": "",
"validation": {"method": "", "benchmark": None, "result": "unvalidated", "detail": ""},
"status": "promoted", "version": 1, "confidence": "high",
"provenance": [{"unit": "owner", "project": r.get("cwd") or "",
"ts": r.get("ts") or "", "kind": "origin"}],
"terms": L.derive_terms(text), "owner_statement": True, "candidate": False,
"entered_via": "migration", "recurrences_after_promotion": 0,
"flagged_not_working": False, "promoted_at": r.get("ts") or L.now(),
"promoted_unit_seq": None, "mechanism_ref": None, "replay": None,
"created": r.get("ts") or L.now()})
L.save_learnings(rows, "migrate: lessons and owner statements become learning records")
return ["learning migration: backed up to %s; %d lesson(s) and %d owner statement(s) became "
"%d learning record(s); %d occurrence(s) became provenance; %d impression(s) dropped "
"(showings are never evidence); nothing is validated"
% (bdir, len(lessons), statements, len(rows),
sum(len(v) for v in occs.values()), impressions)]
# ---- snapshots (before an update) -------------------------------------------------------------
SKIP_TOP = {"backups", "generated", "install", ".lock"}
@@ -431,14 +532,7 @@ def import_archive(path):
f.write(tf.extractfile(m).read())
os.chmod(dst, m.mode & 0o777 or 0o644)
os.utime(dst, (m.mtime, m.mtime))
if not os.path.exists(paths.data_file("retro.db")) and os.path.exists(paths.data_file("lessons.jsonl")):
from . import retro
con = retro.connect()
try:
retro.import_jsonl(paths.data_file("lessons.jsonl"), con)
finally:
con.close()
notes.append("retro.db rebuilt from lessons.jsonl")
notes += migrate_learnings()
notes += pdata.upgrade()
b = overlay.build_canon()
notes.append("rulebook rebuilt: %d lines" % b["lines"])
+22 -97
View File
@@ -1,113 +1,38 @@
"""The owner's standing principles: `sisi learn` statements in the user tier (plus core
statements until the product carries them, and not-yet-tiered ones meanwhile), live at once.
"""Owner statements, printed by `sisi oracle`. One store: learning records with owner_statement.
A statement takes effect the moment it is recorded: `sisi oracle` prints it, request-time
delivery hands it over, and a contract's design section must answer its objections. There is
no quarantine and no holding file. The oracle is a proper document (oracle.md in the personal
folder) whose structure a learning round owns through the whole-document edit in
sisi/documents.py, tracing every statement into the text like any other document; until a
round integrates a statement, `sisi oracle` prints it under its own heading so it is never
parked unread.
"""
import os
from . import paths, store
EMPTY = """# sisi oracle
What the human wants, so a thing is asked once ever. Empty so far: it is filled from
preferences the human stated (`sisi learn`), which take effect at once.
`sisi learn` writes them and `sisi oracle` prints them. The old parallel stores
(learn.jsonl, oracle.md) are merged by the migration in lifecycle.py.
"""
from . import learning as L
def statements():
"""The standing principles, in the order recorded: user-tier statements (how this owner
wants work done), plus core statements until the product carries them, plus not-yet-tiered
statements, which are still delivered while they wait for a tier."""
from . import scope as _scope
out = []
for rec in store.read("learn"):
text = " ".join(str(rec.get("text") or "").split())
if text and _scope.tier_of(rec.get("scope")) != "project":
out.append(dict(rec, text=text))
return out
def core_statements():
return [r for r in statements() if r.get("scope") == "core"]
def unscoped_statements():
"""Statements with no tier yet (old two-way `everywhere` included; a round tiers them)."""
from . import scope as _scope
return [rec for rec in store.read("learn")
if (rec.get("text") or "").strip() and _scope.tier_of(rec.get("scope")) == "unscoped-tier"]
return [{"text": r.get("proposed", {}).get("description") or r.get("title", ""),
"scope": r.get("proposed", {}).get("scope") or "user",
"ts": r.get("created", ""), "id": r.get("id")}
for r in L.owner_statements()]
def plain_of(rec):
"""The principle in plain words on one line: the stored plain form when a round wrote one,
else the statement itself, tidied into a sentence."""
plain = " ".join(str(rec.get("plain") or "").split())
if plain:
return plain
t = " ".join(str(rec.get("text") or "").split()).strip("\"")
if t and t[-1] not in ".!?":
t += "."
return t
def date_of(rec):
return (rec.get("ts") or "")[:10]
def short_lines(limit_chars=None):
"""One short plain line per principle, for request-time and contract-init delivery."""
out, total = [], 0
for rec in statements():
line = "- " + plain_of(rec)
if limit_chars is not None and total + len(line) + 1 > limit_chars and out:
out.append("- ... and more (`sisi oracle` prints them all)")
break
out.append(line)
total += len(line) + 1
return out
def _principle_block(rec):
date = date_of(rec)
return '- %s\n > "%s"%s' % (plain_of(rec), rec["text"], " (%s)" % date if date else "")
def _oracle_file_text():
try:
with open(paths.data_file("oracle.md"), encoding="utf-8") as f:
return f.read()
except OSError:
return None
return rec.get("text") or rec.get("proposed", {}).get("description", "")
def oracle_text():
"""The oracle document as agents should read it now: the round-written document when one
exists, with any not-yet-integrated statements printed after it, never hidden."""
recs = statements()
file_text = _oracle_file_text()
if file_text:
missing = [r for r in recs if r["text"] not in file_text]
if not missing:
return file_text
return (file_text.rstrip("\n") + "\n\n## Not yet integrated\n\n"
"Recorded since the last learning round rewrote this document; in force now.\n\n"
+ "\n".join(_principle_block(r) for r in missing) + "\n")
if not recs:
return EMPTY
lines = ["# sisi oracle", "",
"What the human wants, so a thing is asked once ever. Statements recorded with "
"`sisi learn` take effect at once; a learning round rewrites this document as a "
"whole and traces every statement into it.", "",
"## Standing principles", ""]
lines += [_principle_block(r) for r in recs]
return "No owner statements recorded. `sisi learn \"<what you want>\"` adds one.\n"
lines = ["What the owner wants (recorded with `sisi learn`):"]
for i, r in enumerate(recs, 1):
lines.append("%d. %s" % (i, r["text"]))
return "\n".join(lines) + "\n"
def oracle_path():
return paths.data_file("oracle.md")
def short_lines(limit_chars=1200):
out, used = [], 0
for r in statements():
t = " ".join(r["text"].split())[:180]
if used + len(t) > limit_chars:
break
out.append(t)
used += len(t)
return out
+29 -31
View File
@@ -1,12 +1,22 @@
"""Request-time delivery: `sisi prompt` runs on the human's message (the tool's prompt-submission hook)
and injects the matching "what done means" recipe and lessons as added context, so the agent does not
have to remember to ask (`sisi done for`). Matching is the strict "likely to apply" test from
retro.delivery; when nothing strictly matches, or the message is trivial, nothing is printed. Any
learning.delivery_text (learnings in earned scope, framed as information; no showing is
recorded as evidence); when nothing strictly matches, or the message is trivial, nothing is printed. Any
error exits 0 silently: a hook must never block or fail a turn.
"""
import json, os, sys
from . import store
from . import learning as _L, store
def _stem(w):
return next(iter(_L.stems(w)), w.lower())
def _word_cut(text, limit):
text = " ".join(str(text).split())
return text if len(text) <= limit else text[:limit].rsplit(" ", 1)[0].rstrip(",.;:") + "…"
MAX_CHARS = 2000 # hard cap on the injected context, in characters
RECIPE_MIN_SCORE = 6.0 # two title/applies-to word hits in `sisi done for`'s scoring; below it, no recipe
@@ -27,8 +37,8 @@ def _is_question_without_work(t):
first = low.split(" ", 1)[0].strip("¿?") if low else ""
if not (low.endswith("?") or first in _QUESTION_START):
return False
from . import retro, verifiers as V
stems = {retro._stem(w) for w in V._words(low)}
from . import verifiers as V
stems = {_stem(w) for w in V._words(low)}
return not (stems & _WORK_STEMS)
@@ -53,8 +63,8 @@ def is_design_work(text):
return False # a question about design is not design work
if _is_question_without_work(t):
return False
from . import retro, verifiers as V
stems = {retro._stem(w) for w in V._words(low)}
from . import verifiers as V
stems = {_stem(w) for w in V._words(low)}
if not (stems & _DESIGN_STEMS):
return False
return bool(stems & _WORK_STEMS) or bool(stems & {"build", "design", "creat", "develop"})
@@ -102,15 +112,15 @@ def _best_recipe(query):
delivery must be more precise than an answer the agent asked for: a recipe counts only when at
least two distinct words of the request hit its title, applies-to or id (one generic word like
"new" once outscored "release" + "tag" that way), and the leader must clear RECIPE_MIN_SCORE."""
from . import retro, verifiers as V
from . import verifiers as V
# Match on stems, as lesson matching does: "release" must meet "Releasing" and "tag" must meet
# "Tagging", which done-for's prefix rule (both words longer than three letters) misses.
toks = {retro._stem(t) for t in V._words(query)}
toks = {_stem(t) for t in V._words(query)}
def stems_of(text):
return {retro._stem(x) for x in V._words(text.replace("-", " "))}
return {_stem(x) for x in V._words(text.replace("-", " "))}
generic = retro.COMMON | {retro._stem(w) for w in
generic = set() | {_stem(w) for w in
("agent agents tool tools interface surface command commands function functions "
"program system name names description descriptions user users thing things "
"way ways step steps example examples".split())}
@@ -139,20 +149,21 @@ def _best_recipe(query):
return None
def _done_means(recipe, retro):
def _done_means(recipe):
"""The recipe's must-be-true list in short form: its Done-means bullets, each cut at a word boundary."""
from . import verifiers as V
bullets = []
for line in V._section(recipe["body"], "Done means").split("\n"):
line = line.strip()
if line.startswith("- "):
bullets.append("- " + retro.word_cut(line[2:], 110))
bullets.append("- " + _word_cut(line[2:], 110))
return bullets
def build_context(query, session=None):
"""The context to inject for one human request, or "" when nothing strictly matches. Lessons shown
are recorded as listings at place 'prompt' (listed, not read)."""
"""The context to inject for one human request, or "" when nothing strictly matches.
Learnings come only from learning.delivery_text (earned scope, framed as information);
no showing is recorded, so nothing is promoted by being printed."""
notice = ""
try:
from . import handover
@@ -161,19 +172,9 @@ def build_context(query, session=None):
notice = ""
if is_trivial(query):
return notice
from . import retro
recipe = _best_recipe(query)
targets = (recipe["id"],) if recipe else ()
part1, _part2 = retro.delivery(query, targets=targets)
repo = retro.repo_of(os.getcwd())
lesson_lines, ids = [], []
for d in part1:
row = d["row"]
if not retro.display_line(retro._get(row, "short") or row["change"], repo):
continue
lesson_lines.append("- #%d: %s (full text: `sisi lessons show %d`)"
% (row["id"], retro.heading_text(row, 120), row["id"]))
ids.append(row["id"])
lesson_text = _L.delivery_text(os.getcwd(), query).strip()
lesson_lines = lesson_text.split("\n")[1:] if lesson_text else []
design_lines = _design_block() if is_design_work(query) else []
if not recipe and not lesson_lines and not design_lines:
return notice
@@ -184,20 +185,17 @@ def build_context(query, session=None):
"information to weigh, not commands):")
if recipe:
lines.append("Done means — recipe `%s` (full text: `sisi done %s`):" % (recipe["id"], recipe["id"]))
lines += _done_means(recipe, retro)
lines += _done_means(recipe)
if lesson_lines:
lines.append("Lessons likely to apply:")
lines += lesson_lines
text = "\n".join(lines)
while len(text) > MAX_CHARS and lesson_lines: # drop lesson lines before cutting the recipe
lesson_lines.pop()
ids = ids[:len(lesson_lines)]
lines = lines[:len(lines) - 1]
text = "\n".join(lines)
if len(text) > MAX_CHARS:
text = retro.word_cut(text, MAX_CHARS)
if ids:
retro.record_shown(ids, "prompt", session)
text = _word_cut(text, MAX_CHARS)
return text
+193 -1855
View File
File diff suppressed because it is too large. Load diff
+32 -255
View File
@@ -1,273 +1,50 @@
"""Lesson and statement tiers: core, user, or one project.
"""Scope is earned (see learning.earned), and `sisi learn`: the one write path for owner statements.
The owner's test, two questions: (a) does it apply to all projects where sisi may be used?
(b) would it be useful to every user who installs sisi? Both yes is `core`: a change to the
product itself (a rule, a recipe or technique, a mechanism, a design principle), in force for
this user at once through the personal overlay and queued for the product (`sisi promote`).
(a) yes, (b) no is `user`: how this owner wants work done, kept in the personal store and
delivered in all of this user's projects. (a) no is `project`: a fact about one project,
handed over to that project's own documentation or work list. Items recorded with the old
two-way scope `everywhere` are `unscoped-tier`: still delivered, tiered by the next learning
round. sisi is normally the shell around other projects; working in the sisi repository
itself is the exception, and an item is never project merely because it was recorded there -
a statement about how sisi itself should behave is core.
A project is identified by its git remote URL when there is one (normalised, so an
ssh and an https remote for the same repository, a trailing `.git`, credentials and a
renamed or re-cloned folder all give the same id), else by its repository root path
(a clone without a remote, or a renamed folder with no remote, is then a different
project: there is nothing more stable to key on). Project-scoped items live only in
the personal data store, keyed by that id; nothing is written into the repository.
The universality check is structural only, no model call: it looks at the parts that
are delivered to agents (change, short, when-terms; a learn statement) and refuses
when a core or user item names the current project. The tool's own name, sisi, is always
exempt. History (moment, cause, occurrences) may name the project freely and is never checked.
Project identity helpers stay here for handover and friends. The old claim-based tiers
(core/user/project checked only for naming) are gone: a learning is in force in its origin
project at once and elsewhere only with provenance from at least two units in at least two
projects, or as an owner statement.
"""
import os, re, subprocess
import os, sys
from . import gitutil
SCOPES = ("core", "user", "project")
UNTIERED = (None, "", "unscoped", "unscoped-tier", "everywhere")
TIER_QUESTIONS = (
"Ask two questions: (a) does it apply to all projects where sisi may be used? "
"(b) would it be useful to every user who installs sisi? Both yes: --scope core (a change "
"to sisi itself - a rule, a recipe or technique, a mechanism, a design principle; it takes "
"effect for you at once and is queued for the product, `sisi promote`). (a) yes but (b) no, "
"because it is how this owner wants things: --scope user (kept in your personal store, "
"delivered in all your projects). (a) no: --scope project (a fact about this project, "
"handed over to its own documentation or work list).")
MISSING_SCOPE = (
"sisi: --scope is required (core, user or project). " + TIER_QUESTIONS + " "
"Core and user items are stated in general terms so any project can use them: name the kind "
"of work and the rule that follows, not this project's name, files or address (for example, "
"not 'the exporter here joins rows by hand' but 'write delimited files with a quoting "
"writer'). A statement about how sisi itself should behave is core, even recorded inside "
"the sisi repository. The moment and cause may name this project either way: they stay as "
"its history.")
def tier_of(value):
"""The tier a stored scope value means today: legacy `everywhere` is not yet tiered."""
if value in SCOPES:
return value
return "unscoped-tier"
def normalize_scope(value):
"""A scope given on a command line, canonicalised: legacy `everywhere` is accepted and
stored as unscoped-tier (still delivered; the next learning round tiers it)."""
if value == "everywhere":
return "unscoped-tier"
return value
# File and directory names so common that merely mentioning them names no project.
COMMON_NAMES = {
"readme", "readme.md", "readme.txt", "readme.rst", "changelog", "changelog.md", "changelog.txt",
"history", "history.md", "news", "news.md", "license", "license.md", "licence", "licence.md",
"copying", "authors", "notice", "contributing", "contributing.md", "security", "security.md",
"code_of_conduct", "code_of_conduct.md", ".gitignore", ".gitattributes", "makefile", "dockerfile",
"tests", "test", "src", "source", "docs", "doc", "bin", "lib", "scripts", "script", "examples",
"example", "config", "configs", "build", "dist", "assets", "static", "templates", "vendor",
"main.py", "main.rs", "main.go", "main.c", "main.cpp", "index.html", "index.js", "index.ts",
"app.py", "setup.py", "pyproject.toml", "package.json", "cargo.toml", "go.mod", "requirements.txt",
}
def _git(cwd, *args):
try:
p = subprocess.run(("git",) + args, cwd=cwd, capture_output=True, timeout=5)
return p.stdout.decode("utf-8", "replace").strip() if p.returncode == 0 else ""
except (OSError, subprocess.SubprocessError):
return ""
def normalized_remote(url):
"""One id for the same repository however it was cloned."""
u = " ".join((url or "").split()).strip().rstrip("/")
if u.endswith(".git"):
u = u[:-4]
m = re.match(r"^[^/@]+@([^/:]+)[:/](.+)$", u) # git@host:owner/repo
if m:
u = m.group(1).lower() + "/" + m.group(2)
else:
m = re.match(r"^(?:[a-z][a-z0-9+.-]*://)?(?:[^/@]+@)?([^/]+)/(.+)$", u, re.I)
if m:
u = m.group(1).lower() + "/" + m.group(2)
return u.rstrip("/")
def remote_url(cwd):
url = _git(cwd, "remote", "get-url", "origin")
if not url:
names = _git(cwd, "remote").splitlines()
if names:
url = _git(cwd, "remote", "get-url", names[0].strip())
return url or None
from . import learning as L
def project_id(cwd):
"""Remote URL when there is one, else the repository root path, else the folder."""
url = remote_url(cwd)
if url:
return normalized_remote(url)
root = gitutil.root(cwd)
return os.path.realpath(root or os.path.abspath(cwd))
return L.project_key(cwd)
def project_label(pid):
"""A short human name for a project id (last path part, without .git)."""
s = (pid or "").rstrip("/")
name = s.rsplit("/", 1)[-1]
return name[:-4] if name.endswith(".git") else name
return os.path.basename(str(pid).rstrip("/")) if pid else "(unknown project)"
def visible(scope_value, project_value, cwd=None):
"""Core, user and not-yet-tiered items show in every project; project items only at home."""
if tier_of(scope_value) == "project":
return (project_value or "") == project_id(cwd or os.getcwd())
return True
def row_visible(row, cwd=None):
try:
get = row.get if isinstance(row, dict) else (lambda k: row[k] if k in row.keys() else None)
except Exception:
get = lambda k: None
return visible(get("scope"), get("project"), cwd)
def row_scope(row):
try:
v = row.get("scope") if isinstance(row, dict) else (row["scope"] if "scope" in row.keys() else None)
except Exception:
v = None
return tier_of(v)
def _existing(cwd):
"""(basenames, relative paths) of files and folders in the project, .git excluded."""
root = gitutil.root(cwd) or os.path.abspath(cwd)
names, rels = set(), set()
out = _git(root, "ls-files", "-c", "-o", "--exclude-standard")
if out:
for rel in out.splitlines():
rels.add(rel.replace(os.sep, "/").lower())
parts = rel.split("/")
for p in parts:
names.add(p.lower())
else:
for dp, dns, fns in os.walk(root):
dns[:] = [d for d in dns if d != ".git"][:200]
for n in list(dns) + list(fns):
names.add(n.lower())
if len(names) > 20000:
break
return root, names, rels
def universal_refusal(texts, cwd, kind=None):
"""Reason string when a delivered text names the current project, else None.
Checks the repository name, its remote URL (and the repository name inside it),
any path or file name that exists in it, and the root path itself. The tool's own
name, 'sisi', is always exempt: how sisi itself should behave is core, not project.
"""
texts = [t for t in (texts or []) if t and str(t).strip()]
if not texts:
return None
cwd = cwd or os.getcwd()
root, names, rels = _existing(cwd)
repo_name = os.path.basename(os.path.realpath(root)).lower()
remote = remote_url(cwd)
remote_norm = normalized_remote(remote) if remote else ""
remote_name = project_label(remote_norm).lower() if remote_norm else ""
blob = "\n".join(str(t) for t in texts)
low = blob.lower()
if os.path.realpath(root).lower() in low:
return "it gives this project's path (%s)" % root
for form in {remote or "", remote_norm}:
if form and form.lower() in low:
return "it gives this project's remote address (%s)" % form
tokens = re.findall(r"[A-Za-z0-9_./~:-]+", blob)
for tok in tokens:
t = tok.strip(".,;:()[]{}\"'")
tl = t.lower()
# the repository's own name, as a whole token or inside a path/URL token
for name in {repo_name, remote_name} - {""}:
if tl == name or tl.endswith("/" + name) or ("/" in tl and tl.rsplit("/", 1)[-1] == name):
if name == "sisi":
continue
return "it names this project (%s)" % name
if "/" in tl:
rel = tl.split("://", 1)[-1]
rel = rel[rel.find("/") + 1:] if rel.startswith(("github.com/", "gitlab.com/", "bitbucket.org/")) else rel
if rel in rels:
return "it names a path in this project (%s)" % t
base = rel.rsplit("/", 1)[-1]
if base in names and base not in COMMON_NAMES:
return "it names a file in this project (%s)" % base
elif "." in tl and not tl.startswith(".") or tl.startswith("."):
base = tl.rsplit("/", 1)[-1]
if base in names and base not in COMMON_NAMES and re.search(r"\.[a-z0-9]{1,6}$", base):
return "it names a file in this project (%s)" % base
return None
def refusal_text(reason):
return ("sisi: refused: a core or user item must be universal, and %s. Rewrite it in general "
"terms (the kind of work and the rule that follows, not this project's name, files or address), "
"or record it with --scope project so it stays with this project. " + TIER_QUESTIONS) % reason
def visible_in(rec, cwd):
return L.in_scope(rec, cwd)
def cmd_learn(argv):
"""`sisi learn [--scope core|user|project] TEXT` (also `--scope=X`)."""
from . import store
scope_value, text_parts, i = None, [], 0
argv = list(argv)
while i < len(argv):
a = argv[i]
if a == "--scope" and i + 1 < len(argv):
scope_value = argv[i + 1]; i += 2
"""sisi learn [--scope user|project] TEXT — record an owner statement, live at once."""
scope = "user"
text = []
it = iter(argv)
for a in it:
if a == "--scope":
scope = next(it, "user")
elif a.startswith("--scope="):
scope_value = a.split("=", 1)[1]; i += 1
scope = a.split("=", 1)[1]
else:
text_parts.append(a); i += 1
text = " ".join(text_parts).strip()
if not text:
print("usage: sisi learn --scope core|user|project TEXT")
return 1
if scope_value not in SCOPES and scope_value != "everywhere":
print(MISSING_SCOPE)
text.append(a)
if scope not in L.SCOPES:
print("sisi learn: --scope must be one of %s" % "|".join(L.SCOPES), file=sys.stderr)
return 2
scope_value = normalize_scope(scope_value)
cwd = os.getcwd()
if scope_value in ("core", "user", "unscoped-tier"):
reason = universal_refusal([text], cwd, kind="learn")
if reason:
print(refusal_text(reason))
return 2
rec = {"text": text, "scope": scope_value}
if scope_value == "project":
from . import handover
handover.move_learn(store.stamp(rec), project_id(cwd))
print("recorded for this project; it will be handed over to this "
"project at session start (`sisi handover` lists it)")
return 0
store.append("learn", store.stamp(rec))
try:
from . import cli
cli._commit_personal(store.file_path("learn"),
"learn: %s" % " ".join(text.split())[:60])
except Exception:
pass
if scope_value == "core":
print("recorded as core; it takes effect at once (`sisi oracle` shows it) and is queued "
"for the product (`sisi promote` lists core items)")
elif scope_value == "unscoped-tier":
print("recorded (the old everywhere scope); it takes effect at once and the next "
"learning round will tier it core, user or project")
else:
print("recorded; it takes effect at once as a standing principle (`sisi oracle` shows it)")
statement = " ".join(text).strip()
if len(statement) < 8:
print("usage: sisi learn [--scope user|project] \"<what you want>\"", file=sys.stderr)
return 2
rec = L.new_record(statement, "owner statement", "value",
"promote" if scope != "project" else "record",
os.getcwd(), L.unit_id(), change=statement, mechanism="knowledge",
scope=scope, expect="the agent acts on this statement",
owner_statement=True, entered_via="learn")
print("recorded owner statement %s (printed by `sisi oracle`)" % rec["id"])
return 0
+4 -30
View File
@@ -38,29 +38,8 @@ def _export_session(sid):
def _backlog_line(cwd):
"""Developer mode, inside the sisi source folder: name the top tool backlog item. One short line."""
try:
from . import paths, retro
src = (paths.personal_config().get("developer") or {}).get("source")
if not src:
return ""
src = os.path.realpath(src)
here = os.path.realpath(cwd)
if here != src and not here.startswith(src + os.sep):
return ""
if not os.path.exists(retro.db_path()):
return ""
rows = retro.backlog_rows()
if not rows:
return ""
src = retro._get(rows[0], "short") or rows[0]["change"]
t = retro.safe_line(src, here)
if not t:
return ""
text = " ".join(t.split()) if retro._get(rows[0], "short") else retro.word_cut(t, 110)
return "top sisi backlog #%d (x%d): %s" % (rows[0]["id"], rows[0]["count"], text)
except Exception:
return ""
"""Session start prints no backlog (target section 11); tool learnings live in the learning report."""
return ""
def _deep_line(cwd, fp):
@@ -155,13 +134,8 @@ def main(args=()):
sys.stdout.write(note + "\n")
except Exception as e:
store.log_error("tick-cycle", e)
try:
from . import retro
block = retro.tick_block(cwd, session=sid if isinstance(sid, str) else None)
if block:
sys.stdout.write(block + "\n")
except Exception as e:
store.log_error("tick-lessons", e)
# No lesson list at session start: only what this session can act on (cycle due,
# a decision waiting) is printed, by cycle.due_notice above.
except Exception as e:
store.log_error("tick", e)
return 0