Learning loop: the thirteen review findings fixed

Replay validation only counts a real failure before the fix, in a trusted project;
a mechanism carries the scope its learning has earned and anything wider, unproven
or weakening waits for the owner; approval shows the full action and refuses a
non-terminal; delivery only from sisi's own ledger; subagent findings are held;
the migration merges by legacy id and reports what it skipped; promote and export
work from learning records.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 12:07:18 -07:00
commit 7a32e6dc1d
21 files changed
+3143 -1164

No files matched your search

+34
View File
@@ -16,6 +16,40 @@ written by someone else, and it is treated as such.
- Every check has a time limit. After a few send-backs in a row the gate lets the agent through and marks the
result unverified, so a broken check cannot hold a session forever.
## What learning can change, and who decides
A learning cycle can install checks, rules and risk patterns that shape later sessions. What it may do alone is
limited, and the rest waits for you:
- A mechanism a cycle installs carries its learning's id and the scope that learning has earned (its own project,
unless it was seen in two units in two projects, or you stated it at user scope). Nothing the cycle file claims
about scope or project is trusted: a request for more only makes the change wait.
- These always wait for you: more scope than earned, a shell command that was not seen to fail and then pass in its
own trusted project, a risk pattern that lowers a profile, any replaced or disabled rule, and rule text or a
library entry from a learning confined to one project. Protected rules (`canon/protected.json`) cannot be changed
by a cycle or by `sisi overlay` at all, and if that file cannot be read, no rule can be changed.
- Replaying a command check runs it, so a replay happens only in a repository on the trust list, only if the
command exists at both commits, and only if the earlier commit is an ancestor of the later one.
`sisi approve` lists every waiting change in full (the exact command, the pattern and profile, the rule text as a
diff) and decides it with `--yes` or `--no`. What this does guarantee: a decision from a process with no terminal
(an agent, a script, a pipe) is refused, unless your config has `learning.agent_relayed_approval` set (off by
default), and then the record says `relayed by an agent`; every decision is written to `approvals.jsonl` with the
time, the session if known, and whether it came from a terminal. What it does not guarantee: sisi cannot tell a
person at a terminal from a program that allocates one, and anyone who can write your personal data folder can
edit the config, the pending list or the ledger directly. The protection is that an agent is told to show you the
change and to give you the command to type yourself, and that the cycle cannot apply anything consequential on its
own; it is not a defence against code that already runs with your permissions.
The same limit applies to who recorded something. A learning recorded from a subagent is held as a candidate until
the parent adopts it by id. "Recorded by a subagent" is read from what the hooks recorded in the session record, not
from the environment; a tool without those hooks, or a process that picks another session id, is not detected. A
row added or edited by hand in `learnings.jsonl` is never delivered: only rows that sisi's own commands wrote, as
they wrote them, are in the ledger. `sisi learn` records whether your words appear in a message you typed in the
session transcript; when they do not, or there is no transcript, the statement is marked `relayed by an agent`
and `sisi oracle` shows that. `sisi learn --withdraw ID --reason ...` takes a statement recorded by mistake out of
delivery for good.
## What sisi does not protect against
- A trusted project's contract runs with your permissions. Trust only projects you trust.
+5 -1
View File
@@ -86,7 +86,11 @@ the user store (a learning cycle applied to the copy, not to the real store): it
sample of dev cases plus every counterexample under the current policy and the candidate
and prints the comparison, before anyone is asked to approve the change [11.6]. The
learning loop calls the same code as `sisi.evaluate.compare_for_candidate(dir, sample)`,
and calls `sisi.evaluate.validate_check(case)` before promoting a command check.
and calls `sisi.evaluate.validate_command(repo, before, after, cmd)` before promoting a command
check: `validated` only if the command ran and failed at `before` and ran and passed at `after`
(program present at both commits; not 126/127, a timeout or a signal), `before` an ancestor of
`after`, in a repository on the trust list. A stored case is replayed the same way by
`validate_check(case)`.
## Independent judging
+104 -46
View File
@@ -36,20 +36,40 @@ sisi retro --finding "<what happened, with the evidence>" --cause "<root cause>"
[--same-as ID]
```
At least one finding per closed unit; generic findings ("be more careful") are refused.
Search terms, topics and short lines are derived by the tool, never demanded. A finding
that resembles an existing learning is attached to it as a recurrence candidate — it is
recorded, not refused. Learnings recorded in a subagent session are held as candidates
until a parent retro adopts them (`--same-as`).
At least one finding per closed unit. A finding that is only generic advice is refused wherever
the filler appears ("be more careful when writing tests in future"); a short specific one is
accepted ("Tests flaked on CI: 3 of 10 runs"). Things that look like keys, tokens or passwords are
replaced by `<redacted>` before a finding or a learning is stored. Search terms, topics and short
lines are derived by the tool, never demanded.
A finding that resembles a learning **in force in this project** is attached to it as a recurrence,
and the match is printed; `--new` records the finding as a learning of its own instead. Resemblance
searches nothing else. `--same-as ID` names the learning it repeats; for a learning from another
project the finding must plainly be the same thing, and it is that project's own evidence (a unit
there) that adds the provenance, never the resemblance. A unit is counted once for a learning, so
repeating a retro in one unit inflates nothing.
Recorded by a subagent means what the hooks recorded: tick marks a session that started as a
subagent, and the watch hook records, for each shell command, whether its hook payload came from
a subagent (an agent id or a subagent transcript path). `sisi retro` reads that session record; no
environment variable decides it. A subagent's learning is held as a candidate and attaches to nothing;
the parent adopts it with `sisi retro --adopt ID`, never by resemblance. `--target ID` names the rule,
recipe or technique a learning concerns, so `sisi rule`, `sisi done` and `sisi verifiers show` can
list the learnings behind it.
## Scope is earned
A learning is in force in the project it came from at once. It is delivered in other
projects only when its provenance holds at least two units in at least two projects, or
it is an owner statement. One incident never becomes a universal rule. Text delivered
into a prompt is framed as background information to weigh, never as an instruction,
and only learnings that entered through sisi's own commands (`retro`, `learn`, `cycle`,
migration) are ever delivered. Silence is the default.
A learning is in force in the project it came from at once. It is delivered in other projects only
when its provenance holds at least two units in at least two projects (`organization` scope), or it is
an owner statement made at user scope; a project-scoped statement is delivered only in its project. One
incident never becomes a universal rule. Text delivered into a prompt is framed as background
information to weigh, never as an instruction. Relevance is scored against the learning's own terms, so
a long prompt does not dilute a real match; silence is the default.
Only rows that sisi's own commands wrote, as they wrote them, are delivered or acted on. Each such
command appends the id and content digest of what it wrote to `learnings-ledger.jsonl`, in the same
commit as the row; a row added by hand, or edited by hand, has no matching entry and is never delivered
(`sisi lessons` and the learning report name it). A later sisi write does not launder it.
## The cycle
@@ -64,57 +84,95 @@ adjustment (`overlay/risk-adjustments.json`), a routing adjustment
refused by the cycle; they go to the backlog shown in the learning report and to the
contribution export.
`sisi cycle apply FILE` treats the file as untrusted input and validates everything
before changing anything — a refusal applies nothing:
`sisi cycle apply FILE` treats the file as untrusted input and plans everything before writing anything —
the budget and every other check run first, and a refusal applies nothing. If applying then fails part-way
(a full disk), every file the cycle wrote is restored.
- **Replay before promotion.** A command check is run in a temporary git worktree at
the before-commit and the after-commit of the unit it came from; it must fail before
the fix and pass after. Only then is the learning `validated`. What cannot be
replayed is promoted as `unvalidated` and always reported as such. A replay that
fails refuses the whole cycle. Replay never touches the user's working tree.
- **Protected rules** (`canon/protected.json`: verification before done, truthful
reporting, this governance) cannot be replaced or disabled by a cycle at all.
- **Consequential changes wait for the owner**: disabling any other rule, widening a
scope to all projects, or a command check for every project is stored as pending and
takes effect only after `sisi approve ID --yes|--no`. Session start prints one line
while a decision is waiting.
- **A mechanism reaches only what its learning earned.** Each entry written carries the learning id,
the scope the learning has earned (`learning.earned_scope`: its origin project unless it earned more)
and the origin project. Enforced checks, risk and routing adjustments are filtered by project when read.
A scope or `every_project` flag in the cycle file is a request for more, never the gate.
- **Replay before promotion** (`evaluate.validate_command`, the one replay implementation). A command check
is run in a temporary git worktree at the before-commit and the after-commit, and is `validated` only
if it **ran and failed** before the fix (not exit 126/127, not a timeout, not killed by a signal; its
program, and a script given to an interpreter, must exist at *both* commits) and ran and passed after.
The repository must be the learning's origin project and on the trust list, and `before` must be an
ancestor of `after`; otherwise the result is `unvalidated`, with the reason. A replay that ran and
behaved wrongly refuses the whole cycle. Replay never touches the working tree.
- **Protected rules** (`canon/protected.json`) cannot be replaced or disabled by a cycle or by
`sisi overlay`. If the file cannot be read, no rule can be changed.
- **Consequential changes wait for the owner**: more scope than the learning earned; an enforced command
not proven by replay (or that would run outside its origin project); a risk pattern that lowers a
profile; any replacement or disabling of a rule; rule text or a library entry from a learning confined to
one project; `sisi overlay replace-rule` and `disable-rule`. They are stored as pending and take effect
only after `sisi approve ID --yes|--no`.
- **`sisi approve`** with no arguments lists every waiting change in full: the command, the pattern and
profile, the rule text as a diff, why it needs the owner, and the replay result. A decision made without
a terminal (an agent, a script) is refused unless the user config sets `learning.agent_relayed_approval`;
every decision is recorded in `approvals.jsonl` (when, session, terminal or not, `relayed by an agent`).
Session start prints one line while a decision is waiting, telling the agent to ask the owner through
the host's question dialog and to give him the command to run himself. SECURITY.md says what this does and
does not guarantee.
- **Flagged learnings must be acted on** (below); a cycle that ignores one is refused.
- Each change is its own commit in the user store, and the cycle records the
before/after commits, so `sisi cycle revert [ID]` restores the store exactly.
- Each change is its own commit in the user store, and each cycle (and each approval) is recorded with the
files and learning fields it changed. `sisi cycle revert [ID]` undoes exactly those: statements, findings
and recurrences recorded after the cycle survive, and a revert is refused if a later change touched the
same file.
- A learning that was validated but waits for the owner has status `validated`; once promoted and a unit in
its scope has closed, or it has recurred, `monitored`.
## Monitoring
A recurrence after promotion counts against the learning. Two flag it "not working";
A recurrence after promotion counts against the learning (once per unit). Two flag it "not working";
the next cycle must revise or revert it. `sisi status --learning` prints
`learning.learning_report()`: per promoted learning the units since promotion, the
recurrences, whether it is validated or unvalidated, and the verdict, plus the
realization rate (promoted learnings holding with no recurrence over at least five
relevant units) — or "too few" when the numbers are small. No claim of improvement is
printed from counts of records.
`learning.learning_report()`: per promoted learning the units in its own scope since promotion
(read from `units.jsonl` in the user store, one JSON object per line with `id`, `project`, `closed_at`,
`risk`; the file may not exist yet, which counts as none), the recurrences, whether it is validated or
unvalidated, and the verdict, plus the realization rate (promoted learnings holding with no recurrence over
at least five units in their scope) — or "too few" when the numbers are small. A project-scoped learning
counts only its project's units. No claim of improvement is printed from counts of records.
## Owner statements
One path: `sisi learn "<what you want>"` writes an owner statement into the same
learning store, live at once and delivered in every project; `sisi oracle` prints them.
The old `learn.jsonl` / `oracle.md` stores were merged into it by migration.
One path: `sisi learn "<what you want>"` writes an owner statement into the same learning store, live
at once; `sisi oracle` prints the ones in force in the current project. A user-scope statement is
delivered everywhere, a project-scoped one only in its project. The record says whether the quoted words
appear in a human-typed message of the session transcript (`typed by the owner`) or not, or no transcript is
available (`relayed by an agent`); it is never blocked, and `sisi oracle` shows the relayed ones as such.
`sisi learn --withdraw ID --reason "..."` withdraws a statement recorded by mistake: kept in its history,
never delivered again.
## Migration
`sisi update` (and `sisi migrate`) runs the learning migration once, with a backup
first and idempotently: old lesson rows become learning records with honest statuses (a
lesson folded into prose is `implemented`, always unvalidated; nothing becomes
`validated`), occurrences become provenance, impressions — sisi's own showings — are
dropped, and owner statements join the same store. A store with only the old sqlite
database is read from the database itself. Learnings whose provenance does not meet
the two-units-two-projects rule are delivered only in their origin project, whatever
scope they once claimed.
`sisi update` (and `sisi migrate`, and `sisi learn`/`sisi oracle`) run the learning migration whenever the
old store exists and the `learnings-migrated.json` marker does not: a backup first, merged by legacy id
(a lesson already carried over is not carried twice; a learning recorded before the first migration does
not stop it). Old lesson rows become learning records with honest statuses (a lesson folded into prose
is `implemented`, always unvalidated; nothing becomes `validated`); occurrences become provenance with the
old `repo` values normalised to the project key new code uses, and only occurrences that attach to a
lesson are counted; impressions, sightings and pattern rows are not carried (the backup keeps them);
owner statements join the same store with their scope, duplicates dropped. Malformed lines are counted and
reported, not hidden. A migrated learning is earned beyond its project only under the same
two-units-two-projects rule as a new one. The sqlite store is read too.
## The product
`sisi promote --export` writes the contribution file for `tool` learnings and for learnings that earned
organization scope (scrubbed: no history, no user or project names); `sisi promote L-NNNN [--apply]`
writes the rule or recipe such a learning was folded into into the source folder and marks the learning
`in_product`. `sisi handover` lists the project-scope learnings and statements waiting to be filed in
their own project's documents. `sisi rule ID`, `sisi done ID` and `sisi verifiers show ID` list the
learnings in scope that target that entry.
## Seams for other parts of sisi
- `learning.findings_for_unit(project, unit_id)` — the findings a unit record stores.
- `learning.learning_report()` — the text `sisi status --learning` prints. It replaces
`sisi improve`, `sisi backlog` and `sisi lessons digest`, which are deleted.
- `cycle.enforced_results(contract, project, ...)` — what `sisi verify` runs.
- `cycle.due_notice()` — the one session-start line (cycle due, decision waiting).
- `cycle.enforced_results(contract, project, ...)` — what `sisi verify` runs, filtered by project.
- `cycle.risk_patterns(cwd)` — the learned risk patterns that apply in a project (`risk.load_patterns`).
- `cycle.routing_adjustments(project)` — the learned routing adjustments that apply in a project.
- `cycle.due_notice()` — the session-start lines (cycle due, decision waiting).
- `retro.satisfied(repo, since, fp)` and `retro.TEMPLATE` — what the gate asks.
- `learning.delivery_text(project, query)` — what the prompt hook may add.
- `learning.delivery_text(project, query, targets=())` — what the prompt hook may add.
- `evaluate.validate_command(repo, before, after, cmd)` — the replay.
+19 -12
View File
@@ -27,39 +27,46 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change
sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md)
sisi rollback switch the stable copy back to the previous release
sisi promote [ID|lesson:N] [--apply] | --export [PATH]
no ID: list core-tier items not yet in the product; an ID
scrubs a personal overlay item into the source folder and
drops the personal copy once the product contains it (dry
run unless --apply); lesson:N promotes a core lesson on a
from the clone; --export writes a contribution file
sisi promote [ID|L-NNNN] [--apply] | --export [PATH]
no ID: list items not yet in the product (learnings that change
sisi itself, or earned organization scope); an ID scrubs a
personal overlay item into the source folder and drops the
personal copy once the product contains it (dry run unless
--apply); L-NNNN promotes the rule or recipe a learning was
folded into, from the clone; --export writes a contribution file
(universal text only; nothing is sent anywhere)
sisi update fast-forward the product clone, then back up, migrate and rebuild personal data
sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it
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 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]
sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]
record one finding; promote also needs --change, --mechanism,
--expect and --validate; record needs --limits; drop needs --why-not
--expect and --validate; record needs --limits; drop needs --why-not;
a match in scope is printed and attached as a recurrence (--new records
a learning of its own); --target names the rule or recipe it concerns
sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id
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 approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one
(in a terminal: an agent's --yes without one is refused)
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 learn --withdraw ID --reason WHY
take a statement recorded by mistake out of delivery (kept in history)
sisi risk [--json] risk floor for the working-tree change, with reasons and
what that profile requires
sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]
project items waiting to be filed in this project's own docs or
project-scope learnings waiting to be filed in this project's own docs or
work list; done confirms one is filed (the named file must contain
its key text) and removes it from the pile
its key text) and removes it from the list
sisi oracle print what the human wants: the standing principles from
`sisi learn`, live at once (oracle.md in the personal folder)
`sisi learn`, live at once (project-scoped ones only in their project)
sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)
sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]
list ways to know work is correct, by section
+675 -304
View File
File diff suppressed because it is too large. Load diff
+120 -6
View File
@@ -6,14 +6,15 @@ checks the named commit out into a temporary git worktree and removes it afterwa
Seams for the other parts of sisi (plain functions, see docs/evaluation.md):
capture_case(unit_record) called when a work unit closes
validate_check(case) called by the learning cycle before it promotes a command check
validate_check(case) replay a stored case's checks at its two commits
validate_command(repo, before, after, cmd) the learning cycle's replay of one command (trusted repo, ancestry, ran-and-failed)
compare_for_candidate(dir, sample) called for a consequential policy change before the owner is asked
Standard library only. Replay of ``task`` cases goes through the existing delegation runner
(``sisi.workers.run_delegation``) unless a caller injects ``worker_runner`` or names a
``--worker-cmd``; tests always inject a fake, so no test calls a real AI tool.
"""
import hashlib, json, math, os, re, shutil, statistics, subprocess, sys, tempfile, time, uuid
import hashlib, json, math, os, re, shlex, shutil, statistics, subprocess, sys, tempfile, time, uuid
from . import paths, store
@@ -395,8 +396,81 @@ class _Worktree:
return False
SHELL_BUILTINS = frozenset((":", "true", "false", "test", "[", "[[", "echo", "printf", "exit", "cd", "set",
"export", "unset", "read", "type", "command", "eval", "exec", "return", "source", ".",
"if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case",
"esac", "!", "{", "}", "(", ")", "time", "wait"))
INTERPRETERS = frozenset(("python", "python3", "sh", "bash", "zsh", "dash", "node", "ruby", "perl"))
SCRIPT_EXT = (".py", ".sh", ".js", ".rb", ".pl", ".mjs")
_OPERATORS = frozenset((";", "&&", "||", "|", "&", "(", ")", ";;", "|&"))
def exit_not_ran(code):
"""True when an exit status says the command never really ran: not found (127), not
executable (126), a negative status (killed by a signal, as Python reports it), or the
128+signal a shell reports for a child that was killed."""
return code is None or code < 0 or code in (126, 127) or 129 <= code <= 159
def _segments(cmd):
"""The simple commands of a shell line, as token lists (operators split them). None when the
line does not parse."""
try:
lex = shlex.shlex(str(cmd), posix=True, punctuation_chars=True)
lex.whitespace_split = True
toks = list(lex)
except ValueError:
return None
segs, cur = [], []
for t in toks:
if t in _OPERATORS:
if cur:
segs.append(cur)
cur = []
else:
cur.append(t)
if cur:
segs.append(cur)
return segs
def unresolved_program(cmd, cwd):
"""Why the command's program(s) cannot be found in the tree at ``cwd`` (None when every one
resolves). A path program, and a script given to an interpreter, must exist in this tree, so a
check that only exists in the later commit cannot count as failing in the earlier one."""
segs = _segments(cmd)
if not segs:
return "the command does not parse or is empty"
for seg in segs:
i = 0
while i < len(seg) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i]):
i += 1 # leading VAR=value assignments
if i >= len(seg):
continue
prog = seg[i]
if prog in SHELL_BUILTINS:
continue
if "/" in prog:
target = prog if os.path.isabs(prog) else os.path.join(cwd, prog)
if not (os.path.isfile(target) and os.access(target, os.X_OK)):
return "program %s does not exist in this commit" % prog
elif shutil.which(prog) is None:
return "program %s is not on PATH" % prog
if os.path.basename(prog) in INTERPRETERS:
rest = seg[i + 1:]
if "-c" in rest or "-m" in rest or "-e" in rest:
continue
script = next((t for t in rest if not t.startswith("-")), None)
if script and ("/" in script or script.endswith(SCRIPT_EXT)):
target = script if os.path.isabs(script) else os.path.join(cwd, script)
if not os.path.isfile(target):
return "script %s does not exist in this commit" % script
return None
def _run_checks(case, cwd, timeout_s):
"""Run the case's checks in ``cwd``. Returns (rows, timed_out); rows carry exit/passed."""
"""Run the case's checks in ``cwd``. Returns (rows, timed_out); rows carry exit/passed and
``ran``: False when the command never really ran (program missing, exit 126/127, killed)."""
rows, timed_out = [], False
for c in case.get("checks") or []:
expect = (c.get("expect") or {})
@@ -405,17 +479,23 @@ def _run_checks(case, cwd, timeout_s):
want = int(want)
except (TypeError, ValueError):
want = 0
why = unresolved_program(c.get("cmd"), cwd)
if why:
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False,
"expected_exit": want, "passed": False, "error": why})
continue
try:
r = subprocess.run(str(c.get("cmd")), shell=True, cwd=cwd, capture_output=True,
text=True, timeout=timeout_s)
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": r.returncode,
"ran": not exit_not_ran(r.returncode),
"expected_exit": want, "passed": r.returncode == want})
except subprocess.TimeoutExpired:
timed_out = True
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None,
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False,
"expected_exit": want, "passed": False, "timed_out": True})
except OSError as e:
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None,
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False,
"expected_exit": want, "passed": False, "error": str(e)})
return rows, timed_out
@@ -452,8 +532,14 @@ def _replay_check(case, timeout_s):
if timed_out:
return {"outcome": "not-run", "reason": "check timed out at the %s commit" % label,
"check_results": results + [dict(r, at=label) for r in rows]}
seen[label] = passed
results += [dict(r, at=label) for r in rows]
stuck = [r for r in rows if not r.get("ran", True)]
if stuck:
return {"outcome": "not-run", "check_results": results,
"reason": "the check could not run at the %s commit (%s); a check that did "
"not run proves nothing" % (label, stuck[0].get("error")
or "exit %s" % stuck[0].get("exit"))}
seen[label] = passed
except RuntimeError as e:
return {"outcome": "not-run", "reason": str(e), "check_results": results}
if case.get("split") == "counterexample":
@@ -492,6 +578,34 @@ def validate_check(case, store_dir=None, timeout_s=None, record=False):
return out
def validate_command(repo, before, after, cmd, expect_exit=0, timeout_s=None, store_dir=None):
"""Replay one command at two commits of a local, trusted repository: ``validated`` only when
it ran and failed at ``before`` and ran and passed at ``after``. Anything that stops the
command from really running (program missing at either commit, exit 126/127, a timeout, a
signal) is ``not-run`` with the reason, never a failure. ``before`` must be an ancestor of
``after``; the repository must be a project on the trust list. Returns the replay outcome
dict (``outcome``, ``reason``, ``check_results``); nothing is recorded."""
from . import trust
repo = os.path.realpath(str(repo or ""))
if not os.path.isdir(repo) or _is_remote(repo):
return {"outcome": "not-run", "reason": "the repository is not a local directory", "check_results": []}
if not trust.is_trusted(repo):
return {"outcome": "not-run", "check_results": [],
"reason": "the repository is not on the trust list (`sisi contract trust` in it), "
"so its commands are not replayed"}
if not _commit_exists(repo, before) or not _commit_exists(repo, after):
return {"outcome": "not-run", "reason": "a commit is missing in the repository", "check_results": []}
rc, _o, _e = _git(repo, "merge-base", "--is-ancestor", str(before), str(after))
if rc != 0:
return {"outcome": "not-run", "check_results": [],
"reason": "the before commit is not an ancestor of the after commit"}
case = {"id": "replay", "kind": "check", "split": "dev",
"project": {"repo": repo, "start_commit": str(before), "fix_commit": str(after)},
"checks": [{"id": "c", "cmd": str(cmd), "expect": {"exit": expect_exit}}]}
timeout_s = float(timeout_s or _eval_config(store_dir)["timeout_s"])
return _replay_check(case, timeout_s)
def _rulebook_text(policy_dir):
for p in (os.path.join(policy_dir, "generated", "core.md"), paths.canon("core.md")):
try:
+37 -95
View File
@@ -1,80 +1,53 @@
"""Project handover pile: project-scoped items leave the global store.
"""Project handover: project-scope records leave sisi's care for the project's own documents.
Scoping a lesson or a `sisi learn` statement to a project moves it here: a pile in
the personal store, keyed by project id, kept only until an agent files it in that
project's own design documentation or work list and confirms with
`sisi handover done ID --where PATH`. After confirmation the item is gone from
every global listing; a small filed log (id, project, path, date) keeps the trace,
and the personal store's git history keeps the rest.
A learning or `sisi learn` statement the owner (or the retro) scoped to a project, explicitly,
waits here until an agent files it in that project's own design documentation or work list and
confirms with `sisi handover done ID --where PATH`. The items are read from the learning store;
a small filed log (id, project, path, date) keeps the trace of what was filed, and the user
store's git history keeps the rest.
"""
import json, os
from . import paths, scope, store
def pile_path():
return paths.data_file("handover.json")
from . import learning as L, paths, scope
def filed_path():
return paths.data_file("handover-filed.jsonl")
def _filed():
return {r.get("hid") for r in L._read_jsonl(filed_path())[0]}
def _item(r):
pr = r.get("proposed") or {}
return {"hid": r["id"], "kind": "learn" if r.get("owner_statement") else "lesson", "lesson_id": r["id"],
"project": r.get("origin_project"), "date": r.get("created") or "",
"text": pr.get("description") or r.get("title"), "change": pr.get("description"),
"short": r.get("title"), "aim": (r.get("observation") or {}).get("impact"),
"change_kind": pr.get("mechanism"), "moment": (r.get("observation") or {}).get("evidence"),
"cause": r.get("root_cause"),
"occurrences": [{"ts": p.get("ts"), "repo": p.get("project"), "tool": None}
for p in r.get("provenance") or []]}
def load_pile():
try:
with open(pile_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, list) else []
except (OSError, ValueError):
return []
def save_pile(items):
os.makedirs(os.path.dirname(pile_path()), exist_ok=True)
tmp = pile_path() + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
json.dump(items, f, indent=1, sort_keys=True, ensure_ascii=False)
f.write("\n")
os.replace(tmp, pile_path())
def _next_hid(items):
n = len(items)
try:
with open(filed_path(), encoding="utf-8") as f:
n += sum(1 for _ in f)
except OSError:
pass
return "h%d" % (n + 1)
def add_item(item):
items = load_pile()
item = dict(item)
item.setdefault("hid", _next_hid(items))
item.setdefault("date", store.now())
items.append(item)
save_pile(items)
return item
"""Project-scope records waiting to be filed: explicitly scoped to a project, written by sisi's
own commands, not withdrawn, not yet filed."""
ledger = L.load_ledger()
done = _filed()
return [_item(r) for r in L.load_learnings()
if (r.get("proposed") or {}).get("scope_asked") == "project" and L.is_registered(r, ledger)
and r.get("status") not in L.ENDED and not r.get("candidate") and r["id"] not in done]
def for_project(pid):
return [it for it in load_pile() if it.get("project") == pid]
def counts_by_project():
out = {}
for it in load_pile():
out[it.get("project") or ""] = out.get(it.get("project") or "", 0) + 1
return out
def notice(cwd):
"""The session-start / request-time line inside the owning project only."""
try:
items = for_project(scope.project_id(cwd))
except Exception:
return ""
items = for_project(scope.project_id(cwd))
if not items:
return ""
return ("sisi: %d item(s) recorded by sisi belong to this project. File each in this project's own "
@@ -88,37 +61,6 @@ def _norm(t):
return " ".join(str(t or "").split()).lower()
def move_lesson(con, lesson_id, pid):
"""Copy a lesson (with its occurrences, the historical example) into the pile and remove
it from the delivered global data. Returns the pile item, or None."""
r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone()
if r is None:
return None
d = dict(r)
occ = [dict(o) for o in con.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (lesson_id,))]
item = {"kind": "lesson", "lesson_id": d["id"], "project": pid,
"date": d.get("created") or store.now(),
"aim": d.get("aim"), "change_kind": d.get("change_kind"), "target": d.get("target"),
"change": d.get("change"), "short": d.get("short"), "when": d.get("when_terms"),
"moment": d.get("moment"), "cause": d.get("cause"),
"occurrences": [{"ts": o.get("ts"), "repo": o.get("repo"), "cwd": o.get("cwd"),
"tool": o.get("tool"), "session": o.get("session"), "moment": o.get("moment")}
for o in occ]}
con.execute("DELETE FROM impressions WHERE lesson_id=?", (lesson_id,))
con.execute("DELETE FROM sightings WHERE lesson_id=?", (lesson_id,))
# the occurrence rows stay: they are the history of the work itself (and what satisfies
# the retro gate for that session), not delivered lesson data
con.execute("DELETE FROM lessons WHERE id=?", (lesson_id,))
return add_item(item)
def move_learn(rec, pid):
item = {"kind": "learn", "project": pid, "date": rec.get("ts") or store.now(),
"text": rec.get("text"), "cwd": rec.get("cwd"),
"occurrences": [{"ts": rec.get("ts"), "repo": rec.get("cwd"), "tool": rec.get("tool")}]}
return add_item(item)
def _find(items, ident):
for it in items:
if str(ident) in (str(it.get("hid")), str(it.get("lesson_id") or "")):
@@ -138,7 +80,7 @@ def _item_lines(it):
if it.get("kind") == "learn":
out.append(' what the owner said: "%s"' % " ".join(str(it.get("text") or "").split()))
else:
out.append(" lesson #%s (%s/%s): %s" % (it.get("lesson_id"), it.get("aim"), it.get("change_kind"),
out.append(" learning %s (%s/%s): %s" % (it.get("lesson_id"), it.get("aim"), it.get("change_kind"),
" ".join(str(it.get("change") or "").split())))
if it.get("short"):
out.append(" short: %s" % it["short"])
@@ -201,12 +143,12 @@ def main(argv):
"first, or pass --quote with a quoted fragment of the item that the file does contain."
% (where, " ".join(str(need).split())[:120]))
return 1
save_pile([x for x in items if x is not it])
rec = {"hid": it.get("hid"), "kind": it.get("kind"), "lesson_id": it.get("lesson_id"),
"project": it.get("project"), "where": ap, "date": store.now()}
os.makedirs(os.path.dirname(filed_path()), exist_ok=True)
with open(filed_path(), "a", encoding="utf-8") as f:
f.write(json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n")
"project": it.get("project"), "where": ap, "date": L.now()}
from . import pdata
pdata.write_text("handover-filed.jsonl", (pdata.read_text("handover-filed.jsonl", "") or "")
+ json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n")
pdata.commit("handover: %s filed in %s" % (it.get("hid"), ap), ["handover-filed.jsonl"])
print("filed %s in %s; removed from the handover pile" % (ident, where))
return 0
if argv not in ([], ["--all"]):
+432 -94
View File
@@ -3,6 +3,11 @@
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.
Trust in a row comes from the ledger, never from the row itself: learnings-ledger.jsonl
is appended by sisi's own commands, in the same commit as the row they wrote, and holds
the id and content digest of what they wrote. A row that is not in the ledger with its
current digest (added or edited by hand) is never delivered.
"""
import hashlib, json, os, re, subprocess, time
@@ -10,14 +15,27 @@ from . import paths, pdata
STATUSES = ("observed", "analyzed", "proposed", "implemented", "validated",
"promoted", "monitored", "revised", "reverted", "rejected")
ENDED = ("rejected", "reverted")
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)
SCOPE_RANK = {"project": 0, "user": 1, "organization": 2}
MONITOR_UNITS = 5 # units in a learning's own scope before it can be called "holding"
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())
# Words that carry no information about what happened. A finding made only of these is advice,
# not evidence ("be more careful when writing tests in future").
GENERIC_WORDS = set((
"be being more most careful carefully better best write writing written test tests testing code coding "
"future next time times always never should must need needs try trying remember make sure ensure check "
"checks checking double pay attention use using cheaper cheap models model do does doing done good bad "
"great nothing none na issue issues problem problems thing things work works working improve improved "
"improving improvement quality thorough thoroughly review reviewing think thinking plan planning ahead "
"going forward all any some general generally just really very much many bit little slightly again once "
"ever also too so can could would will may might worse avoid mistakes mistake fine ok okay well everything "
"anything something stuff careless carelessness sloppy rushed hasty lazy diligent diligence").split())
class LearningError(Exception):
pass
@@ -46,6 +64,15 @@ def project_key(cwd):
return os.path.realpath(cwd)
def normalize_project(value):
"""The project key for an old `repo`/`cwd` value: the same key new code uses when the folder
still exists, else the cleaned path."""
if not value:
return ""
value = str(value)
return project_key(value) if os.path.isdir(value) else os.path.realpath(value)
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()
@@ -60,8 +87,32 @@ def unit_id(project=None):
hashlib.sha1(os.path.realpath(project).encode()).hexdigest()[:12])
# ---- who is recording: from recorded session state, never from the caller's environment ----
def session_record():
"""(session id, its recorded state). The id names which record to read; what decides
anything is what the hooks recorded there."""
sid = os.environ.get("SISI_SESSION_ID") or ""
if not sid:
return "", {}
from . import store
return sid, store.load_session(sid)
def is_subagent_session():
return os.environ.get("SISI_SUBAGENT") == "1" or os.environ.get("SISI_AGENT_DEPTH", "") not in ("", "0")
"""Was this retro recorded by a subagent? Decided from the session record: tick marks a
session that started as a subagent, and the watch hook records, for each shell command, whether
its hook payload came from a subagent (an agent id or a subagent transcript path). The latest
retro command on record decides."""
_sid, sess = session_record()
if not sess:
return False
if sess.get("subagent"):
return True
for sh in reversed(sess.get("shells") or []):
if isinstance(sh, dict) and sh.get("retro"):
return bool(sh.get("subagent"))
return False
# ---- store io -----------------------------------------------------------------
@@ -70,6 +121,10 @@ def learnings_path():
return paths.data_file("learnings.jsonl")
def ledger_path():
return paths.data_file("learnings-ledger.jsonl")
def findings_path():
return paths.data_file("findings.jsonl")
@@ -78,25 +133,85 @@ def pending_path():
return paths.data_file("pending.json")
def load_learnings():
out = []
def approvals_path():
return paths.data_file("approvals.jsonl")
def _read_jsonl(path):
"""(rows, skipped): the JSON objects in a jsonl file and how many lines were not one."""
rows, skipped = [], 0
try:
with open(learnings_path(), encoding="utf-8") as f:
with open(path, encoding="utf-8") as f:
for line in f:
if line.strip():
if not line.strip():
continue
try:
d = json.loads(line)
if isinstance(d, dict) and d.get("id"):
out.append(d)
except ValueError:
skipped += 1
continue
if isinstance(d, dict):
rows.append(d)
else:
skipped += 1
except OSError:
pass
return out
return rows, skipped
def save_learnings(rows, msg):
_LOADED = {} # id -> digest of the row as it was on disk at the last read
def load_learnings():
rows = [d for d in _read_jsonl(learnings_path())[0] if d.get("id")]
_LOADED.clear()
_LOADED.update({r["id"]: row_digest(r) for r in rows})
return rows
def row_digest(rec):
return hashlib.sha256(json.dumps(rec, sort_keys=True).encode()).hexdigest()[:20]
def load_ledger():
"""{id: digest of the row as sisi last wrote it}."""
return {d["id"]: d.get("digest") for d in _read_jsonl(ledger_path())[0] if d.get("id")}
def is_registered(rec, ledger=None):
ledger = load_ledger() if ledger is None else ledger
return ledger.get(rec.get("id")) == row_digest(rec)
def save_learnings(rows, msg, touched=(), via="retro", created=()):
"""Rewrite the store. Only the rows a sisi command wrote are entered in the ledger: `created`
(new rows) and `touched` (rows changed by this command, which must have been as sisi last wrote
them when read). A row added or edited by hand never gets a ledger entry, and a later sisi
command that touches it does not launder it."""
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"])
ids = {t["id"] if isinstance(t, dict) else t for t in touched}
new = {t["id"] if isinstance(t, dict) else t for t in created}
ledger = load_ledger()
add = ""
for r in rows:
i = r.get("id")
if i not in ids and i not in new:
continue
d = row_digest(r)
prior = ledger.get(i)
if i in new:
ok = prior is None
else:
ok = prior is not None and _LOADED.get(i) == prior
if ok and prior != d:
add += json.dumps({"id": i, "digest": d, "via": via, "ts": now()}, sort_keys=True) + "\n"
if add:
pdata.write_text("learnings-ledger.jsonl", (pdata.read_text("learnings-ledger.jsonl", "") or "") + add)
pdata.commit(msg, ["learnings.jsonl", "learnings-ledger.jsonl"])
_LOADED.clear()
_LOADED.update({r["id"]: row_digest(r) for r in rows if r.get("id")})
def store_base(rows=None):
@@ -109,17 +224,7 @@ def store_base(rows=None):
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
return _read_jsonl(findings_path())[0]
def append_finding(f, msg="retro: finding"):
@@ -145,6 +250,53 @@ def get(rows, lid):
return None
# ---- text checks: generic findings, secrets -----------------------------------------------
def is_generic(text):
"""True when the text is only generic advice, wherever the filler appears. A number, a
path, a quoted name or any other specific word makes it concrete."""
toks = re.findall(r"[a-z0-9_]+", (text or "").lower())
if not toks:
return True
if any(any(c.isdigit() for c in t) for t in toks):
return False
return not [t for t in toks if len(t) >= 2 and t not in STOP and t not in GENERIC_WORDS]
_SECRET_PATTERNS = [
(re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)"), "<redacted private key>"),
(re.compile(r"\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}"), "<redacted key>"),
(re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}"), "<redacted token>"),
(re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"), "<redacted token>"),
(re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "<redacted key>"),
(re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}"), "<redacted token>"),
(re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}"), "<redacted token>"),
(re.compile(r"(?i)\b(bearer)\s+[A-Za-z0-9._~+/=-]{16,}"), r"\1 <redacted>"),
(re.compile(r"(?i)\b([A-Za-z0-9_.-]*(?:api[_-]?key|secret|token|passw(?:or)?d|passwd|pwd|credentials?|authorization)"
r"[A-Za-z0-9_.-]*)\s*([:=])\s*(['\"]?)[^\s'\",;]{4,}"), r"\1\2 \3<redacted>"),
(re.compile(r"://([^/\s:@]+):[^/\s@]+@"), r"://\1:<redacted>@"),
]
_OPAQUE = re.compile(r"(?<![A-Za-z0-9+/_-])[A-Za-z0-9+/_-]{40,}={0,2}(?![A-Za-z0-9+/_-])")
def scrub_secrets(text):
"""Things that look like keys, tokens or passwords become <redacted> before anything is stored."""
s = str(text or "")
for rx, rep in _SECRET_PATTERNS:
s = rx.sub(rep, s)
def opaque(m):
t = m.group(0)
if re.fullmatch(r"[0-9a-f]{40,64}", t):
return t # a git object id is evidence, not a secret
if "/" in t and not re.search(r"[0-9]", t):
return t # a long path of words
if any(c.isdigit() for c in t) and any(c.isalpha() for c in t):
return "<redacted>"
return t
return _OPAQUE.sub(opaque, s)
# ---- derived text (the tool derives search terms, topics, short lines) ---------
def _stem(w):
@@ -179,8 +331,17 @@ def stems(text):
if len(w) > 2 and w not in STOP}
def derive_terms(*texts):
return sorted(set().union(*[stems(t) for t in texts]))[:24]
def derive_terms(*texts, limit=32):
"""The learning's own search terms, in order of first appearance (never cut alphabetically)."""
out, seen = [], set()
for t in texts:
for w in re.findall(r"[a-z0-9_]+", (t or "").lower()):
if len(w) > 2 and w not in STOP:
s = _stem(w)
if s not in seen:
seen.add(s)
out.append(s)
return out[:limit]
def derive_title(text, limit=90):
@@ -190,66 +351,98 @@ def derive_title(text, limit=90):
def similar_learnings(rows, text, limit=3):
"""Learnings whose own terms are found in the text. The share is taken of the smaller of the
two term sets, so a long prompt does not dilute a match: what counts is how much of the
learning's own vocabulary the text uses."""
q = stems(text)
scored = []
for r in rows:
if r.get("status") in ("rejected", "reverted"):
if r.get("status") in ENDED:
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 >= 1:
scored.append((inter / max(1, len(q)), inter, r))
scored.sort(key=lambda x: -x[0])
return [r for s, inter, r in scored
if s >= 0.3 or (inter >= 1 and s >= 0.25 and len(q) <= 4)][:limit]
own = set(r.get("terms") or []) or stems((r.get("title") or "") + " " + (r.get("proposed", {}).get("description") or ""))
if not own:
continue
inter = len(q & own)
share = inter / max(1, min(len(q), len(own)))
if (inter >= 3 and share >= 0.25) or (inter >= 2 and share >= 0.3) \
or (inter >= 1 and len(q) <= 4 and inter / len(q) >= 0.25): # a short, focused request
scored.append((share, inter, r))
scored.sort(key=lambda x: (-x[0], -x[1]))
return [r for _s, _i, r in scored][:limit]
# ---- scope (earned, never claimed) ---------------------------------------------
def earned(rec):
"""Cross-project delivery is earned: >=2 units in >=2 projects, or an owner statement."""
def earned_scope(rec):
"""The widest scope this learning has earned: `organization` for a learning seen in at least
two units in at least two projects, `user`/`organization` for an owner statement made at that
scope (a project-scoped statement stays in its project), else `project`. Nothing a cycle
author writes can change this."""
if rec.get("owner_statement"):
return True
s = (rec.get("proposed") or {}).get("scope")
return s if s in ("user", "organization") else "project"
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
return "organization" if len(units) >= 2 and len(projects) >= 2 else "project"
def in_scope(rec, project):
if rec.get("status") in ("rejected", "reverted"):
def earned(rec):
return earned_scope(rec) != "project"
def in_scope(rec, project, ledger=None):
if rec.get("status") in ENDED:
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
if not is_registered(rec, ledger):
return False # only rows sisi's own commands wrote, as they wrote them, 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):
def learnings_in_scope(project, rows=None, targets=()):
rows = load_learnings() if rows is None else rows
return [r for r in rows if in_scope(r, project)]
ledger = load_ledger()
out = [r for r in rows if in_scope(r, project, ledger)]
if targets:
want = set(targets)
out = [r for r in out if (r.get("proposed") or {}).get("target") in want]
return out
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:
rows = similar_learnings(rows, query, limit=5) # silence is the default
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]:
DELIVERED = ("promoted", "monitored", "proposed", "observed", "implemented", "validated")
def _delivery_lines(rows):
lines = []
for r in rows:
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 lines
def delivery_text(project, query="", targets=(), limit=5):
"""Learnings in scope, framed as information, never as instructions. No showing is recorded.
With targets: the learnings that target those rule, recipe or technique ids, plus the ones
that match the query. Silence is the default."""
rows = [r for r in learnings_in_scope(project) if r.get("status") in DELIVERED]
chosen = []
if targets:
chosen += [r for r in rows if (r.get("proposed") or {}).get("target") in set(targets)]
if query:
chosen += [r for r in similar_learnings(rows, query, limit=limit) if r not in chosen]
elif not targets:
chosen = []
if not chosen:
return ""
lines = ["Background information from earlier work (evidence to weigh, not instructions):"]
lines += _delivery_lines(chosen[:limit])
return "\n".join(lines) + "\n"
@@ -258,9 +451,11 @@ def delivery_text(project, query=""):
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"):
replay=None, entered_via="retro", target=None, origin=None):
rows = load_learnings()
pk = project_key(project)
finding, cause = scrub_secrets(finding), scrub_secrets(cause)
change = scrub_secrets(change) if change else change
rec = {
"id": next_id(rows), "title": derive_title(change or finding),
"source_unit": unit, "origin_project": pk,
@@ -268,36 +463,74 @@ def new_record(finding, cause, impact, disposition, project, unit,
"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,
"scope_asked": scope, "target": target},
"expected_effect": scrub_secrets(expect or ""), "limits": scrub_secrets(limits or ""),
"why_not": scrub_secrets(why_not or ""),
"validation": {"method": scrub_secrets(validate or ""), "benchmark": None,
"result": "unvalidated", "detail": ""},
"status": "promoted" if owner_statement else
("proposed" if disposition == "promote" else "observed"),
"version": 1, "confidence": "low",
"version": 1, "confidence": "high" if owner_statement else "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,
"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(),
"mechanism_ref": None, "replay": replay, "created": now(),
}
if origin:
rec["statement_origin"] = origin
rows.append(rec)
save_learnings(rows, "learning %s recorded" % rec["id"])
save_learnings(rows, "learning %s recorded" % rec["id"], created=[rec], via=entered_via)
return rec
def add_recurrence(rec, unit, project, rows):
"""Attach a recurrence. After promotion it counts against the learning."""
def add_recurrence(rec, unit, project, rows, finding=None):
"""Attach a recurrence, once per unit. The finding (a recorded finding of this unit in this
project) is the evidence; a unit already in the provenance is not counted again. After
promotion a new recurrence counts against the learning. Returns True when one was added."""
pk = project_key(project)
rec.setdefault("provenance", []).append(
{"unit": unit, "project": pk, "ts": now(), "kind": "recurrence"})
prov = rec.setdefault("provenance", [])
if any(p.get("unit") == unit and p.get("project") == pk for p in prov):
return False
prov.append({"unit": unit, "project": pk, "ts": now(), "kind": "recurrence", "finding": finding})
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"])
if rec["status"] == "promoted":
rec["status"] = "monitored"
save_learnings(rows, "learning %s recurrence" % rec["id"], touched=[rec])
return True
def adopt(lid, unit, project):
"""A parent adopts a subagent's candidate, by id and in its own project only."""
rows = load_learnings()
rec = get(rows, lid)
if rec is None:
raise LearningError("no learning %r" % lid)
if not rec.get("candidate"):
raise LearningError("learning %s is not a candidate" % lid)
if rec.get("origin_project") != project_key(project):
raise LearningError("learning %s was recorded in another project; adopt it there" % lid)
rec["candidate"] = False
rec.setdefault("history", []).append({"ts": now(), "action": "adopt", "unit": unit})
save_learnings(rows, "learning %s adopted" % lid, touched=[rec])
return rec
def withdraw(lid, why):
"""Withdraw an owner statement recorded by mistake: kept in history, never delivered again."""
rows = load_learnings()
rec = get(rows, lid)
if rec is None or not rec.get("owner_statement"):
raise LearningError("no owner statement %r" % lid)
if rec.get("status") in ENDED:
raise LearningError("%s is already withdrawn" % lid)
rec["status"] = "rejected"
rec.setdefault("history", []).append({"ts": now(), "action": "withdraw", "why": scrub_secrets(why)})
save_learnings(rows, "learning %s withdrawn" % lid, touched=[rec], via="learn")
return rec
@@ -307,25 +540,94 @@ def findings_for_unit(project, uid):
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 = []
# ---- owner statements: who said it ------------------------------------------------------
def _norm_words(t):
return " ".join(str(t or "").lower().split())
def statement_origin(statement):
"""`typed by the owner` when the quoted words appear in a human-typed message of this
session's transcript (read with harvest.typed_text, the one definition of "typed by the
human"); `relayed by an agent` when they do not, or when no transcript is available."""
_sid, sess = session_record()
tp = sess.get("transcript_path") if isinstance(sess, dict) else None
if not isinstance(tp, str) or not tp:
return "relayed by an agent"
want = _norm_words(statement)
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):
from . import harvest
path = os.path.expanduser(tp)
size = os.path.getsize(path)
with open(path, "rb") as f:
start = max(0, size - 8 * 1024 * 1024)
f.seek(start)
data = f.read()
lines = data.split(b"\n")
if start:
lines = lines[1:]
for raw in lines:
if b'"user"' not in raw:
continue
try:
d = json.loads(raw)
except ValueError:
continue
if not isinstance(d, dict):
continue
text = harvest.typed_text(d)[0]
if text and want in _norm_words(text):
return "typed by the owner"
except (OSError, ImportError):
pass
return "relayed by an agent"
# ---- units and monitoring --------------------------------------------------------------
def units_seen():
"""Closed units from the unit record's summary file in the user store (one JSON object per
line: id, project, closed_at, risk). The file may not exist yet: then there are none."""
return _read_jsonl(paths.data_file("units.jsonl"))[0]
def units_since_promotion(rec, units=None):
"""Closed units that count for this learning: after its promotion, and in its own scope (its
origin project when the scope is project, any project when it has earned more)."""
units = units_seen() if units is None else units
since = str(rec.get("promoted_at") or "")
if not since:
return []
wide = earned_scope(rec) != "project"
out, cache = [], {}
for u in units:
closed = str(u.get("closed_at") or "")
if not closed or closed < since:
continue
if not wide:
p = u.get("project")
if p not in cache:
cache[p] = normalize_project(p)
if cache[p] != rec.get("origin_project"):
continue
out.append(u)
return out
def unit_seq():
return len(units_seen())
def monitor(rows=None, units=None):
"""Move promoted learnings to `monitored` once monitoring has something to say (a unit in
scope has closed since promotion, or one recurred). Returns the changed records."""
rows = load_learnings() if rows is None else rows
units = units_seen() if units is None else units
changed = []
for r in rows:
if r.get("status") == "promoted" and not r.get("owner_statement") and r.get("promoted_at") \
and (units_since_promotion(r, units) or int(r.get("recurrences_after_promotion") or 0)):
r["status"] = "monitored"
changed.append(r)
return changed
# ---- 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")]
@@ -336,51 +638,51 @@ def learning_report():
rows = load_learnings()
findings = load_findings()
units = units_seen()
ledger = load_ledger()
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))]
odd = [r["id"] for r in rows if not is_registered(r, ledger)]
if odd:
lines.append("not delivered (not written by sisi's own commands, or edited by hand): " + ", ".join(odd))
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 ""))
since = len(units_since_promotion(r, units))
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:
elif since >= MONITOR_UNITS and rec == 0:
verdict = "holding"
elif rec:
verdict = "recurred, watching"
else:
verdict = "too few units to judge"
if since >= 5:
if since >= MONITOR_UNITS:
relevant += 1
if rec == 0:
holding += 1
lines.append("- %s: %d unit(s) since promotion, %d recurrence(s), %s — %s"
lines.append("- %s: %d unit(s) in scope 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))
"over at least five units in their scope" % (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`)"
lines.append("waiting for the owner's decision: %d change(s) (`sisi approve` lists them in full)"
% len(pend))
tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool"
and r.get("status") not in ("rejected", "reverted")]
and r.get("status") not in ENDED]
if tool:
lines.append("tool backlog (changes to sisi itself):")
for r in tool[:8]:
@@ -405,13 +707,49 @@ def save_pending(items, msg="pending decision updated"):
pdata.commit(msg, ["pending.json"])
def next_pending_id(items):
n = 0
for i in items:
m = re.match(r"P-(\d+)$", str(i.get("id", "")))
if m:
n = max(n, int(m.group(1)))
try:
n = max(n, max(int(re.sub(r"\D", "", str(a.get("id"))) or 0) for a in load_approvals()))
except ValueError:
pass
return "P-%04d" % (n + 1)
def load_approvals():
return _read_jsonl(approvals_path())[0]
def record_approval(row):
"""Append-only record of an owner decision; committed with the change it decided."""
pdata.ensure()
pdata.write_text("approvals.jsonl", (pdata.read_text("approvals.jsonl", "") or "")
+ json.dumps(row, sort_keys=True) + "\n")
pdata.commit("approval %s recorded" % row.get("id"), ["approvals.jsonl"])
def approved_ids():
return {a["id"] for a in load_approvals() if a.get("decision") == "yes" and a.get("id")}
def pending_notice():
n = len(load_pending())
return "sisi: %d learning change(s) wait for your decision (`sisi approve`)." % n if n else ""
if not n:
return ""
return ("sisi: %d learning change(s) wait for the owner's decision. Ask the owner through the host's "
"question dialog (`sisi approve` lists each change in full; show the owner what it would do) and give "
"the owner the command to run in a terminal: `sisi approve ID --yes` or `--no`. "
"Do not run it for the owner." % n)
# ---- 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")]
ledger = load_ledger()
return [r for r in rows if r.get("owner_statement") and r.get("status") not in ENDED
and is_registered(r, ledger)]
+146 -97
View File
@@ -245,124 +245,173 @@ def run():
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
db = paths.data_file("retro.db")
if not os.path.exists(src) and os.path.exists(db):
# an install whose committed dump was never written: read the sqlite store directly
con = sqlite3.connect(db, timeout=30)
con.row_factory = sqlite3.Row
try:
for r in con.execute("SELECT * FROM lessons ORDER BY id"):
lessons[r["id"]] = dict(r)
for r in con.execute("SELECT * FROM occurrences ORDER BY id"):
occs.setdefault(r["lesson_id"], []).append(dict(r))
except sqlite3.Error:
lessons, occs = {}, {}
finally:
con.close()
if os.path.exists(src):
with open(src, encoding="utf-8") as f:
def _jsonl_rows(path):
"""(rows, malformed line count) of a jsonl file that may not exist."""
rows, bad = [], 0
try:
with open(path, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
try:
r = json.loads(line)
d = json.loads(line)
except ValueError:
bad += 1
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 = []
if isinstance(d, dict):
rows.append(d)
else:
bad += 1
except OSError:
pass
return rows, bad
def migrate_learnings():
"""Old lesson store -> learning records. Whenever the old store exists and the `migrated`
marker does not; a backup first; merged by legacy id (a lesson already carried over is not
carried twice, so running `sisi learn` before the first migration loses nothing).
lessons.jsonl and the sqlite store hold lesson rows, occurrence rows, impression rows (sisi's
own showings, dropped: never evidence) and pattern rows (not carried; the backup keeps them).
Lessons become learning records with honest statuses (folded into prose is `implemented`,
always unvalidated; nothing becomes `validated`); occurrences become provenance, with the old
repo values normalised to the project key new code uses; a learning is earned wider only under
the same two-units-two-projects rule as a new one. learn.jsonl owner statements become
owner-statement records, keeping their scope. Malformed lines are counted, not hidden. Returns
notes with the counts.
"""
from . import learning as L
marker = paths.data_file("learnings-migrated.json")
if os.path.exists(marker):
return []
src = paths.data_file("lessons.jsonl")
learn_src = paths.data_file("learn.jsonl")
db = paths.data_file("retro.db")
if not (os.path.exists(src) or os.path.exists(learn_src) or os.path.exists(db)):
return []
bdir = snapshot("learning-migration")
lessons, occs = {}, {}
dropped = {"impression": 0, "sighting": 0, "pattern": 0}
malformed = {"lessons.jsonl": 0, "learn.jsonl": 0}
jrows, malformed["lessons.jsonl"] = _jsonl_rows(src)
for r in jrows:
t = r.get("t")
if t == "lesson":
lessons[r.get("id")] = r
elif t == "occurrence":
occs[r.get("id")] = r
elif t in dropped:
dropped[t] += 1
if os.path.exists(db):
con = sqlite3.connect(db, timeout=30)
con.row_factory = sqlite3.Row
try:
for r in con.execute("SELECT * FROM lessons ORDER BY id"):
lessons.setdefault(r["id"], dict(r))
for r in con.execute("SELECT * FROM occurrences ORDER BY id"):
occs.setdefault(r["id"], dict(r))
except sqlite3.Error:
pass
finally:
con.close()
rows = L.load_learnings()
have_legacy = {r.get("legacy_id") for r in rows if r.get("legacy_id") is not None}
have_text = {" ".join(str((r.get("proposed") or {}).get("description") or "").lower().split())
for r in rows if r.get("owner_statement")}
by_lesson = {}
for o in occs.values():
by_lesson.setdefault(o.get("lesson_id"), []).append(o)
added, already, attached, touched = 0, 0, 0, []
for lid in sorted(lessons, key=lambda x: (x is None, x)):
if lid in have_legacy:
already += 1
continue
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 "")
for o in sorted(by_lesson.get(lid, []), key=lambda x: x.get("id") or 0):
proj = L.normalize_project(o.get("repo") or o.get("cwd") or old.get("project"))
unit = ("session:%s" % o["session"]) if o.get("session") else "legacy:%s:%s" % (lid, proj)
prov.append({"unit": unit, "project": proj, "ts": o.get("ts") or "", "kind": "occurrence"})
attached += len(prov)
origin = L.normalize_project(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"}]
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,
target = str(old.get("target") or "")
rec = {
"id": L.next_id(rows), "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 "",
"observation": {"evidence": L.scrub_secrets(old.get("moment") or ""), "impact": "correctness"},
"root_cause": L.scrub_secrets(old.get("cause") or ""),
"proposed": {"description": L.scrub_secrets(old.get("change") or ""),
"mechanism": "tool" if kind == "tool" else ("verification" if kind in ("check", "test") else "policy"),
"scope": "project", "target": old.get("target")},
"scope": "project", "scope_asked": None,
"target": target[5:] if target.startswith("rule:") else (target or None)},
"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",
"owner_statement": False, "candidate": False,
"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)]
"promoted_at": None, "mechanism_ref": old.get("folded_into"),
"replay": None, "created": old.get("created") or L.now()}
rows.append(rec)
touched.append(rec)
added += 1
orphans = sum(len(v) for k, v in by_lesson.items() if k not in lessons)
srows, malformed["learn.jsonl"] = _jsonl_rows(learn_src)
statements, dup = 0, 0
for r in srows:
text = r.get("text") or r.get("statement") or ""
if not text:
continue
key = " ".join(text.lower().split())
if key in have_text:
dup += 1
continue
have_text.add(key)
statements += 1
scope = r.get("scope") if r.get("scope") in ("user", "project", "organization") else "user"
proj = L.normalize_project(r.get("cwd"))
text = L.scrub_secrets(text)
rec = {
"id": L.next_id(rows), "title": L.derive_title(text),
"source_unit": "owner", "origin_project": proj,
"observation": {"evidence": text, "impact": "value"},
"root_cause": "owner statement",
"proposed": {"description": text, "mechanism": "knowledge", "scope": scope,
"scope_asked": scope, "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": proj, "ts": r.get("ts") or "", "kind": "origin"}],
"terms": L.derive_terms(text), "owner_statement": True, "candidate": False,
"statement_origin": "migrated from the old statement file",
"recurrences_after_promotion": 0,
"flagged_not_working": False, "promoted_at": r.get("ts") or L.now(),
"mechanism_ref": None, "replay": None, "created": r.get("ts") or L.now()}
rows.append(rec)
touched.append(rec)
counts = {"lessons_in_old_store": len(lessons), "lessons_migrated": added, "lessons_already_migrated": already,
"owner_statements_migrated": statements, "owner_statements_duplicate": dup,
"occurrences_attached": attached, "occurrences_without_a_lesson": orphans,
"malformed_lines_skipped": dict(malformed), "dropped_rows": dict(dropped),
"learning_records_after": len(rows)}
pdata.ensure()
pdata.write_text("learnings-migrated.json", json.dumps(dict(counts, ts=L.now(), backup=bdir), indent=2, sort_keys=True) + "\n")
L.save_learnings(rows, "migrate: lessons and owner statements become learning records", created=touched, via="migration")
pdata.commit("migrate: learning migration recorded", ["learnings-migrated.json"])
return ["learning migration: backed up to %s; %d lesson(s) in the old store, %d carried over (%d already there); "
"%d owner statement(s) carried over (%d duplicate); %d occurrence(s) attached as provenance, %d without "
"a lesson left out; %d malformed line(s) skipped (lessons.jsonl %d, learn.jsonl %d); dropped as not "
"evidence or not carried: %d impression(s), %d sighting(s), %d pattern row(s); now %d learning record(s); "
"nothing is validated" % (bdir, len(lessons), added, already, statements, dup, attached, orphans,
sum(malformed.values()), malformed["lessons.jsonl"], malformed["learn.jsonl"],
dropped["impression"], dropped["sighting"], dropped["pattern"], len(rows))]
# ---- snapshots (before an update) -------------------------------------------------------------
+65 -4
View File
@@ -216,10 +216,10 @@ def more_line(n):
return "More: `sisi rule %d` (reasons, history, lessons behind it, how it is enforced)." % n
def render():
pre, rules = effective()
def _render(pre, rules):
try:
base_h = sha(open(paths.canon("core.md"), "rb").read())[:8]
with open(paths.canon("core.md"), "rb") as f:
base_h = sha(f.read())[:8]
except OSError:
base_h = "missing"
head = "<!-- generated by sisi from the product canon/core.md (%s) and the personal overlay (%s); " \
@@ -232,6 +232,41 @@ def render():
return "\n\n".join(parts) + "\n"
def render():
pre, rules = effective()
return _render(pre, rules)
def render_with(changes):
"""The rulebook as it would render with these rules (id -> parsed rule) added or replaced:
the size check a cycle runs before it writes anything."""
pre, rules = effective()
rules = list(rules)
at = {r["id"]: i for i, r in enumerate(rules)}
for rid, r in changes.items():
r = dict(r, origin="added")
if rid in at:
rules[at[rid]] = r
else:
at[rid] = len(rules)
rules.append(r)
return _render(pre, rules)
def protected_rules():
"""Ids no cycle and no overlay command may replace or disable (canon/protected.json). Fails
closed: when the file cannot be read, nothing about a rule may be changed."""
try:
with open(paths.canon("protected.json"), encoding="utf-8") as f:
d = json.load(f)
rules = d["rules"]
if not isinstance(rules, list) or not all(isinstance(x, str) for x in rules):
raise ValueError("rules must be a list of ids")
return set(rules)
except (OSError, ValueError, KeyError, TypeError) as e:
raise OverlayError("canon/protected.json cannot be read (%s): changes to rules are refused until it can" % e)
def size(text):
return len(text.splitlines()), len(text)
@@ -659,8 +694,30 @@ def scan_retests():
# ---- command line ----------------------------------------------------------------
def _rule_change_waits(action):
"""Replacing or disabling a rule from the command line obeys the same rules as a cycle: a
protected rule is refused, anything else waits for the owner's `sisi approve`."""
from . import cycle, documents
rid = action["rule_id"]
if rid in protected_rules():
raise OverlayError("rule %r is protected (canon/protected.json); it cannot be replaced or disabled "
"from here or by a cycle" % rid)
if rid not in {x["id"] for x in base_rules()[1]} | set(overlay_rules()):
raise OverlayError("no rule %r (see `sisi overlay list`, or `sisi canon` for the ids)" % rid)
if action["action"] == "replace-rule":
ok, msg = documents.check_budgets(render_with({rid: parse_rule_file(action["rule_text"], rid)}))
if not ok:
raise OverlayError(msg)
pid = cycle.park_rule_change(action, ["%s %s: changing or disabling an existing rule needs the owner" % (action["action"], rid)])
print("%s %s waits for the owner: nothing changed. The owner decides in a terminal: `sisi approve %s --yes`"
% (action["action"], rid, pid))
return 0
USAGE = """usage: sisi overlay list | diff
sisi overlay add-rule [--id ID] FILE|- replace-rule ID FILE|- disable-rule ID enable-rule ID
(replace-rule and disable-rule wait for the owner's `sisi approve`; protected rules are refused)
sisi overlay add-verifier FILE|- replace-verifier ID FILE|- disable-verifier ID enable-verifier ID
sisi overlay add-recipe FILE|- replace-recipe ID FILE|- disable-recipe ID enable-recipe ID
sisi overlay revert COMMIT
@@ -694,6 +751,8 @@ def main(args):
if len(args) != 1:
print(USAGE)
return 1
if kind == "rule" and op == "disable":
return _rule_change_waits({"action": "disable-rule", "rule_id": args[0]})
set_disabled(kind, args[0], op == "disable")
print("%sd %s %s" % (op, kind, args[0]))
return 0
@@ -711,8 +770,10 @@ def main(args):
print(USAGE)
return 1
text = _read_source(args[0])
if kind == "rule" and op == "replace":
return _rule_change_waits({"action": "replace-rule", "rule_id": rid, "rule_text": text})
if kind == "rule":
done = add_rule(text, rid) if op == "add" else replace_rule(rid, text)
done = add_rule(text, rid)
else:
done = put_entry(kind, text, rid, replacing=(op == "replace"))
print("%s %s %s (committed to the personal repository)" % ("added" if op == "add" else "replaced", kind, done))
+15 -50
View File
@@ -1,70 +1,35 @@
"""Owner statements, printed by `sisi oracle`. One store: learning records with owner_statement.
`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; until an install
has migrated, statements are still read from learn.jsonl so nothing goes silent.
`sisi learn` writes them and `sisi oracle` prints them. Statements that predate the learning
store are brought in by lifecycle.migrate_learnings, which runs here first, so nothing goes silent.
"""
import json, os
from . import learning as L, paths
def _legacy_statements():
try:
from . import store
rows = store.read("learn") # also folds any quarantine file in, losslessly
except Exception:
rows = []
try:
with open(paths.data_file("learn.jsonl"), encoding="utf-8") as f:
rows = [json.loads(x) for x in f if x.strip()]
except (OSError, ValueError):
pass
return [{"text": r.get("text") or r.get("statement") or "",
"scope": r.get("scope") or "user", "ts": r.get("ts") or "", "id": None}
for r in rows if (r.get("text") or r.get("statement"))]
from . import learning as L
def statements():
recs = [{"text": r.get("proposed", {}).get("description") or r.get("title", ""),
"""The owner statements in force in the current project: user-scope ones everywhere, a
project-scoped one only in its own project."""
import os
from . import lifecycle
lifecycle.migrate_learnings()
here = os.getcwd()
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()]
if recs or os.path.exists(L.learnings_path()):
return recs
return _legacy_statements()
def plain_of(rec):
return rec.get("text") or rec.get("proposed", {}).get("description", "")
"ts": r.get("created", ""), "id": r.get("id"),
"origin": r.get("statement_origin") or ""}
for r in L.owner_statements() if L.in_scope(r, here)]
def oracle_text():
recs = statements()
if not recs:
legacy = paths.data_file("oracle.md")
if os.path.exists(legacy):
try:
with open(legacy, encoding="utf-8") as f:
return f.read()
except OSError:
pass
return ("The oracle is empty: no owner statements recorded. "
"`sisi learn \"<what you want>\"` adds one.\n")
lines = ["Standing principles — what the owner wants, in their words "
"(recorded with `sisi learn`; this is the oracle):"]
for i, r in enumerate(recs, 1):
date = " (%s)" % str(r["ts"])[:10] if r.get("ts") else ""
lines.append('%d. "%s"%s' % (i, r["text"], date))
flag = " [relayed by an agent, not found in a message the owner typed]" if r["origin"] == "relayed by an agent" else ""
lines.append('%d. "%s"%s%s' % (i, r["text"], date, flag))
return "\n".join(lines) + "\n"
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
+84 -123
View File
@@ -349,28 +349,25 @@ def _merge_rule(core_text, pid, rule_md):
return body
def _waiting_for_product():
"""Learning records in force that belong in the product: changes to sisi itself (`tool`) and
learnings that earned organization scope (seen in two units in two projects), not yet in it."""
from . import learning as L
ledger = L.load_ledger()
return [r for r in L.load_learnings()
if L.is_registered(r, ledger) and not r.get("candidate") and not r.get("in_product")
and r.get("status") not in L.ENDED and not r.get("owner_statement")
and ((r.get("proposed") or {}).get("mechanism") == "tool" or L.earned_scope(r) == "organization")]
def core_items():
"""Core-tier items not yet in the product: ([lesson rows], [statement texts])."""
lessons = []
try:
from . import retro
if os.path.exists(retro.db_path()):
con = retro.connect()
try:
lessons = [dict(r) for r in con.execute(
"SELECT * FROM lessons WHERE scope='core' AND status IN ('open','applied') "
"AND COALESCE(promoted,'')='' ORDER BY id")]
finally:
con.close()
except Exception:
lessons = []
statements = []
try:
from . import principles
statements = [r["text"] for r in principles.core_statements()]
except Exception:
statements = []
return lessons, statements
"""What is waiting for the product: ([learning records], [organization-scope statement texts])."""
from . import learning as L
ledger = L.load_ledger()
statements = [(r.get("proposed") or {}).get("description") or r.get("title") or ""
for r in L.owner_statements() if (r.get("proposed") or {}).get("scope") == "organization"
and not r.get("in_product") and L.is_registered(r, ledger)]
return _waiting_for_product(), [t for t in statements if t]
def _norm_text(t):
@@ -408,20 +405,16 @@ def _drop_personal_copy(kind, pid, f):
overlay.build_canon()
except Exception:
pass
try:
from . import retro, store
if os.path.exists(retro.db_path()):
con = retro.connect()
try:
con.execute("UPDATE lessons SET promoted=? WHERE scope='core' AND "
"(folded_into=? OR folded_into=? OR folded_into LIKE ?)",
(store.now(), pid, "rule:" + pid, "%" + pid + "%"))
con.commit()
finally:
con.close()
retro.sync("lessons: core item %s promoted into the product" % pid)
except Exception:
pass
from . import learning as L
rows = L.load_learnings()
ledger = L.load_ledger()
hit = [r for r in rows if L.is_registered(r, ledger) and not r.get("in_product")
and ((r.get("proposed") or {}).get("target") == pid
or str(r.get("mechanism_ref") or "").split()[-1:] == [pid])]
for r in hit:
r["in_product"] = L.now()
if hit:
L.save_learnings(rows, "learning: item %s promoted into the product" % pid, touched=hit, via="cycle")
def _promote_overlay(pid, apply, src):
@@ -473,41 +466,31 @@ def _promote_overlay(pid, apply, src):
return 0
def _learning_id(arg):
"""`lesson:N`, `lesson:L-0003` or `L-0003` -> the learning id."""
t = arg[7:] if arg.startswith("lesson:") else arg
return "L-%04d" % int(t) if t.isdigit() else t
def _promote_lesson(lid, apply):
from . import retro
if not os.path.exists(retro.db_path()):
print("sisi promote: no lessons yet", file=sys.stderr)
from . import learning as L
rec = L.get(L.load_learnings(), lid)
if rec is None or not L.is_registered(rec):
print("sisi promote: no learning %s (`sisi lessons` lists them)" % lid, file=sys.stderr)
return 1
con = retro.connect()
try:
row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()
finally:
con.close()
if not row:
print("sisi promote: no lesson with id %d" % lid, file=sys.stderr)
return 1
r = dict(row)
if retro._get(r, "scope") != "core":
print("sisi promote: lesson #%d is in the %s tier, not core; only core items are queued "
"for the product" % (lid, retro._get(r, "scope") or "unscoped-tier"), file=sys.stderr)
return 1
if retro._get(r, "promoted"):
print("lesson #%d is already in the product (promoted %s)" % (lid, retro._get(r, "promoted")))
if rec.get("in_product"):
print("learning %s is already in the product (promoted %s)" % (lid, rec["in_product"]))
return 0
targets = [t.strip() for t in str(r.get("folded_into") or "").split(",") if t.strip()]
pid = None
for t in targets:
cand = t[5:] if t.startswith("rule:") else t
if cand.startswith("draft:") or cand == "enforced":
continue
if _find_item(cand):
pid = cand
break
if rec not in _waiting_for_product():
print("sisi promote: learning %s is neither a change to sisi itself (mechanism tool) nor seen in "
"two units in two projects, so it is not queued for the product" % lid, file=sys.stderr)
return 1
targets = [(rec.get("proposed") or {}).get("target")] + str(rec.get("mechanism_ref") or "").split()[-1:]
pid = next((t for t in targets if t and _find_item(t)), None)
if pid is None:
print("sisi promote: lesson #%d is core but is not folded into a personal rule, recipe or "
"technique yet, so there is no product file to write. Fold it in a learning round "
"(`sisi cycle`) first, then promote it; or send it upstream with "
"`sisi promote --export`." % lid, file=sys.stderr)
print("sisi promote: learning %s is not folded into a personal rule, recipe or technique yet, so "
"there is no product file to write. Fold it in a learning round (`sisi cycle`) first, then "
"promote it; or send it upstream with `sisi promote --export`." % lid, file=sys.stderr)
return 1
try:
src = source()
@@ -520,51 +503,31 @@ def _promote_lesson(lid, apply):
def _export_core(path=None):
lessons, statements = core_items()
if not lessons and not statements:
print("no core items are waiting: nothing to export")
recs, statements = core_items()
if not recs and not statements:
print("no items are waiting: nothing to export")
return 0
extra_terms = set()
try:
from . import retro
con = retro.connect()
try:
for r in lessons:
for (repo,) in con.execute("SELECT repo FROM occurrences WHERE lesson_id=?", (r["id"],)):
if repo:
extra_terms.add(os.path.basename(str(repo).rstrip("/")))
finally:
con.close()
except Exception:
pass
lines = ["# sisi core contributions", "",
for r in recs:
for p in [r.get("origin_project")] + [x.get("project") for x in r.get("provenance") or []]:
if p:
extra_terms.add(os.path.basename(str(p).rstrip("/")))
lines = ["# sisi contributions", "",
"Universal text only: no history, no user or project names. Nothing was sent "
"anywhere; send this file upstream yourself if you choose.", ""]
for t in statements:
lines += ["## Statement (core)", "", t, ""]
for r in lessons:
pat = ""
try:
from . import retro
con = retro.connect()
try:
if r.get("pattern_id"):
prow = con.execute("SELECT statement FROM patterns WHERE id=?",
(r["pattern_id"],)).fetchone()
pat = prow[0] if prow else ""
finally:
con.close()
except Exception:
pat = ""
lines += ["## Lesson %d (core, kind %s%s)" % (r["id"], r.get("change_kind") or "",
", target " + r["target"] if r.get("target") else ""), ""]
if pat:
lines += ["Pattern: " + pat, ""]
if r.get("short"):
lines += [str(r["short"]), ""]
lines += [str(r.get("change") or ""), ""]
if r.get("when_terms"):
lines += ["When: " + str(r["when_terms"]), ""]
lines += ["## Statement (organization)", "", t, ""]
for r in recs:
pr = r.get("proposed") or {}
lines += ["## Learning %s (%s%s)" % (r["id"], pr.get("mechanism") or "policy",
", target " + pr["target"] if pr.get("target") else ""), ""]
if r.get("title") and r["title"] != pr.get("description"):
lines += [str(r["title"]), ""]
lines += [str(pr.get("description") or ""), ""]
if r.get("expected_effect"):
lines += ["Expected effect: " + str(r["expected_effect"]), ""]
if r.get("limits"):
lines += ["Applies: " + str(r["limits"]), ""]
text = "\n".join(lines)
for term in sorted(extra_terms):
if len(term) >= 3:
@@ -578,8 +541,8 @@ def _export_core(path=None):
path = path or os.path.join(os.getcwd(), "sisi-core-contribution.md")
with open(path, "w", encoding="utf-8") as fh:
fh.write(clean if clean.endswith("\n") else clean + "\n")
print("wrote %s (%d lesson(s), %d statement(s); universal text only). Nothing was sent anywhere."
% (path, len(lessons), len(statements)))
print("wrote %s (%d learning(s), %d statement(s); universal text only). Nothing was sent anywhere."
% (path, len(recs), len(statements)))
return 0
@@ -593,30 +556,28 @@ def cmd_promote(args):
return 1
return _export_core(rest[0] if rest else None)
if not args:
lessons, statements = core_items()
if not lessons and not statements:
print("no core items are waiting to be promoted")
recs, statements = core_items()
if not recs and not statements:
print("no items are waiting to be promoted")
print("promote one overlay rule, recipe or technique by id: sisi promote <id> [--apply]")
return 0
print("Core items not yet in the product (in force for you through the personal overlay):")
for r in lessons:
from . import retro
print(" lesson:%d [%s] %s (`sisi promote lesson:%d --apply` on a developer install)"
% (r["id"], r.get("change_kind") or "", retro.heading_text(r, 100), r["id"]))
print("Items not yet in the product (in force for you through your own store):")
from . import learning as L
for r in recs:
print(" %s [%s] %s (`sisi promote %s --apply` on a developer install)"
% (r["id"], (r.get("proposed") or {}).get("mechanism") or "policy",
L.derive_title(r.get("title") or "", 100), r["id"]))
for t in statements:
print(" statement (core): %r (fold it into a rule in a learning round, then promote "
print(" statement (organization): %r (fold it into a rule in a learning round, then promote "
"the rule; or `sisi promote --export`)" % t[:100])
return 0
if len(args) != 1:
print("usage: sisi promote [<id>|lesson:N] [--apply] | sisi promote --export [PATH]",
print("usage: sisi promote [<id>|L-NNNN] [--apply] | sisi promote --export [PATH]",
file=sys.stderr)
return 1
pid = args[0]
if pid.startswith("lesson:"):
if not pid[7:].isdigit():
print("usage: sisi promote lesson:N [--apply]", file=sys.stderr)
return 1
return _promote_lesson(int(pid[7:]), apply)
if pid.startswith("lesson:") or re.match(r"^L-\d+$", pid):
return _promote_lesson(_learning_id(pid), apply)
try:
src = source()
except ReleaseError as e:
+79 -47
View File
@@ -8,7 +8,7 @@ existing learning is attached to it as a recurrence candidate, never refused in
Gate compatibility (gate.py calls these; its control flow is unchanged): TEMPLATE,
satisfied(), repo_of(), lessons_block().
"""
import json, os, subprocess, sys
import hashlib, json, os, subprocess, sys
from . import learning as L, paths
@@ -21,7 +21,9 @@ TEMPLATE = (
"infrastructure|verification|knowledge|benchmark --expect \"<observable effect>\" --validate \"<how it will be tested>\"\n"
" record also needs: --limits \"<where it applies and where it does not>\"\n"
" drop also needs: --why-not \"<why it is not worth promoting>\"\n"
"Generic findings are refused. A recurrence of a known learning may add --same-as ID."
"Generic findings are refused. A finding that resembles a learning in scope here is attached to it as\n"
"a recurrence (--new records it as its own); --same-as ID names the learning it repeats.\n"
"A parent adopts a subagent's candidate by id: sisi retro --adopt ID."
)
@@ -29,11 +31,6 @@ def repo_of(cwd):
return L.project_key(cwd)
def notes_for(entry_id):
"""Field notes per library entry were part of the retired trace regime; none remain."""
return None
def _git_head(cwd):
try:
p = subprocess.run(["git", "rev-parse", "HEAD"], cwd=cwd, capture_output=True,
@@ -111,7 +108,7 @@ def unit_summary(project):
OPTS = ("finding", "cause", "impact", "disposition", "change", "mechanism", "scope",
"expect", "validate", "limits", "why-not", "same-as", "candidate")
"expect", "validate", "limits", "why-not", "same-as", "adopt", "target")
def _parse(argv):
@@ -131,70 +128,103 @@ def _parse(argv):
return out
def _refuse(msg):
print("sisi retro: %s" % msg, file=sys.stderr)
return 2
def _adopt(lid, project):
"""A parent adopts a subagent's candidate by id. Never by resemblance, never from a subagent."""
if L.is_subagent_session():
return _refuse("a subagent cannot adopt a candidate; the parent session adopts it by id")
try:
rec = L.adopt(lid, L.unit_id(project), project)
except L.LearningError as e:
return _refuse(str(e))
print("learning %s adopted: no longer a candidate, delivered like any learning in its project" % rec["id"])
return 0
def cmd_retro(argv, stdin=None):
project = os.getcwd()
if not argv:
sys.stdout.write(unit_summary(project))
return 0
o = _parse(argv)
if o.get("adopt"):
return _adopt(o["adopt"], project)
finding = (o.get("finding") or "").strip()
cause = (o.get("cause") or "").strip()
impact = (o.get("impact") or "").strip()
disp = (o.get("disposition") or "").strip()
def refuse(msg):
print("sisi retro: %s" % msg, file=sys.stderr)
return 2
change = (o.get("change") or "").strip()
if not finding or not cause:
return refuse("--finding and --cause are required (run `sisi retro` alone for the unit record)")
if L.GENERIC.match(finding) or len(finding) < 20 or len(cause) < 12:
return refuse("generic findings are refused: say what happened, with evidence, and the root cause")
return _refuse("--finding and --cause are required (run `sisi retro` alone for the unit record)")
if len(finding) < 12 or len(cause) < 8 or L.is_generic(finding) or L.is_generic(cause) \
or (change and L.is_generic(change)):
return _refuse("generic findings are refused: say what happened, with evidence, and the root cause")
if impact not in L.IMPACTS:
return refuse("--impact must be one of %s" % "|".join(L.IMPACTS))
return _refuse("--impact must be one of %s" % "|".join(L.IMPACTS))
if disp not in ("promote", "record", "drop"):
return refuse("--disposition must be promote, record or drop")
return _refuse("--disposition must be promote, record or drop")
if disp == "promote":
if not (o.get("change") or "").strip():
return refuse("promote needs --change \"<the exact improvement>\"")
if not change:
return _refuse("promote needs --change \"<the exact improvement>\"")
if o.get("mechanism") not in L.MECHANISMS:
return refuse("--mechanism must be one of %s" % "|".join(L.MECHANISMS))
return _refuse("--mechanism must be one of %s" % "|".join(L.MECHANISMS))
if o.get("scope") and o["scope"] not in L.SCOPES:
return refuse("--scope must be one of %s" % "|".join(L.SCOPES))
return _refuse("--scope must be one of %s" % "|".join(L.SCOPES))
if not (o.get("expect") or "").strip() or not (o.get("validate") or "").strip():
return refuse("promote needs --expect \"<observable effect>\" and --validate \"<how it will be tested>\"")
return _refuse("promote needs --expect \"<observable effect>\" and --validate \"<how it will be tested>\"")
if disp == "record" and not (o.get("limits") or "").strip():
return refuse("record needs --limits \"<where it applies and where it does not>\"")
return _refuse("record needs --limits \"<where it applies and where it does not>\"")
if disp == "drop" and not (o.get("why-not") or "").strip():
return refuse("drop needs --why-not \"<why it is not worth promoting>\"")
return _refuse("drop needs --why-not \"<why it is not worth promoting>\"")
if o.get("same-as") and o.get("new"):
return _refuse("--same-as and --new contradict each other")
uid = L.unit_id(project)
pk = L.project_key(project)
sub = L.is_subagent_session()
rows = L.load_learnings()
# recurrence candidate: --same-as, an adopted candidate id, or resemblance
target = None
for key in ("same-as", "candidate"):
if o.get(key):
target = L.get(rows, o[key])
if target is None:
return refuse("no learning %r" % o[key])
if target is None:
sim = L.similar_learnings(rows, finding + " " + (o.get("change") or ""), limit=1)
target = sim[0] if sim else None
visible = L.learnings_in_scope(project, rows) # only learnings in force here can be matched
target, how = None, None
if o.get("same-as"):
if sub:
return _refuse("a subagent's findings are held as candidates; it cannot attach to a learning")
target = L.get(visible, o["same-as"])
how = "named with --same-as"
if target is None:
# A learning from another project: this finding, a unit here, is its own evidence for
# it, but only if it plainly is the same thing.
other = L.get(rows, o["same-as"])
if other is None or not L.is_registered(other) or other.get("candidate") or other.get("status") in L.ENDED:
return _refuse("no learning %r" % o["same-as"])
if len(L.stems(finding + " " + cause + " " + change) & set(other.get("terms") or [])) < 2:
return _refuse("this finding does not share enough with %s to be a recurrence of it; "
"record it as its own (--new)" % other["id"])
target, how = other, "named with --same-as; this project's own finding is the evidence"
elif not sub and not o.get("new"):
sim = L.similar_learnings(visible, finding + " " + change, limit=1)
if sim:
target, how = sim[0], "resembles it (--new records this finding as its own learning instead)"
replay = None
head = _git_head(project)
if head:
replay = {"repo": pk, "after": head, "before": None}
f = {"unit": uid, "project": pk, "ts": L.now(), "finding": finding, "cause": cause,
"impact": impact, "disposition": disp,
"learning": target["id"] if target else None, "recurrence_of": target["id"] if target else None}
ts = L.now()
fid = "F-" + hashlib.sha1(("%s|%s|%s|%s" % (uid, pk, ts, finding)).encode()).hexdigest()[:8]
f = {"id": fid, "unit": uid, "project": pk, "ts": ts, "finding": L.scrub_secrets(finding),
"cause": L.scrub_secrets(cause), "impact": impact, "disposition": disp,
"learning": target["id"] if target else None, "recurrence_of": target["id"] if target else None,
"by_subagent": sub}
L.append_finding(f)
if target is not None:
if target.get("candidate") and not L.is_subagent_session():
target["candidate"] = False # a parent retro adopting a subagent candidate
L.add_recurrence(target, uid, project, rows)
print("finding recorded for unit %s; attached to learning %s as a recurrence candidate%s"
% (uid, target["id"],
added = L.add_recurrence(target, uid, project, rows, finding=fid)
print("finding recorded for unit %s; attached to learning %s (%s) as a recurrence%s%s"
% (uid, target["id"], how, "" if added else " (this unit was already counted for it)",
" (flagged not working: the next cycle must revise or revert it)"
if target.get("flagged_not_working") else ""))
return 0
@@ -202,16 +232,16 @@ def cmd_retro(argv, stdin=None):
print("finding recorded for unit %s; dropped: %s" % (uid, o.get("why-not", "")))
return 0
rec = L.new_record(finding, cause, impact, disp, project, uid,
change=(o.get("change") or "").strip() or None,
mechanism=o.get("mechanism"), scope=o.get("scope"),
change=change or None, mechanism=o.get("mechanism"), scope=o.get("scope"),
expect=(o.get("expect") or "").strip() or None,
validate=(o.get("validate") or "").strip() or None,
limits=(o.get("limits") or "").strip() or None,
why_not=(o.get("why-not") or "").strip() or None,
subagent=L.is_subagent_session(), replay=replay)
subagent=sub, replay=replay, target=(o.get("target") or "").strip() or None)
print("finding recorded for unit %s; learning %s (%s)%s"
% (uid, rec["id"], rec["status"],
", held as a candidate until a parent retro adopts it" if rec.get("candidate") else ""))
", held as a candidate until the parent adopts it (`sisi retro --adopt %s`)" % rec["id"]
if rec.get("candidate") else ""))
return 0
@@ -235,8 +265,10 @@ def cmd_lessons(argv):
if not rows:
print("no learnings recorded")
return 0
ledger = L.load_ledger()
for r in rows:
val = (r.get("validation") or {}).get("result") or "unvalidated"
print("%s %-11s %-11s %s" % (r["id"], r.get("status"), val if val == "validated" else "unvalidated",
L.derive_title(r.get("title", ""), 100)))
print("%s %-11s %-11s %s%s" % (r["id"], r.get("status"), val if val == "validated" else "unvalidated",
L.derive_title(r.get("title", ""), 100),
"" if L.is_registered(r, ledger) else " [not delivered: not written by sisi's commands]"))
return 0
+3 -1
View File
@@ -79,11 +79,13 @@ def _patterns_from(table):
def load_patterns(cwd=None):
"""Canon patterns plus user-store and project adjustments, in that order."""
"""Canon patterns plus user-store, learned (cycle) and project adjustments, in that order."""
from . import paths
pats = _patterns_from(default_table())
pats += _patterns_from(_load_json(paths.data_file("risk.json")))
if cwd:
from . import cycle
pats += cycle.risk_patterns(cwd) # learned by a cycle, for this project only unless earned wider
from . import gitutil
root = gitutil.root(cwd) or os.path.abspath(cwd)
pats += _patterns_from(_load_json(os.path.join(root, ".sisi", "risk.json")))
+26 -45
View File
@@ -97,37 +97,24 @@ def _why_paragraphs(body):
def _folded_lessons(rule_id):
try:
from . import retro
if not os.path.exists(retro.db_path()):
return []
con = retro.connect()
try:
return [dict(r) for r in con.execute(
"SELECT * FROM lessons WHERE folded_into=? OR folded_into=? ORDER BY id",
(rule_id, "rule:" + rule_id))]
finally:
con.close()
except Exception:
return []
"""The learnings behind a rule: those whose target is the rule, in scope here."""
from . import learning as L
return L.learnings_in_scope(os.getcwd(), targets=(rule_id,))
def _history(rule_id):
"""Learning rounds that changed this rule, from the cycle records' changed-files evidence."""
try:
from . import cycle
out = []
suffix = "rules/%s.md" % rule_id
for rec in cycle.cycle_records():
changed = rec.get("changed_files") or {}
if any(k.endswith(suffix) for k in changed):
line = "%s (%s): %s" % (rec.get("id"), (rec.get("ts") or "")[:10], rec.get("summary") or "")
if rec.get("reverted"):
line += " (reverted)"
out.append(line)
return out
except Exception:
return []
"""Learning rounds that changed this rule, from the cycle records' changed files."""
from . import cycle
out = []
suffix = "overlay/rules/%s.md" % rule_id
for rec in cycle.cycle_records():
if any(f == suffix for f in rec.get("changed") or []):
line = "%s (%s): %s" % (rec.get("id"), (rec.get("ts") or "")[:10],
"; ".join(x for x in rec.get("lines") or [] if rule_id in x) or rec.get("label") or "")
if rec.get("reverted"):
line += " (reverted)"
out.append(line)
return out
_ORIGIN = {"base": "base text, from the product rulebook (canon/core.md)",
@@ -136,7 +123,7 @@ _ORIGIN = {"base": "base text, from the product rulebook (canon/core.md)",
def _detail(n, rule):
from . import retro
from . import learning as L
print("Rule %d: %s {#%s}\n" % (n, rule["title"], rule["id"]))
print(rule["body"].strip("\n"))
why = _why_paragraphs(rule["body"])
@@ -152,24 +139,18 @@ def _detail(n, rule):
print(" - " + h)
lessons = _folded_lessons(rule["id"])
if lessons:
print("\nLessons folded into this rule:")
print("\nLearnings behind this rule:")
for r in lessons:
date = (retro._get(r, "last_seen") or retro._get(r, "applied_at") or "")[:10]
print(" - #%d (%s, seen %d times): %s (full text: `sisi lessons show %d`)"
% (r["id"], date or "undated", r["count"] or 0,
retro.heading_text(r, 140), r["id"]))
try:
from . import documents as _docs
for _key, _t in _docs.traces_for_lesson(r["id"]):
if _t.get("fragment"):
print(" carried in %s by: %r" % (_key, _t["fragment"]))
except Exception:
pass
if (r.get("moment") or "").strip():
print(" Where this came from (historical example): %s"
% retro.word_cut(r["moment"], 160))
val = (r.get("validation") or {}).get("result") or "unvalidated"
print(" - %s (%s, %d unit(s), %s): %s (full text: `sisi lessons show %s`)"
% (r["id"], (r.get("created") or "undated")[:10],
len({p.get("unit") for p in r.get("provenance") or []}),
val if val == "validated" else "unvalidated", L.derive_title(r.get("title") or "", 140), r["id"]))
ev = (r.get("observation") or {}).get("evidence") or ""
if ev.strip():
print(" Where this came from (historical example): %s" % L.derive_title(ev, 160))
else:
print("\nLessons folded into this rule: none yet.")
print("\nLearnings behind this rule: none yet.")
return 0
+34 -10
View File
@@ -1,9 +1,9 @@
"""Scope is earned (see learning.earned), and `sisi learn`: the one write path for owner statements.
"""Scope is earned (see learning.earned_scope), and `sisi learn`: the one write path for owner statements.
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.
Project identity helpers stay here for handover and friends. 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 made at user (or organization) scope: a project-scoped
statement is delivered only in its project.
"""
import os, sys
@@ -22,9 +22,16 @@ def visible_in(rec, cwd):
return L.in_scope(rec, cwd)
USAGE = ("usage: sisi learn [--scope user|project] \"<what you want>\"\n"
" sisi learn --withdraw ID --reason \"<why it was recorded by mistake>\"")
def cmd_learn(argv):
"""sisi learn [--scope user|project] TEXT — record an owner statement, live at once."""
scope = "user"
"""sisi learn [--scope user|project] TEXT — record an owner statement, live at once.
sisi learn --withdraw ID --reason WHY — withdraw one recorded by mistake (kept in history)."""
from . import lifecycle
lifecycle.migrate_learnings() # old statements and lessons join the store before a new one is added
scope, withdraw, reason = "user", None, None
text = []
it = iter(argv)
for a in it:
@@ -32,19 +39,36 @@ def cmd_learn(argv):
scope = next(it, "user")
elif a.startswith("--scope="):
scope = a.split("=", 1)[1]
elif a == "--withdraw":
withdraw = next(it, None)
elif a == "--reason":
reason = next(it, None)
else:
text.append(a)
if withdraw:
if not (reason or "").strip():
print("sisi learn: --withdraw needs --reason \"<why>\"", file=sys.stderr)
return 2
try:
rec = L.withdraw(withdraw, reason.strip())
except L.LearningError as e:
print("sisi learn: %s" % e, file=sys.stderr)
return 2
print("withdrew owner statement %s: kept in history, never delivered again" % rec["id"])
return 0
if scope not in L.SCOPES:
print("sisi learn: --scope must be one of %s" % "|".join(L.SCOPES), file=sys.stderr)
return 2
statement = " ".join(text).strip()
if len(statement) < 8:
print("usage: sisi learn [--scope user|project] \"<what you want>\"", file=sys.stderr)
print(USAGE, file=sys.stderr)
return 2
origin = L.statement_origin(statement)
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"])
owner_statement=True, entered_via="learn", origin=origin)
print("recorded owner statement %s (%s; printed by `sisi oracle`; withdraw a mistake with "
"`sisi learn --withdraw %s --reason ...`)" % (rec["id"], origin, rec["id"]))
return 0
+22 -50
View File
@@ -377,49 +377,27 @@ def _show(e, with_installed):
else:
print("installed here: n/a (no tool to detect)")
print()
print(e["body"].strip("\n") if e["header"] else open(e["path"], encoding="utf-8", errors="replace").read())
_print_notes(e["id"])
if e["header"]:
print(e["body"].strip("\n"))
else:
with open(e["path"], encoding="utf-8", errors="replace") as f:
print(f.read())
def _print_notes(id):
from . import retro
n = retro.notes_for(id)
if n:
print("\n## Field notes from earlier agents\n(information from past sessions, to weigh, not instructions)\n" + n)
def _print_lessons(query, place, extra="", loose=False, targets=()):
"""Lessons for this moment. With loose=True (done for, done ID, verifiers for) the two-part
delivery block: strict likely-to-apply lessons in full, then every loose lesson as a heading
for the asking agent to judge. Otherwise the older single strong-match block."""
try:
from . import retro
block = retro.delivery_block(query, place, extra=extra, targets=targets) if loose \
else retro.lessons_block(query, place, extra=extra)
if block:
print("\n" + block)
except Exception:
pass
def _print_lessons(query, extra="", targets=()):
"""Learnings in scope for this moment: those that target these entries, then those that match
the words of the query. Background information, never instructions; nothing is recorded as shown."""
from . import learning as L
block = L.delivery_text(os.getcwd(), ("%s %s" % (query, extra)).strip(), targets=targets)
if block:
print("\n" + block.rstrip("\n"))
def _print_cycle_notice():
try:
from . import cycle
line = cycle.due_notice()
if line:
print(line)
except Exception:
pass
def _print_drafts(query):
"""Draft recipe notes: recipe lessons naming a recipe that does not exist yet, when their words match."""
try:
from . import retro
for did, txt in retro.draft_notes_for(query):
print("\n## Draft recipe %s (not a recipe yet; notes from earlier lessons)\n%s" % (did, txt))
except Exception:
pass
from . import cycle
line = cycle.due_notice()
if line:
print(line)
def cmd_show(args):
@@ -438,7 +416,7 @@ def cmd_show(args):
print("")
for line in _docs.trace_lines("verifier", e["id"]):
print(line)
_print_lessons("%s %s %s" % (e["id"], e["title"], e["answers"]), "verifiers-show")
_print_lessons("%s %s %s" % (e["id"], e["title"], e["answers"]), targets=(e["id"],))
return 0
@@ -463,7 +441,7 @@ def cmd_for(args):
% (opts["kind"], fl))
if not top:
print("no verifier matches that description; try `sisi verifiers` to browse")
_print_lessons(desc, "verifiers-for", loose=True)
_print_lessons(desc)
return 0
for i, (f, e) in enumerate(top, 1):
mark = ""
@@ -472,8 +450,7 @@ def cmd_for(args):
print("%d. %s rung %s cost %s installed: %s%s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], mark, origin_tag(e)))
print(" %s" % (e["answers"] or e["title"]))
print("\nsisi verifiers show ID for set-up and a worked example")
_print_lessons(desc, "verifiers-for", extra=" ".join(e["id"] for _, e in top[:3]), loose=True,
targets=tuple(e["id"] for _, e in top))
_print_lessons(desc, extra=" ".join(e["id"] for _, e in top[:3]), targets=tuple(e["id"] for _, e in top))
return 0
@@ -650,20 +627,16 @@ def done_main(args):
scored = rank_recipes(desc, entries=rs)
if not scored:
print("no recipe matches that description; `sisi done` lists them")
_print_drafts(desc)
_print_lessons(desc, "done-for", loose=True)
_print_lessons(desc)
_print_cycle_notice()
return 0
best = scored[0][1]
print("Best match: %s\n" % best["id"])
print("== %s: %s ==%s\napplies to: %s\n" % (best["id"], best["title"], origin_tag(best), best["applies_to"]))
print(best["body"].strip("\n"))
_print_notes(best["id"])
if len(scored) > 1:
print("\nOther candidates: " + ", ".join(r["id"] for _, r in scored[1:4]))
_print_drafts(desc)
_print_lessons(desc, "done-for", extra=best["id"] + " " + best["title"], loose=True,
targets=(best["id"],))
_print_lessons(desc, extra=best["id"] + " " + best["title"], targets=(best["id"],))
_print_cycle_notice()
return 0
if args:
@@ -673,14 +646,13 @@ def done_main(args):
return 1
print("== %s: %s ==%s\napplies to: %s\n" % (r["id"], r["title"], origin_tag(r), r["applies_to"]))
print(r["body"].strip("\n"))
_print_notes(r["id"])
if trace:
from . import documents as _docs
print("")
for line in _docs.trace_lines("recipe", r["id"]):
print(line)
_print_lessons("%s %s %s" % (r["id"].replace("-", " "), r["title"], r["applies_to"]),
"done-show", loose=True, targets=(r["id"],))
targets=(r["id"],))
return 0
if not rs:
print("no recipes")
+13
View File
@@ -108,12 +108,25 @@ def _session(sid, d, cwd):
return sess
def note_shell(sess, cmd, payload):
"""Record, for the learning loop, who ran this shell command: whether it names a retro, and whether
its hook payload came from a subagent (an agent id or a subagent transcript path). `sisi retro`
reads this from the session record to quarantine what a subagent records; it never trusts the
caller's environment. The command text itself is not kept."""
from . import workers
shells = sess.setdefault("shells", [])
shells.append({"retro": "retro" in (cmd or ""), "subagent": bool(workers.is_subagent_payload(payload)),
"ts": time.time()})
del shells[:-8]
def before(payload):
tool, cmd, _ev, cwd, sid = extract(payload)
if not is_shell(tool, cmd):
return
sid = sid or "cwd-" + cwd
sess = _session(sid, payload, cwd)
note_shell(sess, cmd, payload)
store.save_session(sid, sess)
if _may_write(cmd) is False:
return # provably read-only (incl. sisi's own and git commit): no measurement paid
+2 -6
View File
@@ -57,9 +57,7 @@ class TickCleanTests(SisiCase):
"""R-12-2: handover items for this project print once per session, not every session."""
self.git_init()
self.sisi("install")
from sisi import handover, scope
pid = scope.project_id(self.proj)
handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"})
self.assertEqual(self.sisi("learn", "--scope", "project", "file this fact in the project docs").returncode, 0)
r1 = self.sisi("tick", stdin=self.payload())
self.assertIn("belong to this project", r1.stdout)
r2 = self.sisi("tick", stdin=self.payload(source="resume"))
@@ -92,9 +90,7 @@ class PromptReworkTests(SisiCase):
def test_no_handover_notice_in_prompt(self):
"""R-17-3: the per-prompt handover notice is gone."""
from sisi import handover, scope
pid = scope.project_id(self.proj)
handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"})
self.assertEqual(self.sisi("learn", "--scope", "project", "file this fact in the project docs").returncode, 0)
for text in ("fix a typo in the README", "why is the build slow?",
"add multi-page map printing with selectable paper size"):
with self.subTest(text=text):
+1198 -160
View File
File diff suppressed because it is too large. Load diff
+30 -13
View File
@@ -30,6 +30,7 @@ class PersonalCase(SisiCase):
else:
os.symlink(os.path.join(REPO, lib), os.path.join(root, lib))
self.write_product_core(root, rules)
shutil.copy(os.path.join(REPO, "canon", "protected.json"), os.path.join(root, "canon", "protected.json"))
return root
def write_product_core(self, root, rules):
@@ -58,6 +59,17 @@ class PersonalCase(SisiCase):
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r
def ok_owner(self, *a, **kw):
"""A rule replacement or disabling waits for the owner (R-11.5-11): run it, then decide as
the owner would, in a terminal."""
from sisi import learning as L
r = self.ok(*a, **kw)
self.assertTrue(L.load_pending(), "the change should be waiting for the owner")
for item in L.load_pending():
with unittest.mock.patch("sisi.cycle._stdin_is_tty", return_value=True):
self.ok("approve", item["id"], "--yes")
return r
def build_canon(self):
return overlay.build_canon()
@@ -108,8 +120,8 @@ class OverlayTests(PersonalCase):
def test_rules_add_replace_disable_enable(self):
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta rule", "Do delta.\n\nWhy: delta."))
self.ok("overlay", "replace-rule", "beta", "-", stdin=rule_file("Beta, mine", "My beta."))
self.ok("overlay", "disable-rule", "gamma")
self.ok_owner("overlay", "replace-rule", "beta", "-", stdin=rule_file("Beta, mine", "My beta."))
self.ok_owner("overlay", "disable-rule", "gamma")
g = self.generated()
self.assertIn("## 1. Alpha rule {#alpha}", g)
self.assertIn("## 2. Beta, mine {#beta}\n\nMy beta.", g)
@@ -176,7 +188,7 @@ class OverlayTests(PersonalCase):
self.assertLessEqual(len(self.generated().splitlines()), overlay.MAX_LINES)
r = self.sisi("overlay", "add-rule", "--id", "more", "-", stdin=rule_file("More", "\n".join("y%d" % i for i in range(30))))
self.assertEqual(r.returncode, 1)
self.ok("overlay", "replace-rule", "fill", "-", stdin=rule_file("Fill", "short"))
self.ok_owner("overlay", "replace-rule", "fill", "-", stdin=rule_file("Fill", "short"))
self.ok("overlay", "add-rule", "--id", "more", "-", stdin=rule_file("More", "\n".join("y%d" % i for i in range(30))))
def test_generated_is_idempotent_and_staleness_is_cheap(self):
@@ -213,7 +225,12 @@ class OverlayTests(PersonalCase):
(("disable-recipe", "release"), "")]
gens = [self.generated()]
for args, text in steps:
self.ok("overlay", *args, stdin=text)
if args[0] == "replace-rule": # the owner's approval path is tested elsewhere; this is the overlay's own commit
overlay.replace_rule(args[1], text)
elif args[0] == "disable-rule":
overlay.set_disabled("rule", args[1], True)
else:
self.ok("overlay", *args, stdin=text)
gens.append(self.generated())
self.assertEqual(len(self.git_log()), n0 + len(gens) - 1)
self.assertEqual(self.git_log()[0], "overlay: disable recipe release")
@@ -235,9 +252,9 @@ class OverlayTests(PersonalCase):
def test_revert_gives_back_the_same_generated_file(self):
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
before = open(paths.generated(), "rb").read()
self.ok("overlay", "replace-rule", "alpha", "-", stdin=rule_file("Alpha 2", "Other."))
self.ok_owner("overlay", "replace-rule", "alpha", "-", stdin=rule_file("Alpha 2", "Other."))
self.assertNotEqual(open(paths.generated(), "rb").read(), before)
self.ok("overlay", "revert", pdata.git("rev-parse", "--short", "HEAD").stdout.strip())
self.ok("overlay", "revert", pdata.git("log", "--format=%h", "--grep=overlay: replace rule alpha").stdout.split()[0])
self.assertEqual(open(paths.generated(), "rb").read(), before)
def test_doctor_shows_always_loaded_size(self):
@@ -267,8 +284,8 @@ class OverlayTests(PersonalCase):
class UpdateTests(PersonalCase):
def test_update_keeps_additions_replacements_and_disables(self):
self.ok("overlay", "add-rule", "--id", "mine", "-", stdin=rule_file("My rule", "Mine."))
self.ok("overlay", "replace-rule", "beta", "-", stdin=rule_file("Beta, mine", "My beta."))
self.ok("overlay", "disable-rule", "gamma")
self.ok_owner("overlay", "replace-rule", "beta", "-", stdin=rule_file("Beta, mine", "My beta."))
self.ok_owner("overlay", "disable-rule", "gamma")
self.ok("overlay", "add-verifier", "-", stdin=self.verifier_text("my-check", "My check"))
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Shellcheck, my way"))
self.ok("overlay", "replace-verifier", "semgrep-not-there", "-", stdin=self.verifier_text("semgrep-not-there")) \
@@ -344,15 +361,15 @@ class UpdateTests(PersonalCase):
self.assertTrue(open(core).read().endswith("local edit\n"))
open(core, "w").write(orig)
# a person's replacement, then the origin changes that rule
rid = "know-done"
self.ok("overlay", "replace-rule", rid, "-", stdin=rule_file("Know it, my way", "My text."))
rid = "deliver-quickly" # a protected rule (know-done) cannot be replaced at all
self.ok_owner("overlay", "replace-rule", rid, "-", stdin=rule_file("Know it, my way", "My text."))
text = open(os.path.join(origin, "canon", "core.md")).read()
open(os.path.join(origin, "canon", "core.md"), "w").write(text.replace("Skip the contract for small edits", "Skip the contract for tiny edits"))
open(os.path.join(origin, "canon", "core.md"), "w").write(text.replace("never repeating work whose", "never redoing work whose"))
g(origin, "commit", "-q", "-am", "two")
r = self.ok("update")
self.assertIn("->", r.stdout)
self.assertIn("tiny edits", open(core).read())
self.assertIn("kept your version of rule know-done", r.stdout)
self.assertIn("redoing work whose", open(core).read())
self.assertIn("kept your version of rule deliver-quickly", r.stdout)
self.assertIn("Know it, my way", self.generated())
self.assertIn("rulebook rebuilt", r.stdout)
self.assertIn("rulebook", r.stdout.split("doctor:")[1])