diff --git a/CHANGELOG.md b/CHANGELOG.md index 59e104a..07d9407 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ All notable changes to this project are recorded here. The format follows ## Unreleased +### Added + +- Lessons gain an optional short line (one plain sentence, at most 140 characters) and topic + (between one and three lower-case words, at most 30 characters), written at `sisi retro` with + `--short` and `--topic` or by a learning round with a `set-short` note action. The cycle brief + lists every active lesson lacking either field and the topics already in use, and + `sisi cycle check` refuses a file that omits one. `sisi cycle --now` starts a round on demand + when none is due, field-note bullets and agent-facing headings use the short line when present, + and `sisi lessons digest` prints a plain-language summary grouped by topic for the human. + ### Changed - The end-of-turn gate now attributes edits to the session that made them. Edit-tool calls are read diff --git a/README.md b/README.md index cf923cf..ce55334 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,8 @@ is offered to later agents starting matching work. If the problem recurs after a shown, it is strengthened: a note, a candidate rule, then an enforced check the gate runs. `sisi cycle` consolidates lessons into rules and library entries without growing the rulebook. Whether it is due is checked during normal use, so nothing is scheduled; see -[docs/learning.md](docs/learning.md). +[docs/learning.md](docs/learning.md). `sisi lessons digest` prints what has been learned in plain +words, grouped by topic. Improvement needs a way to tell success from failure: diff --git a/docs/learning.md b/docs/learning.md index 1060895..87077bf 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -16,9 +16,17 @@ what "done" means, verifying, or being sent back by the gate. overlap alone cannot bridge "CSV" and "spreadsheet": the recording agent, who knows what the lesson is about, supplies the bridge vocabulary in advance. Lessons recorded before when-terms existed keep working by their own wording and are listed in the cycle brief so a consolidating agent can - add terms. + add terms. A retro may also carry `--short` (one sentence in plain words, at most 140 characters, + no trailing ellipsis and no newline) and `--topic` (between one and three lower-case words, at + most 30 characters, such as "releases" or "asking questions"). Both are optional and checked + only for those limits when given; when either is missing, the retro still succeeds and says + that the next learning round will write it. Stores written before these fields existed gain + them on open, losing nothing, and lessons without them keep working. 2. **It takes effect at once**, in your personal data (the overlay), never in the product files: - - a verifier or recipe lesson naming an entry is attached to it as a field note straight away; + - a verifier or recipe lesson naming an entry is attached to it as a field note straight away. + When the lesson has a short line, the bullet reads "- YYYY-MM-DD: (seen N times; + lesson ID; full text: sisi lessons show ID)" in place of the long change text; an explicit + note text given by a later fold still wins over the short line; - a recipe lesson naming a recipe that does not exist is kept as a draft recipe note; - a rule, oracle or brief lesson becomes an active learned note with trigger words taken from its text; - a tool lesson (a change to sisi itself) goes on the backlog (`sisi backlog`, most seen first). @@ -35,7 +43,11 @@ what "done" means, verifying, or being sent back by the gate. never read, still recurs" means the heading is bad, and the cycle brief says so. `sisi verifiers show` and the gate's send-back message keep the older single strong-match block. Draft recipe notes appear in `sisi done for` when their words match. Lesson text is always framed as information to - weigh, not as commands, and text from a lesson is never executed. + weigh, not as commands, and text from a lesson is never executed. One-line headings — the + other-lessons list, session-start notes, `sisi backlog` and `sisi lessons` — use the short + line when one is present; without one they cut the change at a word boundary and end with + "…", never mid-word. Printed-heading budgets count the short line when present, because that + is what is printed. 4. **Showings are counted.** Every time a lesson is printed or listed, sisi records which lesson, in which session, and where; opening one in full counts separately as read. Promotion needs at least two listings or readings since the last promotion. A later sighting of the same problem — a retro recorded with `--same-as`, which @@ -74,17 +86,22 @@ for strength-3 lessons). The agent answers with one JSON file: The brief names the scratch path to write it to, lists every valid rule, recipe and verifier id (with each recipe's one-line applies-to and the rule number-to-id map), shows full lesson text when it fits its stated text budget (otherwise it says to run `sisi lessons show ID`), and puts the full -format behind `sisi cycle help`. `sisi cycle check FILE` (or `--dry-run`) validates and prints -exactly what would change, changing nothing. +format behind `sisi cycle help`. It also lists every active lesson lacking a short line or topic, +lists the topics already in use so the agent reuses one instead of inventing a near-duplicate, +states the short and topic limits, and requires a `set-short` entry for each listed lesson: +`sisi cycle check FILE` (or `--dry-run`) refuses a file that omits one, naming the lesson, and +prints exactly what would change, changing nothing. A round can be started on demand even when +none is due: `sisi cycle --now` (or plain `sisi cycle`) prints the brief either way. ```json {"version": 1, "base": "", "summary": "one line", "rules": [{"id": "rule-id", "title": "Title", "body": "text, ending with Why: ...", "action": "add|replace", "shortens": "rule-id: what is removed (required when the book would grow in characters)"}], "disable_rules": ["rule-id"], - "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft", + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short", "into": "rule/entry id or [ids]", "merged_into": 4, "note": "split text (optional)", - "when": "at least 5 terms (optional)", "entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", + "when": "at least 5 terms (optional)", "short": "one plain sentence (set-short)", "topic": "topic words (set-short)", + "entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", "reason": "why it stays a draft (keep-as-draft)"}], "enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30}, {"lesson": 4, "type": "contract-requirement", "when": "parser", @@ -95,20 +112,28 @@ exactly what would change, changing nothing. `notes/.md` and marks the lesson applied; `into` may be a list, and two notes for one lesson with different `note` text split a compound lesson. `create-entry` creates a personal recipe or verifier entry in the overlay, lint-checked; `keep-as-draft` keeps it as a draft with a reason. -`set-when` only sets when-terms. Merge only lessons requesting the same change, into the older or -more general one, which keeps its text and count; the other becomes superseded and needs no action. -Tool lessons cannot be done in a cycle: they stay in `sisi backlog`, except merging a duplicate. +`set-when` only sets when-terms. `set-short` writes the short line and topic, and may be combined +with other actions on the same lesson; when it lands on a lesson already folded into an entry, the +entry's existing default bullets are rewritten to the short form. A bullet is treated as a default +bullet only when its text equals the lesson's full change with whitespace normalised; any other +text came from an explicit `note` and is left alone. Merge only lessons requesting the same change, +into the older or more general one, which keeps its text and count; the other becomes superseded +and needs no action. Tool lessons cannot be done in a cycle: they stay in `sisi backlog`, except +merging a duplicate (and a `set-short` for one, so the digest can show it). Retire only what is fully folded and quiet (folded, at least 20 listed/read, no recurrences after first listing); folding in this cycle does not make it quiet. The learned-notes limit counts only -`length(change)` of active strength-1 loose learned notes: folded lessons no longer count, which -is why folding (or merging, retiring, withdrawing, enforcing) reduces it. +`length(change)` of active strength-1 loose learned notes — it counts the change, not the short +line, because it is about content not yet folded — while printed headings count the short line +when present: folded lessons no longer count toward the learned-notes limit, which is why folding +(or merging, retiring, withdrawing, enforcing) reduces it. `sisi cycle apply FILE` checks the file before writing anything: every lesson id exists, the base version is still current, changed rules keep their id and their Why, named `sisi` commands and enforced programs exist, and the resulting rulebook is inside both budgets (120 lines and 7,200 characters) and no longer in characters than before unless `shortens` names what was removed. Rules are re-wrapped to 100 characters on apply. The base version covers only what a cycle may -change (lesson content and status, rules, notes, enforced checks), not listed/read counters, and +change (lesson content and status, short lines and topics, rules, notes, enforced checks), not +listed/read counters, and lessons recorded since the brief are left for the next cycle; a stale refusal names exactly what changed. The base version plus the personal-data lock means two sessions consolidating at once cannot overwrite each other: the second apply is refused and told to read a fresh brief. A successful apply is one commit in your personal repository, with before-and-after @@ -123,6 +148,18 @@ contract-requirement fails a contract that touches its subject without a check o a command check runs in the project like a contract check, and only in projects already on the trust list. +## What has been learned, in plain words + +`sisi lessons digest` is for the human, not for agents. Its first line says how much has been +learned in one sentence, and its last line says how to see a lesson in full (`sisi lessons show +ID`), with the lesson number on every line. Preferences recorded with `sisi learn` appear first, +in the person's own words, under "What you said" when any are stored. Short lines are grouped +under their topic headings, ordered by how much each topic holds, most first. After every line +comes its state in plain words — in the rulebook; attached to a kind of work; a loose note; or a +change to sisi itself, not built yet — plus "seen N times" only when a lesson has been seen more +than once. Lessons without a short line go last, under "Not yet summarized", cut at a word +boundary. Retired, withdrawn and superseded lessons are left out unless `--all` is given. + ## Is it getting better? `sisi improve` (and one line of `sisi status`) answers with what is actually counted: lessons recorded, diff --git a/sisi/cli.py b/sisi/cli.py index 1da5618..e1e636d 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -27,21 +27,25 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co 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 --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" [--target ID] [--same-as ID | --new] + sisi retro --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" [--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 + 5 terms, synonyms included) is how a later agent with different words finds it; + --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 | set ID --status S | apply ID | export [FILE] | import FILE - the shared lessons from retros (--aim --kind --status --repo --top --json) + 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] + 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); - check/--dry-run prints what would change, changing nothing; - help prints the full cycle file format + 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 note TEXT (older; prefer retro) record something that went wrong sisi propose TEXT (older; prefer retro) suggest a rule change @@ -199,7 +203,8 @@ def _status_retro(): 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"]: - print(" active #%-4d x%-3d %s" % (t["id"], t["count"], " ".join(t["change"].split())[:90])) + from . import retro as _R + print(" active #%-4d x%-3d %s" % (t["id"], t["count"], _R.heading_text(t, 90))) def _status_contracts(res): diff --git a/sisi/cycle.py b/sisi/cycle.py index eae1d36..5013f8d 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -9,8 +9,9 @@ A cycle file (what the agent writes, what `sisi cycle apply` checks) is one JSON {"version": 1, "base": "", "summary": "one line", "rules": [{"id": "rule-id", "title": "Title", "body": "text with a Why: line", "action": "add|replace"}], "disable_rules": ["rule-id"], - "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep", - "into": "rule or entry id", "merged_into": 4, + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-short", + "into": "rule or entry id", "merged_into": 4, "short": "one plain sentence, at most 140 characters", + "topic": "1 to 3 lower-case words, at most 30 characters", "when": "csv, tsv, spreadsheet, tabular data, import, parse (optional; sets the lesson's when-terms)"}], "enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30}, {"lesson": 4, "type": "contract-requirement", "when": "parser", @@ -29,7 +30,7 @@ class CycleError(Exception): ACTIONS = ("merge", "fold-into-rule", "fold-into-entry", "retire", "withdraw", "keep", - "set-when", "create-entry", "keep-as-draft") + "set-when", "create-entry", "keep-as-draft", "set-short") # Total characters of lesson text (change+moment+cause) the brief prints in full. Over this, # lessons are truncated and the brief says to run `sisi lessons show ID` for the full text. BRIEF_TEXT_BUDGET = 6000 @@ -192,7 +193,7 @@ def _announce_save(data): # occurrence counters (count, last_seen) and new lessons do NOT count: reading a lesson or a # lesson arriving must never stale a brief (gaps 2 and 3). _RELEVANT = ("aim", "change_kind", "target", "moment", "cause", "change", "status", "strength", - "folded_into", "effect", "when_terms", "check_json", "needs_cycle") + "folded_into", "effect", "when_terms", "check_json", "needs_cycle", "short", "topic") def _snapshot(con): @@ -421,10 +422,11 @@ Shape (all but version/base optional; full detail: `sisi cycle help`): "rules": [{"id": "rule-id", "title": "Title", "body": "text ending with Why: ...", "action": "add|replace", "shortens": "rule-id: what text is removed/shortened (required when the rulebook would grow in characters)"}], "disable_rules": ["rule-id"], - "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft", + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short", "into": "id or [ids] (folds; entry folds append a field note)", "merged_into": 4, "note": "text to append instead of the lesson change (for splitting one lesson)", "when": "at least 5 terms (sets when-terms; alone with action set-when)", + "short": "one plain sentence, at most 140 characters (set-short)", "topic": "1 to 3 lower-case words, at most 30 characters (set-short)", "entry_kind": "recipe|verifier", "entry_text": "full file text (create-entry)", "reason": "why it stays a draft (keep-as-draft)"}], "enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30}, @@ -438,6 +440,8 @@ File: write ONE JSON file at the scratch path the brief prints, then: sisi cycle apply FILE apply it (one commit in the personal repository) sisi cycle revert [ID] undo the newest applied cycle exactly sisi cycle status past cycles and what happened since + sisi cycle print the brief (works whether or not a cycle is due) + sisi cycle --now same: start a round on demand, even when none is due Top level: {"version": 1 (required), "base": "", "summary": "one line", "rules": [...], "disable_rules": [...], "notes": [...], "enforced": [...]} - all else optional. @@ -464,9 +468,12 @@ Notes - one object per decision; the same lesson may appear several times (split fold-into-entry {"lesson": A, "action": "fold-into-entry", "into": "id" or ["id", ...], "note": "optional text"} - appends one field-note bullet to notes/.md: "- YYYY-MM-DD: (aim: ; seen - times; lesson )", and marks the lesson applied / field-note / - folded_into=. To split a compound lesson, use two notes objects with the - same lesson, different `into` and different `note` text each. + times; lesson )", or, when the lesson has a short line and no + explicit `note` was given, "- YYYY-MM-DD: (seen times; lesson + ; full text: sisi lessons show )". An explicit `note` always wins. + Marks the lesson applied / field-note / folded_into=. To split a compound + lesson, use two notes objects with the same lesson, different `into` and + different `note` text each. create-entry {"lesson": A, "action": "create-entry", "into": "new-id", "entry_kind": "recipe|verifier", "entry_text": ""} Creates a personal recipe or verifier entry in the overlay from the lesson, @@ -478,6 +485,17 @@ Notes - one object per decision; the same lesson may appear several times (split recipe note (shown by `sisi done for` when its words match), nothing else. set-when {"lesson": A, "action": "set-when", "when": "at least 5 terms"} - only sets the lesson's when-terms; nothing else changes. + set-short {"lesson": A, "action": "set-short", "short": "...", "topic": "..."} - writes + the lesson's one-line plain-language summary and its topic. Limits: short is + one sentence, at most 140 characters, no trailing ellipsis, no newline; topic + is 1 to 3 lower-case words, at most 30 characters. Reuse a topic already in + use (the brief lists them) instead of inventing a near-duplicate. Every active + lesson the brief lists as lacking a short line or topic needs a set-short in + the file; `sisi cycle check` refuses a file that omits one, naming the lesson + (lessons this file retires, withdraws or merges away are exempt). set-short may + be combined with other actions on the same lesson. When the lesson is already + folded into an entry, its default field-note bullet is rewritten to the short + form; a bullet that came from an explicit `note` is left alone. keep {"lesson": A, "action": "keep"} - leave it; clears its waiting flag. retire leave the active notes. Only when fully folded and quiet: folded into a rule, entry or enforced check, listed/read at least 20 times, and 0 recurrences after @@ -499,9 +517,12 @@ Enforced checks - write none for lessons below strength 3. One per strength-3 NE Complete examples are the two objects above. Learned-notes limit: counts length(change) of active strength-1 loose learned notes only -(limit 4000 characters). Folded, strengthened, retired, withdrawn and tool-backlog lessons do -not count. fold-into-entry, fold-into-rule, merge, retire, withdraw and writing an enforced -check all reduce it; keep and set-when do not. +(limit 4000 characters). It still counts `change`, not `short`: it is about lesson content not +yet folded. Delivery budgets for printed headings (session start, the other-lessons list) count +the short line when one is present, because that is what is printed; without one they count a +word-boundary cut of the change. Folded, strengthened, retired, withdrawn and tool-backlog +lessons do not count toward the learned-notes limit. fold-into-entry, fold-into-rule, merge, +retire, withdraw and writing an enforced check all reduce it; keep, set-when and set-short do not. """ def cycle_file_path(): @@ -534,6 +555,9 @@ def brief_text(): sight = {r["id"]: retro.sightings_count(con, r["id"]) for r in rows} base = base_version(con) before = measures(con) + missing_short = [r for r in rows if r["status"] in retro.ACTIVE + and (not str(r.get("short") or "").strip() or not str(r.get("topic") or "").strip())] + topics_in_use = _topics_in_use(con) finally: con.close() from . import verifiers as V @@ -606,6 +630,10 @@ def brief_text(): elif not r["when_terms"]: out.append(" when: MISSING - add at least 5 terms with set-when or any note's when") out.append(" target: %s folded_into: %s" % (r["target"] or "-", r["folded_into"] or "-")) + if r["status"] in retro.ACTIVE and (not str(r.get("short") or "").strip() or not str(r.get("topic") or "").strip()): + out.append(" short: MISSING - add a set-short for this lesson (short at most %d characters, topic at most %d)" % (retro.SHORT_MAX, retro.TOPIC_MAX)) + elif r.get("short"): + out.append(" short: %s (topic: %s)" % (r["short"], r.get("topic") or "-")) if listed[r["id"]] >= 5 and readn[r["id"]] == 0 and rec[r["id"]] > 0 and r["status"] in retro.ACTIVE: out.append(" LISTED %d TIMES, NEVER READ, STILL RECURS: rewrite the start of its change and its when-terms" % listed[r["id"]]) if sight[r["id"]]: @@ -618,6 +646,16 @@ def brief_text(): missing = [r["id"] for r in rows if r["status"] in retro.ACTIVE and not r["when_terms"]] if missing: out += ["Lessons with no when-terms yet: " + ", ".join("#%d" % i for i in missing), ""] + out += ["Short lines: every active lesson lacking a short line or topic needs a set-short in your file; " + "`sisi cycle check` will refuse a file that omits one, naming the lesson. Write each short as " + "one sentence in plain words, an instruction, at most %d characters, no trailing ellipsis, no " + "newline. Topic: 1 to 3 lower-case words, at most %d characters. Reuse a topic already in use " + "when it fits instead of inventing a near-duplicate. set-short may be combined with other " + "actions on the same lesson (fold, keep, set-when and the rest)." + % (retro.SHORT_MAX, retro.TOPIC_MAX), + "Topics already in use: " + (", ".join(topics_in_use) if topics_in_use else "(none yet)"), + "Lessons lacking a short line or topic: " + + (", ".join("#%d" % r["id"] for r in missing_short) if missing_short else "(none)"), ""] out += ["Do this, in order:", "1. Fold each loose lesson into the recipe/entry whose applies-to (above) fits its kind of " "work, or lift several into one general rule. fold-into-entry appends a field note (see help). " @@ -629,7 +667,9 @@ def brief_text(): "3. Tool lessons (kind tool) cannot be done in a cycle: leave them in `sisi backlog` untouched, except merging a duplicate.", "4. Rules: keep id and Why, format per help; name in `shortens` which existing rule text gets shorter or is replaced whenever a rule is added or the book would grow in characters.", "5. For each NEEDS A CHECK lesson write one enforced check (help has fields and examples); none below strength 3.", - "6. Retire only what is fully folded and quiet (folded, at least 20 listed/read, 0 recurrences " + "6. For every lesson listed above as lacking a short line or topic, add a set-short (it may sit " + "beside its fold, keep or set-when entry). Reuse a topic already in use when it fits.", + "7. Retire only what is fully folded and quiet (folded, at least 20 listed/read, 0 recurrences " "after first listed) - folding now does not make it quiet, so fold and keep, retire next cycle. " "Withdraw what made things worse. set-when only sets when-terms. Keep the rest.", "Every changed rule keeps its id and ends with its Why. Never ask the human anything.", "", FORMAT_DOC] @@ -669,6 +709,41 @@ def _lesson_ids_in(doc): return ids +def _missing_short_at_base(doc, con): + """[(lesson_id, snapshot)] active at the brief whose short line or topic was missing then. + + Lessons recorded since the brief are not included: they are left for the next cycle and + must not make this file fail (see _check_base).""" + old = _load_snapshot(doc.get("base")) if isinstance(doc, dict) and doc.get("base") else None + out = [] + if old and isinstance(old.get("lessons"), dict): + for lid_s, v in old["lessons"].items(): + if not isinstance(v, dict) or v.get("status") not in retro.ACTIVE: + continue + if not str(v.get("short") or "").strip() or not str(v.get("topic") or "").strip(): + try: + out.append((int(lid_s), v)) + except ValueError: + continue + return sorted(out) + try: + for r in con.execute("SELECT * FROM lessons WHERE status IN ('open','applied') ORDER BY id"): + d = dict(r) + if not str(d.get("short") or "").strip() or not str(d.get("topic") or "").strip(): + out.append((d["id"], d)) + except Exception: + pass + return out + + +def _topics_in_use(con): + try: + return sorted({str(r[0]).strip() for r in con.execute( + "SELECT DISTINCT topic FROM lessons WHERE topic IS NOT NULL AND trim(topic)<>''") if r[0] and str(r[0]).strip()}) + except Exception: + return [] + + def static_validate(doc, con): """Every refusal reason that can be known before writing anything. Empty means applicable so far.""" errs = [] @@ -719,9 +794,15 @@ def static_validate(doc, con): errs.append("each note needs an action in %s: %r" % (", ".join(ACTIONS), e)) continue lid = e.get("lesson") - if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when"): + if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when", "set-short"): errs.append("lesson %s: tool lessons cannot be done in a cycle (they change sisi itself); " "leave them in `sisi backlog` untouched, except merging a duplicate" % lid) + if e["action"] == "set-short": + if e.get("short") is None and e.get("topic") is None: + errs.append("lesson %s: set-short needs a short line and/or a topic" % lid) + else: + for sub in retro.validate_short_topic(e.get("short"), e.get("topic")): + errs.append("lesson %s: %s" % (lid, sub)) if e["action"] == "merge" and (not isinstance(e.get("merged_into"), int) or e.get("merged_into") == lid): errs.append("lesson %s: merge needs merged_into naming a different lesson" % lid) if e["action"] in ("fold-into-rule", "fold-into-entry", "create-entry") and not _into_list(e): @@ -782,6 +863,30 @@ def static_validate(doc, con): errs.append("lesson %s: max_rung must be 1-6" % e.get("lesson")) else: errs.append("lesson %s: enforced type must be command or contract-requirement" % e.get("lesson")) + # Every active lesson that lacked a short line or topic in the brief needs a set-short here. + # Lessons this same file retires, withdraws or merges away are exempt: they leave the active + # notes, so a summary would never be shown. Lessons recorded since the brief are not in the + # snapshot and are left for the next cycle. + if isinstance(doc, dict) and doc.get("base"): + notes_list = [e for e in doc.get("notes") or [] if isinstance(e, dict)] + covered = {} + for e in notes_list: + if e.get("action") == "set-short" and isinstance(e.get("lesson"), int): + covered[e["lesson"]] = e + exempt = {e.get("lesson") for e in notes_list if e.get("action") in ("retire", "withdraw", "merge")} + for lid, snap in _missing_short_at_base(doc, con): + if lid in exempt: + continue + e = covered.get(lid) or {} + need = [] + if not str(snap.get("short") or "").strip() and not str(e.get("short") or "").strip(): + need.append("short") + if not str(snap.get("topic") or "").strip() and not str(e.get("topic") or "").strip(): + need.append("topic") + if need: + errs.append("lesson %d: missing set-short (%s) - the brief listed this lesson as needing " + "a short line; add {\"lesson\": %d, \"action\": \"set-short\", \"short\": \"...\", \"topic\": \"...\"}" + % (lid, " and ".join(need), lid)) return errs @@ -845,6 +950,16 @@ def _apply_writes(doc, con): overlay._write(rel, e["entry_text"] if e["entry_text"].endswith("\n") else e["entry_text"] + "\n") con.execute("UPDATE lessons SET status='applied', effect='field-note', folded_into=?, needs_cycle=0, " "applied_at=COALESCE(applied_at,?) WHERE id=?", (",".join(_into_list(e)), store.now(), lid)) + elif act == "set-short": + cols = [c[1] for c in con.execute("PRAGMA table_info(lessons)")] + sets, vals = [], [] + if "short" in cols and e.get("short") is not None: + sets.append("short=?"); vals.append(str(e["short"]).strip()) + if "topic" in cols and e.get("topic") is not None: + sets.append("topic=?"); vals.append(str(e["topic"]).strip()) + if sets: + con.execute("UPDATE lessons SET %s WHERE id=?" % ", ".join(sets), vals + [lid]) + retro.rewrite_notes_for_lesson(con, lid) elif act == "keep-as-draft": con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,)) elif act == "set-when": @@ -1140,6 +1255,10 @@ def check_file(path): extra += " reason=%r" % e["reason"][:60] if e.get("entry_kind"): extra += " entry_kind=%s" % e["entry_kind"] + if e.get("short"): + extra += " short=%r" % e["short"][:60] + if e.get("topic"): + extra += " topic=%r" % e["topic"][:60] out.append(" lesson %s: %s%s" % (e.get("lesson"), e.get("action"), extra)) for e in doc.get("enforced") or []: out.append(" lesson %s: enforced %s %s" % (e.get("lesson"), e.get("type"), @@ -1210,7 +1329,7 @@ def cmd_cycle(args): print("no learning cycle is due (%d lessons since the last cycle, %d waiting, %d note characters)" % (st.get("since", 0), st.get("pending", 0), st.get("notes_chars", 0))) return 1 - if sub in ("brief",): + if sub in ("brief", "--now", "now"): print(brief_text(), end="") return 0 if sub == "apply": @@ -1229,7 +1348,7 @@ def cmd_cycle(args): for line in status_lines(): print(line) return 0 - print("usage: sisi cycle [due|apply FILE|check FILE|--dry-run FILE|revert [ID]|status|help] (no argument prints the brief)") + print("usage: sisi cycle [due|apply FILE|check FILE|--dry-run FILE|revert [ID]|status|help|--now] (no argument, or --now, prints the brief on demand even when none is due)") return 2 except CycleError as e: print("sisi cycle: %s" % e) diff --git a/sisi/retro.py b/sisi/retro.py index 8744051..f431978 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -20,6 +20,72 @@ AUTO_KINDS = ("verifier", "recipe") NOTES_LIMIT_CHARS = 4000 # total text of active strength-1 learned notes before a cycle is due RETIRE_SHOWS = 20 # shown this often with no recurrence (and folded somewhere) a lesson leaves the notes MIN = {"moment": (30, 5), "cause": (15, 3), "change": (25, 4)} # (characters, words) +SHORT_MAX = 140 +TOPIC_MAX = 30 + + +def _get(row, key): + try: + if isinstance(row, dict): + return row.get(key) + return row[key] if key in row.keys() else None + except Exception: + return None + + +def word_cut(text, limit): + """Cut at a word boundary, ending with an ellipsis, never mid-word.""" + t = " ".join((text or "").split()) + if len(t) <= limit: + return t + if limit <= 1: + return "…" + cut = t[:limit - 1] + if " " in cut: + cut = cut.rsplit(" ", 1)[0] + else: + cut = t.split(" ", 1)[0] + return cut.rstrip() + "…" + + +def heading_text(row, limit=90): + """The one-line heading for a lesson: its short line when present, else a word-boundary cut.""" + s = _get(row, "short") + if s and str(s).strip(): + return " ".join(str(s).split()) + return word_cut(_get(row, "change") or "", limit) + + +def validate_short_topic(short, topic): + """Structural checks for the optional short line and topic. Empty list means acceptable.""" + errs = [] + if short is not None: + s = str(short) + if "\n" in s or "\r" in s: + errs.append("short must be one line with no newline (check: short newline)") + st = s.strip() + if not st: + errs.append("short must not be empty (check: short present)") + elif len(st) > SHORT_MAX: + errs.append("short is too long: %d characters, at most %d (check: short length)" % (len(st), SHORT_MAX)) + elif st.endswith("…") or st.endswith("..."): + errs.append("short must not end with an ellipsis (check: short ellipsis)") + if topic is not None: + tp = str(topic) + if "\n" in tp or "\r" in tp: + errs.append("topic must be one line with no newline (check: topic newline)") + tt = tp.strip() + if not tt: + errs.append("topic must not be empty (check: topic present)") + else: + if len(tt) > TOPIC_MAX: + errs.append("topic is too long: %d characters, at most %d (check: topic length)" % (len(tt), TOPIC_MAX)) + words = tt.split() + if len(words) < 1 or len(words) > 3: + errs.append("topic must be 1 to 3 words (check: topic words)") + elif tt != tt.lower() or not re.fullmatch(r"[a-z0-9]+(?:[ -][a-z0-9]+)*", tt): + errs.append("topic must be 1 to 3 lower-case words (check: topic case)") + return errs # ---- database -------------------------------------------------------------- @@ -30,7 +96,7 @@ def db_path(): NEW_LESSON_COLS = (("strength", "INTEGER DEFAULT 1"), ("triggers", "TEXT"), ("effect", "TEXT"), ("applied_at", "TEXT"), ("folded_into", "TEXT"), ("needs_cycle", "INTEGER DEFAULT 0"), ("check_json", "TEXT"), ("change_fp", "TEXT"), ("promoted_shown", "INTEGER DEFAULT 0"), - ("when_terms", "TEXT")) + ("when_terms", "TEXT"), ("short", "TEXT"), ("topic", "TEXT")) def connect(): @@ -88,7 +154,7 @@ def _backfill(con): # ---- the committed dump ------------------------------------------------------ LESSON_COLS = ("id", "created", "aim", "change_kind", "target", "moment", "cause", "change", "status", "count", "last_seen", "strength", "triggers", "effect", "applied_at", "folded_into", "needs_cycle", "check_json", "change_fp", - "promoted_shown", "when_terms") + "promoted_shown", "when_terms", "short", "topic") OCC_COLS = ("id", "lesson_id", "ts", "session", "tool", "cwd", "repo", "moment", "fp", "delivery_s") IMP_COLS = ("id", "lesson_id", "ts", "session", "place", "occ_count") SIGHT_COLS = ("id", "lesson_id", "ts", "session", "moment") @@ -269,6 +335,7 @@ def validate(f, same_as=False): bad = next(t for t in terms if len(t.split()) > 6) errs.append('each --when term should be a word or a short phrase (at most 6 words); %s has %d (check: when-term length)' % (_quote(bad), len(bad.split()))) + errs.extend(validate_short_topic(f.get("short"), f.get("topic"))) if errs: return errs if not same_as: @@ -527,10 +594,19 @@ def new_lesson(con, f, cwd, fp): now = store.now() change, target = f["change"].strip(), f.get("target") or None when = ", ".join(parse_when(f.get("when"))) or None - cur = con.execute("INSERT INTO lessons(created, aim, change_kind, target, moment, cause, change, status, count, last_seen," - " strength, triggers, change_fp, when_terms) VALUES (?,?,?,?,?,?,?, 'open', 0, ?, 1, ?, ?, ?)", + short = (f.get("short") or "").strip() or None + topic = (f.get("topic") or "").strip() or None + # tolerate stores predating short/topic: only insert columns that exist + cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")] + extra_cols = [c for c in ("short", "topic") if c in cols] + extra_vals = [short if c == "short" else topic for c in extra_cols] + base_cols = ("created, aim, change_kind, target, moment, cause, change, status, count, last_seen," + " strength, triggers, change_fp, when_terms") + all_cols = base_cols + (", " + ", ".join(extra_cols) if extra_cols else "") + placeholders = "?,?,?,?,?,?,?, 'open', 0, ?, 1, ?, ?, ?" + (", ?" * len(extra_cols)) + cur = con.execute("INSERT INTO lessons(%s) VALUES (%s)" % (all_cols, placeholders), (now, f["aim"], f["change_kind"], target, f["moment"].strip(), f["cause"].strip(), - change, now, triggers_for(change, target, when), change_fp(change), when)) + change, now, triggers_for(change, target, when), change_fp(change), when) + tuple(extra_vals)) lid = cur.lastrowid add_occurrence(con, lid, f["moment"].strip(), cwd, fp) apply_effect(con, lid) # every lesson takes effect on its first occurrence @@ -539,8 +615,10 @@ def new_lesson(con, f, cwd, fp): def notes_chars(con): """Characters counted toward the learned-notes limit: length(change) of active, strength-1, - still-loose learned notes only. Folded lessons (into a rule, entry, draft or enforced check), - tool backlog lessons and strengthened lessons do not count: folding is what reduces this.""" + still-loose learned notes only. This still counts `change`, not `short`: the limit is about + lesson content not yet folded, not about the printed heading (headings count `short` when + present, because that is what is printed). Folded lessons (into a rule, entry, draft or + enforced check), tool backlog lessons and strengthened lessons do not count.""" try: return con.execute( "SELECT COALESCE(sum(length(change)),0) FROM lessons WHERE status IN ('open','applied') " @@ -552,6 +630,79 @@ def notes_chars(con): "AND COALESCE(strength,1)=1 AND folded_into IS NULL").fetchone()[0] +def _bullet_for(r, note_text=None, date=None): + """One field-note bullet. An explicit note wins; else the short line when present.""" + date = date or store.now()[:10] + lid = _get(r, "id") + count = _get(r, "count") or 1 + aim = _get(r, "aim") + if note_text is not None: + return "- %s: %s (aim: %s; seen %d times; lesson %d)" % (date, " ".join(str(note_text).split()), aim, count, lid) + short = _get(r, "short") + if short and str(short).strip(): + return "- %s: %s (seen %d times; lesson %d; full text: sisi lessons show %d)" % ( + date, " ".join(str(short).split()), count, lid, lid) + return "- %s: %s (aim: %s; seen %d times; lesson %d)" % ( + date, " ".join(str(_get(r, "change") or "").split()), aim, count, lid) + + +def _parse_bullet(line): + """(date, text, lesson_id) for a field-note bullet, or None. Handles old and short forms.""" + import re as _re + m = _re.match(r"^- (\d{4}-\d{2}-\d{2}): (.*) \((?:aim: [^;]+; )?seen \d+ times; lesson (\d+)(?:; full text: sisi lessons show \d+)?\)\s*$", line.rstrip("\n")) + if not m: + return None + return m.group(1), m.group(2), int(m.group(3)) + + +def rewrite_notes_for_lesson(con, lesson_id): + """Rewrite a folded lesson's default bullets to its short form. + + How explicit notes are told apart: a bullet whose text (between the date and the + parenthesised tail) equals the lesson's full `change`, whitespace-normalised, is a + default bullet written from the change. Any other text came from an explicit `note` + in a fold (or was already the short line) and is left alone. + """ + r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone() + if not r: + return [] + short = _get(r, "short") + if not short or not str(short).strip(): + return [] + change_norm = " ".join(str(_get(r, "change") or "").split()) + d = paths.notes_dir() + changed = [] + try: + names = sorted(os.listdir(d)) + except OSError: + return [] + for name in names: + if not name.endswith(".md"): + continue + p = os.path.join(d, name) + try: + with open(p, encoding="utf-8") as f: + lines = f.read().splitlines(True) + except OSError: + continue + out, dirty = [], False + for line in lines: + parsed = _parse_bullet(line) + if parsed and parsed[2] == lesson_id and parsed[1] == change_norm: + nl = "\n" if line.endswith("\n") else "" + out.append(_bullet_for(r, date=parsed[0]) + nl) + dirty = True + else: + out.append(line) + if dirty: + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write("".join(out)) + os.replace(tmp, p) + changed.append(p) + return changed + + def _append_note(kind_file, target, r, draft=False, note_text=None): d = paths.notes_dir() os.makedirs(d, exist_ok=True) @@ -563,8 +714,7 @@ def _append_note(kind_file, target, r, draft=False, note_text=None): if draft: f.write("No recipe with this id exists yet. These notes are shown by `sisi done for` when their " "words match, until a cycle turns them into a recipe or folds them elsewhere.\n\n") - text = note_text if note_text is not None else r["change"] - f.write("- %s: %s (aim: %s; seen %d times; lesson %d)\n" % (store.now()[:10], " ".join(text.split()), r["aim"], r["count"], r["id"])) + f.write(_bullet_for(r, note_text=note_text) + "\n") return p @@ -718,10 +868,11 @@ def tick_block(cwd, n=8, session=None): for r in rows: if len(out) >= n: break - t = safe_line(r["change"], repo) + src = _get(r, "short") or r["change"] + t = safe_line(src, repo) if not t: continue - line = "- %s (seen %d)" % (t[:150], r["count"]) + line = "- %s (seen %d)" % (word_cut(t, 150) if not _get(r, "short") else " ".join(t.split()), r["count"]) if total + len(line) + 1 > LIMIT: continue out.append(line) @@ -867,7 +1018,7 @@ def lessons_block(query, place, session=None, limit=3, max_chars=600, extra=""): room = max_chars - total - 1 if room < 60: continue - line = line[:room - 1] + "…" + line = word_cut(line, room) lines.append(line) ids.append(r["id"]) total += len(line) + 1 @@ -888,8 +1039,11 @@ def _is_loose(row): def loose_heading(row): - return "- #%d (strength %d): %s" % (row["id"], row["strength"] or 1, - " ".join((row["change"] or "").split())[:90]) + # Headings count the short line when present (it is what is printed); without one they + # count a word-boundary cut of the change. See notes_chars for the separate learned-notes + # limit, which still counts length(change). + return "- #%d (strength %d): %s" % (_get(row, "id"), (_get(row, "strength") or 1), + heading_text(row, 90)) def delivery(query, extra="", targets=(), con=None): @@ -932,7 +1086,7 @@ def delivery_block(query, place, session=None, extra="", targets=()): out.append(PART1_HEADER + "\n" + "\n".join(lines1)) lines2, total = [], len(PART2_HEADER) + 1 for d in part2: - if not display_line(d["row"]["change"], repo): + if not display_line(_get(d["row"], "short") or d["row"]["change"], repo): continue line = loose_heading(d["row"]) reserve = 70 if len(listed2) < len(part2) else 0 @@ -942,7 +1096,7 @@ def delivery_block(query, place, session=None, extra="", targets=()): listed2.append(d["row"]["id"]) total += len(line) + 1 if lines2: - omitted = len([d for d in part2 if display_line(d["row"]["change"], repo)]) - len(lines2) + omitted = len([d for d in part2 if display_line(_get(d["row"], "short") or d["row"]["change"], repo)]) - len(lines2) block = PART2_HEADER + "\n" + "\n".join(lines2) if omitted > 0: block += "\n- ... and %d more not listed (`sisi lessons` lists them; a cycle is due)" % omitted @@ -986,7 +1140,8 @@ def backlog_rows(con=None): def _parse(argv): f, flags, i = {}, set(), 0 names = {"--aim": "aim", "--moment": "moment", "--cause": "cause", "--change-kind": "change_kind", - "--change": "change", "--target": "target", "--same-as": "same_as", "--when": "when"} + "--change": "change", "--target": "target", "--same-as": "same_as", "--when": "when", + "--short": "short", "--topic": "topic"} while i < len(argv): a = argv[i] if a in names: @@ -1026,7 +1181,7 @@ def cmd_retro(argv, stdin=None): if k == "new": if v: flags.add("new") - elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as", "when"): + elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as", "when", "short", "topic"): f.setdefault(k, str(v)) for k in list(f): f[k] = f[k].strip() @@ -1083,13 +1238,16 @@ def cmd_retro(argv, stdin=None): fp = current_fp(cwd) # after any field-note write, so the gate sees this retro as for the current tree con.execute("UPDATE occurrences SET fp=? WHERE id=(SELECT max(id) FROM occurrences WHERE lesson_id=?)", (fp, lid)) con.commit() - row = con.execute("SELECT count, effect FROM lessons WHERE id=?", (lid,)).fetchone() - count = row[0] + row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone() + count = row["count"] applied = bool(applied) or (row["effect"] == "field-note" and count == 1) + needs_short = not (_get(row, "short") and str(_get(row, "short")).strip()) or not (_get(row, "topic") and str(_get(row, "topic")).strip()) finally: con.close() sync("lessons: retro recorded for lesson #%d" % lid) print("recorded: lesson #%d, seen %d time%s%s" % (lid, count, "" if count == 1 else "s", "; applied to notes/" if applied else "")) + if needs_short: + print("sisi: this lesson has no short line yet; the next learning round will write one (run `sisi cycle --now` to start it now).") try: from . import cycle line = cycle.due_notice() @@ -1101,14 +1259,101 @@ def cmd_retro(argv, stdin=None): def _lesson_line(r): - return "#%-4d %-9s %-8s %-9s x%-3d s%s %s" % (r["id"], r["status"], r["aim"], r["change_kind"], r["count"], - (r["strength"] or 1) if "strength" in r.keys() else 1, - " ".join(r["change"].split())[:100]) + return "#%-4d %-9s %-8s %-9s x%-3d s%s %s" % (_get(r, "id"), _get(r, "status"), _get(r, "aim"), _get(r, "change_kind"), _get(r, "count"), + (_get(r, "strength") or 1), + heading_text(r, 100)) + + +def plain_state(r): + """A lesson's state in plain words for the human digest (no internal labels).""" + if _get(r, "change_kind") == "tool": + return "change to sisi itself, not built yet" + folded = _get(r, "folded_into") or "" + if folded.startswith("rule:") or folded == "enforced" or _get(r, "check_json"): + return "in the rulebook" + if folded: + first = folded.split(",")[0].strip() + if first.startswith("draft:"): + first = first[6:] + if first: + return "attached to %s work" % first + if _get(r, "effect") == "field-note": + target = _get(r, "target") + if target: + return "attached to %s work" % target + return "loose note" + + +def digest_lines(include_all=False, con=None): + """`sisi lessons digest`: short lines grouped by topic, for the human.""" + own = con is None + if own: + con = connect() + try: + ensure_effects(con) + rows = [dict(r) for r in con.execute("SELECT * FROM lessons ORDER BY id")] + finally: + if own: + con.close() + if not include_all: + rows = [r for r in rows if r.get("status") not in ("retired", "withdrawn", "superseded")] + said = [] + try: + for rec in store.read("quarantine"): + t = " ".join(str(rec.get("text") or "").split()) + if t: + said.append(t) + except Exception: + said = [] + summarized = [r for r in rows if (r.get("short") or "").strip() and (r.get("topic") or "").strip()] + _summ_ids = {r["id"] for r in summarized} + pending = [r for r in rows if r["id"] not in _summ_ids] + n = len(rows) + if n == 1: + count_line = "Sisi has learned 1 lesson from past work, %d summarized and %d not yet summarized." % (len(summarized), len(pending)) + else: + count_line = "Sisi has learned %d lessons from past work, %d summarized and %d not yet summarized." % (n, len(summarized), len(pending)) + out = [count_line, ""] + if said: + out.append("## What you said") + for t in said: + out.append('- "%s"' % t) + out.append("") + groups = {} + for r in summarized: + groups.setdefault(" ".join(str(r["topic"]).split()), []).append(r) + for topic in sorted(groups, key=lambda t: (-len(groups[t]), t)): + out.append("## %s" % topic) + for r in sorted(groups[topic], key=lambda x: (-(x.get("count") or 1), x.get("id"))): + line = "- %s (lesson %d; %s" % (" ".join(str(r["short"]).split()), r["id"], plain_state(r)) + if (r.get("count") or 1) > 1: + line += "; seen %d times" % r["count"] + out.append(line + ")") + out.append("") + if pending: + out.append("## Not yet summarized") + for r in sorted(pending, key=lambda x: x.get("id")): + text = " ".join(str(r["short"]).split()) if (r.get("short") or "").strip() else word_cut(r.get("change") or "", 140) + line = "- %s (lesson %d; %s" % (text, r["id"], plain_state(r)) + if (r.get("count") or 1) > 1: + line += "; seen %d times" % r["count"] + out.append(line + ")") + out.append("") + out.append("To see one lesson in full, run `sisi lessons show ID` with the lesson number in place of ID.") + return out def cmd_lessons(argv): con = connect() try: + if argv and argv[0] == "digest": + extra = argv[1:] + if extra not in ([], ["--all"]): + print("usage: sisi lessons digest [--all]") + return 2 + for line in digest_lines(include_all="--all" in extra, con=con): + print(line) + return 0 if argv and argv[0] == "show": if len(argv) < 2 or not argv[1].isdigit(): print("usage: sisi lessons show ID") @@ -1125,6 +1370,8 @@ def cmd_lessons(argv): listed_count(con, r["id"]), read_count(con, r["id"]), recurrences_after_shown(con, r), sightings_count(con, r["id"]))) print("moment: %s\ncause : %s\nchange: %s" % (r["moment"], r["cause"], r["change"])) + print("short : %s" % (_get(r, "short") or "- (none yet; a learning cycle can write one)")) + print("topic : %s" % (_get(r, "topic") or "-")) print("when : %s" % (r["when_terms"] or "- (none recorded; a cycle can add terms)")) print("\noccurrences:") for o in con.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (r["id"],)): @@ -1205,7 +1452,7 @@ def cmd_lessons(argv): top = int(v) i += 2 else: - print("usage: sisi lessons [--aim A] [--kind K] [--status S] [--repo PATH] [--top N] [--json] | show ID | set ID --status S | apply ID | export [FILE] | import FILE") + print("usage: sisi lessons [--aim A] [--kind K] [--status S] [--repo PATH] [--top N] [--json] | show ID | digest [--all] | set ID --status S | apply ID | export [FILE] | import FILE") return 2 rows = [dict(r) for r in con.execute("SELECT * FROM lessons WHERE %s ORDER BY count DESC, last_seen DESC, id DESC" % " AND ".join(where), args)] if top: @@ -1230,7 +1477,9 @@ def stats(): by = {r[0]: r[1] for r in con.execute("SELECT status, count(*) FROM lessons GROUP BY status")} week = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 7 * 86400)) occ = con.execute("SELECT count(*) FROM occurrences WHERE ts>=?", (week,)).fetchone()[0] - top = [dict(r) for r in con.execute("SELECT id, change, count FROM lessons WHERE status IN ('open','applied') ORDER BY count DESC, last_seen DESC LIMIT 5")] + _cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")] + _sel = "id, change, count" + (", short" if "short" in _cols else "") + top = [dict(r) for r in con.execute("SELECT %s FROM lessons WHERE status IN ('open','applied') ORDER BY count DESC, last_seen DESC LIMIT 5" % _sel)] active = con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied')").fetchone()[0] strength = {r[0]: r[1] for r in con.execute( "SELECT COALESCE(strength,1), count(*) FROM lessons WHERE status IN ('open','applied') GROUP BY 1")} @@ -1284,5 +1533,5 @@ def cmd_backlog(argv): return 0 for r in rows: print("#%-4d x%-3d s%d shown %-3d %s" % (r["id"], r["count"], r["strength"] or 1, shown[r["id"]], - " ".join(r["change"].split())[:110])) + heading_text(r, 110))) return 0 diff --git a/sisi/tick.py b/sisi/tick.py index bb8fea8..36ebb48 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -53,8 +53,12 @@ def _backlog_line(cwd): rows = retro.backlog_rows() if not rows: return "" - t = retro.safe_line(rows[0]["change"], here) - return "top sisi backlog #%d (x%d): %s" % (rows[0]["id"], rows[0]["count"], (t or "")[:110]) + 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 "" diff --git a/tests/test_digest_short.py b/tests/test_digest_short.py new file mode 100644 index 0000000..9b5366c --- /dev/null +++ b/tests/test_digest_short.py @@ -0,0 +1,335 @@ +"""Short lines, topics, the human digest, and the cycle writing them.""" +import json, os, sqlite3, unittest +from support import * +from sisi import cycle, paths, retro, store +from test_verifiers import LibCase, vfile, dfile + +WHEN = "parser, fuzzing, codec, hostile input, generated input, parsing" + + +def fields(**kw): + f = dict(aim="verified", change_kind="rule", target=None, + moment="the parser server waited 90 seconds in step 4 of the nightly job", + cause="no readiness probe existed before the browser step", + change="Prefer a readiness probe over a fixed sleep when waiting for parser servers to answer", + when=WHEN) + f.update(kw) + return f + + +class ShortCase(LibCase): + def setUp(self): + super().setUp() + self.put("prove/fuzz.md", vfile("fuzz")) + self.put("parser-or-codec.md", dfile("parser-or-codec"), self.ddir) + self.notes = os.path.join(self.data, "notes") + + def mk(self, **kw): + con = retro.connect() + try: + lid = retro.new_lesson(con, fields(**kw), self.proj, None) + con.commit() + return lid + finally: + con.close() + + def lesson(self, lid): + con = retro.connect() + try: + return dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()) + finally: + con.close() + + def set_lesson(self, lid, **kw): + con = retro.connect() + try: + for k, v in kw.items(): + con.execute("UPDATE lessons SET %s=? WHERE id=?" % k, (v, lid)) + con.commit() + finally: + con.close() + + def cycle_doc(self, notes=None, **parts): + doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"} + if notes is not None: + doc["notes"] = notes + doc.update(parts) + p = os.path.join(self.tmp, "cycle.json") + with open(p, "w") as f: + json.dump(doc, f) + return p + + def cycle_path(self, doc): + p = os.path.join(self.tmp, "cycle-%s.json" % id(doc)) + with open(p, "w") as f: + json.dump(doc, f) + return p + + +class RetroShortTests(ShortCase): + def retro_cli(self, **over): + from test_retro import argv as retro_argv, GOOD + f = dict(GOOD) + f.update(over) + return self.sisi("retro", "--new", *retro_argv(f)) + + def test_retro_stores_short_and_topic(self): + r = self.retro_cli(short="Add fuzzing to the parser recipe checks.", topic="testing") + self.assertEqual(r.returncode, 0, r.stdout) + con = retro.connect() + rows = [tuple(r) for r in con.execute("SELECT short, topic FROM lessons")] + con.close() + self.assertEqual(rows[0], ("Add fuzzing to the parser recipe checks.", "testing")) + + def test_retro_without_short_says_next_round_will_write_it(self): + r = self.retro_cli() + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn("next learning round will write", r.stdout) + + def test_retro_limits_are_enforced(self): + long_short = "word " * 40 + "end." + self.assertEqual(self.retro_cli(short=long_short.strip()).returncode, 2) + self.assertEqual(self.retro_cli(short="Do the thing...").returncode, 2) + self.assertEqual(self.retro_cli(short="Do the thing\u2026").returncode, 2) + self.assertEqual(self.retro_cli(topic="Testing Stuff").returncode, 2) + self.assertEqual(self.retro_cli(topic="one two three four").returncode, 2) + self.assertEqual(self.retro_cli(topic="a" * 31).returncode, 2) + self.assertEqual(self.retro_cli(short="line one\nline two is long enough here.").returncode, 2) + con = retro.connect() + try: + self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0) + finally: + con.close() + + +class HeadingTests(ShortCase): + def test_word_boundary_cut_never_mid_word(self): + text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda" + cut = retro.word_cut(text, 30) + self.assertTrue(cut.endswith("\u2026"), cut) + self.assertTrue(text.startswith(cut[:-1]), cut) + self.assertEqual(text[len(cut[:-1])], " ") + self.assertLessEqual(len(cut), 30) + + def test_loose_heading_uses_short_when_present(self): + lid = self.mk(short="Use a readiness probe, not a sleep.", topic="testing") + row = self.lesson(lid) + self.assertIn("Use a readiness probe, not a sleep.", retro.loose_heading(row)) + + def test_loose_heading_without_short_is_word_cut(self): + lid = self.mk(change="Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma") + h = retro.loose_heading(self.lesson(lid)) + self.assertTrue(h.endswith("\u2026"), h) + body = h.split(": ", 1)[1][:-1] + self.assertTrue(self.lesson(lid)["change"].startswith(body)) + + def test_lessons_list_and_backlog_use_short(self): + lid = self.mk(short="Use a readiness probe, not a sleep.", topic="testing") + out = self.sisi("lessons").stdout + self.assertIn("Use a readiness probe, not a sleep.", out) + tool = self.mk(change_kind="tool", change="Make sisi cycle print much faster for very large lesson stores", + short="Make sisi cycle faster.", topic="sisi itself") + bout = self.sisi("backlog").stdout + self.assertIn("Make sisi cycle faster.", bout) + + +class DigestTests(ShortCase): + def seed_digest(self): + a = self.mk(short="Use a readiness probe, not a sleep.", topic="testing") + self.set_lesson(a, folded_into="rule:know-done", effect="learned-note", status="applied") + b = self.mk(change_kind="verifier", target="fuzz", + change="Seed the fuzz corpus from golden parser files before fuzzing anything", + moment="fuzz seeds were missing at step 5 of the job", + short="Seed the fuzz corpus from golden files.", topic="testing") + self.set_lesson(b, count=3) + c = self.mk(change="Ask the person before guessing when the request is unclear about success", + moment="a guess about success at step 2 was wrong", + short="Ask before guessing what success means.", topic="asking questions") + d = self.mk(change_kind="tool", change="Make sisi lessons digest group lessons by topic for the owner", + moment="the owner asked for a digest at step 1", + short="Group the digest by topic.", topic="releases") + e = self.mk(change="Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega extra words here", + moment="a long lesson moment at step 9") + f = self.mk(short="Retired short line should hide.", topic="testing") + self.set_lesson(f, status="retired", folded_into="rule:know-done") + return a, b, c, d, e, f + + def test_digest_grouping_plain_states_and_order(self): + a, b, c, d, e, f = self.seed_digest() + out = self.sisi("lessons", "digest").stdout + lines = out.splitlines() + self.assertTrue(lines[0].count(".") >= 1 and "lesson" in lines[0], lines[0]) + self.assertIn("5 lessons", lines[0]) + # topics by size: testing (2) before singletons, Not yet summarized last topical heading + self.assertLess(out.index("## testing"), out.index("## asking questions")) + self.assertLess(out.index("## asking questions"), out.index("## Not yet summarized")) + self.assertIn("Use a readiness probe, not a sleep.", out) + self.assertIn("in the rulebook", out) + self.assertIn("attached to fuzz work", out) + self.assertIn("loose note", out) + self.assertIn("change to sisi itself, not built yet", out) + self.assertIn("seen 3 times", out) + # seen only when > 1: lesson a has count 1, its line must not say seen + a_line = [l for l in lines if "lesson %d" % a in l][0] + self.assertNotIn("seen", a_line) + self.assertNotIn("#%d" % f, out) # retired left out by default + self.assertNotIn("Retired short line", out) + self.assertIn("lesson %d" % e, out) # every line shows its ID + last = [l for l in lines if l.strip()][-1] + self.assertIn("sisi lessons show", last) + low = out.lower() + for bad in ("strength", "field-note", "aim:"): + self.assertNotIn(bad, low) + + def test_digest_all_includes_retired_and_not_yet_is_word_cut(self): + a, b, c, d, e, f = self.seed_digest() + out = self.sisi("lessons", "digest", "--all").stdout + self.assertIn("Retired short line should hide.", out) + e_line = [l for l in out.splitlines() if "lesson %d" % e in l][0] + self.assertTrue(e_line.rstrip().endswith(("\u2026", ")")) or "\u2026" in e_line, e_line) + + def test_digest_shows_what_you_said_first(self): + self.seed_digest() + self.assertEqual(self.sisi("learn", "Always", "show", "the", "options.").returncode, 0) + out = self.sisi("lessons", "digest").stdout + self.assertIn("## What you said", out) + self.assertIn("Always show the options.", out) + self.assertLess(out.index("## What you said"), out.index("## testing")) + + +class CycleShortTests(ShortCase): + def test_brief_lists_lacking_topics_and_limits(self): + have = self.mk(short="Use a readiness probe, not a sleep.", topic="testing") + need = self.mk(change="Widget caching lesson about parser readiness probes for servers", + moment="widget wait at step 2") + out = cycle.brief_text() + self.assertIn("short line", out) + self.assertIn("#%d" % need, out) + self.assertIn("testing", out) # topics already in use + self.assertIn("140", out) + self.assertIn("30", out) + self.assertIn("set-short", out) + + def test_check_refuses_file_omitting_set_short_naming_lesson(self): + need = self.mk() + doc = self.cycle_doc(notes=[{"lesson": need, "action": "keep"}]) + r = self.sisi("cycle", "check", doc) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("set-short", r.stdout) + self.assertIn(str(need), r.stdout) + good = self.cycle_doc(notes=[{"lesson": need, "action": "keep"}, + {"lesson": need, "action": "set-short", + "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]) + r2 = self.sisi("cycle", "check", good) + self.assertEqual(r2.returncode, 0, r2.stdout + r2.stderr) + + def test_set_short_combined_and_limits_in_cycle(self): + lid = self.mk() + bad = self.cycle_doc(notes=[{"lesson": lid, "action": "set-short", + "short": "word " * 40, "topic": "testing"}]) + r = self.sisi("cycle", "check", bad) + self.assertEqual(r.returncode, 1, r.stdout) + good = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}, + {"lesson": lid, "action": "set-short", + "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]) + self.assertEqual(self.sisi("cycle", "apply", good).returncode, 0) + l = self.lesson(lid) + self.assertEqual((l["short"], l["topic"]), ("Use a readiness probe, not a sleep.", "testing")) + + def test_cycle_now_prints_brief_when_not_due(self): + self.assertEqual(self.sisi("cycle", "due").returncode, 1) + r = self.sisi("cycle", "--now") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn("Base version", r.stdout) + + +class BulletTests(ShortCase): + def test_field_note_bullet_uses_short_at_creation(self): + lid = self.mk(change_kind="verifier", target="fuzz", + change="Seed the fuzz corpus from golden parser files before fuzzing anything", + moment="fuzz seeds were missing at step 5", + short="Seed the fuzz corpus from golden files.", topic="testing") + text = open(os.path.join(self.notes, "fuzz.md")).read() + self.assertIn("Seed the fuzz corpus from golden files.", text) + self.assertIn("seen 1 times; lesson %d; full text: sisi lessons show %d" % (lid, lid), text) + + def test_bullet_rewrite_and_exact_revert(self): + lid = self.mk(change_kind="verifier", target="fuzz", + change="Seed the fuzz corpus from golden parser files before fuzzing anything", + moment="fuzz seeds were missing at step 5") + p = os.path.join(self.notes, "fuzz.md") + before = open(p, "rb").read() + self.assertIn(b"Seed the fuzz corpus from golden parser files", before) + doc = self.cycle_doc(notes=[{"lesson": lid, "action": "set-short", + "short": "Seed the fuzz corpus from golden files.", "topic": "testing"}]) + r = self.sisi("cycle", "apply", doc) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + after = open(p, "rb").read() + self.assertNotEqual(after, before) + self.assertIn(b"Seed the fuzz corpus from golden files.", after) + self.assertIn(("full text: sisi lessons show %d" % lid).encode(), after) + self.assertNotIn(b"Seed the fuzz corpus from golden parser files before fuzzing", after) + r = self.sisi("cycle", "revert") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual(open(p, "rb").read(), before) # exact bytes restored + l = self.lesson(lid) + self.assertIsNone(l["short"]) + self.assertIsNone(l["topic"]) + + def test_explicit_note_bullet_is_not_rewritten(self): + lid = self.mk(change="Parser recipes need a readiness probe before any server work begins", + moment="server wait at step 3") + doc = self.cycle_doc(notes=[ + {"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec", + "note": "Explicit split note about readiness probes"}, + {"lesson": lid, "action": "set-short", + "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]) + self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) + text = open(os.path.join(self.notes, "parser-or-codec.md")).read() + self.assertIn("Explicit split note about readiness probes", text) + # a later set-short in a new cycle also leaves the explicit bullet alone + self.set_lesson(lid, short=None, topic=None) + # restore base: the previous cycle changed the lesson, so clear via a fresh cycle file + doc2 = {"version": 1, "base": cycle.base_version(), "summary": "second", + "notes": [{"lesson": lid, "action": "set-short", + "short": "Prefer probes over sleeps.", "topic": "testing"}]} + p2 = self.cycle_path(doc2) + r = self.sisi("cycle", "apply", p2) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + text2 = open(os.path.join(self.notes, "parser-or-codec.md")).read() + self.assertIn("Explicit split note about readiness probes", text2) + self.assertNotIn("Prefer probes over sleeps.", text2) + + +class MigrationTests(ShortCase): + def test_old_store_without_fields_still_loads(self): + old = os.path.join(self.tmp, "old.db") + con = sqlite3.connect(old) + con.executescript(""" + CREATE TABLE lessons(id INTEGER PRIMARY KEY, created TEXT, aim TEXT, change_kind TEXT, target TEXT, + moment TEXT, cause TEXT, change TEXT, status TEXT DEFAULT 'open', count INTEGER DEFAULT 1, last_seen TEXT); + CREATE TABLE occurrences(id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, tool TEXT, + cwd TEXT, repo TEXT, moment TEXT, fp TEXT); + """) + con.execute("INSERT INTO lessons VALUES (1,'2020-01-01T00:00:00Z','speed','verifier','fuzz','m','c'," + "'Seed the fuzz corpus from golden parser files','open',2,'2020-01-02T00:00:00Z')") + con.commit(); con.close() + import shutil + os.makedirs(os.path.dirname(retro.db_path()), exist_ok=True) + shutil.copy(old, retro.db_path()) + con = retro.connect() + try: + row = dict(con.execute("SELECT * FROM lessons WHERE id=1").fetchone()) + cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")] + finally: + con.close() + self.assertIn("short", cols) + self.assertIn("topic", cols) + self.assertEqual(row["change"], "Seed the fuzz corpus from golden parser files") + self.assertIsNone(row["short"]) + out = self.sisi("lessons", "digest").stdout + self.assertIn("Seed the fuzz corpus", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_learning.py b/tests/test_learning.py index b9f67c5..ac35253 100644 --- a/tests/test_learning.py +++ b/tests/test_learning.py @@ -55,6 +55,35 @@ class LearningCase(LibCase): def cycle_doc(self, **parts): doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"} doc.update(parts) + # A cycle file must now summarise every active lesson lacking a short line: + # add a set-short for any not already covered or leaving the active notes. + try: + con = retro.connect() + try: + rows = [dict(r) for r in con.execute( + "SELECT id, short, topic FROM lessons WHERE status IN ('open','applied')")] + finally: + con.close() + notes = list(doc.get("notes") or []) + covered = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-short"} + exempt = {e.get("lesson") for e in notes if isinstance(e, dict) + and e.get("action") in ("retire", "withdraw", "merge")} + extra = [] + for r in rows: + if r["id"] in covered or r["id"] in exempt: + continue + if (r.get("short") or "").strip() and (r.get("topic") or "").strip(): + continue + e = {"lesson": r["id"], "action": "set-short"} + if not (r.get("short") or "").strip(): + e["short"] = "Use a readiness probe, not a sleep." + if not (r.get("topic") or "").strip(): + e["topic"] = "testing" + extra.append(e) + if extra: + doc["notes"] = notes + extra + except Exception: + pass p = os.path.join(self.tmp, "cycle.json") with open(p, "w") as f: json.dump(doc, f) @@ -445,8 +474,9 @@ class CycleApplyTests(LearningCase): a = self.mk(change="Session one lesson about parser readiness", moment="s1 wait at step 1") b = self.mk(change="Session two lesson about widget caching", moment="s2 wait at step 2") base = cycle.base_version() # both sessions read the same brief - doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}]} - doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}]} + _ss = lambda lid: {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"} + doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b)]} + doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b)]} paths_ = [] for i, d in enumerate((doc1, doc2)): p = os.path.join(self.tmp, "two-%d.json" % i) @@ -1020,7 +1050,8 @@ class CycleGapTests(LearningCase): retro.record_shown([lid], "done-for", "s") doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}]) # cycle_doc recomputes base; rebuild with the original base - d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}]} + d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}, + {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]} p = os.path.join(self.tmp, "g2.json") with open(p, "w") as f: json.dump(d, f) @@ -1044,7 +1075,8 @@ class CycleGapTests(LearningCase): lid = self.mk() base = cycle.base_version() self.mk(change="Brand new parser lesson arriving mid cycle", moment="new wait at step 5") - d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}]} + d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}, + {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]} p = os.path.join(self.tmp, "g3.json") with open(p, "w") as f: json.dump(d, f)