Merge t3/rebuild-learning-loop into spec-reconciliation

Learning loop rebuilt on sisi/learning.py as the single store; retro,
cycle, scope and documents cut down; improve/backlog/lessons digest
retired, approve added. Conflicts resolved keeping the risk-and-
relevance hook behaviour (silence by default, 2,000-char prompt cap,
structured recipe matcher) on the new learning functions, the union
of both sides' CLI changes, and our rewritten README.
This commit is contained in:
swaits committed 2026-11-23 11:20:24 -07:00
commit 6c5d87e5db
31 files changed
+1957 -9830

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
{
"rules": ["know-done", "strongest-check", "finish-by-verifying", "retro-every-time"],
"note": "Non-negotiable rules: a learning cycle must never replace or disable these. They carry verification before done, truthful reporting, and this governance itself. Changing them is product work by the owner, never a cycle."
}
+97 -357
View File
@@ -1,380 +1,120 @@
# How sisi learns
# The learning loop
**There is nothing to schedule. You install it and use your AI; it improves from use.** No cron, no
timers, no daemons, nothing to set up. Every step below happens inside commands and hooks that run
because you used a tool: recording a lesson at the end of a piece of work, starting a session, asking
what "done" means, verifying, or being sent back by the gate.
How sisi turns what happened in one work unit into a mechanism that helps the next.
The rule throughout: a behaviour is wanted either as a mechanism or as policy that is
measured. Prose that nothing checks or measures is not learning.
## The loop in plain words
## The record
1. **A lesson is recorded.** At the end of each piece of work the agent answers how it could have gone
better (`sisi retro`): the aim it fell short of, the concrete moment, why, and the change to sisi
that would make the next agent do it right without being told. Every lesson, and every
`sisi learn` statement, has a tier (`--scope core|user|project` is required; a missing scope is
refused with a paragraph stating the test). The test is two questions: does it apply to all
projects where sisi may be used, and would it be useful to every user who installs sisi? Both
yes is `core`: a change to sisi itself, in force for this user at once through the overlay and
queued for the product (below, `sisi promote`). Yes then no is `user`: how this owner wants work
done, kept in the personal store and delivered in all of this user's projects; the owner's
standing principles (`sisi oracle`) are built from user statements, plus core ones until the
product carries them. No to the first is `project`: a fact about this one project, which does
not stay in sisi's store: it moves to that project's
handover pile (below) and on into the project's own documentation or work list. A project is
identified by its git remote URL when it has one — normalised, so clones, an ssh or https remote,
and a renamed folder are the same project — else by its repository root path (a clone or rename
with no remote is then, unavoidably, a different project). The lesson splits in two: the
delivered part (`change`, `short`, `--when`; a learn statement) must be universal in the core
and user tiers, and a structural check (no model call) refuses it when that part names the
current project — the repository's name, a path or file name that exists in it, or its remote
URL — saying to rewrite it in general terms or scope it to the project. The tool's own name is
always exempt: how sisi itself should behave is core, even recorded inside the sisi repository,
and nothing is project merely for being recorded there (sisi is normally the shell around other
projects). Its history (`moment`, `cause`, the
occurrence records with repository, date and tool) is the historical example of where it came
from and may name the project freely; only the delivered part is checked. Lessons and statements
recorded before tiers existed (including the old two-way `everywhere`) are not yet tiered: they
keep being delivered as before until a learning round tiers them (below), and printed headings
count the short line when present. A lesson also names its pattern (`--pattern`, required): the
general failure of thinking this incident is an instance of, in one line that would apply to
unrelated work. A pattern naming the project or merely restating the change is refused by the
same style of check. `sisi retro patterns` lists the patterns so far and `--pattern-id N`
reuses one, so near-duplicates start rare and a round merges the rest. Patterns are how lessons
generalise upward instead of piling up as incident fixes (below).
`sisi lessons show ID` prints the universal lesson first, then a section headed "Where this came
from (historical example)" with the moment, cause and occurrences; session start, request-time
delivery and field notes show only the universal part plus the command that prints the example.
It also names, with `--when` (at
least five comma-separated words or short phrases, required), the kinds of work the lesson applies
to in the words a different agent would use, synonyms included — for a CSV lesson: "csv, tsv,
spreadsheet, tabular data, import, export, parse, delimited file". This matters because word
overlap alone cannot bridge "CSV" and "spreadsheet": the recording agent, who knows what the lesson
is about, supplies the bridge vocabulary in advance. Lessons recorded before when-terms existed
keep working by their own wording and are listed in the cycle brief so a consolidating agent can
add terms. A retro may also carry `--short` (one sentence in plain words, at most 140 characters,
no trailing ellipsis and no newline) and `--topic` (between one and three lower-case words, at
most 30 characters, such as "releases" or "asking questions"). Both are optional and checked
only for those limits when given; when either is missing, the retro still succeeds and says
that the next learning round will write it. Stores written before these fields existed gain
them on open, losing nothing, and lessons without them keep working.
2. **It takes effect at once**, in your personal data (the overlay), never in the product files:
- a verifier or recipe lesson naming an entry is attached to it as a field note straight away.
When the lesson has a short line, the bullet reads "- YYYY-MM-DD: <short> (seen N times;
lesson ID; full text: sisi lessons show ID)" in place of the long change text; an explicit
note text given by a later fold still wins over the short line;
- a recipe lesson naming a recipe that does not exist is kept as a draft recipe note;
- a rule, oracle or brief lesson becomes an active learned note with trigger words taken from its text;
- a tool lesson (a change to sisi itself) goes on the backlog (`sisi backlog`, most seen first).
A session started inside the sisi source folder is told the top item.
3. **It is shown at the moment it matters**, not only at session start. Session start prints up to
eight active lessons, strongest first. `sisi done for`, `sisi done ID`, `sisi verifiers for` and
`sisi contract init` print a two-part block, because the asking agent is a far better matcher than
word overlap: part one, "likely to apply", holds at most three lessons in full and only on a
strict test (at least two of the request's own content words inside the when-terms, or one plus
the lesson's target being the entry being printed); part two lists every remaining loose lesson as
a one-line heading (best overlap first, within a 1,500-character budget, saying how many were left
out) for the agent to open with `sisi lessons show ID`. Being printed or listed counts as
*listed*; opening counts as *read* — the two are reported separately, because "listed many times,
never read, still recurs" means the heading is bad, and the cycle brief says so. `sisi verifiers
show` and the gate's send-back message keep the older single strong-match block. The same strict
part-one test also runs at the moment the human's request arrives: where the tool documents a
prompt-submission event with a context channel, `sisi prompt` injects the best-matching recipe's
"done means" list in short form plus the matching lessons' short lines, each with the command
that prints it in full (`sisi done ID`, `sisi lessons show ID`), within a 2,000-character cap.
A recipe counts only when at least two distinct non-generic request words hit its title,
applies-to or id, at least one of them in its title (matched on stems, so "tag" meets
"tagging") — the same strict floor lessons use. A message that is a question to the agent and
names no work (no fix, build, change or the like), trivial messages (a bare yes or no, a slash
command, a short question) and unmatched requests inject nothing at all. These
showings count as *listed* at place `prompt`. The hook never blocks a turn: any error exits
silently. Draft recipe notes
appear in `sisi done for` when their words match. Lesson text is always framed as information to
weigh, not as commands, and text from a lesson is never executed. One-line headings — the
other-lessons list, session-start notes, `sisi backlog` and `sisi lessons` — use the short
line when one is present; without one they cut the change at a word boundary and end with
"…", never mid-word. Printed-heading budgets count the short line when present, because that
is what is printed.
4. **Showings are counted.** Every time a lesson is printed or listed, sisi records which lesson, in
which session, and where; opening one in full counts separately as read. Promotion needs at least
two listings or readings since the last promotion. A later sighting of the same problem — a retro recorded with `--same-as`, which
is also where the "a similar lesson exists" answer sends you — is a recurrence. When sisi itself
spots the resemblance and refuses a duplicate, that unconfirmed sighting is recorded too (shown by
`sisi lessons show ID` and in the cycle brief), so it is not lost even if the agent files its lesson
separately; it counts toward strengthening only once confirmed with `--same-as`. Recurrences after a
lesson has been shown are the signal that the lesson is not working.
5. **Recurring lessons get stronger.** Each lesson has a strength: 1 (a note), 2 (a candidate rule),
3 (enforced). A recurrence after at least two showings since the last promotion moves it up one
step — each step needs its own fresh evidence. A strength-2 lesson
becomes a real rule only through consolidation (below), because the rulebook has hard budgets in
lines and characters (`sisi doctor` prints them), and must not grow without shortening. A strength-3 lesson needs a check the gate can run; a folded lesson
shown 20 times with no recurrence is retired from the notes (it stays in history); a lesson that
still recurs at strength 3 is withdrawn, and the same wording will not be learned again.
6. **Consolidation happens in a cycle**, run by whichever agent is working — see below.
One store: `learnings.jsonl` in the user store (`~/.local/share/sisi`), one JSON object
per learning, committed to that folder's git repository — git is the history. Retro
findings live in `findings.jsonl`. There is no second copy and no database mirror.
## Project facts are handed over, not kept (`sisi handover`)
A learning record carries: id, title, source unit, observation (evidence and impact),
root cause, the proposed change (description, mechanism type, scope, target), expected
effect, validation (method, benchmark, result), status, version, provenance (every unit
and project it was seen in) and confidence. Status moves through `observed`, `analyzed`,
`proposed`, `implemented`, `validated`, `promoted`, `monitored`, and may end `revised`,
`reverted` or `rejected`. Showings are never recorded: being printed is not evidence.
Project-specific details might be recorded, with where the lesson came from as a historical
example — but they might not live in the global store: sisi is used across many projects, so
everything it leaves behind is at the broad or meta level, and project facts belong in that
project's own work list and design documentation. Scoping an item `project` (at `sisi retro` /
`sisi learn` time, or in a learning round) moves it out of the delivered global data into a
per-project handover pile in the personal store, kept only until filed. At session start inside
that project (and in request-time delivery there) sisi says, in plain words, how many items
belong to this project and asks the agent to file each in the project's own design documentation
or work list — wherever the project keeps them; if it has neither, a short section in its main
agent instructions file or a docs file — and then confirm with `sisi handover done ID --where
PATH`. `sisi handover` lists the waiting items in full, including the owner's quoted words and
the date, so nothing is lost in the move. The confirmation checks that the named file exists
inside the project and contains the item's key text (or a quoted fragment passed with `--quote`)
before removing it from the pile, and records where it went (id, project, path, date) in a small
filed log. After confirmation the item is gone from every global listing, digest and delivery;
the digest shows only a count per project of items still waiting to be filed. History stays in
the personal store's git history. The end-of-turn check is not involved: this is a
start-of-session notice that repeats until filed.
## The retro
## The cycle (`sisi cycle`)
`sisi retro` with no arguments prints the unit's record and what stands out — it reads
`sisi.unit.summary_for_retro(project)` when that module is present, otherwise the open
contract and the verification results on record. Each finding is then recorded with a
disposition, and only the fields that disposition needs:
Consolidation is due when enough lessons have been recorded since the last cycle, or a lesson is
waiting to move up a step, or the learned notes or the loose lessons pass their limits (`sisi cycle
due` states the live reason and its limit). The due test counts only what a round can act on:
tool lessons (changes to sisi itself, which a round cannot fold) and project-scoped items (handed
over to their project) do not count toward it; tool lessons are shown by `sisi backlog` under
their own separate heading cap, and a tool lesson whose change has been built is closed with
`sisi lessons set ID --status applied`, which takes it off the backlog and stops the digest
calling it "not built yet". The loose list stays short
by construction, because the brief's first instruction is to fold lessons into the recipe or entry
for their kind of work, or lift several into one rule, so they leave it. That is a counter check, not a
schedule: it runs at session start, at the end of every turn in the gate, and in the output of
`sisi retro`, `sisi verify` and `sisi done for` — commands agents run in every tool, so the loop works
in tools with no hooks at all. `sisi cycle due` runs the same check by hand. A session that has been
told is not told again until 20 further checks pass or the counter grows.
`sisi cycle` prints a brief the agent can act on without any other context: the lessons with their
counts and measurements, the current rulebook with its line count and budget, and instructions (merge
lessons that say the same thing; lift specific lessons into one general rule; fold a lesson into the
entry it belongs to; say which existing rule text gets shorter so the book does not grow; write checks
for strength-3 lessons). The agent answers with one JSON file:
The brief names the scratch path to write it to, lists every valid rule, recipe and verifier id
(with each recipe's one-line applies-to and the rule number-to-id map), shows full lesson text when
it fits its stated text budget (otherwise it says to run `sisi lessons show ID`), and puts the full
format behind `sisi cycle help`. It also lists every active lesson lacking a short line or topic,
lists the topics already in use so the agent reuses one instead of inventing a near-duplicate,
states the short and topic limits, and requires a `set-short` entry for each listed lesson:
`sisi cycle check FILE` (or `--dry-run`) refuses a file that omits one, naming the lesson, and
prints exactly what would change, changing nothing. A round can be started on demand even when
none is due: `sisi cycle --now` (or plain `sisi cycle`) prints the brief either way.
The brief also lists every not-yet-tiered lesson and `sisi learn` statement, with the repository
each was recorded in where known, and requires a tier for each: a note
`{"lesson": A, "action": "set-scope", "scope": "core|user|project", "project": "<id, when
project>"}` for a lesson, and the equivalent `{"text": "<the exact statement>", "action":
"set-scope", ...}` in a top-level `"learn"` list for a statement (the full format is behind
`sisi cycle help`). The brief states the two questions with generic examples of each tier.
Scoping to a project moves the item to that project's handover pile, and `sisi cycle check`
refuses to fold a project-scoped item into the rulebook or the general recipe/technique notes.
The brief likewise lists patterns with the lessons under each, and requires the round to assign
a pattern to every lesson lacking one (`set-pattern`, reusing a listed pattern before naming a
new one), merge near-duplicate patterns (a top-level `patterns` merge), and — for any pattern
explaining at least three lessons and at least six incidents (two constants in the code) — write
or update its statement in the rulebook as one strategic behaviour, traced like any folded
lesson. These three pressures are what keep patterns few: reuse is listed before invention is
allowed, exact duplicates merge themselves, and anything left over is merged or promoted each
round. The brief also lists core items waiting for the product; run from the clone it says
to run `sisi promote` after folding, otherwise to export. A file containing only the required
set-short/set-scope/set-pattern entries is acceptable when nothing else is ready to fold — a
cleanup-only round, startable at once with `sisi cycle --now`. Reading lessons during a round cannot stale it: automatic retirement (a
folded lesson shown 20 times) is deferred while a round is open, so `sisi lessons show` during
the round leaves its base current. `sisi cycle apply` prints the rulebook's lines and characters
before and after, matching what `sisi cycle check` predicted.
```json
{"version": 1, "base": "<base version from the brief>", "summary": "one line",
"rules": [{"id": "rule-id", "title": "Title", "body": "text, ending with Why: ...", "action": "add|replace",
"shortens": "rule-id: what is removed (required when the book would grow in characters)"}],
"disable_rules": ["rule-id"],
"notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short|set-scope|set-pattern",
"into": "rule/entry id or [ids]", "merged_into": 4, "note": "split text (optional)",
"when": "at least 5 terms (optional)", "short": "one plain sentence (set-short)", "topic": "topic words (set-short)",
"entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", "scope": "core|user|project (set-scope)", "project": "id (set-scope)", "pattern": "one line (set-pattern)", "pattern_id": 1,
"reason": "why it stays a draft (keep-as-draft)"}],
"learn": [{"text": "the exact learn statement", "action": "set-scope", "scope": "core|user|project", "project": "id, when project"}],
"patterns": [{"pattern": 1, "action": "merge|set-statement|fold-into-rule|keep", "into": 2, "statement": "sharpened one line"}],
"documents": [{"doc": "recipe:<id>", "action": "rewrite", "text": "<full new text>",
"trace": [{"lesson": 3, "fragment": "the exact sentence in the new text that carries it"}]},
{"doc": "verifier:<id>", "action": "reviewed", "reason": "why its structure is already right"}],
"rule_order": ["every rule id exactly once, in reading order"],
"enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30},
{"lesson": 4, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}]}
```
sisi retro --finding "<what happened, with the evidence>" --cause "<root cause>"
--impact value|correctness|time|cost|attention
--disposition promote|record|drop
promote: --change "<exact improvement>" --mechanism policy|orchestration|skill|tool|
infrastructure|verification|knowledge|benchmark --scope ... (optional)
--expect "<observable effect>" --validate "<how it will be tested>"
record: --limits "<where it applies and where it does not>"
drop: --why-not "<why it is not worth promoting>"
[--same-as ID]
```
`fold-into-entry` appends a dated field-note bullet (the lesson's change, or `note`) to
`notes/<id>.md` and marks the lesson applied; `into` may be a list, and two notes for one lesson
with different `note` text split a compound lesson. `create-entry` creates a personal recipe or
verifier entry in the overlay, lint-checked; `keep-as-draft` keeps it as a draft with a reason.
`set-when` only sets when-terms. `set-short` writes the short line and topic, and may be combined
with other actions on the same lesson; when it lands on a lesson already folded into an entry, the
entry's existing default bullets are rewritten to the short form. A bullet is treated as a default
bullet only when its text equals the lesson's full change with whitespace normalised; any other
text came from an explicit `note` and is left alone. Merge only lessons requesting the same change,
into the older or more general one, which keeps its text and count; the other becomes superseded
and needs no action. Tool lessons cannot be done in a cycle: they stay in `sisi backlog`, except
merging a duplicate (and a `set-short` for one, so the digest can show it).
Retire only what is fully folded and quiet (folded, at least 20 listed/read, no recurrences after
first listing); folding in this cycle does not make it quiet. The learned-notes limit counts only
`length(change)` of active strength-1 loose learned notes — it counts the change, not the short
line, because it is about content not yet folded — while printed headings count the short line
when present: folded lessons no longer count toward the learned-notes limit, which is why folding
(or merging, retiring, withdrawing, enforcing) reduces it.
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`).
`sisi cycle apply FILE` checks the file before writing anything: every lesson id exists, the base
version is still current, changed rules keep their id and their Why, named `sisi` commands and
enforced programs exist, and the resulting rulebook is inside both budgets (lines and
characters, printed by `sisi doctor`) and no longer in characters than before
unless `shortens` names what was removed.
Rules are re-wrapped to 100 characters on apply. The base version covers only what a cycle may
change (lesson content and status, short lines and topics, rules, notes, enforced checks), not
listed/read counters, and
lessons recorded since the brief are left for the next cycle; a stale refusal names exactly what
changed. The base version plus the personal-data lock means two sessions consolidating at once
cannot overwrite each other: the second apply is refused and told to read a fresh brief. A successful apply is one commit in your personal repository, with before-and-after
measurements. `sisi cycle revert` undoes the newest applied cycle exactly (the changed files byte for
byte, and the lesson rows it touched). `sisi cycle status` shows each cycle with what happened since:
deliveries, send-backs each, median time, and recurrences of the lessons it touched. A cycle whose
deliveries got worse after at least 10 of them is flagged, and the next brief says to revert or repair
it first.
## Scope is earned
Every round ends with a whole-document edit. The things agents read are documents — the
rulebook, the oracle (the owner's standing principles, one plain line per principle followed by
his quoted words and the date), each "what done means" recipe, each technique entry — and a
folded lesson belongs in
the document's own text, in the section where it fits (in a recipe: Done means, Checks, or
Common false finishes), in the document's voice, not as one more dated bullet in a journal.
The brief prints, for every document that has appended field notes, was folded into, has a
personal copy whose product text has since changed, or has had no whole-document review for
the configured number of rounds, its full current text and the lessons folded into it
(universal part only), together with a short editorial standard: one instruction per bullet or
sentence; most important and most often violated first; related instructions grouped under
one heading; no duplicates; imperative, concrete, plain words; each rule keeps its reason;
exceptions beside the instruction they qualify; no history or narrative. The cycle file then
needs, for each listed document, a rewrite (the full new text) or a `reviewed` entry with a
one-line reason; `sisi cycle check` refuses a file that skips one. The personal version of a
recipe or technique lives in the overlay and shadows the product's, with the product hash it
was derived from on record; when the product later changes, the next brief lists the document
as needing a re-merge rather than silently keeping the stale copy. Field-note files from
before this existed are listed the same way and keep being shown until rewritten.
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.
For the oracle the same tracing applies to statements: a rewrite traces every statement to the
line that carries it, and until a round integrates one, `sisi oracle` prints it under its own
heading so a new statement is in force at once and never parked unread.
## The cycle
Nothing folded may be lost in a rewrite. For each lesson folded into a document the file gives
the exact sentence or bullet in the new text that carries it, or an explicit disposition:
moved to another named document (with its fragment there), merged with another lesson (both
ids point at the same fragment), or retired under the usual retirement rule. A rewrite that
leaves any lesson without one of these is refused. For the rulebook the same holds for rule
ids: each survives or is merged into another id, and each keeps its Why. The trace map is
stored beside the document, outside the text agents load; `sisi lessons show ID`,
`sisi rule N` and `sisi done ID --trace` print where a lesson lives. Structure is checked
mechanically: the rulebook budgets, rule headings with ids, Why paragraphs and the generated
pointer lines, the library lint for recipes and techniques, the house width after wrapping,
run-on bullets, and dated journal-style bullets. A round may also reorder the rulebook
(`rule_order`): ids stay stable, numbers follow the order, and stored data refers to rules by
id. Each rewrite is recorded on its cycle, so `sisi cycle status` shows recurrences of the
rewritten document's lessons before and after it, and flags a rewrite followed by more.
Reverting a round restores documents, order and trace maps along with everything else.
Promotion is the cycle, due by a counter checked during normal use (no scheduler):
`sisi cycle` prints the brief for a cheap worker, which writes one JSON cycle file
(`sisi cycle help` is the format). Mechanism kinds a cycle can install in the user
store: an enforced contract requirement, an enforced command check (both in
`overlay/enforced.json`), a library entry (recipe or verifier), rule text, a risk-table
adjustment (`overlay/risk-adjustments.json`), a routing adjustment
(`overlay/routing-adjustments.json`), or a benchmark case
(`overlay/benchmarks/<name>.json`). `tool` learnings — changes to sisi's own code — are
refused by the cycle; they go to the backlog shown in the learning report and to the
contribution export.
Enforced checks live in `overlay/enforced.json` and are checked like the minimum-rung floors: a
contract-requirement fails a contract that touches its subject without a check of the required kind;
a command check runs in the project like a contract check, and only in projects already on the trust
list.
`sisi cycle apply FILE` treats the file as untrusted input and validates everything
before changing anything — a refusal applies nothing:
## Every rule points at its own detail (`sisi rule`)
- **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.
- **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.
The generated rulebook ends each rule with one generated line — `More: sisi rule N` — so a rule an
agent is reading names the command that explains it. `sisi rule` with no argument tables every rule
in the effective rulebook with how it is enforced, in plain words, derived from what the code does
(which hooks are wired, whether the floors and the gate checks exist): a rule with no mechanism
says so ("not enforced: depends on the agent") instead of implying otherwise. `sisi rule N` (or
`sisi rule ID`) prints the rule in full with its reasons, how it is enforced, whether the text is
base or overlay, which learning rounds changed it, and the lessons folded into it, each with
`sisi lessons show ID`. One rule gained a mechanism this way: where the tool has a question dialog
and a readable transcript (Claude Code; Qwen Code is wired the same way but its transcript shape is
unconfirmed, so the check may find nothing to read there), the end-of-turn gate sends the agent back
once when its final message ends by asking the human a question in reply text and no dialog was
used in that turn — the last sentence ending in a question mark outside code blocks, quotes and
known rhetorical forms. Subagents and dialog-less tools are exempt, and the same message is never
sent back twice.
## Monitoring
## What has been learned, in plain words
A recurrence after promotion counts against the learning. 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.
`sisi lessons digest` is for the human, not for agents. Its first line says how much has been
learned in one sentence, and its last line says how to see a lesson in full (`sisi lessons show
ID`), with the lesson number on every line. Patterns come first: the handful of strategic
behaviours, each with how many incidents it explains and whether its recurrence is falling.
Then the tiers: "In sisi itself, for every user" holds core items, each marked in the product
or waiting to be promoted; "How you want work done" holds user items; items waiting to be
filed in their projects appear only as a count per project (run `sisi handover` inside that
project to see them). Statements not yet tiered appear in the person's own words under "What
you said" when any are stored. The remaining short lines are grouped
under their topic headings, ordered by how much each topic holds, most first. After every line
comes its state in plain words — in the rulebook; attached to a kind of work (named by the
entry's human title, never its internal id); a loose note; a change to sisi itself, not built
yet, or built once closed with `sisi lessons set ID --status applied` — plus "seen N times" only
when a lesson has been seen more than once. Lessons without a short line go last, under "Not yet
summarized", cut at a word boundary. Retired, withdrawn and superseded lessons are left out
unless `--all` is given. `sisi rule N` lists the lessons behind a rule the same split way as
`sisi lessons show ID`: the lesson line, then its historical example.
## Owner statements
## Is it getting better?
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.
`sisi improve` (and one line of `sisi status`) answers with what is actually counted: patterns first
(each with its incidents and recurrence trend), then lessons recorded,
taking effect, strengthened, retired and withdrawn; the recurrence rate this week against the week
before; send-backs per delivery and median time to delivery, this week against before; and the
rulebook size against its budget. With too little data it says so.
## Migration
## Safety, and what is not claimed
`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.
Changes take effect first and are measured after; there is deliberately no replay testing before a
change ships. Safety comes from narrow scope instead: everything lands in the personal overlay,
every cycle is one commit that can be reverted exactly, the rulebook cannot grow past its budget, and
a change whose measures get worse is flagged and withdrawn. The human is never asked anything by this
loop.
## Seams for other parts of sisi
What is measured is counts and times: showings, recurrences, send-backs, delivery times, rulebook
lines. What is not measured is whether the delivered work is what the human meant — that still rests
on contract checks and the human's corrections.
Matching is measured, not asserted — twice over, and correctness no longer rests on it: part one is
deliberately strict, and everything else still reaches the asking agent as a heading it can judge.
The test suite carries two labelled sets, each measured the same way: how often a wrong lesson is
shown in full in part one (precision), and how often the right lesson is reached at all (in part one,
or listed in part two within its budget). The first set (25 should-match pairs, each request
rephrased but sharing vocabulary with its lesson, and 26 should-not) is a regression floor only — one
author wrote both sides, so of course they share words: reach 25/25, part-one wrong 0/26, proving
little beyond "does not regress". The second is harder and is the honest test: 21 pairs whose
requests share *no* content word with the lesson's moment, cause or change text (the test asserts
this), so only the recording agent's when-terms can bridge them, against 24 should-not requests:
reach 21/21 (20 of them already in part one; one — a request sharing a single when-word — reaches
only as a heading, as designed), part-one wrong 0/24. Both sets are small and hand-written; treat
even those figures as evidence about this mechanism on these examples, not as a promise about yours.
Two more labelled sets guard the newer checks, measured the same way in `tests/test_scope.py`
and `tests/test_prompt.py`: lesson texts labelled universal or project-bound (including
universal lessons that merely mention common file names such as README or CHANGELOG, which
pass, and universal changes whose moment names a project, which also pass because only the
delivered part is checked), and long real-style multi-part requests plus plain questions for
request-time recipe delivery (a hit is the expected recipe; any other recipe is a false match).
Delivery therefore depends on the quality of the when-terms the recording agent writes. Thin or
copy-of-the-text terms leave a lesson findable only by its own wording, exactly the failure they
exist to prevent. What sisi ultimately measures is not match scores but the outcome that matters:
whether the same problem recurs after a lesson has been shown. A lesson that is never found cannot be
shown, which is why the cycle brief lists lessons still missing terms.
At most three lessons are shown as matches, and every showing is on record in `sisi lessons show ID`.
Two display rules differ by surface: at session start (unsolicited), a lesson whose text reads like
an instruction to run something is withheld; when an agent's own query asked (`done for`, gate
send-back and friends), ordinary verbs like "run a property test" are shown — framed as information —
while URLs, shell constructs and outside paths are refused in both places. The task-set experiments
and taste judge in [design.md](design.md) remain unbuilt.
- `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).
- `retro.satisfied(repo, since, fp)` and `retro.TEMPLATE` — what the gate asks.
- `learning.delivery_text(project, query)` — what the prompt hook may add.
+2 -2
View File
@@ -1444,8 +1444,8 @@
{
"id": "R-11.1-14",
"status": "met",
"how": "cmd_retro persists each learning review as a structured lesson row with occurrences in the personal store",
"evidence": "tests/test_retro.py",
"how": "cmd_retro persists each finding as a structured learning record with provenance in the personal store",
"evidence": "tests/test_learning_loop.py",
"gap": ""
},
{
+23 -51
View File
@@ -32,35 +32,20 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
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 --scope core|user|project --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" --pattern "the general failure of thinking, one line" [--pattern-id N] [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"]
(or --json - with the same keys on stdin)
end of every piece of work: HOW it could have gone better; --when (at least
5 terms, synonyms included) is how a later agent with different words finds it;
--pattern is required (one line that would apply to unrelated
work; `sisi retro patterns` lists existing ones to reuse);
--short (at most 140 characters) and --topic (at most 30) are optional: when
omitted, the next learning round writes them
aims: level (the human could have worked at a higher level), verified (a stronger check was
possible), hands-off (the human was interrupted more than needed), intent (the result was not
what they meant), speed (it took longer than it had to)
sisi lessons [filters] | show ID | digest [--all] | set ID --status S | apply ID | export [FILE] | import FILE
the shared lessons from retros (--aim --kind --status --repo --top --json);
digest prints a short plain-language summary grouped by topic, for the human
sisi backlog tool lessons: changes to sisi itself, most seen first
sisi cycle [due|apply FILE|check FILE|--dry-run FILE|revert [ID]|status|help|--now]
consolidate lessons into rules, entries and enforced checks (no
scheduler: due-ness is a counter checked during normal use);
with no argument, or with --now, it prints the brief on demand even
when none is due; check/--dry-run prints what would change, changing
nothing; help prints the full cycle file format
sisi improve is it getting better? lessons, recurrence, send-backs, time, rulebook size
sisi learn --scope core|user|project TEXT
record a human-stated preference; it takes effect at once.
--scope is required, by two questions: (a) does it apply to
all projects where sisi may be used? (b) would it be useful
to every user who installs sisi? Both yes: core (in force
for you, queued for the product). (a) only: user (your
standing principles). Neither: project (handed over to it)
sisi retro print the unit's record and what stands out in it
sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID]
record one finding; promote also needs --change, --mechanism,
--expect and --validate; record needs --limits; drop needs --why-not
sisi lessons [--json] | show ID the learning records and their statuses
sisi cycle [due|apply FILE|check FILE|revert [ID]|help]
turn proposed learnings into mechanisms (no scheduler:
due-ness is a counter); apply validates and replays before
promoting; help prints the cycle file format
sisi approve [ID --yes|--no] decide a consequential learning change a cycle parked
sisi 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 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]
@@ -130,8 +115,8 @@ def cmd_contract(args):
"(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and "
"the end-of-turn gate ignores it." % p)
try:
from . import retro
block = retro.delivery_block(goal or "", "contract-init", extra="contract checks verified")
from . import learning as _L
block = _L.delivery_text(os.getcwd(), goal or "")
if block:
print(block)
except Exception:
@@ -201,18 +186,13 @@ def cmd_oracle():
def _status_retro():
try:
from . import retro
st = retro.stats()
from . import learning as _L
rows = _L.load_learnings()
print("learnings : %d total, %d proposed, %d promoted (`sisi status --learning` for the report)"
% (len(rows), sum(1 for r in rows if r.get("status") == "proposed"),
sum(1 for r in rows if r.get("status") in ("promoted", "monitored"))))
except Exception:
return
print("lessons : %d total, %d open, %d applied; %d occurrences in the last 7 days"
% (st["total"], st["open"], st["applied"], st["occ7"]))
w = st["sessions_with_work"]
print("retros : %s of sessions with real work recorded one (%d of %d)"
% ("%.0f%%" % (100 * st["sessions_with_retro"] / w) if w else "n/a", st["sessions_with_retro"], w))
for t in st["top"]:
from . import retro as _R
print(" active #%-4d x%-3d %s" % (t["id"], t["count"], _R.heading_text(t, 90)))
def _status_contracts(res):
@@ -278,11 +258,6 @@ def cmd_status():
except Exception:
pass
_status_retro()
try:
from . import cycle
print(cycle.improve_line())
except Exception:
pass
_status_contracts(res)
from . import verifiers
vs = [e for e in verifiers.load_verifiers() if e["header"]]
@@ -426,15 +401,12 @@ def main(argv):
if cmd == "lessons":
from . import retro
return retro.cmd_lessons(args)
if cmd == "backlog":
from . import retro
return retro.cmd_backlog(args)
if cmd == "cycle":
from . import cycle
return cycle.cmd_cycle(args)
if cmd == "improve":
if cmd == "approve":
from . import cycle
return cycle.cmd_improve(args)
return cycle.cmd_approve(args)
if cmd == "oracle":
return cmd_oracle()
if cmd == "risk":
+490 -1975
View File
File diff suppressed because it is too large. Load diff
+27 -848
View File
@@ -1,861 +1,40 @@
"""Whole-document edits: the things agents read are documents, and a learning round ends by
rewriting them as documents -- not by appending one more dated bullet.
"""Rulebook structure and budget checks. The per-lesson trace regime is gone.
Documents: the rulebook (doc `rulebook`), each recipe (`recipe:<id>`) and each technique entry
(`verifier:<id>`). A folded lesson ends up as part of the document's own text, in the section
where it belongs. The personal version of a recipe or technique lives in the overlay and
shadows the product's; the overlay records the product text's hash it was derived from
(`overlay.bases()`), and when the product later changes the next brief lists the document as
needing a re-merge -- never silently keeping a stale copy, never silently dropping additions.
Nothing may be lost: a rewrite in a cycle file gives, for every lesson folded into the
document, the exact fragment of the new text that carries it (or that it moved, merged, or was
retired under the usual retirement rule). The trace map lives beside the document in
`overlay/traces/`, never in the text agents load. `sisi lessons show ID`, `sisi rule N` and
`sisi done ID --trace` print where a lesson lives.
Structure is checked mechanically (see `structure_problems`): budgets, headings and Why,
the library lint, the house width after wrapping, run-on bullets, and dated journal bullets.
Kept: what a cycle needs to prove about rule text — every rule keeps an id and a Why,
and the rendered rulebook stays inside its line and character budgets.
"""
import json, os, re, tempfile, textwrap
from . import overlay, paths
EDITORIAL_STANDARD = [
"one instruction per bullet or sentence;",
"most important and most often violated first;",
"related instructions grouped under one heading;",
"no duplicates or near-duplicates;",
"imperative, concrete, plain words;",
"each rule keeps its reason (its Why);",
"exceptions next to the instruction they qualify;",
"nothing that is history or narrative (that lives in the lesson's own record).",
]
DEFAULT_REVIEW_ROUNDS = 10 # a document with no whole-document review for this many rounds is listed
DEFAULT_MAX_BULLET_CHARS = 650
DATED_BULLET = re.compile(r"^\s*[-*]\s+\d{4}-\d{2}-\d{2}\s*:")
MORE_LINE = re.compile(r"^More: `sisi rule \d+`.*$")
from . import overlay
def _cfg(key, default):
class DocumentError(Exception):
pass
def check_rule_text(text, rid=None):
"""Parse and check one rule; returns the parsed rule or raises DocumentError."""
try:
v = (paths.personal_config().get("cycle") or {}).get(key)
return int(v) if v is not None else default
except Exception:
return default
def review_every_rounds():
return _cfg("review_every_rounds", DEFAULT_REVIEW_ROUNDS)
def max_bullet_chars():
return _cfg("max_bullet_chars", DEFAULT_MAX_BULLET_CHARS)
def doc_key(kind, id):
if kind == "rulebook":
return "rulebook"
if kind == "oracle":
return "oracle"
return "%s:%s" % (kind, id)
def parse_doc_key(key):
if key == "rulebook":
return "rulebook", "rulebook"
if key in ("oracle", "oracle:oracle"):
return "oracle", "oracle"
if isinstance(key, str) and ":" in key:
kind, _, id = key.partition(":")
if kind in ("recipe", "verifier") and id:
return kind, id
return None, None
# ---- trace maps and review bookkeeping (overlay/traces/) --------------------
def _trace_rel(kind, id):
return "traces/%s.json" % doc_key(kind, id).replace(":", "-")
def load_trace(kind, id):
try:
with open(paths.overlay_dir(_trace_rel(kind, id)), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def trace_entries(kind, id):
e = load_trace(kind, id).get("entries")
return e if isinstance(e, dict) else {}
def all_traces():
"""{doc_key: entries} for every trace map on disk."""
out = {}
d = paths.overlay_dir("traces")
try:
names = sorted(os.listdir(d))
except OSError:
return out
for n in names:
if not n.endswith(".json") or n == "reviews.json":
continue
try:
with open(os.path.join(d, n), encoding="utf-8") as f:
rec = json.load(f)
if isinstance(rec, dict) and rec.get("doc"):
out[rec["doc"]] = rec.get("entries") or {}
except (OSError, ValueError):
continue
return out
r = overlay.parse_rule_file(text, rid)
except Exception as e:
raise DocumentError("rule text does not parse: %s" % e)
body = r.get("body") or r.get("text") or ""
if "Why" not in body and "why" not in body.split(":", 1)[0].lower():
raise DocumentError("rule %r has no Why paragraph" % r.get("id"))
return r
def traces_for_lesson(lesson_id):
"""[(doc_key, entry)] -- every trace map that says where this lesson lives."""
out = []
for key, entries in sorted(all_traces().items()):
e = entries.get(str(lesson_id))
if isinstance(e, dict):
out.append((key, e))
return out
return [] # the per-lesson trace regime is retired; provenance lives on the learning record
def load_reviews():
try:
with open(paths.overlay_dir("traces", "reviews.json"), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def trace_lines(kind, entry_id):
return []
def _save_reviews(reviews):
overlay._write("traces/reviews.json", json.dumps(reviews, indent=1, sort_keys=True) + "\n")
def next_round_number():
from . import cycle
return len(cycle.cycle_records()) + 1
# ---- what a document currently says, and which lessons are folded into it ----
def effective_text(kind, id):
if kind == "rulebook":
return overlay.render()
if kind == "oracle":
from . import principles
return principles.oracle_text()
from . import verifiers as V
entries = V.load_recipes() if kind == "recipe" else V.load_verifiers()
for e in entries:
if e["id"] == id:
try:
with open(e["path"], encoding="utf-8") as f:
return f.read()
except OSError:
return ""
return ""
def _notes_lesson_ids(entry_id):
from . import retro
ids = []
try:
with open(os.path.join(paths.notes_dir(), entry_id + ".md"), encoding="utf-8") as f:
for line in f:
p = retro._parse_bullet(line)
if p:
ids.append(p[2])
except OSError:
pass
return ids
def folded_lesson_ids(con, kind, id):
"""Lessons folded into this document: by the lessons table, by its field-note bullets,
and by an existing trace map. Superseded lessons are history and do not count."""
ids = set()
try:
for r in con.execute("SELECT id, folded_into, status FROM lessons"):
if r[2] == "superseded":
continue
targets = [t.strip() for t in str(r[1] or "").split(",") if t.strip()]
if kind == "rulebook":
hit = any(t.startswith("rule:") or t == "rulebook" for t in targets)
else:
hit = id in targets
if hit:
ids.add(r[0])
except Exception:
pass
if kind != "rulebook":
ids.update(_notes_lesson_ids(id))
for k in trace_entries(kind, id):
try:
ids.add(int(k))
except ValueError:
pass
key = doc_key(kind, id)
for _src, entries in all_traces().items():
for lid_s, t in entries.items():
if isinstance(t, dict) and t.get("disposition") == "moved" and t.get("to") == key:
try:
ids.add(int(lid_s))
except ValueError:
pass
return sorted(ids)
def _personal_exists(kind, id):
return bool(overlay._overlay_entry_paths(kind, id))
def _stale_reason(kind, id):
if kind == "rulebook" or not _personal_exists(kind, id):
return None
cur = overlay.base_hash(kind, id)
if cur is None:
return None # a personal addition: there is no product text to drift from
recorded = overlay.bases().get("%s:%s" % (kind, id))
if recorded != cur:
return ("the product text changed since the personal copy was made: needs a re-merge "
"(keep the personal additions, take in the product's changes)")
return None
def required_documents(con):
"""Documents the next round must rewrite or mark reviewed: field notes not yet integrated,
a stale personal copy, or no whole-document review for the configured number of rounds.
Returns [{doc, kind, id, reasons, lessons}] -- lessons are the unintegrated ones."""
from . import cycle, verifiers as V
reviews = load_reviews()
rounds = len(cycle.cycle_records())
every = review_every_rounds()
cands = [("rulebook", "rulebook"), ("oracle", "oracle")]
cands += [("recipe", e["id"]) for e in V.load_recipes() if e["header"]]
cands += [("verifier", e["id"]) for e in V.load_verifiers() if e["header"]]
out = []
for kind, id in cands:
key = doc_key(kind, id)
if kind == "oracle":
from . import principles as _pr
recs = _pr.statements()
if not recs:
continue
file_text = _pr._oracle_file_text() or ""
entries = trace_entries(kind, id)
traced_texts = {e.get("statement") for e in entries.values() if isinstance(e, dict)}
missing = [r for r in recs if r["text"] not in traced_texts or r["text"] not in file_text]
reasons = []
if missing:
reasons.append("standing principles not yet integrated and traced into the "
"oracle document (they are in force; this round owns the document)")
last = int((reviews.get(key) or {}).get("round") or 0)
if rounds >= every and rounds - last >= every:
reasons.append("no whole-document review for %d rounds" % (rounds - last))
if reasons:
out.append({"doc": key, "kind": kind, "id": id, "reasons": reasons,
"lessons": [], "statements": [r["text"] for r in missing]})
continue
folded = folded_lesson_ids(con, kind, id)
traced = {int(k) for k in trace_entries(kind, id) if str(k).isdigit()}
covered = set((reviews.get(key) or {}).get("covered") or [])
unintegrated = [i for i in folded if i not in traced and i not in covered]
reasons = []
if unintegrated:
reasons.append("appended field notes not yet integrated into the document's own text"
if kind != "rulebook" else
"lessons folded into rules are not yet traced to the text that carries them")
stale = _stale_reason(kind, id)
if stale:
reasons.append(stale)
eligible = kind == "rulebook" or bool(folded) or bool(traced) or _personal_exists(kind, id)
last = int((reviews.get(key) or {}).get("round") or 0)
if eligible and rounds >= every and rounds - last >= every:
reasons.append("no whole-document review for %d rounds" % (rounds - last))
if reasons:
out.append({"doc": key, "kind": kind, "id": id, "reasons": reasons,
"lessons": unintegrated})
return out
# ---- structure checks ---------------------------------------------------------
def _bullets(text):
"""Joined bullet texts (a bullet plus its indented continuation lines)."""
out, cur = [], None
for line in text.split("\n"):
if re.match(r"^\s*[-*]\s+", line):
if cur is not None:
out.append(cur)
cur = line.strip()
elif cur is not None and line.startswith(" ") and line.strip():
cur += " " + line.strip()
elif cur is not None:
out.append(cur)
cur = None
if cur is not None:
out.append(cur)
return out
def _sentence_count(text):
t = re.sub(r"`[^`]*`", " ", text) # code spans are not prose
t = re.sub(r"https?://\S+", " ", t)
return len(re.findall(r"[.!?]+(?=\s+[A-Z0-9\"']|\s*$)", t))
def wrap_text(text, width=overlay.HOUSE_WIDTH):
"""Wrap prose paragraphs and bullets to the house width. Front matter, code fences,
indented code, tables and headings are left alone."""
lines = text.split("\n")
out, i, fence, front = [], 0, False, bool(lines and lines[0].strip() == "---")
while i < len(lines):
line = lines[i]
if front:
out.append(line)
if i > 0 and line.strip() == "---":
front = False
i += 1
continue
if line.strip().startswith("```"):
fence = not fence
out.append(line); i += 1; continue
if fence or not line.strip() or line.startswith((" ", "\t", "|", "#")):
out.append(line); i += 1; continue
m = re.match(r"^(\s*)([-*]|\d+\.)\s+(.*)$", line)
if m:
indent, marker, rest = m.groups()
parts = [rest]
i += 1
while i < len(lines) and lines[i].startswith(" ") and lines[i].strip() \
and not re.match(r"^\s*[-*]\s+", lines[i]):
parts.append(lines[i].strip()); i += 1
joined = " ".join(parts)
sub = indent + " " * (len(marker) + 1)
wrapped = textwrap.wrap(joined, width=width, initial_indent="%s%s " % (indent, marker),
subsequent_indent=sub, break_long_words=False,
break_on_hyphens=False)
out.extend(wrapped or ["%s%s " % (indent, marker)])
continue
parts = [line.strip()]
i += 1
while i < len(lines) and lines[i].strip() and not lines[i].startswith((" ", "\t", "|", "#")) \
and not re.match(r"^\s*([-*]|\d+\.)\s+", lines[i]) \
and not lines[i].strip().startswith("```"):
parts.append(lines[i].strip()); i += 1
out.extend(textwrap.wrap(" ".join(parts), width=width, break_long_words=False,
break_on_hyphens=False) or [""])
return "\n".join(out)
def _long_line_problems(text):
wrapped = wrap_text(text)
out, fence, front = [], False, wrapped.startswith("---")
for n, line in enumerate(wrapped.split("\n"), 1):
if front:
if n > 1 and line.strip() == "---":
front = False
continue
if line.strip().startswith("```"):
fence = not fence
continue
if fence or line.startswith((" ", "\t", "|")):
continue
if len(line) > overlay.HOUSE_WIDTH:
out.append("line %d is %d characters after wrapping (house width %d)"
% (n, len(line), overlay.HOUSE_WIDTH))
return out
def _entry_lint_problems(kind, text, doc_id):
"""The library lint for one candidate entry, mirroring `verifiers.lint()`."""
from . import contract as C, verifiers as V
tmp = tempfile.NamedTemporaryFile("w", suffix=".md", prefix=(doc_id or "entry") + "-",
delete=False, encoding="utf-8")
try:
tmp.write(text); tmp.close()
# parse under the entry's own file name so the id-equals-stem check means something
named = os.path.join(os.path.dirname(tmp.name), (doc_id or "entry") + ".md")
os.replace(tmp.name, named)
e = V.parse(named)
finally:
for p in (tmp.name, os.path.join(os.path.dirname(tmp.name), (doc_id or "entry") + ".md")):
try:
os.unlink(p)
except OSError:
pass
out = list(e["problems"])
h = e["header"]
if not h:
return out or ["no header block"]
keys, heads = (V.V_KEYS, V.V_HEADINGS) if kind == "verifier" else (V.D_KEYS, V.D_HEADINGS)
for k in keys:
if k not in h or (not h[k] and k != "detect"):
out.append("missing or empty %r" % k)
if doc_id and h.get("id") and h["id"] != doc_id:
out.append("header id %r must equal the document id %r" % (h["id"], doc_id))
for m in V._missing_headings(e["body"], heads):
out.append("body lacks the heading %r" % m)
if kind == "verifier":
if not re.fullmatch(r"[1-6]", h.get("rung", "")):
out.append("rung must be an integer 1-6")
if h.get("section") and h["section"] not in V.SECTIONS:
out.append("unknown section %r" % h["section"])
if h.get("cost") and h["cost"] not in V.COSTS:
out.append("cost must be one of %s" % ", ".join(V.COSTS))
if h.get("ran_here") and h["ran_here"] not in ("yes", "no"):
out.append("ran_here must be yes or no")
for k in V._list(h.get("kinds")):
if k != "any" and k not in C.KINDS:
out.append("unknown kind %r" % k)
else:
known = {x["id"] for x in V.load_verifiers()} | set(overlay.disabled("verifier"))
fake = dict(e, body=e["body"])
for i in dict.fromkeys(V.cited_ids(fake)):
if i not in known:
out.append("Checks cites unknown verifier id %r" % i)
return out
def rulebook_problems(text):
out = []
pre, rules = overlay.parse_rules(text)
headings = [l for l in text.split("\n") if l.startswith("## ")]
if len(headings) != len(rules):
out.append("the rulebook text does not parse into rules")
seen = set()
for line, r in zip(headings, rules):
if not overlay.ID_TAIL.search(line):
out.append("rule heading %r lacks its {#id}" % line[:60])
if r["id"] in seen:
out.append("duplicate rule id %r" % r["id"])
seen.add(r["id"])
if not any(p.lstrip().startswith("Why:") for p in r["body"].split("\n\n")):
out.append("rule %s lacks its Why paragraph" % r["id"])
cand = candidate_render(pre, rules)
lines, chars = overlay.size(cand)
def check_budgets(rendered=None):
"""(ok, message) for the rendered rulebook against the overlay budgets."""
rendered = overlay.render() if rendered is None else rendered
lines, chars = overlay.size(rendered)
if lines > overlay.MAX_LINES or chars > overlay.MAX_CHARS:
out.append("the rulebook would be %d lines and %d characters; the budgets are %d lines "
"and %d characters" % (lines, chars, overlay.MAX_LINES, overlay.MAX_CHARS))
for n in range(1, len(rules) + 1):
if overlay.more_line(n) not in cand:
out.append("rule %d lacks its generated `More: sisi rule %d` line" % (n, n))
return out
def candidate_render(pre, rules):
try:
head = overlay.render().splitlines()[0]
except Exception:
head = "<!-- candidate rulebook -->"
parts = [head]
if (pre or "").strip():
parts.append(pre)
for n, r in enumerate(rules, 1):
body = "\n".join(l for l in r["body"].split("\n") if not MORE_LINE.match(l.strip()))
parts.append("## %d. %s {#%s}\n\n%s\n%s" % (n, r["title"], r["id"], body.strip("\n"),
overlay.more_line(n)))
return "\n\n".join(parts) + "\n"
def structure_problems(kind, text, doc_id=None):
"""Mechanical refusals for a rewritten document. Empty means the structure is acceptable.
The bullet test is deliberately simple: one bullet, once it passes the configured length
(default %d characters), may not end more than one sentence.""" % DEFAULT_MAX_BULLET_CHARS
out = []
for n, line in enumerate(text.split("\n"), 1):
if DATED_BULLET.match(line):
out.append("line %d is a dated journal-style bullet; integrate it into the "
"document's own text instead" % n)
limit = max_bullet_chars()
for b in _bullets(text):
if len(b) > limit and _sentence_count(b) > 1:
out.append("a bullet of %d characters holds %d sentences; one instruction per "
"bullet (limit %d characters): %r" % (len(b), _sentence_count(b), limit, b[:60]))
out.extend(_long_line_problems(text))
if kind == "oracle" and not (text or "").lstrip().startswith("# "):
out.append("the oracle document must start with a `# title` heading")
if kind == "rulebook":
out.extend(rulebook_problems(text))
elif kind in ("recipe", "verifier"):
out.extend(_entry_lint_problems(kind, text, doc_id))
return out
def _norm(s):
return " ".join(str(s or "").split())
def _fragment_in(fragment, text):
return bool(fragment) and _norm(fragment) in _norm(text)
# ---- validation of a cycle file's documents part ------------------------------
def _retirement_ok(con, lid):
from . import retro
r = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()
if not r:
return "no such lesson"
if not r["folded_into"]:
return "it is not folded anywhere yet"
if retro.shown_count(con, lid) < retro.RETIRE_SHOWS:
return "it has been shown %d times (retirement needs %d quiet showings)" % (
retro.shown_count(con, lid), retro.RETIRE_SHOWS)
if retro.recurrences_after_shown(con, r):
return "it still recurs after being shown"
return None
def validate_documents(doc, con, required=None):
errs = []
entries = doc.get("documents") or []
if not isinstance(entries, list):
return ["documents must be a list"]
by_doc = {}
for e in entries:
if not isinstance(e, dict) or not e.get("doc"):
errs.append("each documents entry needs a doc (\"rulebook\", \"oracle\", \"recipe:<id>\" or \"verifier:<id>\"): %r" % (e,))
continue
kind, id = parse_doc_key(e["doc"])
if kind is None:
errs.append("documents entry %r: doc must be \"rulebook\", \"oracle\", \"recipe:<id>\" or \"verifier:<id>\"" % e["doc"])
continue
if kind != "rulebook" and not effective_text(kind, id):
errs.append("document %s: no such %s" % (e["doc"], kind))
continue
by_doc[e["doc"]] = e
if required is None:
required = required_documents(con)
# an oracle whose only unintegrated statements this same file scopes to their project
# needs no rewrite: they leave the global store in this round
_to_project = {e.get("text") for e in doc.get("learn") or []
if isinstance(e, dict) and e.get("scope") == "project"}
if _to_project:
required = [r for r in required
if not (r.get("doc") == "oracle" and r.get("statements")
and all(t in _to_project for t in r["statements"]))]
for req in required:
if req["doc"] not in by_doc:
errs.append("document %s: missing whole-document entry - the brief listed it (%s); add a "
"documents entry {\"doc\": %r, \"action\": \"rewrite\", \"text\": ..., \"trace\": [...]} "
"or {\"doc\": %r, \"action\": \"reviewed\", \"reason\": \"...\"}"
% (req["doc"], "; ".join(req["reasons"]), req["doc"], req["doc"]))
# lessons this same file folds into a document also need a trace entry in its rewrite
extra_folded = {}
for e in doc.get("notes") or []:
if not isinstance(e, dict) or not isinstance(e.get("lesson"), int):
continue
intos = e.get("into")
intos = intos if isinstance(intos, list) else ([intos] if intos else [])
if e.get("action") == "fold-into-entry":
from . import verifiers as V
rids = {x["id"] for x in V.load_recipes() if x["header"]}
for into in intos:
key = doc_key("recipe" if into in rids else "verifier", into)
extra_folded.setdefault(key, set()).add(e["lesson"])
elif e.get("action") == "fold-into-rule":
extra_folded.setdefault("rulebook", set()).add(e["lesson"])
new_texts = {k: e.get("text") or "" for k, e in by_doc.items() if e.get("action") == "rewrite"}
for key, e in sorted(by_doc.items()):
kind, id = parse_doc_key(key)
act = e.get("action")
if act not in ("rewrite", "reviewed"):
errs.append("document %s: action must be rewrite or reviewed" % key)
continue
if act == "reviewed":
if not str(e.get("reason") or "").strip():
errs.append("document %s: reviewed needs a one-line reason why its structure is already right" % key)
continue
text = e.get("text")
if not str(text or "").strip():
errs.append("document %s: rewrite needs text (the full new document)" % key)
continue
for p in structure_problems(kind, text, None if kind == "rulebook" else id):
errs.append("document %s: %s" % (key, p))
needed = set(folded_lesson_ids(con, kind, id)) | extra_folded.get(key, set())
trace = e.get("trace") or []
if not isinstance(trace, list):
errs.append("document %s: trace must be a list" % key)
trace = []
seen = {}
for t in trace:
if isinstance(t, dict) and isinstance(t.get("lesson"), int):
seen[t["lesson"]] = t
for lid in sorted(needed - set(seen)):
errs.append("lesson #%d: no trace entry in the rewrite of %s - give the exact fragment "
"of the new text that carries it, or a moved/merged/retired disposition" % (lid, key))
for lid, t in sorted(seen.items()):
disp = t.get("disposition") or "carried"
frag = t.get("fragment")
if disp == "carried":
if not _fragment_in(frag, text):
errs.append("lesson #%d: its fragment %r does not occur in the new text of %s"
% (lid, str(frag)[:60], key))
elif disp == "merged":
other = t.get("merged_with")
if not isinstance(other, int) or other == lid:
errs.append("lesson #%d: merged needs merged_with naming a different lesson" % lid)
elif not _fragment_in(frag, text):
errs.append("lesson #%d: its merged fragment %r does not occur in the new text of %s"
% (lid, str(frag)[:60], key))
elif other in seen and _norm(seen[other].get("fragment")) != _norm(frag):
errs.append("lesson #%d: merged with #%d but their fragments differ; both ids must "
"point at the same fragment" % (lid, other))
elif disp == "moved":
to_kind, to_id = parse_doc_key(t.get("to") or "")
if to_kind is None:
errs.append("lesson #%d: moved needs \"to\" naming the document it moved to" % lid)
else:
target_text = new_texts.get(t["to"]) or effective_text(to_kind, to_id)
if not _fragment_in(frag, target_text):
errs.append("lesson #%d: its fragment %r does not occur in %s, where it is said to live now"
% (lid, str(frag)[:60], t["to"]))
elif disp == "retired":
if not str(t.get("reason") or "").strip():
errs.append("lesson #%d: retired needs a reason" % lid)
else:
why_not = _retirement_ok(con, lid)
if why_not:
errs.append("lesson #%d: cannot retire it in a rewrite: %s" % (lid, why_not))
else:
errs.append("lesson #%d: disposition must be carried, moved, merged or retired" % lid)
if kind == "oracle":
from . import principles as _pr
stmt_seen = {t["statement"]: t for t in trace
if isinstance(t, dict) and isinstance(t.get("statement"), str)}
for rec in _pr.statements():
t = stmt_seen.get(rec["text"])
if t is None:
errs.append("principle %r: no trace entry in the rewrite of oracle - give the "
"exact fragment of the new text that carries it (every statement "
"must be traced)" % rec["text"][:60])
elif not _fragment_in(t.get("fragment"), text):
errs.append("principle %r: its fragment %r does not occur in the new oracle text"
% (rec["text"][:60], str(t.get("fragment"))[:60]))
if kind == "rulebook":
_pre, new_rules = overlay.parse_rules(text)
new_ids = [r["id"] for r in new_rules]
merges = {}
for m in e.get("rule_merges") or []:
if isinstance(m, dict) and m.get("from") and m.get("into"):
merges[m["from"]] = m["into"]
_p2, eff = overlay.effective()
for r in eff:
if r["id"] not in new_ids and r["id"] not in merges:
errs.append("rule %s: every existing rule id must survive a rulebook rewrite or be "
"merged into another id (rule_merges)" % r["id"])
for frm, into in sorted(merges.items()):
if into not in new_ids:
errs.append("rule %s: merged into %s, which is not in the new rulebook" % (frm, into))
order = doc.get("rule_order")
if order is not None:
_pre, eff = overlay.effective()
want = {r["id"] for r in eff} - set(doc.get("disable_rules") or [])
want |= {e.get("id") for e in doc.get("rules") or []
if isinstance(e, dict) and e.get("action") == "add"}
rb = by_doc.get("rulebook") or {}
if rb.get("action") == "rewrite" and rb.get("text"):
_p3, new_rules = overlay.parse_rules(rb["text"])
want = {r["id"] for r in new_rules}
if not isinstance(order, list) or set(order) != want or len(order) != len(set(order)):
errs.append("rule_order must name every rule id exactly once (missing: %s; unknown: %s)"
% (", ".join(sorted(want - set(order if isinstance(order, list) else []))) or "-",
", ".join(sorted(set(order if isinstance(order, list) else []) - want)) or "-"))
return errs
def candidate_rulebook(doc):
"""The rulebook text a cycle file would produce, or None when it does not touch the
rulebook as a document or its order (the older per-rule prediction then applies)."""
entries = {e.get("doc"): e for e in doc.get("documents") or [] if isinstance(e, dict)}
rb = entries.get("rulebook") or {}
if rb.get("action") == "rewrite" and rb.get("text"):
pre, rules = overlay.parse_rules(rb["text"])
if isinstance(doc.get("rule_order"), list):
rank = {id: i for i, id in enumerate(doc["rule_order"])}
rules = sorted(rules, key=lambda r: rank.get(r["id"], len(rank)))
return candidate_render(pre, rules)
if isinstance(doc.get("rule_order"), list):
pre, eff = overlay.effective()
by_id = {r["id"]: r for r in eff}
for rid in doc.get("disable_rules") or []:
by_id.pop(rid, None)
for e in doc.get("rules") or []:
if isinstance(e, dict) and e.get("id"):
by_id[e["id"]] = {"id": e["id"], "title": e.get("title") or e["id"],
"body": overlay.wrap_rule_body(e.get("body") or "")}
rules = [by_id[i] for i in doc["rule_order"] if i in by_id]
rules += [r for i, r in by_id.items() if i not in doc["rule_order"]]
return candidate_render(pre, rules)
return None
# ---- applying a validated cycle file's documents part -------------------------
def _drop_note_bullets(entry_id, lesson_ids):
from . import retro
p = os.path.join(paths.notes_dir(), entry_id + ".md")
try:
with open(p, encoding="utf-8") as f:
lines = f.read().splitlines(True)
except OSError:
return
keep = []
for line in lines:
parsed = retro._parse_bullet(line)
if parsed and parsed[2] in lesson_ids:
continue
keep.append(line)
if not any(retro._parse_bullet(l) for l in keep):
try:
os.unlink(p)
except OSError:
pass
elif keep != lines:
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
f.write("".join(keep))
os.replace(tmp, p)
def _record_review(reviews, key, con, kind, id, action):
reviews[key] = {"round": next_round_number(), "action": action,
"covered": folded_lesson_ids(con, kind, id)}
def apply_documents(doc, con, touched):
"""Write rewrites, trace maps, reviews and rule order. Caller holds the personal-data
lock and has already validated. Returns {doc_key: [lesson ids]} for rewritten documents."""
from . import store
reviews = load_reviews()
changed = {}
for e in doc.get("documents") or []:
if not isinstance(e, dict):
continue
kind, id = parse_doc_key(e.get("doc") or "")
if kind is None:
continue
key = e["doc"]
if e.get("action") == "reviewed":
_record_review(reviews, key, con, kind, id, "reviewed")
continue
if e.get("action") != "rewrite":
continue
text = e["text"] if e["text"].endswith("\n") else e["text"] + "\n"
trace = {t["lesson"]: t for t in e.get("trace") or []
if isinstance(t, dict) and isinstance(t.get("lesson"), int)}
if kind == "rulebook":
_apply_rulebook(e, text, con, touched)
elif kind == "oracle":
from . import principles as _pr
p = _pr.oracle_path()
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
os.replace(tmp, p)
for t in e.get("trace") or []:
if isinstance(t, dict) and isinstance(t.get("statement"), str):
entries = trace_entries(kind, id)
entries[t["statement"]] = {"statement": t["statement"],
"fragment": t.get("fragment"),
"disposition": t.get("disposition") or "carried"}
rec = {"doc": key, "kind": kind, "id": id, "base_hash": None, "entries": entries}
overlay._write(_trace_rel(kind, id), json.dumps(rec, indent=1, sort_keys=True) + "\n")
_record_review(reviews, key, con, kind, id, "rewrite")
changed[key] = []
continue
else:
_id, rel, mine = overlay._put_entry(kind, text, id, True)
for p in mine:
overlay._remove(p)
overlay._write(rel, text)
overlay._set_base(kind, id, overlay.base_hash(kind, id))
if trace:
_drop_note_bullets(id, set(trace))
entries = trace_entries(kind, id)
for lid, t in trace.items():
touched.add(lid)
disp = t.get("disposition") or "carried"
entries[str(lid)] = {"fragment": t.get("fragment"), "disposition": disp,
"to": t.get("to"), "merged_with": t.get("merged_with"),
"reason": t.get("reason")}
if disp == "moved":
to_kind, to_id = parse_doc_key(t.get("to") or "")
folded = "rule:%s" % to_id if to_kind == "rulebook" else to_id
if to_kind == "rulebook":
# the fragment lives in one rule; keep the lesson pointing at the rulebook
folded = "rulebook"
con.execute("UPDATE lessons SET folded_into=? WHERE id=?", (folded, lid))
elif disp == "retired":
con.execute("UPDATE lessons SET status='retired', needs_cycle=0 WHERE id=?", (lid,))
rec = {"doc": key, "kind": kind, "id": id,
"base_hash": overlay.base_hash(kind, id) if kind != "rulebook" else None,
"entries": entries}
if kind == "rulebook" and e.get("rule_merges"):
rec["rule_merges"] = {m["from"]: m["into"] for m in e["rule_merges"]
if isinstance(m, dict) and m.get("from")}
overlay._write(_trace_rel(kind, id), json.dumps(rec, indent=1, sort_keys=True) + "\n")
_record_review(reviews, key, con, kind, id, "rewrite")
changed[key] = sorted(trace)
if isinstance(doc.get("rule_order"), list):
overlay._set_lines("rules/full-order.txt", list(doc["rule_order"]))
if reviews != load_reviews() or changed:
_save_reviews(reviews)
return changed
def _apply_rulebook(e, text, con, touched):
pre, rules = overlay.parse_rules(text)
base = {r["id"]: r for r in overlay.base_rules()[1]}
merges = {m["from"]: m["into"] for m in e.get("rule_merges") or []
if isinstance(m, dict) and m.get("from") and m.get("into")}
for r in rules:
body = overlay.wrap_rule_body("\n".join(
l for l in r["body"].split("\n") if not MORE_LINE.match(l.strip())))
cand = {"id": r["id"], "title": r["title"], "body": body}
b = base.get(r["id"])
rel = "rules/%s.md" % r["id"]
if b and b["title"] == cand["title"] and overlay.wrap_rule_body(b["body"]) == body:
overlay._remove(paths.overlay_dir(rel)) # back to the product text: no personal copy
overlay._set_base("rule", r["id"], None)
else:
overlay._write(rel, overlay.rule_text(cand))
if b:
overlay._set_base("rule", r["id"], overlay.base_hash("rule", r["id"]))
if merges:
off = overlay.disabled("rule")
overlay._set_lines("rules/disabled.txt", off + [x for x in merges if x not in off])
for frm, into in merges.items():
overlay._remove(paths.overlay_dir("rules/%s.md" % frm))
for row in con.execute("SELECT id, folded_into FROM lessons WHERE folded_into LIKE ?",
("%" + "rule:" + frm + "%",)):
touched.add(row[0])
new = ",".join("rule:" + into if t.strip() == "rule:" + frm else t.strip()
for t in str(row[1]).split(","))
con.execute("UPDATE lessons SET folded_into=? WHERE id=?", (new, row[0]))
overlay._set_lines("rules/full-order.txt", [r["id"] for r in rules])
def trace_lines(kind, id):
"""Plain lines for `sisi done ID --trace` and friends: where each lesson lives."""
entries = trace_entries(kind, id)
if not entries:
return ["no whole-document rewrite has traced lessons into %s yet" % doc_key(kind, id)]
out = ["where each lesson lives in %s (trace map, not part of the text agents load):"
% doc_key(kind, id)]
for lid_s in sorted(entries, key=lambda s: int(s) if str(s).isdigit() else 0):
t = entries[lid_s]
disp = t.get("disposition") or "carried"
if disp == "moved":
out.append(" #%s moved to %s as %r" % (lid_s, t.get("to"), t.get("fragment")))
elif disp == "merged":
out.append(" #%s merged with #%s as %r" % (lid_s, t.get("merged_with"), t.get("fragment")))
elif disp == "retired":
out.append(" #%s retired: %s" % (lid_s, t.get("reason")))
else:
out.append(" #%s lives as %r" % (lid_s, t.get("fragment")))
return out
return False, ("rulebook over budget: %d lines (max %d), %d chars (max %d)"
% (lines, overlay.MAX_LINES, chars, overlay.MAX_CHARS))
return True, "%d lines, %d chars, inside budget" % (lines, chars)
+417
View File
@@ -0,0 +1,417 @@
"""Learning records: the single store behind retro, cycle, learn/oracle and monitoring.
One store: learnings.jsonl in the user store (one JSON object per learning, rewritten
atomically; git in the user store is the history). Findings of a retro live in
findings.jsonl. Showings are never recorded as evidence. See docs/learning.md.
"""
import hashlib, json, os, re, subprocess, time
from . import paths, pdata
STATUSES = ("observed", "analyzed", "proposed", "implemented", "validated",
"promoted", "monitored", "revised", "reverted", "rejected")
MECHANISMS = ("policy", "orchestration", "skill", "tool", "infrastructure",
"verification", "knowledge", "benchmark")
IMPACTS = ("value", "correctness", "time", "cost", "attention")
SCOPES = ("organization", "user", "project", "task-class")
GENERIC = re.compile(r"^\s*(nothing|none|n/?a|be more careful|write better tests|"
r"use cheaper models|do better|all good|no issues?)\W*$", re.I)
STOP = set("the a an and or of to in is was were be been it its this that with for on at by as not no do does did when then than from we i".split())
class LearningError(Exception):
pass
def now():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def project_key(cwd):
"""Stable project identity: the git root (main repo for linked worktrees), else the dir."""
try:
from . import groundtruth
root, _vcs = groundtruth.main_repo_of(cwd)
if root:
return os.path.realpath(root)
except Exception:
pass
try:
out = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=cwd,
capture_output=True, text=True, timeout=10)
if out.returncode == 0 and out.stdout.strip():
return os.path.realpath(out.stdout.strip())
except (OSError, subprocess.SubprocessError):
pass
return os.path.realpath(cwd)
def unit_id(project=None):
"""Seam with the work-unit worker: the id in .sisi/contract.json, else a session fallback."""
project = project or os.getcwd()
try:
with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f:
c = json.load(f)
if isinstance(c, dict) and c.get("id"):
return str(c["id"])
except (OSError, ValueError):
pass
return "session:" + (os.environ.get("SISI_SESSION_ID") or
hashlib.sha1(os.path.realpath(project).encode()).hexdigest()[:12])
def is_subagent_session():
return os.environ.get("SISI_SUBAGENT") == "1" or os.environ.get("SISI_AGENT_DEPTH", "") not in ("", "0")
# ---- store io -----------------------------------------------------------------
def learnings_path():
return paths.data_file("learnings.jsonl")
def findings_path():
return paths.data_file("findings.jsonl")
def pending_path():
return paths.data_file("pending.json")
def load_learnings():
out = []
try:
with open(learnings_path(), encoding="utf-8") as f:
for line in f:
if line.strip():
d = json.loads(line)
if isinstance(d, dict) and d.get("id"):
out.append(d)
except OSError:
pass
return out
def save_learnings(rows, msg):
pdata.ensure()
text = "".join(json.dumps(r, sort_keys=True) + "\n" for r in rows)
pdata.write_text("learnings.jsonl", text)
pdata.commit(msg, ["learnings.jsonl"])
def store_base(rows=None):
rows = load_learnings() if rows is None else rows
h = hashlib.sha256()
for r in rows:
h.update(json.dumps(r, sort_keys=True).encode())
h.update(b"\n")
return h.hexdigest()[:16]
def load_findings():
out = []
try:
with open(findings_path(), encoding="utf-8") as f:
for line in f:
if line.strip():
d = json.loads(line)
if isinstance(d, dict):
out.append(d)
except OSError:
pass
return out
def append_finding(f, msg="retro: finding"):
pdata.ensure()
old = pdata.read_text("findings.jsonl", "") or ""
pdata.write_text("findings.jsonl", old + json.dumps(f, sort_keys=True) + "\n")
pdata.commit(msg, ["findings.jsonl"])
def next_id(rows):
n = 0
for r in rows:
m = re.match(r"L-(\d+)$", str(r.get("id", "")))
if m:
n = max(n, int(m.group(1)))
return "L-%04d" % (n + 1)
def get(rows, lid):
for r in rows:
if r.get("id") == lid:
return r
return None
# ---- derived text (the tool derives search terms, topics, short lines) ---------
def _stem(w):
"""A crude stem so 'parsing', 'parser' and 'parse' meet, as do plurals."""
s = w
if len(s) > 4 and s.endswith("ies"):
s = s[:-3] + "y"
else:
done = False
for suf in ("ingly", "ing", "edly", "ed"):
if s.endswith(suf) and len(s) - len(suf) >= 3:
base = s[:-len(suf)]
if len(base) >= 2 and base[-1] == base[-2] and base[-1] not in "aeious":
base = base[:-1]
s, done = base, True
break
if not done:
if s.endswith(("ses", "xes", "zes", "ches", "shes")) and len(s) - 2 >= 3:
s = s[:-2]
else:
for suf in ("ers", "er", "s"):
if s.endswith(suf) and len(s) - len(suf) >= 3:
s = s[:-len(suf)]
break
if len(s) >= 4 and s.endswith("e"):
s = s[:-1]
return s
def stems(text):
return {_stem(w) for w in re.findall(r"[a-z0-9_]+", (text or "").lower())
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_title(text, limit=90):
t = " ".join((text or "").split())
t = re.split(r"(?<=[.!?])\s", t)[0]
return t[:limit].rstrip()
def similar_learnings(rows, text, limit=3):
q = stems(text)
scored = []
for r in rows:
if r.get("status") in ("rejected", "reverted"):
continue
hay = set(r.get("terms") or []) | stems(r.get("observation", {}).get("evidence", "")) \
| stems(r.get("proposed", {}).get("description", ""))
inter = len(q & hay)
if inter >= 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]
# ---- scope (earned, never claimed) ---------------------------------------------
def earned(rec):
"""Cross-project delivery is earned: >=2 units in >=2 projects, or an owner statement."""
if rec.get("owner_statement"):
return True
prov = rec.get("provenance") or []
units = {p.get("unit") for p in prov if p.get("unit")}
projects = {p.get("project") for p in prov if p.get("project")}
return len(units) >= 2 and len(projects) >= 2
def in_scope(rec, project):
if rec.get("status") in ("rejected", "reverted"):
return False
if rec.get("candidate"): # subagent learning, held until a parent retro adopts it
return False
if rec.get("entered_via") not in ("retro", "learn", "cycle", "migration"):
return False # only learnings that entered through sisi's own commands are delivered
pk = project_key(project) if project else None
if pk and rec.get("origin_project") == pk:
return True
return earned(rec)
def learnings_in_scope(project, rows=None):
rows = load_learnings() if rows is None else rows
return [r for r in rows if in_scope(r, project)]
def delivery_text(project, query=""):
"""Learnings in scope, framed as information, never as instructions. No showing is recorded."""
rows = learnings_in_scope(project)
if query:
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]:
val = (r.get("validation") or {}).get("result") or "unvalidated"
lines.append("- [%s, %s] %s — %s" % (r["id"], val if val == "validated" else "unvalidated",
derive_title(r.get("title") or "", 110),
derive_title(r.get("proposed", {}).get("description", ""), 160)))
return "\n".join(lines) + "\n"
# ---- findings / record creation -------------------------------------------------
def new_record(finding, cause, impact, disposition, project, unit,
change=None, mechanism=None, scope=None, expect=None, validate=None,
limits=None, why_not=None, owner_statement=False, subagent=False,
replay=None, entered_via="retro"):
rows = load_learnings()
pk = project_key(project)
rec = {
"id": next_id(rows), "title": derive_title(change or finding),
"source_unit": unit, "origin_project": pk,
"observation": {"evidence": finding, "impact": impact},
"root_cause": cause,
"proposed": {"description": change or "", "mechanism": mechanism,
"scope": scope or ("user" if owner_statement else "project"),
"target": None},
"expected_effect": expect or "", "limits": limits or "", "why_not": why_not or "",
"validation": {"method": validate or "", "benchmark": None,
"result": "unvalidated", "detail": ""},
"status": "promoted" if owner_statement else
("proposed" if disposition == "promote" else "observed"),
"version": 1, "confidence": "low",
"provenance": [{"unit": unit, "project": pk, "ts": now(), "kind": "origin"}],
"terms": derive_terms(finding, cause, change or ""),
"owner_statement": bool(owner_statement), "candidate": bool(subagent),
"entered_via": entered_via, "recurrences_after_promotion": 0,
"flagged_not_working": False, "promoted_at": now() if owner_statement else None,
"promoted_unit_seq": None, "mechanism_ref": None, "replay": replay,
"created": now(),
}
rows.append(rec)
save_learnings(rows, "learning %s recorded" % rec["id"])
return rec
def add_recurrence(rec, unit, project, rows):
"""Attach a recurrence. After promotion it counts against the learning."""
pk = project_key(project)
rec.setdefault("provenance", []).append(
{"unit": unit, "project": pk, "ts": now(), "kind": "recurrence"})
if rec.get("status") in ("promoted", "monitored", "validated", "implemented") and rec.get("promoted_at"):
rec["recurrences_after_promotion"] = int(rec.get("recurrences_after_promotion") or 0) + 1
if rec["recurrences_after_promotion"] >= 2:
rec["flagged_not_working"] = True
save_learnings(rows, "learning %s recurrence" % rec["id"])
return rec
def findings_for_unit(project, uid):
"""Seam for the unit record: the findings recorded for one unit in one project."""
pk = project_key(project)
return [f for f in load_findings() if f.get("unit") == uid and f.get("project") == pk]
def units_seen():
"""Closed-unit summary lines from the unit worker's store, when it exists."""
out = []
try:
with open(paths.data_file("units.jsonl"), encoding="utf-8") as f:
for line in f:
if line.strip():
out.append(json.loads(line))
except (OSError, ValueError):
pass
return out
def unit_seq():
return len(units_seen())
# ---- monitoring -----------------------------------------------------------------
def flagged(rows=None):
rows = load_learnings() if rows is None else rows
return [r for r in rows if r.get("flagged_not_working") and r.get("status") not in ("revised", "reverted", "rejected")]
def learning_report():
"""Seam for `sisi status --learning`. No claim of improvement from counts of records."""
rows = load_learnings()
findings = load_findings()
units = units_seen()
lines = ["Learning loop (recorded facts; no improvement is claimed from counts):",
"learnings: %d findings: %d closed units known: %d"
% (len(rows), len(findings), len(units))]
promoted = [r for r in rows if r.get("status") in ("promoted", "monitored") and not r.get("owner_statement")]
if promoted:
lines.append("promoted learnings:")
holding = 0
relevant = 0
for r in promoted:
since = None
if r.get("promoted_unit_seq") is not None:
since = len(units) - int(r["promoted_unit_seq"])
else:
since = sum(1 for u in units if str(u.get("ts", "")) >= str(r.get("promoted_at") or ""))
rec = int(r.get("recurrences_after_promotion") or 0)
val = (r.get("validation") or {}).get("result") or "unvalidated"
if r.get("flagged_not_working"):
verdict = "not working (flagged: next cycle must revise or revert)"
elif since >= 5 and rec == 0:
verdict = "holding"
elif rec:
verdict = "recurred, watching"
else:
verdict = "too few units to judge"
if since >= 5:
relevant += 1
if rec == 0:
holding += 1
lines.append("- %s: %d unit(s) since promotion, %d recurrence(s), %s — %s"
% (r["id"], since, rec, val if val == "validated" else "unvalidated", verdict))
if relevant < 5:
lines.append("realization rate: too few (fewer than five promoted learnings have "
"five relevant units; no rate is claimed)")
else:
lines.append("realization rate: %d of %d promoted learnings holding with no recurrence "
"over at least five units" % (holding, relevant))
fl = flagged(rows)
if fl:
lines.append("flagged not working: " + ", ".join(r["id"] for r in fl))
pend = load_pending()
if pend:
lines.append("waiting for the owner's decision: %d change(s) (`sisi approve ID --yes|--no`)"
% len(pend))
tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool"
and r.get("status") not in ("rejected", "reverted")]
if tool:
lines.append("tool backlog (changes to sisi itself):")
for r in tool[:8]:
lines.append("- %s: %s" % (r["id"], derive_title(r["title"], 110)))
return "\n".join(lines) + "\n"
# ---- pending approvals -----------------------------------------------------------
def load_pending():
try:
with open(pending_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, list) else []
except (OSError, ValueError):
return []
def save_pending(items, msg="pending decision updated"):
pdata.ensure()
pdata.write_text("pending.json", json.dumps(items, indent=2, sort_keys=True) + "\n")
pdata.commit(msg, ["pending.json"])
def pending_notice():
n = len(load_pending())
return "sisi: %d learning change(s) wait for your decision (`sisi approve`)." % n if n else ""
# ---- owner statements (one path: learn writes, oracle prints) ---------------------
def owner_statements(rows=None):
rows = load_learnings() if rows is None else rows
return [r for r in rows if r.get("owner_statement") and r.get("status") not in ("rejected", "reverted")]
+125 -17
View File
@@ -99,7 +99,6 @@ def _merge_retro_db(src, dst):
b.row_factory = sqlite3.Row
added = 0
try:
from . import retro
key = lambda r: (r["aim"], r["change_kind"], r["target"], r["change"])
have = {key(r): r["id"] for r in b.execute("SELECT * FROM lessons")}
for r in a.execute("SELECT * FROM lessons ORDER BY id"):
@@ -107,7 +106,7 @@ def _merge_retro_db(src, dst):
lid = have[key(r)]
else:
bcols = [x[1] for x in b.execute("PRAGMA table_info(lessons)")]
cols = [c for c in retro.LESSON_COLS if c != "id" and c in bcols]
cols = [c for c in bcols if c != "id"] # legacy schema, read from the db itself
cur = b.execute("INSERT INTO lessons(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))),
[r[c] if c in r.keys() else None for c in cols])
lid = cur.lastrowid
@@ -117,7 +116,8 @@ def _merge_retro_db(src, dst):
if b.execute("SELECT 1 FROM occurrences WHERE lesson_id=? AND ts=? AND session IS ? AND moment=?",
(lid, o["ts"], o["session"], o["moment"])).fetchone():
continue
cols = [c for c in retro.OCC_COLS if c not in ("id", "lesson_id")]
ocols = [x[1] for x in b.execute("PRAGMA table_info(occurrences)")]
cols = [c for c in ocols if c not in ("id", "lesson_id")]
b.execute("INSERT INTO occurrences(lesson_id,%s) VALUES(?,%s)" % (",".join(cols), ",".join("?" * len(cols))),
[lid] + [o[c] if c in o.keys() else None for c in cols])
b.commit()
@@ -239,17 +239,132 @@ def run():
_union_lines(src, paths.data_file(name))
os.unlink(src)
notes.append("%s moved" % name)
try:
from . import retro
retro.export_jsonl()
except Exception as e:
store.log_error("migrate-export", e)
notes.append("lessons dump failed: %r" % e)
pdata.commit("migrate: move personal data out of the product and the state folder", strict=True)
notes += pdata.upgrade()
notes += migrate_learnings()
return notes
def migrate_learnings():
"""Old lesson store -> learning records. Idempotent, with a backup first, lossless.
lessons.jsonl mixed lesson rows with occurrence and impression rows. Lessons become
learning records with honest statuses (folded into prose is `implemented`, always
unvalidated; nothing becomes `validated`); occurrences become provenance; impressions
(sisi's own showings) are dropped, never evidence. learn.jsonl owner statements become
owner-statement records in the same store. Returns notes with before/after counts.
"""
from . import learning as L
if os.path.exists(L.learnings_path()):
return []
src = paths.data_file("lessons.jsonl")
learn_src = paths.data_file("learn.jsonl")
if not os.path.exists(src) and not os.path.exists(learn_src) \
and not os.path.exists(paths.data_file("retro.db")):
return []
bdir = snapshot("learning-migration")
lessons, occs, impressions = {}, {}, 0
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:
for line in f:
if not line.strip():
continue
try:
r = json.loads(line)
except ValueError:
continue
t = r.get("t")
if t == "lesson":
lessons[r.get("id")] = r
elif t == "occurrence":
occs.setdefault(r.get("lesson_id"), []).append(r)
elif t == "impression":
impressions += 1
rows = []
for lid in sorted(lessons, key=lambda x: (x is None, x)):
old = lessons[lid]
prov = []
for o in occs.get(lid, []):
prov.append({"unit": "session:%s" % (o.get("session") or o.get("id")),
"project": o.get("repo") or o.get("cwd") or old.get("project") or "",
"ts": o.get("ts") or "", "kind": "occurrence"})
origin = old.get("project") or (prov[0]["project"] if prov else "")
if not prov:
prov = [{"unit": "legacy:%s" % lid, "project": origin, "ts": old.get("created") or "",
"kind": "origin"}]
status = {"applied": "implemented", "retired": "reverted"}.get(old.get("status"), "observed")
kind = old.get("change_kind")
rows.append({
"id": "L-%04d" % (len(rows) + 1), "legacy_id": lid,
"title": L.derive_title(old.get("short") or old.get("change") or old.get("moment") or ""),
"source_unit": prov[0]["unit"], "origin_project": origin,
"observation": {"evidence": old.get("moment") or "", "impact": "correctness"},
"root_cause": old.get("cause") or "",
"proposed": {"description": old.get("change") or "",
"mechanism": "tool" if kind == "tool" else ("verification" if kind in ("check", "test") else "policy"),
"scope": "project", "target": old.get("target")},
"expected_effect": "", "limits": "", "why_not": "",
"validation": {"method": "", "benchmark": None, "result": "unvalidated",
"detail": "migrated from the old lesson store; never replay-validated"},
"status": status, "version": 1, "confidence": "low", "provenance": prov,
"terms": L.derive_terms(old.get("moment") or "", old.get("cause") or "", old.get("change") or ""),
"owner_statement": False, "candidate": False, "entered_via": "migration",
"recurrences_after_promotion": 0, "flagged_not_working": False,
"promoted_at": None, "promoted_unit_seq": None, "mechanism_ref": old.get("folded_into"),
"replay": None, "created": old.get("created") or L.now()})
statements = 0
if os.path.exists(learn_src):
with open(learn_src, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
try:
r = json.loads(line)
except ValueError:
continue
text = r.get("text") or r.get("statement") or ""
if not text:
continue
statements += 1
rows.append({
"id": "L-%04d" % (len(rows) + 1), "title": L.derive_title(text),
"source_unit": "owner", "origin_project": r.get("cwd") or "",
"observation": {"evidence": text, "impact": "value"},
"root_cause": "owner statement",
"proposed": {"description": text, "mechanism": "knowledge",
"scope": "user", "target": None},
"expected_effect": "the agent acts on this statement", "limits": "", "why_not": "",
"validation": {"method": "", "benchmark": None, "result": "unvalidated", "detail": ""},
"status": "promoted", "version": 1, "confidence": "high",
"provenance": [{"unit": "owner", "project": r.get("cwd") or "",
"ts": r.get("ts") or "", "kind": "origin"}],
"terms": L.derive_terms(text), "owner_statement": True, "candidate": False,
"entered_via": "migration", "recurrences_after_promotion": 0,
"flagged_not_working": False, "promoted_at": r.get("ts") or L.now(),
"promoted_unit_seq": None, "mechanism_ref": None, "replay": None,
"created": r.get("ts") or L.now()})
L.save_learnings(rows, "migrate: lessons and owner statements become learning records")
return ["learning migration: backed up to %s; %d lesson(s) and %d owner statement(s) became "
"%d learning record(s); %d occurrence(s) became provenance; %d impression(s) dropped "
"(showings are never evidence); nothing is validated"
% (bdir, len(lessons), statements, len(rows),
sum(len(v) for v in occs.values()), impressions)]
# ---- snapshots (before an update) -------------------------------------------------------------
SKIP_TOP = {"backups", "generated", "install", ".lock"}
@@ -431,14 +546,7 @@ def import_archive(path):
f.write(tf.extractfile(m).read())
os.chmod(dst, m.mode & 0o777 or 0o644)
os.utime(dst, (m.mtime, m.mtime))
if not os.path.exists(paths.data_file("retro.db")) and os.path.exists(paths.data_file("lessons.jsonl")):
from . import retro
con = retro.connect()
try:
retro.import_jsonl(paths.data_file("lessons.jsonl"), con)
finally:
con.close()
notes.append("retro.db rebuilt from lessons.jsonl")
notes += migrate_learnings()
notes += pdata.upgrade()
b = overlay.build_canon()
notes.append("rulebook rebuilt: %d lines" % b["lines"])
+6 -7
View File
@@ -280,23 +280,22 @@ def is_stale():
def cost():
"""Always-loaded size: the generated rulebook and the largest session-start lessons block."""
from . import retro
"""Always-loaded size: the generated rulebook. No lesson list is loaded at session start."""
try:
lines, chars = size(_read(paths.generated()))
except OSError:
lines = chars = None
return {"rulebook_lines": lines, "rulebook_chars": chars, "rulebook_budget_lines": MAX_LINES,
"rulebook_budget_chars": MAX_CHARS,
"lessons_block_max_chars": retro.LIMIT, "lessons_block_max_lines": 1 + 8}
"rulebook_budget_chars": MAX_CHARS}
def cost_line(c=None):
c = c or cost()
if c["rulebook_lines"] is None:
return "rulebook not generated yet (run `sisi update`); lessons block at most %d characters" % c["lessons_block_max_chars"]
return "rulebook %d lines (budget %d), %d characters (budget %d); session-start lessons block at most %d characters, %d lines" % (
c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], c.get("rulebook_budget_chars", MAX_CHARS), c["lessons_block_max_chars"], c["lessons_block_max_lines"])
return "rulebook not generated yet (run `sisi update`)"
return "rulebook %d lines (budget %d), %d characters (budget %d)" % (
c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"],
c.get("rulebook_budget_chars", MAX_CHARS))
# ---- library overlay (verifiers, recipes) ---------------------------------------
+51 -94
View File
@@ -1,113 +1,70 @@
"""The owner's standing principles: `sisi learn` statements in the user tier (plus core
statements until the product carries them, and not-yet-tiered ones meanwhile), live at once.
"""Owner statements, printed by `sisi oracle`. One store: learning records with owner_statement.
A statement takes effect the moment it is recorded: `sisi oracle` prints it, request-time
delivery hands it over when it matches a request. There is
no quarantine and no holding file. The oracle is a proper document (oracle.md in the personal
folder) whose structure a learning round owns through the whole-document edit in
sisi/documents.py, tracing every statement into the text like any other document; until a
round integrates a statement, `sisi oracle` prints it under its own heading so it is never
parked unread.
`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.
"""
import os
import json, os
from . import paths, store
from . import learning as L, paths
EMPTY = """# sisi oracle
What the human wants, so a thing is asked once ever. Empty so far: it is filled from
preferences the human stated (`sisi learn`), which take effect at once.
"""
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"))]
def statements():
"""The standing principles, in the order recorded: user-tier statements (how this owner
wants work done), plus core statements until the product carries them, plus not-yet-tiered
statements, which are still delivered while they wait for a tier."""
from . import scope as _scope
out = []
for rec in store.read("learn"):
text = " ".join(str(rec.get("text") or "").split())
if text and _scope.tier_of(rec.get("scope")) != "project":
out.append(dict(rec, text=text))
return out
def core_statements():
return [r for r in statements() if r.get("scope") == "core"]
def unscoped_statements():
"""Statements with no tier yet (old two-way `everywhere` included; a round tiers them)."""
from . import scope as _scope
return [rec for rec in store.read("learn")
if (rec.get("text") or "").strip() and _scope.tier_of(rec.get("scope")) == "unscoped-tier"]
recs = [{"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):
"""The principle in plain words on one line: the stored plain form when a round wrote one,
else the statement itself, tidied into a sentence."""
plain = " ".join(str(rec.get("plain") or "").split())
if plain:
return plain
t = " ".join(str(rec.get("text") or "").split()).strip("\"")
if t and t[-1] not in ".!?":
t += "."
return t
def date_of(rec):
return (rec.get("ts") or "")[:10]
def short_lines(limit_chars=None):
"""One short plain line per principle, for request-time and contract-init delivery."""
out, total = [], 0
for rec in statements():
line = "- " + plain_of(rec)
if limit_chars is not None and total + len(line) + 1 > limit_chars and out:
out.append("- ... and more (`sisi oracle` prints them all)")
break
out.append(line)
total += len(line) + 1
return out
def _principle_block(rec):
date = date_of(rec)
return '- %s\n > "%s"%s' % (plain_of(rec), rec["text"], " (%s)" % date if date else "")
def _oracle_file_text():
try:
with open(paths.data_file("oracle.md"), encoding="utf-8") as f:
return f.read()
except OSError:
return None
return rec.get("text") or rec.get("proposed", {}).get("description", "")
def oracle_text():
"""The oracle document as agents should read it now: the round-written document when one
exists, with any not-yet-integrated statements printed after it, never hidden."""
recs = statements()
file_text = _oracle_file_text()
if file_text:
missing = [r for r in recs if r["text"] not in file_text]
if not missing:
return file_text
return (file_text.rstrip("\n") + "\n\n## Not yet integrated\n\n"
"Recorded since the last learning round rewrote this document; in force now.\n\n"
+ "\n".join(_principle_block(r) for r in missing) + "\n")
if not recs:
return EMPTY
lines = ["# sisi oracle", "",
"What the human wants, so a thing is asked once ever. Statements recorded with "
"`sisi learn` take effect at once; a learning round rewrites this document as a "
"whole and traces every statement into it.", "",
"## Standing principles", ""]
lines += [_principle_block(r) for r in recs]
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))
return "\n".join(lines) + "\n"
def oracle_path():
return paths.data_file("oracle.md")
def short_lines(limit_chars=1200):
out, used = [], 0
for r in statements():
t = " ".join(r["text"].split())[:180]
if used + len(t) > limit_chars:
break
out.append(t)
used += len(t)
return out
+23 -43
View File
@@ -1,12 +1,22 @@
"""Request-time delivery: `sisi prompt` runs on the human's message (the tool's prompt-submission hook)
and injects the matching "what done means" recipe and lessons as added context, so the agent does not
have to remember to ask (`sisi done for`). Matching is the strict "likely to apply" test from
retro.delivery; when nothing strictly matches, or the message is trivial, nothing is printed. Any
learning.delivery_text (learnings in earned scope, framed as information; no showing is
recorded as evidence); when nothing strictly matches, or the message is trivial, nothing is printed. Any
error exits 0 silently: a hook must never block or fail a turn.
"""
import json, os, sys
from . import store
from . import learning as _L, store
def _stem(w):
return _L._stem(w.lower())
def _word_cut(text, limit):
text = " ".join(str(text).split())
return text if len(text) <= limit else text[:limit].rsplit(" ", 1)[0].rstrip(",.;:") + "…"
MAX_CHARS = 2000 # hard cap on the injected context, in characters
RECIPE_MIN_SCORE = 22.0 # a structured kind/tag match in the new matcher; below it, no recipe
@@ -27,8 +37,8 @@ def _is_question_without_work(t):
first = low.split(" ", 1)[0].strip("¿?") if low else ""
if not (low.endswith("?") or first in _QUESTION_START):
return False
from . import retro, verifiers as V
stems = {retro._stem(w) for w in V._words(low)}
from . import verifiers as V
stems = {_stem(w) for w in V._words(low)}
return not (stems & _WORK_STEMS)
@@ -61,53 +71,26 @@ def _best_recipe(query):
return None
def _done_means(recipe, retro):
def _done_means(recipe):
"""The recipe's must-be-true list in short form: its Done-means bullets, each cut at a word boundary."""
from . import verifiers as V
bullets = []
for line in V._section(recipe["body"], "Done means").split("\n"):
line = line.strip()
if line.startswith("- "):
bullets.append("- " + retro.word_cut(line[2:], 110))
bullets.append("- " + _word_cut(line[2:], 110))
return bullets
def build_context(query, session=None):
"""The context to inject for one human request, or "" when nothing strictly matches. Lessons shown
are recorded as listings at place 'prompt' (listed, not read)."""
"""The context to inject for one human request, or "" when nothing strictly matches.
Learnings come only from learning.delivery_text (earned scope, framed as information);
no showing is recorded, so nothing is promoted by being printed."""
if is_trivial(query):
return ""
from . import retro
recipe = _best_recipe(query)
targets = (recipe["id"],) if recipe else ()
part1, _part2 = retro.delivery(query, targets=targets)
repo = retro.repo_of(os.getcwd())
lesson_lines, ids = [], []
for d in part1:
row = d["row"]
if not retro.display_line(retro._get(row, "short") or row["change"], repo):
continue
lesson_lines.append("- #%d: %s (full text: `sisi lessons show %d`)"
% (row["id"], retro.heading_text(row, 120), row["id"]))
ids.append(row["id"])
# Learnings in scope: ask the learning module if it offers a scoped view.
try:
from . import scope as _scope_mod # noqa: F401
scoped = None
for _name in ("prompt_lines", "in_scope_lines", "scoped_lines"):
_fn = getattr(_scope_mod, _name, None)
if callable(_fn):
try:
scoped = _fn(query, os.getcwd())
except TypeError:
scoped = _fn(query)
break
if scoped:
for _ln in scoped:
if isinstance(_ln, str) and _ln.strip():
lesson_lines.append(_ln if _ln.startswith("- ") else "- " + _ln)
except Exception:
pass
lesson_text = _L.delivery_text(os.getcwd(), query).strip()
lesson_lines = lesson_text.split("\n")[1:] if lesson_text else []
if not recipe and not lesson_lines:
return ""
lines = []
@@ -115,20 +98,17 @@ def build_context(query, session=None):
"information to weigh, not commands):")
if recipe:
lines.append("Done means — recipe `%s` (full text: `sisi done %s`):" % (recipe["id"], recipe["id"]))
lines += _done_means(recipe, retro)
lines += _done_means(recipe)
if lesson_lines:
lines.append("Lessons likely to apply:")
lines += lesson_lines
text = "\n".join(lines)
while len(text) > MAX_CHARS and lesson_lines: # drop lesson lines before cutting the recipe
lesson_lines.pop()
ids = ids[:len(lesson_lines)]
lines = lines[:len(lines) - 1]
text = "\n".join(lines)
if len(text) > MAX_CHARS:
text = retro.word_cut(text, MAX_CHARS)
if ids:
retro.record_shown(ids, "prompt", session)
text = _word_cut(text, MAX_CHARS)
return text
+195 -1852
View File
File diff suppressed because it is too large. Load diff
+32 -255
View File
@@ -1,273 +1,50 @@
"""Lesson and statement tiers: core, user, or one project.
"""Scope is earned (see learning.earned), and `sisi learn`: the one write path for owner statements.
The owner's test, two questions: (a) does it apply to all projects where sisi may be used?
(b) would it be useful to every user who installs sisi? Both yes is `core`: a change to the
product itself (a rule, a recipe or technique, a mechanism, a design principle), in force for
this user at once through the personal overlay and queued for the product (`sisi promote`).
(a) yes, (b) no is `user`: how this owner wants work done, kept in the personal store and
delivered in all of this user's projects. (a) no is `project`: a fact about one project,
handed over to that project's own documentation or work list. Items recorded with the old
two-way scope `everywhere` are `unscoped-tier`: still delivered, tiered by the next learning
round. sisi is normally the shell around other projects; working in the sisi repository
itself is the exception, and an item is never project merely because it was recorded there -
a statement about how sisi itself should behave is core.
A project is identified by its git remote URL when there is one (normalised, so an
ssh and an https remote for the same repository, a trailing `.git`, credentials and a
renamed or re-cloned folder all give the same id), else by its repository root path
(a clone without a remote, or a renamed folder with no remote, is then a different
project: there is nothing more stable to key on). Project-scoped items live only in
the personal data store, keyed by that id; nothing is written into the repository.
The universality check is structural only, no model call: it looks at the parts that
are delivered to agents (change, short, when-terms; a learn statement) and refuses
when a core or user item names the current project. The tool's own name, sisi, is always
exempt. History (moment, cause, occurrences) may name the project freely and is never checked.
Project identity helpers stay here for handover and friends. The old claim-based tiers
(core/user/project checked only for naming) are gone: a learning is in force in its origin
project at once and elsewhere only with provenance from at least two units in at least two
projects, or as an owner statement.
"""
import os, re, subprocess
import os, sys
from . import gitutil
SCOPES = ("core", "user", "project")
UNTIERED = (None, "", "unscoped", "unscoped-tier", "everywhere")
TIER_QUESTIONS = (
"Ask two questions: (a) does it apply to all projects where sisi may be used? "
"(b) would it be useful to every user who installs sisi? Both yes: --scope core (a change "
"to sisi itself - a rule, a recipe or technique, a mechanism, a design principle; it takes "
"effect for you at once and is queued for the product, `sisi promote`). (a) yes but (b) no, "
"because it is how this owner wants things: --scope user (kept in your personal store, "
"delivered in all your projects). (a) no: --scope project (a fact about this project, "
"handed over to its own documentation or work list).")
MISSING_SCOPE = (
"sisi: --scope is required (core, user or project). " + TIER_QUESTIONS + " "
"Core and user items are stated in general terms so any project can use them: name the kind "
"of work and the rule that follows, not this project's name, files or address (for example, "
"not 'the exporter here joins rows by hand' but 'write delimited files with a quoting "
"writer'). A statement about how sisi itself should behave is core, even recorded inside "
"the sisi repository. The moment and cause may name this project either way: they stay as "
"its history.")
def tier_of(value):
"""The tier a stored scope value means today: legacy `everywhere` is not yet tiered."""
if value in SCOPES:
return value
return "unscoped-tier"
def normalize_scope(value):
"""A scope given on a command line, canonicalised: legacy `everywhere` is accepted and
stored as unscoped-tier (still delivered; the next learning round tiers it)."""
if value == "everywhere":
return "unscoped-tier"
return value
# File and directory names so common that merely mentioning them names no project.
COMMON_NAMES = {
"readme", "readme.md", "readme.txt", "readme.rst", "changelog", "changelog.md", "changelog.txt",
"history", "history.md", "news", "news.md", "license", "license.md", "licence", "licence.md",
"copying", "authors", "notice", "contributing", "contributing.md", "security", "security.md",
"code_of_conduct", "code_of_conduct.md", ".gitignore", ".gitattributes", "makefile", "dockerfile",
"tests", "test", "src", "source", "docs", "doc", "bin", "lib", "scripts", "script", "examples",
"example", "config", "configs", "build", "dist", "assets", "static", "templates", "vendor",
"main.py", "main.rs", "main.go", "main.c", "main.cpp", "index.html", "index.js", "index.ts",
"app.py", "setup.py", "pyproject.toml", "package.json", "cargo.toml", "go.mod", "requirements.txt",
}
def _git(cwd, *args):
try:
p = subprocess.run(("git",) + args, cwd=cwd, capture_output=True, timeout=5)
return p.stdout.decode("utf-8", "replace").strip() if p.returncode == 0 else ""
except (OSError, subprocess.SubprocessError):
return ""
def normalized_remote(url):
"""One id for the same repository however it was cloned."""
u = " ".join((url or "").split()).strip().rstrip("/")
if u.endswith(".git"):
u = u[:-4]
m = re.match(r"^[^/@]+@([^/:]+)[:/](.+)$", u) # git@host:owner/repo
if m:
u = m.group(1).lower() + "/" + m.group(2)
else:
m = re.match(r"^(?:[a-z][a-z0-9+.-]*://)?(?:[^/@]+@)?([^/]+)/(.+)$", u, re.I)
if m:
u = m.group(1).lower() + "/" + m.group(2)
return u.rstrip("/")
def remote_url(cwd):
url = _git(cwd, "remote", "get-url", "origin")
if not url:
names = _git(cwd, "remote").splitlines()
if names:
url = _git(cwd, "remote", "get-url", names[0].strip())
return url or None
from . import learning as L
def project_id(cwd):
"""Remote URL when there is one, else the repository root path, else the folder."""
url = remote_url(cwd)
if url:
return normalized_remote(url)
root = gitutil.root(cwd)
return os.path.realpath(root or os.path.abspath(cwd))
return L.project_key(cwd)
def project_label(pid):
"""A short human name for a project id (last path part, without .git)."""
s = (pid or "").rstrip("/")
name = s.rsplit("/", 1)[-1]
return name[:-4] if name.endswith(".git") else name
return os.path.basename(str(pid).rstrip("/")) if pid else "(unknown project)"
def visible(scope_value, project_value, cwd=None):
"""Core, user and not-yet-tiered items show in every project; project items only at home."""
if tier_of(scope_value) == "project":
return (project_value or "") == project_id(cwd or os.getcwd())
return True
def row_visible(row, cwd=None):
try:
get = row.get if isinstance(row, dict) else (lambda k: row[k] if k in row.keys() else None)
except Exception:
get = lambda k: None
return visible(get("scope"), get("project"), cwd)
def row_scope(row):
try:
v = row.get("scope") if isinstance(row, dict) else (row["scope"] if "scope" in row.keys() else None)
except Exception:
v = None
return tier_of(v)
def _existing(cwd):
"""(basenames, relative paths) of files and folders in the project, .git excluded."""
root = gitutil.root(cwd) or os.path.abspath(cwd)
names, rels = set(), set()
out = _git(root, "ls-files", "-c", "-o", "--exclude-standard")
if out:
for rel in out.splitlines():
rels.add(rel.replace(os.sep, "/").lower())
parts = rel.split("/")
for p in parts:
names.add(p.lower())
else:
for dp, dns, fns in os.walk(root):
dns[:] = [d for d in dns if d != ".git"][:200]
for n in list(dns) + list(fns):
names.add(n.lower())
if len(names) > 20000:
break
return root, names, rels
def universal_refusal(texts, cwd, kind=None):
"""Reason string when a delivered text names the current project, else None.
Checks the repository name, its remote URL (and the repository name inside it),
any path or file name that exists in it, and the root path itself. The tool's own
name, 'sisi', is always exempt: how sisi itself should behave is core, not project.
"""
texts = [t for t in (texts or []) if t and str(t).strip()]
if not texts:
return None
cwd = cwd or os.getcwd()
root, names, rels = _existing(cwd)
repo_name = os.path.basename(os.path.realpath(root)).lower()
remote = remote_url(cwd)
remote_norm = normalized_remote(remote) if remote else ""
remote_name = project_label(remote_norm).lower() if remote_norm else ""
blob = "\n".join(str(t) for t in texts)
low = blob.lower()
if os.path.realpath(root).lower() in low:
return "it gives this project's path (%s)" % root
for form in {remote or "", remote_norm}:
if form and form.lower() in low:
return "it gives this project's remote address (%s)" % form
tokens = re.findall(r"[A-Za-z0-9_./~:-]+", blob)
for tok in tokens:
t = tok.strip(".,;:()[]{}\"'")
tl = t.lower()
# the repository's own name, as a whole token or inside a path/URL token
for name in {repo_name, remote_name} - {""}:
if tl == name or tl.endswith("/" + name) or ("/" in tl and tl.rsplit("/", 1)[-1] == name):
if name == "sisi":
continue
return "it names this project (%s)" % name
if "/" in tl:
rel = tl.split("://", 1)[-1]
rel = rel[rel.find("/") + 1:] if rel.startswith(("github.com/", "gitlab.com/", "bitbucket.org/")) else rel
if rel in rels:
return "it names a path in this project (%s)" % t
base = rel.rsplit("/", 1)[-1]
if base in names and base not in COMMON_NAMES:
return "it names a file in this project (%s)" % base
elif "." in tl and not tl.startswith(".") or tl.startswith("."):
base = tl.rsplit("/", 1)[-1]
if base in names and base not in COMMON_NAMES and re.search(r"\.[a-z0-9]{1,6}$", base):
return "it names a file in this project (%s)" % base
return None
def refusal_text(reason):
return ("sisi: refused: a core or user item must be universal, and %s. Rewrite it in general "
"terms (the kind of work and the rule that follows, not this project's name, files or address), "
"or record it with --scope project so it stays with this project. " + TIER_QUESTIONS) % reason
def visible_in(rec, cwd):
return L.in_scope(rec, cwd)
def cmd_learn(argv):
"""`sisi learn [--scope core|user|project] TEXT` (also `--scope=X`)."""
from . import store
scope_value, text_parts, i = None, [], 0
argv = list(argv)
while i < len(argv):
a = argv[i]
if a == "--scope" and i + 1 < len(argv):
scope_value = argv[i + 1]; i += 2
"""sisi learn [--scope user|project] TEXT — record an owner statement, live at once."""
scope = "user"
text = []
it = iter(argv)
for a in it:
if a == "--scope":
scope = next(it, "user")
elif a.startswith("--scope="):
scope_value = a.split("=", 1)[1]; i += 1
scope = a.split("=", 1)[1]
else:
text_parts.append(a); i += 1
text = " ".join(text_parts).strip()
if not text:
print("usage: sisi learn --scope core|user|project TEXT")
return 1
if scope_value not in SCOPES and scope_value != "everywhere":
print(MISSING_SCOPE)
text.append(a)
if scope not in L.SCOPES:
print("sisi learn: --scope must be one of %s" % "|".join(L.SCOPES), file=sys.stderr)
return 2
scope_value = normalize_scope(scope_value)
cwd = os.getcwd()
if scope_value in ("core", "user", "unscoped-tier"):
reason = universal_refusal([text], cwd, kind="learn")
if reason:
print(refusal_text(reason))
return 2
rec = {"text": text, "scope": scope_value}
if scope_value == "project":
from . import handover
handover.move_learn(store.stamp(rec), project_id(cwd))
print("recorded for this project; it will be handed over to this "
"project at session start (`sisi handover` lists it)")
return 0
store.append("learn", store.stamp(rec))
try:
from . import cli
cli._commit_personal(store.file_path("learn"),
"learn: %s" % " ".join(text.split())[:60])
except Exception:
pass
if scope_value == "core":
print("recorded as core; it takes effect at once (`sisi oracle` shows it) and is queued "
"for the product (`sisi promote` lists core items)")
elif scope_value == "unscoped-tier":
print("recorded (the old everywhere scope); it takes effect at once and the next "
"learning round will tier it core, user or project")
else:
print("recorded; it takes effect at once as a standing principle (`sisi oracle` shows it)")
statement = " ".join(text).strip()
if len(statement) < 8:
print("usage: sisi learn [--scope user|project] \"<what you want>\"", file=sys.stderr)
return 2
rec = L.new_record(statement, "owner statement", "value",
"promote" if scope != "project" else "record",
os.getcwd(), L.unit_id(), change=statement, mechanism="knowledge",
scope=scope, expect="the agent acts on this statement",
owner_statement=True, entered_via="learn")
print("recorded owner statement %s (printed by `sisi oracle`)" % rec["id"])
return 0
+1 -31
View File
@@ -37,31 +37,6 @@ def _export_session(sid):
pass
def _decision_line():
"""One line for a decision waiting for the owner, via the learning module when it
provides one; a missing function prints nothing."""
for mod_name in ("cycle", "retro", "scope"):
try:
mod = __import__("sisi." + mod_name, fromlist=["*"])
except Exception:
continue
for name in ("pending_decision_line", "owner_decision_line", "decision_waiting_line",
"pending_owner_line"):
fn = getattr(mod, name, None)
if callable(fn):
try:
out = fn()
except TypeError:
try:
out = fn(os.getcwd())
except Exception:
return ""
except Exception:
return ""
return out if isinstance(out, str) else ""
return ""
def _handover_line(sess, sid, cwd):
"""Handover items for this project, once per session."""
try:
@@ -144,17 +119,12 @@ def main(args=()):
store.log_error("tick-workers", e)
try:
from . import cycle
# cycle.due_notice carries both the due-cycle line and the pending-decision line (learning.pending_notice).
note = cycle.due_notice(session=sid if isinstance(sid, str) else None)
if note:
sys.stdout.write(note + "\n")
except Exception as e:
store.log_error("tick-cycle", e)
try:
decision = _decision_line()
if decision:
sys.stdout.write(decision + "\n")
except Exception as e:
store.log_error("tick-decision", e)
try:
sess2 = rec or store.load_session(sid)
hline = _handover_line(sess2, sid if isinstance(sid, str) else "cwd", cwd)
-17
View File
@@ -222,23 +222,6 @@ class DeliveryRowTests(SisiCase):
per = (time.perf_counter() - t) / 5
self.assertLess(per, 0.25)
def test_retro_stores_the_request_time_with_the_lesson(self):
store.save_session("r-1", {"session_id": "r-1", "transcript_path": self.tp, "cwd": self.proj})
os.environ["SISI_SESSION_ID"] = "r-1"
con = retro.connect()
try:
lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="`make build` took 9 minutes in lib/src", cause="no cache here",
change="add a cache recipe for `make build`"), self.proj, None)
con.commit()
v = con.execute("SELECT delivery_s FROM occurrences WHERE lesson_id=?", (lid,)).fetchone()[0]
finally:
con.close()
self.assertGreaterEqual(v, 89)
self.assertLess(v, 200)
self.assertIn("it took longer than it had to", self.sisi("help").stdout)
def ref_percentile(xs, p):
s = sorted(xs)
if len(s) == 1:
-373
View File
@@ -1,373 +0,0 @@
"""Short lines, topics, the human digest, and the cycle writing them."""
import json, os, sqlite3, unittest
from support import *
from sisi import cycle, paths, retro, store
from test_verifiers import LibCase, vfile, dfile
WHEN = "parser, fuzzing, codec, hostile input, generated input, parsing"
def fields(**kw):
f = dict(aim="verified", change_kind="rule", target=None,
moment="the parser server waited 90 seconds in step 4 of the nightly job",
cause="no readiness probe existed before the browser step",
change="Prefer a readiness probe over a fixed sleep when waiting for parser servers to answer",
when=WHEN)
f.update(kw)
return f
class ShortCase(LibCase):
def setUp(self):
super().setUp()
self.put("prove/fuzz.md", vfile("fuzz"))
self.put("parser-or-codec.md", dfile("parser-or-codec"), self.ddir)
self.notes = os.path.join(self.data, "notes")
def mk(self, **kw):
con = retro.connect()
try:
lid = retro.new_lesson(con, fields(**kw), self.proj, None)
con.commit()
return lid
finally:
con.close()
def lesson(self, lid):
con = retro.connect()
try:
return dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone())
finally:
con.close()
def set_lesson(self, lid, **kw):
con = retro.connect()
try:
for k, v in kw.items():
con.execute("UPDATE lessons SET %s=? WHERE id=?" % k, (v, lid))
con.commit()
finally:
con.close()
def cycle_doc(self, notes=None, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"}
if notes is not None:
notes = list(notes)
have = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"}
for e in list(notes):
if isinstance(e, dict) and isinstance(e.get("lesson"), int) and e["lesson"] not in have:
notes.append({"lesson": e["lesson"], "action": "set-scope", "scope": "core"})
have.add(e["lesson"])
# every active lesson lacking a pattern needs a set-pattern too
try:
_con = retro.connect()
try:
_prows = [dict(r) for r in _con.execute(
"SELECT id, pattern_id, scope FROM lessons WHERE status IN ('open','applied')")]
finally:
_con.close()
_have_p = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-pattern"}
_exempt = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") in ("retire", "withdraw", "merge")}
for r in _prows:
if not r.get("pattern_id") and r["id"] not in _have_p and r["id"] not in _exempt and r.get("scope") != "project":
notes.append({"lesson": r["id"], "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"})
except Exception:
pass
doc["notes"] = notes
doc.update(parts)
# A cycle file must also answer for every document the brief lists for whole-document
# review: mark them reviewed here (tests of rewriting itself live in test_documents).
try:
from sisi import documents as _docs
_con = retro.connect()
try:
_have = {e.get("doc") for e in doc.get("documents") or [] if isinstance(e, dict)}
_rev = [{"doc": d["doc"], "action": "reviewed", "reason": "test helper: structure left as it is"}
for d in _docs.required_documents(_con) if d["doc"] not in _have]
finally:
_con.close()
if _rev:
doc["documents"] = list(doc.get("documents") or []) + _rev
except Exception:
pass
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as f:
json.dump(doc, f)
return p
def cycle_path(self, doc):
p = os.path.join(self.tmp, "cycle-%s.json" % id(doc))
with open(p, "w") as f:
json.dump(doc, f)
return p
class RetroShortTests(ShortCase):
def retro_cli(self, **over):
from test_retro import argv as retro_argv, GOOD
f = dict(GOOD)
f.update(over)
return self.sisi("retro", "--new", *retro_argv(f))
def test_retro_stores_short_and_topic(self):
r = self.retro_cli(short="Add fuzzing to the parser recipe checks.", topic="testing")
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
rows = [tuple(r) for r in con.execute("SELECT short, topic FROM lessons")]
con.close()
self.assertEqual(rows[0], ("Add fuzzing to the parser recipe checks.", "testing"))
def test_retro_without_short_says_next_round_will_write_it(self):
r = self.retro_cli()
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("next learning round will write", r.stdout)
def test_retro_limits_are_enforced(self):
long_short = "word " * 40 + "end."
self.assertEqual(self.retro_cli(short=long_short.strip()).returncode, 2)
self.assertEqual(self.retro_cli(short="Do the thing...").returncode, 2)
self.assertEqual(self.retro_cli(short="Do the thing\u2026").returncode, 2)
self.assertEqual(self.retro_cli(topic="Testing Stuff").returncode, 2)
self.assertEqual(self.retro_cli(topic="one two three four").returncode, 2)
self.assertEqual(self.retro_cli(topic="a" * 31).returncode, 2)
self.assertEqual(self.retro_cli(short="line one\nline two is long enough here.").returncode, 2)
con = retro.connect()
try:
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0)
finally:
con.close()
class HeadingTests(ShortCase):
def test_word_boundary_cut_never_mid_word(self):
text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda"
cut = retro.word_cut(text, 30)
self.assertTrue(cut.endswith("\u2026"), cut)
self.assertTrue(text.startswith(cut[:-1]), cut)
self.assertEqual(text[len(cut[:-1])], " ")
self.assertLessEqual(len(cut), 30)
def test_loose_heading_uses_short_when_present(self):
lid = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
row = self.lesson(lid)
self.assertIn("Use a readiness probe, not a sleep.", retro.loose_heading(row))
def test_loose_heading_without_short_is_word_cut(self):
lid = self.mk(change="Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma")
h = retro.loose_heading(self.lesson(lid))
self.assertTrue(h.endswith("\u2026"), h)
body = h.split(": ", 1)[1][:-1]
self.assertTrue(self.lesson(lid)["change"].startswith(body))
def test_lessons_list_and_backlog_use_short(self):
lid = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
out = self.sisi("lessons").stdout
self.assertIn("Use a readiness probe, not a sleep.", out)
tool = self.mk(change_kind="tool", change="Make sisi cycle print much faster for very large lesson stores",
short="Make sisi cycle faster.", topic="sisi itself")
bout = self.sisi("backlog").stdout
self.assertIn("Make sisi cycle faster.", bout)
class DigestTests(ShortCase):
def seed_digest(self):
a = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
self.set_lesson(a, folded_into="rule:know-done", effect="learned-note", status="applied")
b = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing anything",
moment="fuzz seeds were missing at step 5 of the job",
short="Seed the fuzz corpus from golden files.", topic="testing")
self.set_lesson(b, count=3)
c = self.mk(change="Ask the person before guessing when the request is unclear about success",
moment="a guess about success at step 2 was wrong",
short="Ask before guessing what success means.", topic="asking questions")
d = self.mk(change_kind="tool", change="Make sisi lessons digest group lessons by topic for the owner",
moment="the owner asked for a digest at step 1",
short="Group the digest by topic.", topic="releases")
e = self.mk(change="Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega extra words here",
moment="a long lesson moment at step 9")
f = self.mk(short="Retired short line should hide.", topic="testing")
self.set_lesson(f, status="retired", folded_into="rule:know-done")
return a, b, c, d, e, f
def test_digest_grouping_plain_states_and_order(self):
a, b, c, d, e, f = self.seed_digest()
out = self.sisi("lessons", "digest").stdout
lines = out.splitlines()
self.assertTrue(lines[0].count(".") >= 1 and "lesson" in lines[0], lines[0])
self.assertIn("5 lessons", lines[0])
# topics by size: testing (2) before singletons, Not yet summarized last topical heading
self.assertLess(out.index("## testing"), out.index("## asking questions"))
self.assertLess(out.index("## asking questions"), out.index("## Not yet summarized"))
self.assertIn("Use a readiness probe, not a sleep.", out)
self.assertIn("in the rulebook", out)
self.assertIn("attached to Fuzz work", out)
self.assertIn("loose note", out)
self.assertIn("change to sisi itself, not built yet", out)
self.assertIn("seen 3 times", out)
# seen only when > 1: lesson a has count 1, its line must not say seen
a_line = [l for l in lines if "lesson %d" % a in l][0]
self.assertNotIn("seen", a_line)
self.assertNotIn("#%d" % f, out) # retired left out by default
self.assertNotIn("Retired short line", out)
self.assertIn("lesson %d" % e, out) # every line shows its ID
last = [l for l in lines if l.strip()][-1]
self.assertIn("sisi lessons show", last)
low = out.lower()
for bad in ("strength", "field-note", "aim:"):
self.assertNotIn(bad, low)
def test_digest_all_includes_retired_and_not_yet_is_word_cut(self):
a, b, c, d, e, f = self.seed_digest()
out = self.sisi("lessons", "digest", "--all").stdout
self.assertIn("Retired short line should hide.", out)
e_line = [l for l in out.splitlines() if "lesson %d" % e in l][0]
self.assertTrue(e_line.rstrip().endswith(("\u2026", ")")) or "\u2026" in e_line, e_line)
def test_digest_shows_what_you_said_first(self):
self.seed_digest()
self.assertEqual(self.sisi("learn", "--scope", "everywhere", "Always", "show", "the", "options.").returncode, 0)
out = self.sisi("lessons", "digest").stdout
self.assertIn("## What you said", out)
self.assertIn("Always show the options.", out)
self.assertLess(out.index("## What you said"), out.index("## testing"))
class CycleShortTests(ShortCase):
def test_brief_lists_lacking_topics_and_limits(self):
have = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
need = self.mk(change="Widget caching lesson about parser readiness probes for servers",
moment="widget wait at step 2")
out = cycle.brief_text()
self.assertIn("short line", out)
self.assertIn("#%d" % need, out)
self.assertIn("testing", out) # topics already in use
self.assertIn("140", out)
self.assertIn("30", out)
self.assertIn("set-short", out)
def test_check_refuses_file_omitting_set_short_naming_lesson(self):
need = self.mk()
doc = self.cycle_doc(notes=[{"lesson": need, "action": "keep"}])
r = self.sisi("cycle", "check", doc)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("set-short", r.stdout)
self.assertIn(str(need), r.stdout)
good = self.cycle_doc(notes=[{"lesson": need, "action": "keep"},
{"lesson": need, "action": "set-short",
"short": "Use a readiness probe, not a sleep.", "topic": "testing"}])
r2 = self.sisi("cycle", "check", good)
self.assertEqual(r2.returncode, 0, r2.stdout + r2.stderr)
def test_set_short_combined_and_limits_in_cycle(self):
lid = self.mk()
bad = self.cycle_doc(notes=[{"lesson": lid, "action": "set-short",
"short": "word " * 40, "topic": "testing"}])
r = self.sisi("cycle", "check", bad)
self.assertEqual(r.returncode, 1, r.stdout)
good = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"},
{"lesson": lid, "action": "set-short",
"short": "Use a readiness probe, not a sleep.", "topic": "testing"}])
self.assertEqual(self.sisi("cycle", "apply", good).returncode, 0)
l = self.lesson(lid)
self.assertEqual((l["short"], l["topic"]), ("Use a readiness probe, not a sleep.", "testing"))
def test_cycle_now_prints_brief_when_not_due(self):
self.assertEqual(self.sisi("cycle", "due").returncode, 1)
r = self.sisi("cycle", "--now")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("Base version", r.stdout)
class BulletTests(ShortCase):
def test_field_note_bullet_uses_short_at_creation(self):
lid = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing anything",
moment="fuzz seeds were missing at step 5",
short="Seed the fuzz corpus from golden files.", topic="testing")
text = open(os.path.join(self.notes, "fuzz.md")).read()
self.assertIn("Seed the fuzz corpus from golden files.", text)
self.assertIn("seen 1 times; lesson %d; full text: sisi lessons show %d" % (lid, lid), text)
def test_bullet_rewrite_and_exact_revert(self):
lid = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing anything",
moment="fuzz seeds were missing at step 5")
p = os.path.join(self.notes, "fuzz.md")
before = open(p, "rb").read()
self.assertIn(b"Seed the fuzz corpus from golden parser files", before)
doc = self.cycle_doc(notes=[{"lesson": lid, "action": "set-short",
"short": "Seed the fuzz corpus from golden files.", "topic": "testing"}])
r = self.sisi("cycle", "apply", doc)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
after = open(p, "rb").read()
self.assertNotEqual(after, before)
self.assertIn(b"Seed the fuzz corpus from golden files.", after)
self.assertIn(("full text: sisi lessons show %d" % lid).encode(), after)
self.assertNotIn(b"Seed the fuzz corpus from golden parser files before fuzzing", after)
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(open(p, "rb").read(), before) # exact bytes restored
l = self.lesson(lid)
self.assertIsNone(l["short"])
self.assertIsNone(l["topic"])
def test_explicit_note_bullet_is_not_rewritten(self):
lid = self.mk(change="Parser recipes need a readiness probe before any server work begins",
moment="server wait at step 3")
doc = self.cycle_doc(notes=[
{"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec",
"note": "Explicit split note about readiness probes"},
{"lesson": lid, "action": "set-short",
"short": "Use a readiness probe, not a sleep.", "topic": "testing"}])
self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0)
text = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Explicit split note about readiness probes", text)
# a later set-short in a new cycle also leaves the explicit bullet alone
self.set_lesson(lid, short=None, topic=None)
# restore base: the previous cycle changed the lesson, so clear via a fresh cycle file
doc2 = {"version": 1, "base": cycle.base_version(), "summary": "second",
"notes": [{"lesson": lid, "action": "set-short",
"short": "Prefer probes over sleeps.", "topic": "testing"}],
"documents": [{"doc": "recipe:parser-or-codec", "action": "reviewed",
"reason": "this round only rewrites the short line"}]}
p2 = self.cycle_path(doc2)
r = self.sisi("cycle", "apply", p2)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
text2 = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Explicit split note about readiness probes", text2)
self.assertNotIn("Prefer probes over sleeps.", text2)
class MigrationTests(ShortCase):
def test_old_store_without_fields_still_loads(self):
old = os.path.join(self.tmp, "old.db")
con = sqlite3.connect(old)
con.executescript("""
CREATE TABLE lessons(id INTEGER PRIMARY KEY, created TEXT, aim TEXT, change_kind TEXT, target TEXT,
moment TEXT, cause TEXT, change TEXT, status TEXT DEFAULT 'open', count INTEGER DEFAULT 1, last_seen TEXT);
CREATE TABLE occurrences(id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, tool TEXT,
cwd TEXT, repo TEXT, moment TEXT, fp TEXT);
""")
con.execute("INSERT INTO lessons VALUES (1,'2020-01-01T00:00:00Z','speed','verifier','fuzz','m','c',"
"'Seed the fuzz corpus from golden parser files','open',2,'2020-01-02T00:00:00Z')")
con.commit(); con.close()
import shutil
os.makedirs(os.path.dirname(retro.db_path()), exist_ok=True)
shutil.copy(old, retro.db_path())
con = retro.connect()
try:
row = dict(con.execute("SELECT * FROM lessons WHERE id=1").fetchone())
cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")]
finally:
con.close()
self.assertIn("short", cols)
self.assertIn("topic", cols)
self.assertEqual(row["change"], "Seed the fuzz corpus from golden parser files")
self.assertIsNone(row["short"])
out = self.sisi("lessons", "digest").stdout
self.assertIn("Seed the fuzz corpus", out)
if __name__ == "__main__":
unittest.main()
-289
View File
@@ -1,289 +0,0 @@
"""Whole-document edits in a learning round: folded lessons become part of the document's own
text, every lesson stays traceable to the exact fragment that carries it, structure is checked
mechanically, and a stale personal copy is listed for re-merge instead of silently kept."""
import json, os, unittest
from support import *
from sisi import cycle, documents, overlay, paths, retro
from test_verifiers import LibCase, vfile, dfile
WHEN = "parser, codec, parse, decode, round trip, fuzzing, tabular data"
RECIPE_BODY = """## Done means
- The parser accepts every valid input in the corpus.
- Invalid input is refused with a clear error.
## Checks
- Round trip: `proptest` (many-inputs), rung 2.
## Common false finishes
- Only the examples in the report were tried.
"""
REWRITE = """---
id: parser-or-codec
title: Parser or codec work
applies_to: parsing work
---
## Done means
- The parser accepts every valid input in the corpus.
- Invalid input is refused with a clear error.
- Seed the corpus from the golden files before fuzzing.
- Try truncated input at every length.
## Checks
- Round trip: `proptest` (many-inputs), rung 2.
## Common false finishes
- Only the examples in the report were tried.
"""
class DocCase(LibCase):
def setUp(self):
super().setUp()
self.put("prove/fuzz.md", vfile("fuzz"))
self.put("many-inputs/proptest.md", vfile("proptest", "many-inputs", 2))
self.put("parser-or-codec.md",
dfile("parser-or-codec", title="Parser or codec work", applies="parsing work",
body="\n" + RECIPE_BODY), self.ddir)
self.notes = os.path.join(self.data, "notes")
def mk(self, change, **kw):
f = dict(aim="verified", change_kind="recipe", target="parser-or-codec",
moment="the parser accepted a truncated file in the nightly job",
cause="no truncated-input case existed", change=change, when=WHEN,
scope="core", short="Seed the corpus from golden files.", topic="parsing", pattern="Reach for the familiar tool instead of the check that fits the claim")
f.update(kw)
con = retro.connect()
try:
lid = retro.new_lesson(con, f, self.proj, None)
con.commit()
return lid
finally:
con.close()
def cycle_file(self, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "document round"}
doc.update(parts)
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as fh:
json.dump(doc, fh)
return p
def tree_bytes(self):
out = {}
for root in (paths.overlay_dir(), paths.notes_dir()):
for dp, dns, fns in os.walk(root):
for n in fns:
p = os.path.join(dp, n)
with open(p, "rb") as fh:
out[p] = fh.read()
return out
class BriefAndCheckTests(DocCase):
def test_brief_lists_recipe_with_field_notes_in_full(self):
a = self.mk("Seed the corpus from the golden files before fuzzing parsers")
b = self.mk("Try truncated input at every length when testing a parser",
short="Try truncated input at every length.")
brief = cycle.brief_text()
self.assertIn("recipe:parser-or-codec", brief)
self.assertIn("whole-document", brief.lower())
self.assertIn("Seed the corpus from the golden files", brief) # the folded lesson, universal part
self.assertIn("one instruction per bullet", brief.lower()) # the editorial standard
self.assertIn(RECIPE_BODY.splitlines()[1], brief) # the document's current text
def test_check_refuses_a_file_that_skips_a_listed_document(self):
self.mk("Seed the corpus from the golden files before fuzzing parsers")
r = self.sisi("cycle", "check", self.cycle_file())
self.assertEqual(r.returncode, 1)
self.assertIn("recipe:parser-or-codec", r.stdout)
self.assertIn("documents", r.stdout)
def test_reviewed_entry_satisfies_the_round(self):
self.mk("Seed the corpus from the golden files before fuzzing parsers")
p = self.cycle_file(documents=[{"doc": "recipe:parser-or-codec", "action": "reviewed",
"reason": "two short sections, one instruction per bullet, nothing duplicated"}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
# still shown as a field note until a rewrite integrates it
self.assertIn("Seed the corpus", retro.notes_for("parser-or-codec"))
class RewriteTests(DocCase):
def _two_lessons(self):
a = self.mk("Seed the corpus from the golden files before fuzzing parsers")
b = self.mk("Try truncated input at every length when testing a parser",
short="Try truncated input at every length.")
return a, b
def test_rewrite_integrates_lessons_and_traces_them(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("done", "parser-or-codec").stdout
self.assertIn("Seed the corpus from the golden files before fuzzing.", out)
self.assertNotIn("Field notes from earlier agents", out) # integrated, not appended
self.assertEqual(retro.notes_for("parser-or-codec"), "")
show = self.sisi("lessons", "show", str(a)).stdout
self.assertIn("recipe:parser-or-codec", show)
self.assertIn("Seed the corpus from the golden files before fuzzing.", show)
traced = self.sisi("done", "parser-or-codec", "--trace").stdout
self.assertIn("#%d" % a, traced)
self.assertIn("Seed the corpus", traced)
def test_rewrite_missing_one_fragment_is_refused(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("lesson #%d" % b, r.stdout)
def test_fragment_must_occur_in_the_new_text(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "This sentence is nowhere in the document."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("fragment", r.stdout)
def test_dated_journal_bullet_is_refused(self):
a, b = self._two_lessons()
bad = REWRITE + "- 2024-01-02: an old note (aim: verified; seen 1 times; lesson %d)\n" % a
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": bad,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("dated", r.stdout.lower())
def test_lint_failing_recipe_is_refused(self):
a, b = self._two_lessons()
bad = REWRITE.replace("## Checks", "## Things")
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": bad,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
def test_revert_restores_documents_and_notes_byte_for_byte(self):
a, b = self._two_lessons()
before = self.tree_bytes()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertNotEqual(self.tree_bytes(), before)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertEqual(self.tree_bytes(), before)
def test_product_change_lists_the_document_for_remerge(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertNotIn("needs a re-merge", cycle.brief_text())
prod = os.path.join(self.ddir, "parser-or-codec.md")
with open(prod) as fh:
text = fh.read()
with open(prod, "w") as fh:
fh.write(text.replace("Invalid input is refused", "Bad input is refused"))
brief = cycle.brief_text()
self.assertIn("Document recipe:parser-or-codec", brief)
self.assertIn("needs a re-merge", brief)
class RulebookTests(DocCase):
def test_rule_order_applies_and_numbers_follow_it(self):
_pre, rules = overlay.effective()
ids = [r["id"] for r in rules]
new_order = [ids[1], ids[0]] + ids[2:]
p = self.cycle_file(rule_order=new_order)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout)
_pre2, rules2 = overlay.effective()
self.assertEqual([x["id"] for x in rules2], new_order)
out = self.sisi("rule", "1").stdout
self.assertIn("{#%s}" % new_order[0], out)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
_pre3, rules3 = overlay.effective()
self.assertEqual([x["id"] for x in rules3], ids)
def _rulebook_text(self, drop=None, extra=None):
pre, rules = overlay.effective()
parts = [pre] if pre.strip() else []
for r in rules:
if r["id"] == drop:
continue
body = r["body"] + (("\n\n" + extra) if extra and r["id"] == "know-done" else "")
parts.append("## %s {#%s}\n\n%s" % (r["title"], r["id"], body))
return "\n\n".join(parts) + "\n"
def test_rulebook_rewrite_traces_a_rule_lesson(self):
lid = self.mk("Name the check that decides done before starting the work",
change_kind="rule", target=None, short="Name the deciding check first.")
p = self.cycle_file(notes=[{"lesson": lid, "action": "fold-into-rule", "into": "know-done"}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
frag = "Name the check that decides done before starting."
bad = self.cycle_file(documents=[{"doc": "rulebook", "action": "rewrite",
"text": self._rulebook_text(drop="deliver-quickly", extra=frag),
"shortens": "know-done: tightened while integrating",
"trace": [{"lesson": lid, "fragment": frag}]}])
r = self.sisi("cycle", "check", bad)
self.assertEqual(r.returncode, 1)
self.assertIn("deliver-quickly", r.stdout)
good = self.cycle_file(documents=[{"doc": "rulebook", "action": "rewrite",
"text": self._rulebook_text(extra=frag),
"shortens": "know-done: tightened while integrating",
"trace": [{"lesson": lid, "fragment": frag}]}])
r = self.sisi("cycle", "apply", good)
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("rule", "know-done").stdout
self.assertIn(frag, out)
self.assertIn("carried in rulebook", out)
self.assertIn("lives : in rulebook", self.sisi("lessons", "show", str(lid)).stdout)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertNotIn(frag, self.sisi("rule", "know-done").stdout)
def test_rule_order_must_name_every_rule_once(self):
_pre, rules = overlay.effective()
p = self.cycle_file(rule_order=[rules[0]["id"]])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("rule_order", r.stdout)
class StructureTests(unittest.TestCase):
def test_existing_library_passes_the_structure_checks(self):
bad = []
for kind, root in (("recipe", os.path.join(REPO, "done")),
("verifier", os.path.join(REPO, "verifiers"))):
for dp, dns, fns in os.walk(root):
for n in sorted(fns):
if not n.endswith(".md"):
continue
p = os.path.join(dp, n)
with open(p, encoding="utf-8") as fh:
text = fh.read()
for prob in documents.structure_problems(kind, text, n[:-3]):
bad.append("%s: %s" % (p, prob))
self.assertEqual(bad, [])
if __name__ == "__main__":
unittest.main()
+9 -8
View File
@@ -869,14 +869,15 @@ class GateSingleSessionEquivalenceTests(GateBase):
return d
def retro_for(self, proj, sid, n):
from test_retro import GOOD, argv as retro_argv
f = dict(GOOD, moment="`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n,
change="Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n, new=True)
r = self.sisi("retro", *retro_argv(f), cwd=proj, env={"SISI_SESSION_ID": sid})
if r.returncode == 4: # same lesson as the twin's: add an occurrence for this repo instead
r = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` twin run %d, no fuzz" % n,
cwd=proj, env={"SISI_SESSION_ID": sid})
self.assertEqual(r.returncode, 0, r.stdout)
r = self.sisi("retro",
"--finding", "`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n,
"--cause", "the recipe never named a fuzz verifier for parsers",
"--impact", "time", "--disposition", "promote",
"--change", "Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n,
"--mechanism", "verification", "--expect", "parser work gets a fuzz check",
"--validate", "run the recipe checks on a parser change",
cwd=proj, env={"SISI_SESSION_ID": sid})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
def test_seeded_sequences_match_the_reference(self):
os.environ["SISI_RETRO_REQUIRED"] = "1"
+30
View File
@@ -23,6 +23,36 @@ class TickCleanTests(SisiCase):
self.assertIn("sisi doctor", r.stdout)
self.assertLessEqual(len(r.stdout.strip().splitlines()), 1)
def test_deep_state_and_backlog_are_silent_at_session_start(self):
"""Ported from the retired tiers tests: session start prints no deep-check
state and no backlog; `sisi verify --state` owns the deep state."""
import time # noqa: F401 (kept with the ported test's original imports)
def deepc(id, cmd="true"):
c = check(id, cmd, rung=3)
c["tier"] = "deep"
return c
self.git_init()
self.sisi("install")
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.assertEqual(self.sisi("tick", stdin=self.payload()).stdout, "")
self.sisi("verify", "--deep")
self.assertEqual(self.sisi("tick", stdin=self.payload()).stdout, "")
with open(os.path.join(self.proj, "n.txt"), "w") as f:
f.write("x")
self.assertEqual(self.sisi("tick", stdin=self.payload()).stdout, "")
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
self.sisi("verify", "--deep")
self.assertEqual(self.sisi("tick", stdin=self.payload()).stdout, "")
self.assertNotIn("backlog", self.sisi("tick", stdin=self.payload()).stdout)
def test_help_points_to_retro_and_retired_store_commands_are_gone(self):
"""Ported from the retired retro tests: help names retro; note/propose stay retired."""
out = self.sisi("help").stdout
self.assertIn("sisi retro", out)
for retired in ("note", "propose"):
self.assertNotIn("sisi " + retired + " ", out)
self.assertEqual(self.sisi(retired, "still works").returncode, 64)
def test_handover_shown_once_per_session(self):
"""R-12-2: handover items for this project print once per session, not every session."""
self.git_init()
-492
View File
@@ -1,492 +0,0 @@
import json, os, random, subprocess, sys, time, unittest
from support import SisiCase, REPO
from sisi import escapes, groundtruth, harvest, learn_cli, scoreboard, store, taskset
T0 = harvest.epoch("2026-11-01T10:00:00.000Z")
def iso(t):
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(t))
def rec(typ, t, sid="S1", cwd="/nowhere", sidechain=False, agent=None, **kw):
d = {"parentUuid": None, "isSidechain": sidechain, "type": typ, "timestamp": iso(t), "cwd": cwd, "sessionId": sid,
"entrypoint": "cli", "userType": "external", "gitBranch": "main"}
if agent:
d["agentId"] = agent
d.update(kw)
return json.dumps(d, separators=(",", ":"))
def user(t, text, **kw):
return rec("user", t, message={"role": "user", "content": text}, **kw)
def asst(t, text=None, tool=None, cmd=None, model="claude-sonnet-5-5", **kw):
blocks = []
if text is not None:
blocks.append({"type": "text", "text": text})
if tool:
blocks.append({"type": "tool_use", "id": "tu1", "name": tool, "input": {"command": cmd} if cmd else {}})
return rec("assistant", t, message={"role": "assistant", "model": model, "content": blocks}, **kw)
def tool_result(t, **kw):
return rec("user", t, message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "ok"}]},
toolUseResult={"stdout": "ok"}, **kw)
def git(cwd, *args, date=None):
env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t")
if date:
env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = iso(date)
p = subprocess.run(["git"] + list(args), cwd=cwd, env=env, capture_output=True, text=True)
assert p.returncode == 0, p.stderr
return p.stdout.strip()
class Fixture(SisiCase):
def projdir(self, name="-home-t-Code-r"):
d = os.path.join(self.home, ".claude", "projects", name)
os.makedirs(d, exist_ok=True)
return d
def write(self, path, lines, mode="w"):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, mode, encoding="utf-8") as f:
for ln in lines:
f.write(ln + "\n")
def session(self, sid, lines, proj="-home-t-Code-r"):
p = os.path.join(self.projdir(proj), sid + ".jsonl")
self.write(p, lines)
return p
def harvest(self):
con = harvest.connect()
st = harvest.run(home=self.home, workers=1, con=con)
return con, st
def repo(self, name="r"):
d = os.path.join(self.home, "Code", name)
os.makedirs(d)
git(d, "init", "-q", "-b", "main")
return d
def commit(self, d, fname, t, content="x"):
with open(os.path.join(d, fname), "a") as f:
f.write(content + "\n")
git(d, "add", "-A")
git(d, "commit", "-q", "-m", "c " + fname, date=t)
return git(d, "rev-parse", "HEAD")
class TestTypedText(unittest.TestCase):
def test_rule(self):
tt = harvest.typed_text
h = {"type": "user", "message": {"content": "please fix the build"}}
self.assertEqual(tt(h)[0], "please fix the build")
self.assertIsNone(tt({"type": "user", "isMeta": True, "message": {"content": "hi"}})[0])
self.assertIsNone(tt({"type": "user", "toolUseResult": {}, "message": {"content": "hi"}})[0])
self.assertIsNone(tt({"type": "user", "message": {"content": [{"type": "tool_result", "content": "x"}]}})[0])
self.assertIsNone(tt({"type": "user", "origin": {"kind": "task-notification"}, "message": {"content": "x"}})[0])
self.assertIsNone(tt({"type": "user", "origin": {"kind": "peer"}, "message": {"content": "x"}})[0])
self.assertEqual(tt({"type": "user", "origin": {"kind": "human"}, "message": {"content": "yo"}})[0], "yo")
for wrapped in ("<system-reminder>x</system-reminder>", "<local-command-stdout>x</local-command-stdout>",
"<task-notification>x</task-notification>", "This session is being continued from a previous conversation",
"<local-command-caveat>Caveat: x</local-command-caveat>"):
self.assertIsNone(tt({"type": "user", "message": {"content": wrapped}})[0], wrapped)
self.assertIsNone(tt({"type": "user", "isCompactSummary": True, "message": {"content": "summary"}})[0])
self.assertEqual(tt({"type": "user", "message": {"content": "[Request interrupted by user for tool use]"}}), (None, 0, True))
self.assertIsNone(tt({"type": "user", "message": {"content": "<command-name>/clear</command-name><command-args></command-args>"}})[0])
self.assertEqual(tt({"type": "user", "message": {"content": "<command-name>/x</command-name><command-args>do it</command-args>"}})[0], "do it")
txt, pasted, _ = tt({"type": "user", "message": {"content": "look <pasted_content id=\"1\">" + "z" * 50 + "</pasted_content> now"}})
self.assertEqual(txt, "look now")
self.assertGreater(pasted, 50)
txt, _, _ = tt({"type": "user", "message": {"content": [{"type": "text", "text": "[Image #1] see this"}, {"type": "image"}]}})
self.assertEqual(txt, "see this")
self.assertEqual(tt({"type": "user", "message": {"content": [{"type": "text", "text": "[Image #1]"}, {"type": "image"}]}})[0], "")
def test_queued_command(self):
a = {"type": "queued_command", "commandMode": "prompt", "prompt": "do more", "origin": {"kind": "human"}}
self.assertEqual(harvest.typed_text(a, queued_prompt=a["prompt"])[0], "do more")
b = dict(a, origin={"kind": "task-notification"})
self.assertIsNone(harvest.typed_text(b, queued_prompt="x")[0])
class TestHeuristics(unittest.TestCase):
def test_machine(self):
self.assertTrue(harvest.machine_reason("You are a worker: do this", None, "cli")[0])
self.assertTrue(harvest.machine_reason("Act as the design sub-agent for this task.", None, "t3-code")[0])
self.assertTrue(harvest.machine_reason("x" * 4000, None, "cli")[0])
self.assertTrue(harvest.machine_reason(None)[0])
self.assertTrue(harvest.machine_reason("Generate a title that will help the user", None, "sdk-cli")[0])
self.assertFalse(harvest.machine_reason("Tell me how you work with subagents", None, "cli")[0])
self.assertFalse(harvest.machine_reason("fix the login bug in app.py please", None, "cli")[0])
def test_correction(self):
self.assertTrue(harvest.is_correction("No, that's not what I asked"))
self.assertTrue(harvest.is_correction("it still doesn't work"))
self.assertFalse(harvest.is_correction("great, now add tests"))
self.assertFalse(harvest.is_correction("no" + " blah" * 600))
class TestHarvest(Fixture):
def test_main_vs_subagent_and_counts(self):
proj = self.projdir()
main = [user(T0, "fix the parser bug", cwd="/x"),
asst(T0 + 5, "Which file?"),
user(T0 + 60, "parser.py"),
asst(T0 + 70, tool="Bash", cmd="git commit -am x"),
tool_result(T0 + 71),
asst(T0 + 80, tool="Bash", cmd="sisi verify"),
asst(T0 + 90, tool="AskUserQuestion"),
asst(T0 + 100, "All tests pass. Done."),
user(T0 + 200, "no, that's wrong, it still fails"),
rec("user", T0 + 205, message={"role": "user", "content": "[Request interrupted by user]"}),
asst(T0 + 300, "Fixed it.")]
self.write(os.path.join(proj, "S1.jsonl"), main)
sub = os.path.join(proj, "S1", "subagents", "agent-abc.jsonl")
self.write(sub, [user(T0 + 10, "You are a worker: do X", sid="S1", sidechain=True, agent="abc"),
asst(T0 + 20, "done", sid="S1", sidechain=True, agent="abc", model="claude-haiku-5-5")])
with open(sub[:-6] + ".meta.json", "w") as f:
json.dump({"agentType": "x", "model": "haiku"}, f)
wf = os.path.join(proj, "S1", "subagents", "workflows", "wf_1234abcd-xx", "agent-zzz.jsonl")
self.write(wf, [user(T0 + 12, "brief two", sid="S1", sidechain=True, agent="zzz")])
self.write(os.path.join(proj, "S1", "subagents", "workflows", "wf_1234abcd-xx", "journal.jsonl"), ['{"a":1}'])
con, st = self.harvest()
self.assertEqual(st["seen"], 3)
m = con.execute("SELECT * FROM sessions WHERE kind='main'").fetchone()
self.assertEqual(m["id"], "S1")
self.assertEqual(m["user_turns"], 3)
self.assertEqual(m["n_corrections"], 1)
self.assertEqual(m["n_premature_done"], 1) # correction right after a completion claim
self.assertEqual(m["n_interrupts"], 1)
self.assertEqual(m["n_ask"], 1)
self.assertEqual(m["n_question_turns"], 1)
self.assertEqual((m["ran_commit"], m["used_verify"], m["used_contract"]), (1, 1, 0))
self.assertEqual(m["last_claims_done"], 1)
self.assertEqual(json.loads(m["tools"])["Bash"], 2)
self.assertEqual(m["machine"], 0)
subs = {r["agent_id"]: r for r in con.execute("SELECT * FROM sessions WHERE kind='subagent'")}
self.assertEqual(set(subs), {"abc", "zzz"})
self.assertEqual(subs["abc"]["parent_id"], "S1")
self.assertEqual(subs["abc"]["user_turns"], 0)
self.assertEqual(json.loads(subs["abc"]["meta"])["model"], "haiku")
self.assertTrue(subs["abc"]["first_message"].startswith("You are a worker"))
msgs = [r["text"] for r in con.execute("SELECT text FROM user_msgs WHERE session_id='S1' ORDER BY idx")]
self.assertEqual(msgs, ["fix the parser bug", "parser.py", "no, that's wrong, it still fails"])
self.assertEqual(con.execute("SELECT correction FROM user_msgs WHERE idx=2").fetchone()[0], 1)
def test_incremental(self):
p = self.session("S1", [user(T0, "do a thing please", cwd="/x"), asst(T0 + 5, "ok")])
con, st = self.harvest()
self.assertEqual((st["parsed"], st["skipped"]), (1, 0))
con.close()
con, st = self.harvest()
self.assertEqual((st["parsed"], st["skipped"]), (0, 1))
self.write(p, [user(T0 + 100, "and another thing")], mode="a")
con.close()
con, st = self.harvest()
self.assertEqual((st["parsed"], st["skipped"]), (1, 0))
self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 2)
self.assertEqual(con.execute("SELECT COUNT(*) FROM user_msgs").fetchone()[0], 2)
def test_malformed_lines_never_raise(self):
p = os.path.join(self.projdir(), "S1.jsonl")
with open(p, "wb") as f:
f.write(b"not json at all\n")
f.write(b'{"parentUuid":null,"type":"user","message":{"content":\n') # truncated
f.write(b'{"parentUuid":null,"type":"user","message":null,"timestamp":12}\n')
f.write(b'{"parentUuid":null,"type":"assistant","message":{"content":[1,"x",null]},"timestamp":"garbage"}\n')
f.write(b'\xff\xfe\x00bad bytes\n')
f.write(b'{"parentUuid":null,"type":"attachment","attachment":{"type":"queued_command","prompt":7}}\n')
f.write((user(T0, "a real request here", cwd="/x") + "\n").encode())
con, st = self.harvest()
self.assertEqual(st["errors"], 0)
self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 1)
def test_queued_message_counts_once(self):
att = rec("attachment", T0 + 50, attachment={"type": "queued_command", "prompt": "also do this", "commandMode": "prompt",
"origin": {"kind": "human"}, "timestamp": iso(T0 + 50)})
note = rec("attachment", T0 + 60, attachment={"type": "queued_command", "prompt": "<task-notification>x", "commandMode": "task-notification",
"origin": {"kind": "task-notification"}})
self.session("S1", [user(T0, "start the work", cwd="/x"), asst(T0 + 10, tool="Read"), att, note, user(T0 + 51, "also do this")])
con, _ = self.harvest()
self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 2)
class TestGroundTruth(Fixture):
def test_start_commit_ignores_foreign_refs(self):
d = self.repo()
c1 = self.commit(d, "a", T0 - 7200)
c2 = self.commit(d, "b", T0 - 3600)
# a checkpoint commit made after c2 and before the session, reachable only from refs/t3/...
git(d, "checkout", "-q", "--detach")
c3 = self.commit(d, "ckpt", T0 - 600)
git(d, "update-ref", "refs/t3/x/checkpoints/1", c3)
git(d, "checkout", "-q", "main")
git(d, "reset", "-q", "--hard", c2)
git(d, "update-ref", "-d", "refs/heads/detached") if False else None
self.assertEqual(groundtruth.estimate_start(d, T0), c2)
self.assertEqual(groundtruth.estimate_start(d, T0 - 5000), c1)
self.assertIsNone(groundtruth.estimate_start(d, T0 - 99999))
# a remote-tracking ref counts
git(d, "update-ref", "refs/remotes/origin/main", c3)
self.assertEqual(groundtruth.estimate_start(d, T0), c3)
def test_ground_truth_end_to_end(self):
d = self.repo()
with open(os.path.join(d, "justfile"), "w") as f:
f.write("check:\n\techo ok\n")
git(d, "add", "-A")
git(d, "commit", "-q", "-m", "init", date=T0 - 1000)
start = git(d, "rev-parse", "HEAD")
after = self.commit(d, "new.py", T0 + 600)
late = self.commit(d, "late.py", T0 + 12000) # beyond window + 2h
self.session("S1", [user(T0, "add the feature to new.py", cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 3000, "ok")], proj="-p1")
con, _ = self.harvest()
groundtruth.run(con, home=self.home, workers=1)
g = con.execute("SELECT * FROM groundtruth WHERE session_id='S1'").fetchone()
self.assertEqual((g["start_commit"], g["start_kind"]), (start, "estimated"))
self.assertEqual([c["sha"] for c in json.loads(g["commits"])], [after])
self.assertEqual(g["test_cmd"], "just check")
self.assertEqual(g["repo_root"], os.path.realpath(d))
# sisi's own record makes it exact
store.save_session("S1", {"session_id": "S1", "head": start})
con.execute("DELETE FROM groundtruth")
groundtruth.run(con, home=self.home, workers=1)
g = con.execute("SELECT * FROM groundtruth WHERE session_id='S1'").fetchone()
self.assertEqual(g["start_kind"], "exact")
def test_missing_t3_worktree_recovered(self):
d = self.repo("proj")
self.commit(d, "a", T0 - 100)
gone = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-abc")
root, how, _ = groundtruth.resolve_repo(gone, self.home)
self.assertEqual((root, how), (os.path.realpath(d), "t3-worktree-recovery"))
self.assertEqual(groundtruth.resolve_repo(os.path.join(self.home, ".t3", "worktrees", "nothere", "x"), self.home)[0], None)
self.assertEqual(groundtruth.resolve_repo(self.proj, self.home)[1], "not-a-git-repo")
def test_linked_worktree_resolves_to_main_repo(self):
d = self.repo()
self.commit(d, "a", T0 - 100)
wt = os.path.join(self.tmp, "wt")
git(d, "worktree", "add", "-q", "-b", "t3/x", wt)
self.assertEqual(groundtruth.resolve_repo(wt, self.home)[0], os.path.realpath(d))
def test_test_command_detection(self):
d = self.repo()
for name, content, want in (("Cargo.toml", "[package]\n", "cargo test"),):
with open(os.path.join(d, name), "w") as f:
f.write(content)
git(d, "add", "-A")
git(d, "commit", "-q", "-m", "i", date=T0)
self.assertEqual(groundtruth.test_command(d, git(d, "rev-parse", "HEAD"))[0], "cargo test")
e = self.repo("e")
with open(os.path.join(e, "package.json"), "w") as f:
json.dump({"scripts": {"test": "jest"}}, f)
self.assertEqual(groundtruth.test_command(e, None)[0], "npm test")
with open(os.path.join(e, "package.json"), "w") as f:
json.dump({"scripts": {"test": "echo \"Error: no test specified\" && exit 1"}}, f)
self.assertIsNone(groundtruth.test_command(e, None)[0])
def test_overlap_detection(self):
d = self.repo()
self.commit(d, "a", T0 - 100)
self.session("A", [user(T0, "task one here", cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 1000, "x")], proj="-p")
self.session("B", [user(T0 + 500, "task two here", cwd=d), asst(T0 + 600, tool="Read"), asst(T0 + 700, "x")], proj="-p")
self.session("C", [user(T0 + 50000, "task three here", cwd=d), asst(T0 + 50010, "x")], proj="-p")
con, _ = self.harvest()
groundtruth.run(con, home=self.home, workers=1)
g = {r["session_id"]: r for r in con.execute("SELECT * FROM groundtruth")}
self.assertEqual((g["A"]["overlap_any"], g["A"]["overlap_writers"]), (1, 0)) # B only read
self.assertEqual((g["B"]["overlap_any"], g["B"]["overlap_writers"]), (1, 1)) # A wrote
self.assertEqual(g["C"]["overlap_any"], 0)
class TestTaskset(Fixture):
def test_split_is_stable_and_roughly_70_30(self):
ids = ["h-%08x" % random.Random(i).getrandbits(32) for i in range(2000)]
first = {i: taskset.split_of(i) for i in ids}
dev = sum(1 for v in first.values() if v == "dev") / len(ids)
self.assertTrue(0.65 < dev < 0.75, dev)
for i in ids:
self.assertEqual(taskset.split_of(i), first[i])
def test_adding_tasks_never_moves_existing(self):
con = harvest.connect()
now = time.time()
existing = {}
rng = random.Random(7)
for round_ in range(5):
for _ in range(40):
tid = "t%d" % rng.getrandbits(40)
taskset._upsert(con, existing, now, id=tid, kind="human", session_id=tid, grade="B", reasons="[]")
existing[tid] = con.execute("SELECT split FROM tasks WHERE id=?", (tid,)).fetchone()[0]
snap = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")}
for tid, sp in snap.items(): # re-upserting with another grade keeps the split
taskset._upsert(con, existing, now, id=tid, kind="human", session_id=tid, grade="C", reasons="[]")
after = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")}
self.assertEqual(snap, after)
self.assertTrue(all(sp == taskset.split_of(t) for t, sp in after.items()))
def row(self, **kw):
base = dict(start_kind="estimated", test_cmd="just test", overlap_any=0, overlap_writers=0, n_commits=2,
first_message="please implement the feature in detail", ran_commit=1, tools="{}")
base.update(kw)
return base
def test_grades(self):
g = lambda **kw: taskset.grade_human(self.row(**kw), self.row(**kw))[0]
self.assertEqual(g(), "A") # no sibling, test command
self.assertEqual(g(start_kind="exact", test_cmd=None), "A") # exact start
self.assertEqual(g(start_kind="exact", test_cmd=None, overlap_any=1, overlap_writers=1), "C")
self.assertEqual(g(overlap_any=1, overlap_writers=1), "B") # estimated, siblings wrote, has tests
self.assertEqual(g(test_cmd=None, overlap_any=1, overlap_writers=0), "B")
self.assertEqual(g(test_cmd=None), "B") # no sibling but no tests: not A
self.assertEqual(g(n_commits=80), "C")
self.assertEqual(g(first_message="continue"), "C")
self.assertEqual(g(ran_commit=0), "C")
self.assertEqual(g(ran_commit=0, tools='{"Edit": 3}'), "A")
def test_build_end_to_end_with_duplicates(self):
d = self.repo()
with open(os.path.join(d, "justfile"), "w") as f:
f.write("test:\n\ttrue\n")
git(d, "add", "-A")
git(d, "commit", "-q", "-m", "i", date=T0 - 500)
self.commit(d, "n.py", T0 + 400)
msg = "please implement the new feature in n.py"
self.session("S1", [user(T0, msg, cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 500, "ok")], proj="-p")
self.session("S2", [user(T0 + 90000, msg, cwd=d), asst(T0 + 90010, tool="Edit"), asst(T0 + 90500, "ok")], proj="-p")
self.session("M1", [user(T0 + 300000, "You are a worker. Do the thing.", cwd=d)], proj="-p")
con, _ = self.harvest()
groundtruth.run(con, home=self.home, workers=1)
r = taskset.build(con, home=self.home)
self.assertEqual(r["human"], 1) # only S1 has following commits; M1 is machine-written
t = taskset.list_tasks(con, kind="human")[0]
self.assertEqual((t["id"], t["grade"], t["test_cmd"]), ("h-S1", "A", "just test"))
split = t["split"]
taskset.build(con, home=self.home)
self.assertEqual(taskset.list_tasks(con, kind="human")[0]["split"], split)
self.assertEqual(taskset.get_task(con, "h-S")["id"], "h-S1")
def test_ledger_matching(self):
sub = lambda i, t0, t1: {"id": i, "t0": t0, "t1": t1, "names": {"r"}, "classes": {"sonnet"}}
led = lambda i, ts, w="sonnet", m=None, p="r": {"id": i, "ts": ts, "worker": w, "project": p, "outcome": "accepted", "minutes": m}
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, m=10)])
self.assertEqual((out["a"][1], out["a"][0]["id"]), ("high", "L1"))
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, m=90)])
self.assertEqual(out["a"][1], "medium")
out = taskset.match_ledger([sub("a", T0, T0 + 600), sub("b", T0 + 100, T0 + 650)], [led("L1", T0 + 700)])
self.assertEqual((out["a"][1], out["a"][0]), ("low", None))
self.assertEqual(out["b"][1], "low")
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, w="opencode-go/x")])
self.assertEqual(out["a"][1], "none")
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, p="other")])
self.assertEqual(out["a"][1], "none")
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 9000)])
self.assertEqual(out["a"][1], "none")
class TestEscapesChecksScoreboard(Fixture):
def results(self, project, t, ok=True, session=None):
return [{"ts": iso(t)[:19] + "Z", "contract": "c", "project": project, "check": "unit", "status": "passed" if ok else "failed",
"run": "r%d" % t, "session": session}]
def test_escapes(self):
d = self.repo()
self.commit(d, "a", T0 - 100)
self.session("S1", [user(T0, "implement the thing in a", cwd=d), asst(T0 + 100, "All tests pass. Done."),
user(T0 + 200, "no, that's wrong, it still fails"), asst(T0 + 300, "sorry")], proj="-p")
con, _ = self.harvest()
groundtruth.run(con, home=self.home, workers=1)
res = self.results(d, T0 + 120) # attributed by time and project, no session field
out = escapes.find(con, res)
kinds = [e["kind"] for e in out]
self.assertIn("contract-then-correction", kinds)
self.assertIn("premature-done", kinds)
# a failed run is not "verified"
self.assertEqual([e for e in escapes.find(con, self.results(d, T0 + 120, ok=False)) if e["kind"].startswith("contract")], [])
# a correction BEFORE the pass is not an escape
self.assertEqual([e for e in escapes.find(con, self.results(d, T0 + 250)) if e["kind"].startswith("contract")], [])
def test_fix_session_escape(self):
d = self.repo()
self.commit(d, "a.py", T0 - 100)
self.commit(d, "a.py", T0 + 100)
self.session("S1", [user(T0, "implement the thing in a.py", cwd=d), asst(T0 + 50, tool="Edit"), asst(T0 + 150, "ok")], proj="-p")
c2 = self.commit(d, "a.py", T0 + 86400 * 2, "fix")
self.session("S2", [user(T0 + 86400 * 2 - 100, "the thing in a.py is broken, please fix it", cwd=d), asst(T0 + 86400 * 2 - 50, tool="Edit"),
asst(T0 + 86400 * 2 + 60, "ok")], proj="-p")
con, _ = self.harvest()
groundtruth.run(con, home=self.home, workers=1)
out = escapes.find(con, self.results(d, T0 + 120, session="S1"))
fix = [e for e in out if e["kind"] == "contract-then-fix-session"]
self.assertEqual(len(fix), 1)
self.assertEqual(fix[0]["evidence"]["later_session"], "S2")
def test_check_stats(self):
rs = [{"check": "a", "status": "passed", "verifier": "v1"} for _ in range(12)]
rs += [{"check": "b", "status": "failed"}, {"check": "b", "status": "timeout"}, {"check": "gate", "status": "unverified"}]
rs += [{"check": "c", "status": "passed", "verifier": "v2"}, "junk"]
st = scoreboard.check_stats(rs)
by = {s["id"]: s for s in st["checks"]}
self.assertTrue(by["a"]["never_seen_failing"])
self.assertEqual((by["b"]["runs"], by["b"]["failures"], by["b"]["timeouts"]), (2, 1, 1))
self.assertFalse(by["b"]["never_seen_failing"])
self.assertFalse(by["c"]["never_seen_failing"]) # too few runs
self.assertNotIn("gate", by)
self.assertEqual({s["id"]: s["runs"] for s in st["verifiers"]}, {"v1": 12, "v2": 1})
def test_scoreboard_weeks(self):
w1 = harvest.epoch("2026-11-02T10:00:00.000Z") # Monday of ISO week 45
w2 = w1 + 7 * 86400
self.session("S1", [user(w1, "do the first task here", cwd="/x"), asst(w1 + 5, "Done. All tests pass."),
user(w1 + 60, "no, that's wrong"), asst(w1 + 70, tool="Bash", cmd="sisi contract check")], proj="-p")
self.session("S2", [user(w2, "do the second task here", cwd="/x"), asst(w2 + 5, "ok?")], proj="-p")
self.session("M", [user(w2, "You are a worker. Do X.", cwd="/x")], proj="-p")
con, _ = self.harvest()
sb = scoreboard.scoreboard(con)
self.assertEqual(list(sb["weeks"]), ["2026-W45", "2026-W46"])
a = sb["weeks"]["2026-W45"]
self.assertEqual((a["sessions"], a["turns_per_session"], a["corrections_per_100"], a["contract_share"], a["premature_done_share"]),
(1, 2.0, 50.0, 1.0, 1.0))
self.assertEqual(sb["weeks"]["2026-W46"]["sessions"], 1) # machine-written session excluded
self.assertEqual(sb["weeks"]["2026-W46"]["questions_per_100"], 100.0)
class TestCli(Fixture):
def run_cli(self, *args):
env = dict(os.environ, PYTHONPATH=REPO)
return subprocess.run([sys.executable, "-m", "sisi.learn_cli"] + list(args), capture_output=True, text=True, env=env, cwd=self.proj, timeout=120)
def test_commands_run(self):
d = self.repo()
self.commit(d, "a", T0 - 100)
self.session("S1", [user(T0, "implement the thing here please", cwd=d), asst(T0 + 100, "ok")], proj="-p")
p = self.run_cli("harvest", "--json", "--workers", "1")
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(json.loads(p.stdout)["transcripts"]["parsed"], 1)
self.assertEqual(json.loads(self.run_cli("harvest", "--json").stdout)["transcripts"]["parsed"], 0)
self.assertEqual(self.run_cli("tasks", "build").returncode, 0)
self.assertEqual(self.run_cli("tasks", "list", "--json").returncode, 0)
self.assertEqual(self.run_cli("tasks", "show", "nope").returncode, 1)
self.assertEqual(self.run_cli("escapes", "--json").returncode, 0)
self.assertEqual(self.run_cli("checks").returncode, 0)
sb = json.loads(self.run_cli("scoreboard", "--json").stdout)
self.assertEqual(sb["weeks"]["2026-W44"]["sessions"], 1)
def test_register_attaches_commands(self):
import argparse
ap = argparse.ArgumentParser()
learn_cli.register(ap.add_subparsers(dest="cmd"))
for argv in (["harvest"], ["tasks", "build"], ["tasks", "list", "--grade", "A"], ["tasks", "show", "x"], ["escapes"], ["checks"], ["scoreboard", "--json"]):
self.assertTrue(callable(ap.parse_args(argv).func))
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+327
View File
@@ -0,0 +1,327 @@
"""The learning loop, rebuilt. Docstrings cite docs/spec/requirements.json ids."""
import json, os, subprocess
from support import SisiCase
def _contract(case, uid="u1", proj=None):
d = proj or case.proj
os.makedirs(os.path.join(d, ".sisi"), exist_ok=True)
with open(os.path.join(d, ".sisi", "contract.json"), "w") as f:
json.dump({"id": uid, "goal": "g", "checks": []}, f)
PROMOTE = ("retro", "--finding", "f.txt held the word bug and shipped without a content check",
"--cause", "no check asserted file contents before delivery",
"--impact", "correctness", "--disposition", "promote",
"--change", "grep for fixed in f.txt must pass", "--mechanism", "verification",
"--expect", "bug text is caught", "--validate", "replay the grep before and after")
class LearningLoop(SisiCase):
def retro(self, *a, **kw):
return self.sisi("retro", *a, **kw)
def rows(self):
from sisi import learning as L
return L.load_learnings()
def test_generic_finding_refused(self):
"""R-11.1-9, R-11.1-13: generic findings are refused, not invented."""
_contract(self)
r = self.retro("--finding", "be more careful", "--cause", "x" * 20,
"--impact", "time", "--disposition", "drop", "--why-not", "no value here")
self.assertNotEqual(r.returncode, 0)
self.assertEqual(self.rows(), [])
def test_dispositions_record_only_what_they_need(self):
"""R-11.1-14, R-11.1-16, R-11.4-1: promote/record/drop persist concrete findings."""
_contract(self)
self.assertEqual(self.retro(*PROMOTE[1:]).returncode, 0)
self.assertEqual(self.retro(
"--finding", "the fixture had one file so nothing general was learned here at all",
"--cause", "single file fixture scope", "--impact", "time",
"--disposition", "record", "--limits", "single-file fixtures only").returncode, 0)
self.assertEqual(self.retro(
"--finding", "commit messages in the fixture were terse single letters today",
"--cause", "fixture brevity by design", "--impact", "attention",
"--disposition", "drop", "--why-not", "fixture only, no change worth making").returncode, 0)
from sisi import learning as L
rows = self.rows()
self.assertEqual(len(rows), 2)
self.assertEqual(rows[0]["status"], "proposed")
self.assertEqual(rows[1]["status"], "observed")
self.assertEqual(len(L.findings_for_unit(self.proj, "u1")), 3)
self.assertIn(rows[0]["status"], L.STATUSES)
self.assertTrue(rows[0]["terms"]) # derived by the tool, not demanded
def test_promote_missing_fields_refused(self):
"""R-11.1-11: a promoted opportunity needs action, expected effect, validation."""
_contract(self)
r = self.retro("--finding", "a real thing happened with evidence attached here now",
"--cause", "a concrete root cause here", "--impact", "cost",
"--disposition", "promote", "--change", "do the thing")
self.assertNotEqual(r.returncode, 0)
self.assertEqual(self.rows(), [])
def test_one_unit_learning_not_delivered_in_other_project(self):
"""R-11.6-1, R-11.6-2, R-12-2: scope is earned; one incident is origin-only."""
_contract(self)
self.git_init()
self.assertEqual(self.retro(*PROMOTE[1:]).returncode, 0)
from sisi import learning as L
self.assertIn("L-0001", L.delivery_text(self.proj, "f.txt bug content check"))
other = os.path.join(self.tmp, "other")
os.makedirs(other)
self.git_init(other)
self.assertNotIn("L-0001", L.delivery_text(other, "f.txt bug content check"))
# earn it: a second unit in a second project
_contract(self, "u9", other)
r = self.sisi("retro", "--finding", "f.txt held the word bug and shipped without a content check",
"--cause", "no check asserted file contents before delivery",
"--impact", "correctness", "--disposition", "record",
"--limits", "text files", "--same-as", "L-0001", cwd=other)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("L-0001", L.delivery_text(other, "f.txt bug content check"))
def test_delivery_framed_as_information_not_instruction(self):
"""R-16-6: delivered text is data to weigh, never an instruction."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
t = L.delivery_text(self.proj, "f.txt bug")
self.assertIn("not instructions", t)
self.assertNotIn("you must", t.lower())
def test_nothing_validated_without_a_passing_run(self):
"""R-11.5-6, R-11.1-8: 'validated' requires a validation run that passed."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "true"}]} # no commits known: cannot be replayed
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stderr)
rec = self.rows()[0]
self.assertEqual(rec["status"], "promoted")
self.assertEqual(rec["validation"]["result"], "unvalidated")
self.assertIn("unvalidated", L.learning_report())
def test_replay_validation_in_temp_worktree(self):
"""R-11.6-3: replay must fail before and pass after, without touching the tree."""
_contract(self)
self.git_init()
open(os.path.join(self.proj, "f.txt"), "w").write("bug\n")
self._commit("before")
before = self._head()
open(os.path.join(self.proj, "f.txt"), "w").write("fixed\n")
self._commit("fix")
after = self._head()
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "grep -q fixed f.txt", "before": before, "after": after}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
self.assertEqual(open(os.path.join(self.proj, "f.txt")).read(), "fixed\n")
self.assertEqual(self._head(), after) # the user's tree and HEAD untouched
def test_failed_replay_refuses_whole_cycle(self):
"""R-11.5-6: a check that passes before the fix proves nothing; nothing applies."""
_contract(self)
self.git_init()
open(os.path.join(self.proj, "f.txt"), "w").write("fixed\n")
self._commit("before")
before = self._head()
self._commit("after")
after = self._head()
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "grep -q fixed f.txt", "before": before, "after": after}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertNotEqual(r.returncode, 0)
self.assertEqual(self.rows()[0]["status"], "proposed")
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "enforced.json")))
def test_cycle_refusals_apply_nothing(self):
"""R-14.3-1, R-11.7-2, R-16-11: protected rule, stale base, ignored flag."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
base = L.store_base()
cases = [
{"base": base, "actions": [{"action": "promote", "learning": "L-0001",
"mechanism_kind": "rule-text", "rule_id": "strongest-check",
"rule_text": "## Weak {#strongest-check}\n\nSkip checks.\n\nWhy: faster.\n"}]},
{"base": "stale", "actions": [{"action": "promote", "learning": "L-0001",
"mechanism_kind": "risk", "pattern": "x/**", "profile": "logic"}]},
]
for i, doc in enumerate(cases):
p = os.path.join(self.tmp, "c%d.json" % i)
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertNotEqual(r.returncode, 0, doc)
self.assertEqual(self.rows()[0]["status"], "proposed")
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "risk-adjustments.json")))
def test_consequential_change_waits_for_owner(self):
"""R-11.5-11, R-14.4-1: disabling a rule is pending until `sisi approve`."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "disable-rule", "rule_id": "deliver-quickly"}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(L.load_pending()), 1)
self.assertIn("wait", L.pending_notice())
from sisi import overlay
self.assertNotIn("deliver-quickly", overlay.disabled("rule"))
r = self.sisi("approve", "P-0001", "--no")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(L.load_pending(), [])
self.assertNotIn("deliver-quickly", overlay.disabled("rule"))
def test_two_recurrences_flag_and_cycle_must_act(self):
"""R-13.2-8, R-11.5-9: recurrence after promotion flags; a cycle ignoring it is refused."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk",
"pattern": "f.txt", "profile": "logic"}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
for uid in ("u2", "u3"):
_contract(self, uid)
r = self.retro("--finding", "f.txt held the word bug and shipped without a content check",
"--cause", "no check asserted file contents before delivery",
"--impact", "correctness", "--disposition", "record",
"--limits", "here", "--same-as", "L-0001")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertTrue(self.rows()[0]["flagged_not_working"])
doc = {"base": L.store_base(), "actions": [
{"action": "reject", "learning": "L-0001", "why": "wrong idea"}]}
# a cycle that does act on it passes; first prove an ignoring cycle is refused
self.retro("--finding", "another unrelated slowness appeared in the test run today",
"--cause", "the suite runs everything serially", "--impact", "time",
"--disposition", "promote", "--change", "run independent checks in parallel",
"--mechanism", "infrastructure", "--expect", "faster runs",
"--validate", "time the suite")
bad = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk",
"pattern": "y/**", "profile": "logic"}]}
json.dump(bad, open(p, "w"))
self.assertNotEqual(self.sisi("cycle", "apply", p).returncode, 0)
doc["base"] = L.store_base()
json.dump(doc, open(p, "w"))
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertEqual(self.rows()[0]["status"], "rejected")
def test_revert_is_exact(self):
"""R-11.6-6, R-16-9: reverting a cycle restores the user store."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "true"}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertTrue(os.path.exists(os.path.join(self.data, "overlay", "enforced.json")))
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "enforced.json")))
self.assertEqual(self.rows()[0]["status"], "proposed")
def test_subagent_learning_held_until_parent_adopts(self):
"""R-16-10: a subagent's learning is a candidate until the parent retro adopts it."""
_contract(self)
r = self.sisi("retro", *PROMOTE[1:], env={"SISI_SUBAGENT": "1"})
self.assertEqual(r.returncode, 0, r.stderr)
from sisi import learning as L
self.assertTrue(self.rows()[0]["candidate"])
self.assertEqual(L.delivery_text(self.proj, "f.txt bug"), "")
_contract(self, "u2")
r = self.retro("--finding", "adopting the subagent finding about f.txt content checks now",
"--cause", "the parent reviewed the subagent report", "--impact", "correctness",
"--disposition", "record", "--limits", "here", "--same-as", "L-0001")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse(self.rows()[0]["candidate"])
def test_learn_and_oracle_one_path(self):
"""R-12-1, R-12-5: `sisi learn` writes, `sisi oracle` prints, one store."""
r = self.sisi("learn", "prefer short plain reports over long ones")
self.assertEqual(r.returncode, 0, r.stderr)
r = self.sisi("oracle")
self.assertIn("prefer short plain reports", r.stdout)
from sisi import learning as L
self.assertEqual(len(L.owner_statements()), 1)
def test_dead_commands_gone(self):
"""Target section 13: improve, backlog and lessons digest are retired."""
self.assertNotEqual(self.sisi("improve").returncode, 0)
self.assertNotEqual(self.sisi("backlog").returncode, 0)
self.assertNotEqual(self.sisi("lessons", "digest").returncode, 0)
def test_report_claims_no_rate_when_too_few(self):
"""R-13.2-7: the realization rate says 'too few' instead of inventing a number."""
from sisi import learning as L
self.assertIn("too few", L.learning_report())
def test_migration_is_lossless_and_idempotent(self):
"""R-12-10: every old lesson and owner statement survives; counts asserted."""
os.makedirs(self.data, exist_ok=True)
rows = [
{"t": "lesson", "id": 1, "moment": "m one happened here", "cause": "c one",
"change": "change one", "change_kind": "rule", "status": "applied",
"project": self.proj, "created": "2026-01-01T00:00:00Z"},
{"t": "lesson", "id": 2, "moment": "m two happened here", "cause": "c two",
"change": "change two", "change_kind": "tool", "status": "open",
"project": self.proj, "created": "2026-01-01T00:00:00Z"},
{"t": "occurrence", "id": 1, "lesson_id": 1, "repo": self.proj,
"session": "s1", "ts": "2026-01-01T00:00:00Z"},
{"t": "impression", "id": 1, "lesson_id": 1, "place": "tick",
"ts": "2026-01-01T00:00:00Z"},
]
with open(os.path.join(self.data, "lessons.jsonl"), "w") as f:
for r in rows:
f.write(json.dumps(r) + "\n")
with open(os.path.join(self.data, "learn.jsonl"), "w") as f:
f.write(json.dumps({"text": "always ask before spending", "ts": "2026-01-01T00:00:00Z"}) + "\n")
from sisi import lifecycle, learning as L
notes = lifecycle.migrate_learnings()
self.assertTrue(notes)
got = self.rows()
self.assertEqual(len(got), 3) # 2 lessons + 1 statement; impression dropped
self.assertEqual(got[0]["status"], "implemented")
self.assertTrue(all(r["validation"]["result"] != "validated" for r in got))
self.assertEqual(len(got[0]["provenance"]), 1)
self.assertEqual(len(L.owner_statements()), 1)
self.assertEqual(lifecycle.migrate_learnings(), []) # idempotent
self.assertEqual(len(self.rows()), 3)
def _commit(self, msg):
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "add", "."],
cwd=self.proj, check=True, capture_output=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q",
"--allow-empty", "-m", msg], cwd=self.proj, check=True, capture_output=True)
def _head(self):
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=self.proj,
capture_output=True, text=True).stdout.strip()
-167
View File
@@ -1,167 +0,0 @@
"""Patterns: `sisi retro --pattern`, `sisi retro patterns`, the cycle's set-pattern action,
and patterns-first digest/improve."""
import json, os, unittest
from support import *
from sisi import retro
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
PATTERN = "Build the obvious thing instead of using what the environment already provides"
def retro_args(**kw):
f = dict(aim="verified", moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with the writer the project already had",
change_kind="rule", change="Write delimited files with a quoting writer so fields survive",
when=WHEN, scope="core", pattern=PATTERN,
short="Use a quoting writer for delimited exports.", topic="data files")
f.update(kw)
out = []
for k in ("aim", "moment", "cause", "change_kind", "change", "when", "scope", "short", "topic", "pattern"):
if f.get(k) is not None:
out += ["--" + k.replace("_", "-"), str(f[k])]
if f.get("pattern_id") is not None:
out += ["--pattern-id", str(f["pattern_id"])]
return out
class RetroPatternTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def test_pattern_is_required_for_a_new_lesson(self):
r = self.sisi("retro", *retro_args(pattern=None))
self.assertNotEqual(r.returncode, 0, r.stdout)
self.assertIn("pattern", (r.stdout + r.stderr).lower())
def test_pattern_is_stored_and_reused_not_duplicated(self):
r = self.sisi("retro", *retro_args())
self.assertEqual(r.returncode, 0, r.stdout)
r = self.sisi("retro", "--new", *retro_args(
moment="another export broke on an embedded newline at step 4 of the run",
change="Write delimited files with a quoting writer so newlines survive"))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
try:
pats = retro.patterns(con)
self.assertEqual(len(pats), 1, pats)
self.assertEqual(pats[0]["statement"], PATTERN)
ids = [row[0] for row in con.execute("SELECT pattern_id FROM lessons ORDER BY id")]
self.assertEqual(ids, [pats[0]["id"], pats[0]["id"]])
finally:
con.close()
def test_retro_patterns_lists_them_and_pattern_id_selects(self):
self.assertEqual(self.sisi("retro", *retro_args()).returncode, 0)
out = self.sisi("retro", "patterns").stdout
self.assertIn(PATTERN, out)
r = self.sisi("retro", "--new", *retro_args(
pattern=None, pattern_id=1,
moment="a third export broke on a delimiter in a name at step 1 of the run",
change="Write delimited files with a quoting writer so delimiters survive"))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
try:
self.assertEqual(len(retro.patterns(con)), 1)
finally:
con.close()
def test_pattern_naming_the_project_or_restating_the_change_is_refused(self):
r = self.sisi("retro", *retro_args(pattern="proj export rows are joined by hand in this repo"))
self.assertNotEqual(r.returncode, 0, r.stdout)
r = self.sisi("retro", *retro_args(pattern="Write delimited files with a quoting writer so fields survive"))
self.assertNotEqual(r.returncode, 0, r.stdout)
class CyclePatternTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def lesson_without_pattern(self):
con = retro.connect()
try:
lid = retro.new_lesson(con, dict(
aim="verified", change_kind="rule", target=None,
moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so fields survive",
when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files",
scope="core"), self.proj, None)
con.commit()
return lid
finally:
con.close()
def test_cycle_brief_lists_patterns_and_check_requires_set_pattern(self):
lid = self.lesson_without_pattern()
brief = self.sisi("cycle", "--now").stdout
self.assertIn("pattern", brief.lower())
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "x",
"notes": [{"lesson": lid, "action": "keep"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("set-pattern", r.stdout)
doc["notes"].append({"lesson": lid, "action": "set-pattern", "pattern": PATTERN})
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
self.assertEqual(retro.patterns(con)[0]["statement"], PATTERN)
finally:
con.close()
def test_pattern_merge_keeps_one(self):
con = retro.connect()
try:
a = retro.get_or_create_pattern(con, PATTERN)
b = retro.get_or_create_pattern(con, "Rebuild what already exists instead of calling it")
con.commit()
finally:
con.close()
lid = self.lesson_without_pattern()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "merge patterns",
"notes": [{"lesson": lid, "action": "set-pattern", "pattern_id": b}],
"patterns": [{"pattern": b, "action": "merge", "into": a}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
pats = retro.patterns(con)
self.assertEqual([x["id"] for x in pats], [a])
self.assertEqual(con.execute("SELECT pattern_id FROM lessons WHERE id=?", (lid,)).fetchone()[0], a)
finally:
con.close()
class PatternsFirstTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.assertEqual(self.sisi("retro", *retro_args()).returncode, 0)
def test_digest_shows_patterns_first(self):
out = self.sisi("lessons", "digest").stdout
self.assertIn("## Patterns", out)
self.assertLess(out.index("## Patterns"), out.index("## In sisi itself"))
self.assertIn(PATTERN, out)
def test_improve_shows_patterns(self):
out = self.sisi("improve").stdout
self.assertIn(PATTERN, out)
if __name__ == "__main__":
unittest.main()
+66 -73
View File
@@ -2,7 +2,7 @@
install migration, and the property that sisi never writes inside the product."""
import hashlib, json, os, signal, time, shutil, sqlite3, stat, subprocess, sys, tarfile, unittest, unittest.mock
from support import *
from sisi import lifecycle, overlay, paths, pdata, retro, wiring
from sisi import lifecycle, overlay, paths, pdata, wiring
RULES = [("alpha", "Alpha rule", "Do alpha things.\n\nWhy: alpha."),
("beta", "Beta rule", "Do beta things.\n\nWhy: beta."),
@@ -246,7 +246,7 @@ class OverlayTests(PersonalCase):
lines = len(self.generated().splitlines())
self.assertIn("rulebook %d lines" % lines, out)
self.assertIn("%d characters" % len(self.generated()), out)
self.assertIn("lessons block at most %d characters" % retro.LIMIT, out)
self.assertNotIn("lessons block", out) # no lesson list is loaded at session start
self.assertIn("rulebook %d lines" % lines, self.ok("status").stdout)
def test_core_md_rules_have_unique_ids_and_the_budget_holds(self):
@@ -367,6 +367,23 @@ class UpdateTests(PersonalCase):
self.assertIn("not a git clone", r.stdout)
def _seed_legacy_db(path, lessons, proj):
"""A pre-rebuild retro.db: the sqlite lesson store the migration reads."""
con = sqlite3.connect(path)
con.execute("CREATE TABLE lessons (id INTEGER PRIMARY KEY, aim TEXT, change_kind TEXT, target TEXT,"
" moment TEXT, cause TEXT, change TEXT, status TEXT, project TEXT, created TEXT)")
con.execute("CREATE TABLE occurrences (id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT,"
" moment TEXT, repo TEXT)")
for f in lessons:
cur = con.execute("INSERT INTO lessons(aim,change_kind,target,moment,cause,change,status,project,created)"
" VALUES(?,?,?,?,?,?,?,?,?)",
(f.get("aim"), f.get("change_kind"), f.get("target"), f.get("moment"),
f.get("cause"), f.get("change"), "open", proj, "2026-01-01T00:00:00Z"))
con.execute("INSERT INTO occurrences(lesson_id,ts,session,moment,repo) VALUES(?,?,?,?,?)",
(cur.lastrowid, "2026-01-01T00:00:00Z", "s0", f.get("moment"), proj))
con.commit(); con.close()
class MigrationTests(PersonalCase):
LESSONS = [dict(aim="verified", moment="ran pytest and it passed without the new test", cause="the test never failed",
change_kind="rule", change="Always watch a new test fail without the change first", target=None),
@@ -377,13 +394,8 @@ class MigrationTests(PersonalCase):
"""Lay out an old-style installation: personal files in the state dir, oracle and notes in the product."""
os.makedirs(os.path.join(self.state, "backups"))
db = os.path.join(self.state, "retro.db")
with unittest.mock.patch.object(retro, "db_path", return_value=db):
con = retro.connect()
for f in self.LESSONS + ([dict(aim="intent", moment="built the wrong thing for a day", cause="no check with the human",
change_kind="rule", change="Confirm the goal in one line before starting", target=None)] if extra_lesson else []):
retro.new_lesson(con, dict(f), self.proj, None)
con.commit()
con.close()
_seed_legacy_db(db, self.LESSONS + ([dict(aim="intent", moment="built the wrong thing for a day", cause="no check with the human",
change_kind="rule", change="Confirm the goal in one line before starting", target=None)] if extra_lesson else []), self.proj)
json.dump([self.proj], open(os.path.join(self.state, "trusted.json"), "w"))
json.dump({"verify": {"fast_limit_s": 9}}, open(os.path.join(self.state, "config.json"), "w"))
for n, t in (("learn-quarantine.jsonl", "quarantined"), ("notes.jsonl", "a note"), ("proposals.jsonl", "a proposal")):
@@ -424,11 +436,11 @@ class MigrationTests(PersonalCase):
self.assertIn("/x/CLAUDE.md", json.load(open(os.path.join(self.data, "install", "manifest.json")))["files"])
# committed: the learned content is in git history, the database is not
files = pdata.git("ls-files").stdout.split()
for f in ("oracle.md", "lessons.jsonl", "trusted.json", "config.json", "notes/fuzz.md", "VERSION", "learn-quarantine.jsonl"):
for f in ("oracle.md", "learnings.jsonl", "trusted.json", "config.json", "notes/fuzz.md", "VERSION", "learn-quarantine.jsonl"):
self.assertIn(f, files)
self.assertNotIn("retro.db", files)
self.assertEqual(len(open(os.path.join(self.data, "lessons.jsonl")).read().splitlines()), 2 + len(before[1]))
self.assertTrue(any(l.startswith("migrate:") for l in self.git_log()))
self.assertEqual(len(open(os.path.join(self.data, "learnings.jsonl")).read().splitlines()), 2) # one record per lesson; occurrences are provenance inside it
self.assertTrue(self.git_log()[0].startswith("migrate:"))
# the backup has what moved, before it moved
bk = os.path.join(self.data, "backups")
b = next(os.path.join(bk, d) for d in sorted(os.listdir(bk))
@@ -440,31 +452,29 @@ class MigrationTests(PersonalCase):
self.assertTrue(os.path.exists(os.path.join(self.p1, "canon", "oracle.md")))
# a second run does nothing
n = len(self.git_log())
self.ok("update", "--post")
self.ok("update", "--post") # a second run migrates nothing more
self.assertEqual(len(self.git_log()), n)
self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before)
self.assertEqual(self.ok("lessons", "--json").stdout.count('"change_kind"'), 2)
self.assertEqual(self.ok("lessons", "--json").stdout.count('"id": "L-'), 2)
def test_old_layout_keeps_working_before_migration(self):
self.legacy_state()
self.ok("update", "--post") # lessons now live in learnings.jsonl; migration is the one path in
self.assertEqual(self.ok("lessons").stdout.count("\n"), 2)
self.assertEqual(wiring.quick_problem(), None)
from sisi import trust
self.assertTrue(trust.is_trusted(self.proj))
self.assertEqual(self.ok("tick", stdin="{}").returncode, 0)
self.assertEqual(self.sisi("tick", stdin="{}").stdout, "") # no lesson list at session start
self.assertNotIn("Always watch", self.sisi("tick", stdin="{}").stdout) # no lesson list at session start
def test_migrate_merges_when_both_old_and_new_databases_exist(self):
self.legacy_state(extra_lesson=True)
# the new location already has one of the same lessons and one of its own
with unittest.mock.patch.object(retro, "db_path", return_value=os.path.join(self.data, "retro.db")):
os.makedirs(self.data)
con = retro.connect()
retro.new_lesson(con, dict(self.LESSONS[0]), self.proj, None)
retro.new_lesson(con, dict(aim="level", moment="asked about a thing the oracle already answered", cause="did not run oracle",
change_kind="rule", change="Run sisi oracle before asking anything", target=None), self.proj, None)
con.commit()
con.close()
os.makedirs(self.data, exist_ok=True)
_seed_legacy_db(os.path.join(self.data, "retro.db"),
[dict(self.LESSONS[0]),
dict(aim="level", moment="asked about a thing the oracle already answered", cause="did not run oracle",
change_kind="rule", change="Run sisi oracle before asking anything", target=None)], self.proj)
self.ok("update", "--post")
rows, _ = self.lessons_of(os.path.join(self.data, "retro.db"))
changes = sorted(r["change"] for r in rows)
@@ -555,11 +565,12 @@ class ExportImportTests(PersonalCase):
def test_round_trip_is_lossless_for_committed_content(self):
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Mine"))
self.ok("learn", "--scope", "everywhere", "never", "ask", "twice")
self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim",
"--change", "write the failing test first and show it fail with `pytest -k new`")
self.ok("learn", "--scope", "user", "never ask the same thing twice")
self.ok("retro", "--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--impact", "correctness",
"--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`",
"--mechanism", "verification", "--expect", "new tests are seen failing first",
"--validate", "replay the new test at the parent commit")
os.makedirs(os.path.join(self.state, "sessions"))
open(os.path.join(self.state, "sessions", "s1.json"), "w").write('{"a": 1}')
open(os.path.join(self.state, "results.jsonl"), "w").write('{"r": 1}\n')
@@ -572,7 +583,7 @@ class ExportImportTests(PersonalCase):
with tarfile.open(arc) as tf:
names = tf.getnames()
self.assertIn("personal/overlay/rules/delta.md", names)
self.assertIn("personal/retro.db", names)
self.assertIn("personal/learnings.jsonl", names)
self.assertIn("state/results.jsonl", names)
self.assertIn("state/sessions/s1.json", names)
self.assertFalse([n for n in names if "/generated" in n or "/backups" in n or "/install" in n])
@@ -591,22 +602,16 @@ class ExportImportTests(PersonalCase):
self.assertTrue(os.path.exists(os.path.join(self.state, "sessions", "s1.json")))
self.assertRegex(self.ok("verifiers", "--section", "safety").stdout, r"shellcheck .*Mine")
def test_import_sets_existing_data_aside_and_rebuilds_db_from_the_dump(self):
self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim",
"--change", "write the failing test first and show it fail with `pytest -k new`")
def test_import_sets_existing_data_aside_and_restores_learnings(self):
self.ok("retro", "--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--impact", "correctness",
"--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`",
"--mechanism", "verification", "--expect", "new tests are seen failing first",
"--validate", "replay the new test at the parent commit")
arc = os.path.join(self.tmp, "out.tar.gz")
self.ok("export", arc)
# an archive without the database: the dump recreates it
slim = os.path.join(self.tmp, "slim.tar.gz")
with tarfile.open(arc) as a, tarfile.open(slim, "w:gz") as b:
for m in a.getmembers():
if m.name != "personal/retro.db":
b.addfile(m, a.extractfile(m) if m.isfile() else None)
r = self.ok("import", slim)
r = self.ok("import", arc)
self.assertIn("set aside", r.stdout)
self.assertIn("rebuilt from lessons.jsonl", r.stdout)
self.assertTrue(glob_aside(self.data))
self.assertEqual(self.ok("lessons").stdout.count("\n"), 1)
@@ -628,46 +633,34 @@ def glob_aside(data):
def LessonRows():
con = retro.connect()
try:
return retro.dump_lines(con)
finally:
con.close()
from sisi import learning as _L
return [json.dumps(r, sort_keys=True) for r in _L.load_learnings()]
class LessonDumpTests(PersonalCase):
RETRO = ["--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim",
"--change", "write the failing test first and show it fail with `pytest -k new`"]
"""The learning store is learnings.jsonl, committed; git is the history. No sqlite mirror."""
RETRO = ["--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--impact", "correctness",
"--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`",
"--mechanism", "verification", "--expect", "new tests are seen failing first",
"--validate", "replay the new test at the parent commit"]
def test_dump_is_committed_sorted_and_the_database_is_not(self):
def test_learnings_are_committed_and_no_database_exists(self):
self.ok("retro", *self.RETRO)
self.assertEqual(self.git_log()[0], "lessons: retro recorded for lesson #1")
self.assertIn("learnings.jsonl", pdata.git("ls-files").stdout)
self.assertNotIn("retro.db", pdata.git("ls-files").stdout)
lines = open(os.path.join(self.data, "lessons.jsonl")).read().splitlines()
self.assertEqual(json.loads(lines[0])["t"], "lesson")
self.assertEqual(json.loads(lines[1])["t"], "occurrence")
n = len(self.git_log())
self.ok("lessons", "set", "1", "--status", "rejected")
self.assertEqual(len(self.git_log()), n + 1)
self.assertIn("lesson #1 set to rejected", self.git_log()[0])
self.assertEqual(json.loads(open(os.path.join(self.data, "lessons.jsonl")).readline())["status"], "rejected")
# recoverable from history alone
old = pdata.git("show", "HEAD~1:lessons.jsonl").stdout
self.assertEqual(json.loads(old.splitlines()[0])["status"], "open")
# export is stable
a = open(os.path.join(self.data, "lessons.jsonl")).read()
self.ok("lessons", "export")
self.assertEqual(open(os.path.join(self.data, "lessons.jsonl")).read(), a)
self.assertEqual(len(self.git_log()), n + 1)
self.assertFalse(os.path.exists(os.path.join(self.data, "retro.db")))
lines = open(os.path.join(self.data, "learnings.jsonl")).read().splitlines()
rec = json.loads(lines[0])
self.assertEqual(rec["status"], "proposed")
self.assertEqual(rec["validation"]["result"], "unvalidated")
def test_learn_and_note_are_personal_and_committed(self):
self.ok("learn", "--scope", "everywhere", "Always", "use", "options")
self.assertIn("learn: Always use options", self.git_log()[0])
self.assertIn("learn.jsonl", pdata.git("ls-files").stdout)
self.ok("learn", "--scope", "user", "Always use options when asking")
self.assertIn("learnings.jsonl", pdata.git("ls-files").stdout)
self.assertFalse(os.path.exists(os.path.join(self.state, "learn.jsonl")))
self.assertIn("oracle", self.ok("oracle").stdout.lower())
self.assertIn("Always use options when asking", self.ok("oracle").stdout)
class IsolationTests(PersonalCase):
@@ -742,7 +735,7 @@ class ProductIsReadOnlyTests(PersonalCase):
gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False})
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("status",),
("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"),
("learn", "--scope", "everywhere", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
("learn", "--scope", "user", "x"), ("lessons",), ("verifiers", "show", "shellcheck"),
("contract", "init", "--goal", "g"), ("verify",), ("update", "--post"),
("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)]
for c in cmds:
+21 -22
View File
@@ -6,7 +6,7 @@ phrases requests in different words from the lessons so only the when-terms can
"""
import json, os, statistics, time, unittest
from support import *
from sisi import retro
from sisi import learning as L
def fields(**kw):
@@ -22,13 +22,11 @@ def fields(**kw):
class PromptCase(SisiCase):
def mk(self, **kw):
con = retro.connect()
try:
lid = retro.new_lesson(con, fields(**kw), self.proj, None)
con.commit()
return lid
finally:
con.close()
f = fields(**kw)
rec = L.new_record(f["moment"], f["cause"], "correctness", "promote", self.proj, "u-test",
change=f["change"], mechanism="policy", scope="project",
expect="caught before delivery", validate="replay")
return rec["id"]
def prompt(self, payload, tool=None):
args = ["prompt"] + (["--tool", tool] if tool else [])
@@ -45,21 +43,17 @@ class PromptHookTests(PromptCase):
self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit")
self.assertIn("release", ctx)
self.assertIn("sisi done release", ctx)
self.assertIn("Check tag, version and changelog agree", ctx)
self.assertIn("sisi lessons show %d" % lid, ctx)
self.assertIn("check the tag, the manifest version and the changelog", ctx)
self.assertIn(lid, ctx)
from sisi import prompt as P
self.assertLessEqual(len(ctx), P.MAX_CHARS)
def test_listing_is_counted(self):
lid = self.mk()
def test_showing_is_not_recorded_as_evidence(self):
"""Being shown is not evidence: delivery writes nothing to the learning store."""
self.mk()
before = L.store_base()
self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
con = retro.connect()
try:
self.assertGreaterEqual(retro.listed_count(con, lid), 1)
places = [r[0] for r in con.execute("SELECT place FROM impressions WHERE lesson_id=?", (lid,))]
self.assertIn("prompt", places)
finally:
con.close()
self.assertEqual(L.store_base(), before)
def test_nothing_for_trivial_or_unmatched_messages(self):
self.mk()
@@ -122,14 +116,19 @@ class LabelledMatchingTests(PromptCase):
def ctx(self, text):
from sisi import prompt as P
return P.build_context(text, session="labelled")
old = os.getcwd()
os.chdir(self.proj) # delivery is scoped to the project the hook runs in
try:
return P.build_context(text, session="labelled")
finally:
os.chdir(old)
def test_labelled_set(self):
# A hit: the expected lesson's short line is injected. A false match: either lesson is
# injected for a request it does not apply to. (A recipe for the request's own kind of work
# is the feature working, not a false match, so it is measured separately below.)
release_short = "Check tag, version and changelog agree"
csv_short = "Use a quoting writer"
release_short = "check the tag, the manifest version and the changelog"
csv_short = "quoting writer so embedded newlines"
should = [
("cut a new release and tag it", release_short),
("publish the next version to the package index please", release_short),
-685
View File
@@ -1,685 +0,0 @@
import io, json, os, random, shutil, sqlite3, sys, time, unittest
from unittest import mock
from support import *
from sisi import cli, gate, retro, store
from test_verifiers import LibCase, vfile, dfile
GOOD = dict(aim="verified",
moment="I ran `cargo test` for 4 minutes before noticing that the fuzz verifier for parser work was never chosen",
cause="the parser-or-codec recipe does not list the fuzz verifier under Checks",
change_kind="recipe",
change="Add the fuzz verifier to the Checks of the parser-or-codec recipe so parser work picks it by default",
when="parser, fuzzing, codec, hostile input, generated input, parsing",
scope="everywhere", target="parser-or-codec", pattern="Reach for the familiar tool instead of the check that fits the claim")
def argv(f):
out = []
for k, v in f.items():
if k == "new":
out.append("--new")
else:
out += ["--" + k.replace("_", "-"), v]
return out
class RetroCase(LibCase):
def setUp(self):
super().setUp()
os.environ["SISI_RETRO_REQUIRED"] = "1"
self.put("prove/fuzz.md", vfile("fuzz"))
self.put("parser-or-codec.md", dfile("parser-or-codec"), self.ddir)
self.notes = os.path.join(self.data, "notes")
def retro(self, f=None, env=None, **kw):
return self.sisi("retro", *argv(dict(GOOD, **(f or {}), **kw)), env=env)
def lessons(self):
con = retro.connect()
try:
return [dict(r) for r in con.execute("SELECT * FROM lessons ORDER BY id")]
finally:
con.close()
def occurrences(self):
con = retro.connect()
try:
return con.execute("SELECT count(*) FROM occurrences").fetchone()[0]
finally:
con.close()
class RefusalTests(RetroCase):
def test_good_answer_accepted(self):
r = self.retro()
self.assertEqual(r.returncode, 0, r.stdout)
l = self.lessons()
# a recipe lesson with a valid target takes effect at once, on its first occurrence
self.assertEqual((len(l), l[0]["count"], l[0]["status"], l[0]["aim"]), (1, 1, "applied", "verified"))
self.assertEqual(self.occurrences(), 1)
def test_each_refusal(self):
# Structural checks only: presence, length, enums, moment-is-not-change, exact empty answers.
bad = {
"missing aim": {"aim": ""}, "missing moment": {"moment": ""}, "missing cause": {"cause": " "},
"missing change": {"change": ""}, "bad aim": {"aim": "vibes"}, "bad kind": {"change_kind": "magic"},
"nothing change": {"change": "None"}, "na cause": {"cause": "n/a"},
"nothing moment exact": {"moment": "nothing"},
"be more careful exact": {"change": "be more careful"},
"short moment": {"moment": "it was slow"}, "short change": {"change": "fix the rule"},
"short cause": {"cause": "bad"},
"same text": {"moment": GOOD["change"], "change": GOOD["change"]},
}
for name, over in bad.items():
with self.subTest(name):
r = self.retro(over)
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("refused", r.stdout)
self.assertIn("(check:", r.stdout) # every refusal names the check that failed
self.assertEqual(self.lessons(), [])
self.assertEqual(self.occurrences(), 0)
VALID = [
("Dates in the report were one day early for users in Sydney",
"the code formatted UTC timestamps without the user's time zone",
"For anything that shows or compares dates, test with a time zone ahead of and behind UTC and across a daylight saving change"),
("Everything looked fine on my machine and then failed for everyone in the beta",
"my local data was a week old and far too small",
"Anything that reads user data should always be checked against a large recent copy before shipping"),
("Nothing could be imported after the upgrade and nobody noticed for a day",
"the importer swallowed every error and reported success",
"An import should never report success when everything was skipped; zero imported is a failure"),
("The button did nothing at all when pressed quickly twice in a row",
"the handler always waited for the first request to finish",
"Buttons that start work should disable themselves until the work settles, always"),
("It was never clear which of the three copies was the newest one",
"each tool kept its own copy and none said which was live",
"Anything installed in two places should print which copy is running and how old it is"),
("Everything was rebuilt from scratch even for a one-word edit",
"the build never reused anything between runs at all",
"A build should always say what it reused and what it redid, so waste is visible"),
("The search found nothing for a perfectly ordinary plural word",
"matching compared whole words only, with no stemming at all",
"Search over user text should stem words so plurals and verb forms meet"),
("Users in Auckland saw tomorrow's date on everything after midnight",
"dates were formatted in the server zone, never the viewer's",
"For anything dated, format in the viewer's zone and test both sides of UTC"),
("The whole page went blank whenever one record had no title",
"rendering assumed every field is always present on every record",
"Rendering should survive any single record missing any optional field"),
("Nobody could tell whether the job had finished or was still running",
"long work reported nothing between starting and ending",
"Anything that takes more than a few seconds should say what stage it is at"),
("The same invoice was sent twice to the same customer in one morning",
"a retry after a timeout could not tell the first send had landed",
"Anything sent to a customer should carry an id that makes a retry harmless"),
("Accented names vanished from the list after the upgrade finished",
"the new code compared names byte for byte across normalisation forms",
"Names should be normalised the same way on write and on every later read"),
("The report said twenty thousand users when nothing had been measured",
"a file count was presented as a session count without checking",
"Any number a decision depends on should come from measuring the thing it names"),
("Saving appeared to work while nothing was actually written anywhere",
"the write error was logged once and the indicator stayed green",
"A failed save should be visible where the save was asked for, never only in a log"),
("The oldest message in the inbox was never shown to anyone at all",
"paging always sorted newest first and the tail fell off the page",
"Any list that pages should be checked for items that can never be reached"),
("Everything slowed down only when the office came online at nine",
"every client retried at the same second after any failure",
"Retries should always spread out with jitter so clients never stampede together"),
("A file that should never change was quietly rewritten by the installer",
"the install step wrote everywhere instead of only where asked",
"Installers should write nothing outside the places the user was told about"),
("The totals never matched the spreadsheet by exactly one cent",
"money travelled as floats and rounded differently in two places",
"Money should be integer minor units from end to end, always, no exceptions"),
("Nobody could open the attachment because its name had spaces in it",
"the download path was built by joining text with no escaping anywhere",
"Anything that turns a name into a path should be tested with spaces and accents"),
("The night run silently did nothing because the clock had moved",
"a fixed local time never occurred on the spring-forward night",
"Scheduled work should say what happens when its local time never occurs"),
("Search results showed records the signed-in person should never see",
"the filter ran after results were already assembled for display",
"Visibility should be decided before anything user-shaped is assembled for output"),
("The copy on the laptop and the copy at work disagreed about everything",
"sync copied files both ways with nothing recording which won",
"Sync should record, for every conflict, which side won and why it won"),
("It always picked the first answer even when the first was clearly stale",
"ranking never considered how old a result was at selection time",
"Anything cached should carry its age and prefer a fresh answer over a stale one"),
("Nothing was logged when the payment provider answered with an error",
"the error path returned early without touching the log at all",
"Every early return on an error path should leave exactly one log line behind"),
("The whole import stopped on one row that nobody could identify later",
"rows were counted from one in the file and from zero in the message",
"Errors about a row should name it the way the person holding the file counts it"),
("Settings changed on one machine never appeared on the other machine",
"settings were read once at startup and never watched afterwards",
"Anything read at startup that users can edit should say when a restart is needed"),
("The preview and the printed page never agreed about the typeface",
"the preview used a font the printer substituted without telling anyone",
"Anything printable should be checked in the form it is finally printed in"),
("Undo brought back a version nobody recognised from any point in time",
"undo restored whole files while other work had landed in between",
"Undo should reverse one change exactly and refuse when later work touches it"),
("The helper kept asking questions that the request had already answered",
"it never read the answers already recorded earlier in the session",
"Before asking anything, an agent should check what was already settled and say so"),
("Everything passed locally and the first real user hit a crash at once",
"tests only ever used the small tidy examples written by hand",
"Anything parsing outside files should be tested on generated hostile examples"),
]
def test_valid_lessons_in_varied_wording_are_all_accepted(self):
self.assertGreaterEqual(len(self.VALID), 30)
for moment, cause, change in self.VALID:
f = dict(GOOD, moment=moment, cause=cause, change=change)
self.assertEqual(retro.validate(f), [], moment)
# and through the real command, Sydney included (no digit, no path, no ALLCAPS in the moment)
m, c, ch = self.VALID[0]
r = self.retro({"moment": m, "cause": c, "change": ch})
self.assertEqual(r.returncode, 0, r.stdout)
EMPTY = [
{"moment": "nothing"}, {"moment": "None."}, {"cause": "n/a"}, {"cause": "nothing"},
{"change": "be more careful"}, {"change": "test more"}, {"change": "none"},
{"moment": "ok"}, {"cause": "all good"}, {"change": "short"}, {"moment": "it went well"},
{"cause": "fine"}, {"change": "no"},
]
def test_empty_answers_are_refused_with_the_check_named(self):
self.assertGreaterEqual(len(self.EMPTY), 12)
for over in self.EMPTY:
with self.subTest(over):
errs = retro.validate(dict(GOOD, **over))
self.assertTrue(errs)
self.assertTrue(any("(check:" in e for e in errs), errs)
r = self.retro({"change": "be more careful"})
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn('change is an empty answer: "be more careful"', r.stdout)
def test_missing_message_names_the_field(self):
r = self.sisi("retro", "--aim", "speed")
self.assertEqual(r.returncode, 2)
for w in ("moment", "cause", "change-kind", "change", "--when"):
self.assertIn(w, r.stdout)
self.assertIn("at least 5 terms", r.stdout)
def test_when_is_required_with_five_terms_for_new_lessons(self):
no_when = dict(GOOD); no_when.pop("when")
r = self.sisi("retro", *argv(no_when))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("--when needs at least 5 terms", r.stdout)
self.assertIn("delimited file", r.stdout) # the worked example in the refusal
few = self.retro({"when": "parser, fuzzing"})
self.assertEqual(few.returncode, 2, few.stdout)
self.assertIn("--when has 2 term(s)", few.stdout)
self.assertEqual(self.lessons(), [])
self.assertEqual(self.retro().returncode, 0) # five-plus terms: accepted and stored
self.assertIn("fuzzing", self.lessons()[0]["when_terms"])
same = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran for 5 minutes with no fuzz verifier chosen")
self.assertEqual(same.returncode, 0, same.stdout) # --same-as needs no --when
def test_json_on_stdin(self):
r = self.sisi("retro", "--json", "-", stdin=json.dumps({k.replace("_", "-"): v for k, v in GOOD.items()}))
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(len(self.lessons()), 1)
self.assertEqual(self.sisi("retro", "--json", "-", stdin="not json").returncode, 2)
self.assertEqual(self.sisi("retro", "--json", "-", stdin=json.dumps({"aim": "speed"})).returncode, 2)
def test_property_refused_answers_are_never_stored(self):
# Only structural failures belong here now: exact empty answers, too-short text, bad enums.
generic = ["nothing", "n/a", "none", "it went well", "be more careful", "test more", "short", "", " ", "ok"]
for seed in [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
rng = random.Random(seed)
for _ in range(8 * ITERS):
f = dict(GOOD)
for k in rng.sample(["aim", "moment", "cause", "change_kind", "change"], rng.randint(1, 3)):
f[k] = rng.choice(generic)
with self.subTest(seed=seed, f=f):
argv_ = []
for k, v in f.items():
argv_ += ["--" + k.replace("_", "-"), v]
self.assertEqual(retro.validate({k: v for k, v in f.items()}) != [], True)
r = self.sisi("retro", *argv_)
self.assertEqual(r.returncode, 2, r.stdout)
self.assertEqual(self.lessons(), [])
self.assertEqual(self.occurrences(), 0)
class SimilarityAndSameAsTests(RetroCase):
def test_similar_lessons_listed_exit_4_then_new_or_same_as(self):
self.retro()
near = dict(moment="I again ran `cargo test` for 6 minutes before noticing that the fuzz verifier for parser work was never chosen",
change="Add the fuzz verifier to the parser-or-codec recipe Checks so parser work picks it")
r = self.retro(near)
self.assertEqual(r.returncode, 4)
self.assertIn("#1", r.stdout)
self.assertIn("seen 1", r.stdout)
self.assertIn("--same-as", r.stdout)
self.assertEqual(len(self.lessons()), 1) # nothing stored
self.assertEqual(self.retro(near, new=True).returncode, 0)
self.assertEqual(len(self.lessons()), 2)
def test_dissimilar_lesson_accepted_directly(self):
self.retro()
other = dict(aim="speed", change_kind="tool", target="", scope="everywhere",
pattern="Reach for the familiar tool instead of the check that fits the claim",
moment="the screenshot comparison in `web-ui` waited 90 seconds on a dev server that never started",
cause="no readiness probe before the browser step",
when="browser, screenshot, dev server, port waiting, ui checks, startup",
change="Make sisi verify wait for the declared port instead of sleeping a fixed time")
other.pop("target")
self.assertEqual(self.sisi("retro", *argv(other)).returncode, 0)
self.assertEqual(len(self.lessons()), 2)
def test_same_as_adds_one_occurrence_to_exactly_one_lesson(self):
self.retro()
for i in range(3):
self.retro(aim="speed", change_kind="tool", moment="distinct %d: `make build` took 9 minutes in lib%d/src" % (i, i),
cause="a cold cache every time on this machine", change="Cache the build artefacts between %d runs in the gate config" % (1000 + i * 7919),
target="", new=True) if False else None
self.assertEqual(len(self.lessons()), 1)
r = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran for 5 minutes with no fuzz verifier chosen")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("seen 2", r.stdout)
l = self.lessons()
self.assertEqual((len(l), l[0]["count"]), (1, 2))
self.assertEqual(self.occurrences(), 2)
def test_same_as_needs_a_real_moment_and_an_existing_id(self):
self.retro()
self.assertEqual(self.sisi("retro", "--same-as", "1", "--moment", "nothing").returncode, 2)
self.assertEqual(self.sisi("retro", "--same-as", "1").returncode, 2)
self.assertEqual(self.sisi("retro", "--same-as", "99", "--moment", "again `cargo test` ran for 5 minutes, no fuzz").returncode, 2)
self.assertEqual(self.lessons()[0]["count"], 1)
def test_property_same_as_increments_exactly_one(self):
ids = []
for i in range(4):
r = self.retro(aim=["speed", "level", "intent", "hands-off"][i], change_kind="tool", target=None,
moment="unique%dx: `cmd%d --flag` hung for %d minutes at step number %d" % (i, i, 7 + i, i),
cause="reason %d: widget%d misconfigured" % (i, i),
change="Teach tool%d to %s%d automatically" % (i, ["zip", "yank", "frob", "quux"][i], i)) if False else None
con = retro.connect()
lid = retro.new_lesson(con, dict(GOOD, aim="speed", change_kind="tool", target=None,
moment="m%d: command%d failed %d times" % (i, i, i),
cause="cause%d" % i, change="change%d" % i), self.proj, None)
con.commit()
con.close()
ids.append(lid)
counts = {i: 1 for i in ids}
for seed in [0, 1, random.randrange(2 ** 32)]:
rng = random.Random(seed)
for _ in range(5 * ITERS):
lid = rng.choice(ids)
r = self.sisi("retro", "--same-as", str(lid), "--moment", "again `cmd%d` failed in run number %d of the gate suite" % (lid, rng.randrange(1000)))
self.assertEqual(r.returncode, 0, r.stdout)
counts[lid] += 1
self.assertEqual({l["id"]: l["count"] for l in self.lessons()}, counts)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM occurrences").fetchone()[0], sum(counts.values()))
con.close()
class AutoApplyAndLessonsTests(RetroCase):
def occ(self, sid, lid=None):
env = {"SISI_SESSION_ID": sid}
if lid is None:
return self.retro(env=env)
return self.sisi("retro", "--same-as", str(lid), "--moment", "again `cargo test` ran 5 min, no fuzz verifier chosen (%s)" % sid, env=env)
def test_second_occurrence_from_second_session_applies_to_notes(self):
# The learning loop changed this: the field note is written on the FIRST occurrence,
# and later occurrences never duplicate the bullet.
r = self.occ("s1")
self.assertEqual(r.returncode, 0)
self.assertIn("applied", r.stdout)
self.assertTrue(os.path.exists(os.path.join(self.notes, "parser-or-codec.md")))
self.assertEqual(self.lessons()[0]["status"], "applied")
r = self.occ("s2", 1)
self.assertEqual(r.returncode, 0, r.stdout)
text = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Add the fuzz verifier", text)
self.assertEqual(text.count("Add the fuzz verifier"), 1)
self.assertEqual(self.lessons()[0]["status"], "applied")
# the entry itself is untouched, and show/done print the notes under a heading
self.assertNotIn("Field notes", open(os.path.join(self.ddir, "parser-or-codec.md")).read())
out = self.sisi("done", "parser-or-codec").stdout
self.assertIn("Field notes from earlier agents", out)
self.assertIn("Add the fuzz verifier", out)
def test_verifier_notes_in_show_and_other_kinds_never_auto_apply(self):
f = dict(GOOD, change_kind="verifier", target="fuzz")
self.sisi("retro", *argv(f), env={"SISI_SESSION_ID": "a"})
self.sisi("retro", "--same-as", "1", "--moment", "again `fuzz` was skipped in run 2", env={"SISI_SESSION_ID": "b"})
self.assertIn("Field notes from earlier agents", self.sisi("verifiers", "show", "fuzz").stdout)
for kind in ("rule", "oracle", "tool", "brief"):
with self.subTest(kind):
con = retro.connect()
lid = retro.new_lesson(con, dict(GOOD, change_kind=kind, target="fuzz", moment="m %s" % kind, cause="c", change="x %s" % kind), self.proj, None)
for s in ("p", "q", "r"):
os.environ["SISI_SESSION_ID"] = s
retro.add_occurrence(con, lid, "again", self.proj, None)
self.assertFalse(retro.maybe_auto_apply(con, lid))
os.environ.pop("SISI_SESSION_ID")
con.commit()
self.assertEqual(con.execute("SELECT status FROM lessons WHERE id=?", (lid,)).fetchone()[0], "open")
con.close()
self.assertFalse(os.path.exists(os.path.join(self.notes, "x rule.md")))
def test_invalid_target_is_never_applied_and_manual_apply_rules(self):
con = retro.connect()
a = retro.new_lesson(con, dict(GOOD, target="no-such-recipe"), self.proj, None)
b = retro.new_lesson(con, dict(GOOD, change_kind="rule", target=None, moment="m rule", change="rule change text"), self.proj, None)
c = retro.new_lesson(con, dict(GOOD, moment="m ok `x` 1", change="ok change for the recipe notes"), self.proj, None)
con.commit(); con.close()
self.assertEqual(self.sisi("lessons", "apply", str(a)).returncode, 1)
self.assertEqual(self.sisi("lessons", "apply", str(b)).returncode, 1)
self.assertEqual(self.sisi("lessons", "apply", str(c)).returncode, 0)
self.assertEqual(self.sisi("lessons", "apply", str(c)).stdout.strip(), "already applied")
self.assertEqual(open(os.path.join(self.notes, "parser-or-codec.md")).read().count("ok change"), 1)
def test_lessons_listing_filters_order_show_set(self):
con = retro.connect()
mk = lambda n, **k: retro.new_lesson(con, dict(GOOD, moment="m%d `x`" % n, cause="c", change="change number %d" % n, **k), self.proj, None)
l1 = mk(1, target=None, aim="speed", change_kind="tool") if False else None
ids = []
for n, (aim, kind) in enumerate([("speed", "tool"), ("intent", "rule"), ("speed", "rule")]):
g = dict(GOOD, aim=aim, change_kind=kind, target=None, moment="m%d `x`" % n, cause="c", change="change number %d" % n)
ids.append(retro.new_lesson(con, g, self.proj, None))
retro.add_occurrence(con, ids[1], "again", self.proj, None)
retro.add_occurrence(con, ids[1], "again", self.proj, None)
con.commit(); con.close()
out = self.sisi("lessons").stdout.splitlines()
self.assertTrue(out[0].startswith("#%-4d" % ids[1])) # highest count first
self.assertEqual(len(self.sisi("lessons", "--aim", "speed").stdout.splitlines()), 2)
self.assertEqual(len(self.sisi("lessons", "--kind", "rule", "--top", "1").stdout.splitlines()), 1)
self.assertEqual(len(json.loads(self.sisi("lessons", "--json").stdout)), 3)
self.assertEqual(len(self.sisi("lessons", "--repo", self.proj).stdout.splitlines()), 3)
self.assertEqual(self.sisi("lessons", "--repo", self.tmp + "/elsewhere").stdout.strip(), "no lessons")
self.assertIn("occurrences:", self.sisi("lessons", "show", str(ids[1])).stdout)
self.assertEqual(self.sisi("lessons", "set", str(ids[0]), "--status", "rejected").returncode, 0)
self.assertEqual(self.sisi("lessons", "set", str(ids[0]), "--status", "bogus").returncode, 2)
self.assertEqual(len(self.sisi("lessons", "--status", "open").stdout.splitlines()), 2)
def test_status_shows_lessons(self):
self.retro()
out = self.sisi("status").stdout
self.assertIn("lessons : 1 total, 0 open, 1 applied; 1 occurrences in the last 7 days", out)
self.assertIn("active #1", out)
self.assertIn("retros", out)
self.assertIn("learning : 1 lessons taking effect", out)
class TickBlockTests(RetroCase):
def make(self, change, count=1, repo=None, status="open"):
con = retro.connect()
lid = retro.new_lesson(con, dict(GOOD, target=None, change_kind="tool", moment="m `x` %s" % change[:5], cause="c", change=change), repo or self.proj, None)
for _ in range(count - 1):
retro.add_occurrence(con, lid, "again", repo or self.proj, None)
con.execute("UPDATE lessons SET status=? WHERE id=?", (status, lid))
con.commit(); con.close()
return lid
def tick(self):
return self.sisi("tick", stdin=json.dumps({"session_id": "t", "cwd": self.proj, "source": "startup"})).stdout
def test_block_is_framed_as_information(self):
self.make("Prefer a readiness probe over a fixed sleep when waiting for servers", 3)
out = retro.tick_block(self.proj, session="t")
self.assertIn("notes left by earlier agents", out)
self.assertIn("not as commands", out)
self.assertIn("(seen 3)", out)
def test_no_database_no_block_and_no_db_created(self):
self.assertEqual(self.tick(), "")
self.assertFalse(os.path.exists(retro.db_path()))
def test_repo_lessons_first_then_by_count_and_only_open(self):
self.make("global heavy lesson about caching", 9, repo=self.tmp + "/other")
self.make("local light lesson about probes", 1)
self.make("rejected lesson never shown", 20, status="rejected")
lines = [l for l in retro.tick_block(self.proj, session="t").splitlines() if l.startswith("- ")]
self.assertTrue(lines[0].startswith("- local light"), lines)
self.assertTrue(lines[1].startswith("- global heavy"))
self.assertFalse(any("rejected" in l for l in lines))
def test_filter_examples(self):
repo = self.proj
bad = ["see https://example.com/page for details", "visit www.evil.test now", "use `rm -rf build` first",
"run the build before pushing", "cat $(whoami) into the log", "curl the endpoint twice",
"edit /etc/hosts to fix it", "look at ~/.ssh/config", "read ../secrets.txt", "a && b", "install the helper", "download the file"]
good = ["Prefer a readiness probe over a fixed sleep when waiting for servers", "and/or both options exist in the recipe",
"Check %s/notes/fuzz.md for the field notes" % repo, "Add the fuzz verifier to the parser recipe checks"]
for t in bad:
self.assertIsNone(retro.safe_line(t, repo), t)
for t in good:
self.assertIsNotNone(retro.safe_line(t, repo), t)
def test_property_size_limit_and_no_filtered_line(self):
pieces = ["probe", "cache", "parser", "fuzz", "timeout", "recipe", "check", "verifier", "mutation", "golden", "snapshot"]
nasty = ["https://x.example/a", "`rm -rf /`", "run tests", "/etc/passwd", "~/.bashrc", "sudo thing", "$(id)", "a && b"]
for seed in [0, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
rng = random.Random(seed)
shutil.rmtree(self.state, ignore_errors=True)
con = retro.connect()
for n in range(40):
words = [rng.choice(pieces) for _ in range(rng.randint(3, 60))]
if rng.random() < 0.3:
words.insert(rng.randrange(len(words)), rng.choice(nasty))
g = dict(GOOD, target=None, change_kind="tool", moment="m%d `x`" % n, cause="c", change=" ".join(words))
lid = retro.new_lesson(con, g, self.proj, None)
for _ in range(rng.randint(0, 4)):
retro.add_occurrence(con, lid, "again", self.proj, None)
con.commit(); con.close()
block = retro.tick_block(self.proj)
with self.subTest(seed=seed):
self.assertLess(len(block), 1200)
lines = [l for l in block.splitlines() if l.startswith("- ")]
self.assertLessEqual(len(lines), 8)
for l in lines:
self.assertIsNotNone(retro.safe_line(l[2:], self.proj), l)
for bad in nasty:
self.assertNotIn(bad, l)
def test_tick_with_many_lessons_stays_fast(self):
con = retro.connect()
for i in range(150):
lid = retro.new_lesson(con, dict(GOOD, target=None, change_kind="tool", moment="m `x` %d" % i, cause="c",
change="lesson number %d about caching and probes" % i), self.proj, None)
for _ in range(i % 3):
retro.add_occurrence(con, lid, "again", self.proj, None)
con.commit(); con.close()
self.tick()
best = 9
for _ in range(5):
t = time.perf_counter()
self.tick()
best = min(best, time.perf_counter() - t)
__import__('support').skip_timing_if_busy(self)
self.assertLess(best, 0.2)
def test_env_file_export_when_claude_provides_one(self):
envf = os.path.join(self.tmp, "envfile")
self.sisi("tick", stdin=json.dumps({"session_id": "abc 1", "cwd": self.proj, "source": "startup"}), env={"CLAUDE_ENV_FILE": envf})
self.assertIn("export SISI_SESSION_ID='abc 1'", open(envf).read())
class GateRetroTests(RetroCase):
sid = "gr"
def setUp(self):
super().setUp()
self.git_init()
self.write_contract(contract([check("ok", "true")]))
self.tick()
def tick(self):
self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"}))
def gate(self, sid=None):
return gate.decide({"session_id": sid or self.sid, "cwd": self.proj})
def work(self, text="x"):
with open(os.path.join(self.proj, "work.txt"), "a") as f:
f.write(text + "\n")
def do_retro(self, n=0):
r = self.sisi("retro", *argv(dict(GOOD, moment="`cargo test` run %d took 4 minutes before the fuzz verifier showed up" % n,
change="Add the fuzz verifier to the parser-or-codec recipe Checks, variant %d" % n, new=True)))
self.assertEqual(r.returncode, 0, r.stdout)
def test_question_only_turn_is_never_asked(self):
self.assertEqual(self.gate(), ("allow", None))
self.assertEqual(self.gate(), ("allow", None))
def test_real_work_needs_a_retro_for_this_tree_state(self):
self.work()
a, msg = self.gate()
self.assertEqual(a, "block")
self.assertIn("sisi retro --scope", msg)
self.assertIn("--change-kind", msg)
self.assertIn("how, not whether", msg)
self.do_retro()
self.assertEqual(self.gate()[0], "allow")
self.assertEqual(self.gate()[0], "allow") # unchanged since: not asked again
self.work("more") # the tree changed after the retro
self.assertEqual(self.gate()[0], "block")
def test_same_as_also_satisfies(self):
self.do_retro()
self.work()
self.assertEqual(self.gate()[0], "block")
self.assertEqual(self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran 5 min with no fuzz verifier").returncode, 0)
self.assertEqual(self.gate()[0], "allow")
def test_three_strike_release_and_switch(self):
self.work()
self.assertEqual([self.gate()[0] for _ in range(3)], ["block"] * 3)
a, msg = self.gate()
self.assertEqual(a, "allow")
self.assertIn("retrospective", msg)
self.assertNotIn("unverified", [r["status"] for r in self.results()]) # a missing retro is not an unverified result
os.environ["SISI_RETRO_REQUIRED"] = "0"
self.work("again")
self.assertEqual(self.gate("other")[0], "allow")
def test_waiver_counts_as_real_work(self):
shutil.rmtree(os.path.join(self.proj, ".sisi"))
self.tick()
self.work()
self.assertEqual(self.gate()[0], "allow") # small change, no waiver: not real work
self.sisi("contract", "waive", "typo")
self.work("typo fix")
self.assertEqual(self.gate()[0], "block")
self.do_retro()
self.assertEqual(self.gate()[0], "allow")
def test_hook_output_is_a_block_for_claude(self):
self.work()
r = self.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj}))
d = json.loads(r.stdout)
self.assertEqual(d["decision"], "block")
self.assertIn("sisi retro", d["reason"])
def test_property_no_pass_after_real_work_without_a_retro(self):
for seed in [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
rng = random.Random(seed)
for n in range(4 * ITERS):
sid = "pr-%d-%d" % (seed, n)
self.tick_for(sid)
did_work = rng.random() < 0.7
recorded = rng.random() < 0.5
if did_work:
self.work("%d-%d" % (seed, n))
if did_work and recorded:
self.do_retro(seed % 1000 * 100 + n)
with self.subTest(seed=seed, n=n, work=did_work, retro=recorded):
if not did_work:
self.assertEqual(self.gate(sid)[0], "allow") # nothing changed: never asked
elif recorded:
self.assertEqual(self.gate(sid)[0], "allow")
else:
self.assertEqual([self.gate(sid)[0] for _ in range(3)], ["block"] * 3) # never passes early
self.assertEqual(self.gate(sid)[0], "allow") # only the 3-strike release
def tick_for(self, sid):
self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj, "source": "startup"}))
class SubagentTests(RetroCase):
def transcript(self, edits=True, start="2020-01-01T00:00:00.000Z", name="agent-a1.jsonl"):
p = os.path.join(self.tmp, name)
rows = [{"timestamp": start, "message": {"role": "user", "content": "do it"}}]
content = [{"type": "tool_use", "name": "Edit" if edits else "Read", "input": {}}]
rows.append({"timestamp": start, "message": {"role": "assistant", "content": content}})
with open(p, "w") as f:
f.write("\n".join(json.dumps(r) for r in rows) + "\n")
return p
def hook(self, **kw):
payload = dict({"session_id": "s", "cwd": self.proj, "hook_event_name": "SubagentStop", "agent_id": "a1",
"agent_type": "general-purpose", "stop_hook_active": False}, **kw)
return self.sisi("gate", "--subagent", stdin=json.dumps(payload))
def test_subagent_that_edited_files_must_retro(self):
r = self.hook(agent_transcript_path=self.transcript())
d = json.loads(r.stdout)
self.assertEqual(d["decision"], "block")
self.assertIn("sisi retro", d["reason"])
self.assertEqual(self.retro().returncode, 0)
self.assertEqual(self.hook(agent_transcript_path=self.transcript()).stdout, "")
def test_retro_older_than_the_subagent_does_not_count(self):
self.retro()
r = self.hook(agent_transcript_path=self.transcript(start="2999-01-01T00:00:00.000Z"))
self.assertEqual(json.loads(r.stdout)["decision"], "block")
def test_read_only_or_undeterminable_subagents_are_never_blocked(self):
self.assertEqual(self.hook(agent_transcript_path=self.transcript(edits=False)).stdout, "")
self.assertEqual(self.hook().stdout, "") # no transcript path in the input
self.assertEqual(self.hook(agent_transcript_path=self.tmp + "/missing.jsonl").stdout, "") # fail open
p = os.path.join(self.tmp, "garbage.jsonl")
open(p, "w").write("not json\n{{{")
self.assertEqual(self.hook(agent_transcript_path=p).stdout, "")
def test_three_strikes_per_agent_and_switch_and_no_contract_checks(self):
self.write_contract(contract([check("bad", "false")])) # the contract is irrelevant for subagents
t = self.transcript()
acts = [self.hook(agent_transcript_path=t).stdout != "" for _ in range(4)]
self.assertEqual(acts, [True, True, True, False])
self.assertTrue(self.hook(agent_transcript_path=t, agent_id="other").stdout != "") # separate counter
os.environ["SISI_RETRO_REQUIRED"] = "0"
self.assertEqual(self.hook(agent_transcript_path=t, agent_id="third").stdout, "")
class CliHookTests(SisiCase):
def test_learn_cli_commands_are_reachable(self):
r = self.sisi("scoreboard", "--json")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("harvest", self.sisi("harvest", "--help").stdout)
self.assertEqual(self.sisi("nonsense").returncode, 64)
def test_broken_or_absent_learn_cli_does_not_break_the_cli(self):
broken = mock.MagicMock()
broken.register.side_effect = TypeError("boom")
import sisi
with mock.patch.dict(sys.modules, {"sisi.learn_cli": broken}), mock.patch.object(sisi, "learn_cli", broken, create=True):
self.assertEqual(cli._learn_cli("harvest", []), 70)
with mock.patch.dict(sys.modules, {"sisi.learn_cli": None}), mock.patch.object(sisi, "learn_cli", None, create=True):
self.assertEqual(cli._learn_cli("harvest", []), 70) # import of the module fails
self.assertEqual(self.sisi("help").returncode, 0)
def test_help_points_to_retro(self):
out = self.sisi("help").stdout
self.assertIn("sisi retro", out)
for retired in ("note", "propose"):
self.assertNotIn("sisi " + retired + " ", out)
self.assertEqual(self.sisi(retired, "still works").returncode, 64)
if __name__ == "__main__":
unittest.main()
-20
View File
@@ -45,26 +45,6 @@ class RuleDetailTests(SisiCase):
self.assertEqual(self.sisi("rule", "no-such-rule").returncode, 1)
self.assertEqual(self.sisi("rule", "99").returncode, 1)
def test_folded_lessons_are_shown_with_show_command(self):
con = retro.connect()
try:
lid = retro.new_lesson(con, dict(
aim="hands-off", change_kind="rule", target=None,
moment="the agent buried a naming question at the end of a long report",
cause="asking in prose felt quicker than opening the dialog",
change="Ask naming questions through the dialog with options",
when="naming, question, dialog, options, ask the human, choice",
short="Ask through the dialog, with options."), self.proj, None)
con.execute("UPDATE lessons SET folded_into='decide-dont-ask', count=3 WHERE id=?", (lid,))
con.commit()
finally:
con.close()
r = self.sisi("rule", "decide-dont-ask")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("Ask through the dialog, with options.", r.stdout)
self.assertIn("sisi lessons show %d" % lid, r.stdout)
self.assertIn("buried a naming question", r.stdout) # the moment, as the example
def test_overlay_replacement_is_named_as_overlay(self):
d = os.path.join(self.data, "overlay", "rules")
os.makedirs(d, exist_ok=True)
-279
View File
@@ -1,279 +0,0 @@
import json, os, subprocess, unittest
from support import *
from sisi import retro, scope, store
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
def retro_args(**kw):
f = dict(aim="verified", moment="the export broke in the acme-widgets repo when a field held a newline",
cause="rows were joined by hand in acme-widgets instead of with a quoting writer",
change_kind="rule",
change="Write delimited files with a quoting writer so embedded newlines survive",
when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files",
pattern="Build the obvious thing instead of using what the environment already provides")
f.update(kw)
out = []
for k, v in f.items():
out += ["--" + k.replace("_", "-"), v]
return out
# (text, kind, expected) expected True = universal passes, False = refused as naming this project
LABELLED = [
("Write delimited files with a quoting writer so embedded newlines survive", "rule", True),
("Check the README and CHANGELOG agree with the version before publishing", "rule", True),
("Update the changelog when behaviour changes and keep the readme example runnable", "rule", True),
("Run the whole test suite before saying work is done", "rule", True),
("Prefer a readiness probe over a fixed sleep when waiting for servers", "rule", True),
("Write the failing test first and watch it fail before fixing code", "rule", True),
("Keep functions small enough to test without a display or network", "rule", True),
("Never report success when every input record was skipped silently", "rule", True),
("Compare totals before and after any data migration with an independent count", "rule", True),
("Make error messages name the field that failed and what would be valid", "rule", True),
("In the acme-widgets project always quote fields by hand in the exporter", "rule", False),
("The acme-widgets exporter must join rows with its own quoting code", "rule", False),
("Fix export in widget_export.py by using a quoting writer there", "rule", False),
("Change src/widget_export.py to use a quoting writer for every row", "rule", False),
("See https://github.com/acme/acme-widgets for how exports should work here", "rule", False),
("In acme-widgets, release notes live in the changelog of that repository only", "rule", False),
("sisi should refuse lessons that name the project they came from", "tool", True),
("sisi must show the backlog separately from loose lesson headings", "tool", True),
("Agents should record a retro at the end of every piece of work", "rule", True),
("A parser should reject overlong input instead of allocating without bound", "rule", True),
("Use the acme-widgets keyboard layout with control on the left in every project", "rule", False),
("Keep the widget test fixture frozen at the acme-widgets sample rows", "rule", False),
("Always run tests with the licence and security notes updated for releases", "rule", True),
("Document every public function with its errors and limits in the readme", "rule", True),
]
class ScopeCase(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
subprocess.run(["git", "remote", "add", "origin", "https://github.com/acme/acme-widgets.git"], cwd=self.proj, check=True)
with open(os.path.join(self.proj, "widget_export.py"), "w") as f:
f.write("x=1\n")
os.makedirs(os.path.join(self.proj, "src"))
with open(os.path.join(self.proj, "src", "widget_export.py"), "w") as f:
f.write("x=1\n")
class ProjectIdTests(ScopeCase):
def test_remote_id_stable_across_clone_and_rename(self):
self.assertEqual(scope.project_id(self.proj), scope.normalized_remote("git" + chr(64) + "github.com:acme/acme-widgets.git"))
other = os.path.join(self.tmp, "renamed")
subprocess.run(["git", "clone", "-q", self.proj, other], check=True)
# clone from local path has local remote; set same remote
subprocess.run(["git", "remote", "set-url", "origin", "git" + chr(64) + "github.com:acme/acme-widgets"], cwd=other, check=True)
self.assertEqual(scope.project_id(other), scope.project_id(self.proj))
def test_path_fallback_without_remote(self):
d = os.path.join(self.tmp, "plainproj"); os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
self.assertEqual(scope.project_id(d), os.path.realpath(d))
class LabelledUniversalTests(ScopeCase):
def test_labelled_set(self):
hits = false_refusals = 0
for text, kind, want_pass in LABELLED:
reason = scope.universal_refusal([text], self.proj, kind=kind)
got_pass = reason is None
if got_pass and want_pass:
hits += 1
if not got_pass and want_pass:
false_refusals += 1
self.assertEqual(got_pass, want_pass, "%r kind=%s reason=%s" % (text, kind, reason))
self.assertGreaterEqual(len(LABELLED), 20)
def test_universal_change_with_project_moment_passes(self):
# amendment: moment/cause may name the project; only delivered parts are checked
for text in LABELLED[:4]:
self.assertIsNone(scope.universal_refusal([text], self.proj, kind="rule"))
r = self.sisi("retro", *retro_args(scope="everywhere"))
self.assertEqual(r.returncode, 0, r.stdout)
class RetroScopeTests(ScopeCase):
def test_missing_scope_refused_with_explanation(self):
r = self.sisi("retro", *retro_args())
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("core", r.stdout); self.assertIn("user", r.stdout); self.assertIn("project", r.stdout)
self.assertIn("general terms", r.stdout)
def test_everywhere_naming_project_refused(self):
r = self.sisi("retro", *retro_args(scope="everywhere",
change="In acme-widgets always use a quoting writer in the exporter for rows"))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("rewrite", r.stdout.lower())
def test_project_scope_goes_to_handover_not_global(self):
r = self.sisi("retro", *retro_args(scope="project",
change="Use a quoting writer for delimited exports in this project",
short="Use a quoting writer here."))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0); con.close()
from sisi import handover
items = handover.for_project(scope.project_id(self.proj))
self.assertEqual(len(items), 1)
self.assertIn("acme-widgets", items[0]["moment"])
part1, part2 = retro.delivery("csv spreadsheet export delimited file")
self.assertFalse(part1 or part2)
self.assertIn("belong to this project", retro.tick_block(self.proj))
other = os.path.join(self.tmp, "otherproj"); os.makedirs(other)
self.assertNotIn("belong to this project", retro.tick_block(other))
out = self.sisi("handover").stdout
self.assertIn("Use a quoting writer for delimited exports in this project", out)
hid = items[0]["hid"]
bad = self.sisi("handover", "done", hid, "--where", "NOTES.md")
self.assertEqual(bad.returncode, 1, bad.stdout)
with open(os.path.join(self.proj, "NOTES.md"), "w") as f:
f.write("# design notes\n\nUse a quoting writer for delimited exports in this project.\n")
ok = self.sisi("handover", "done", hid, "--where", "NOTES.md")
self.assertEqual(ok.returncode, 0, ok.stdout)
self.assertEqual(handover.load_pile(), [])
self.assertIn("NOTES.md", open(handover.filed_path()).read())
def test_learn_missing_scope_and_project_learn(self):
r = self.sisi("learn", "always show options")
self.assertEqual(r.returncode, 2, (r.stdout, r.stderr))
r = self.sisi("learn", "--scope", "project", "use the left control key here")
self.assertEqual(r.returncode, 0, (r.stdout, r.stderr))
self.assertEqual(store.read("quarantine"), [])
from sisi import handover
items = handover.for_project(scope.project_id(self.proj))
self.assertEqual(items[-1]["text"], "use the left control key here")
r = self.sisi("learn", "--scope", "everywhere", "in acme-widgets always show options")
self.assertEqual(r.returncode, 2, (r.stdout, r.stderr))
def test_lessons_show_split(self):
r = self.sisi("retro", *retro_args(scope="everywhere"))
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("lessons", "show", "1").stdout
self.assertIn("Where this came from (historical example)", out)
self.assertLess(out.index("Write delimited files"), out.index("Where this came from"))
self.assertIn("acme-widgets", out.split("Where this came from (historical example)", 1)[1])
def test_digest_universal_first_then_project(self):
self.sisi("retro", *retro_args(scope="everywhere"))
self.sisi("retro", "--new", *retro_args(scope="project",
change="Use a quoting writer for delimited exports in this project",
short="Use a quoting writer here.", moment="another export broke at step 2 in this repo today"))
out = self.sisi("lessons", "digest").stdout
self.assertIn("Use a quoting writer for delimited exports.", out)
self.assertNotIn("Use a quoting writer here.", out)
self.assertIn("waiting to be filed", out)
self.assertIn("acme-widgets", out)
class StaleReadingTests(ScopeCase):
def test_reading_lessons_does_not_stale_cycle(self):
# folded lesson shown 20x via lessons show retires; cycle check must still pass
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="verifier", target=None,
moment="fuzz seeds missing at step 5 of the nightly run",
cause="the corpus was not seeded from golden files",
change="Seed the fuzz corpus from golden parser files before fuzzing",
when=WHEN, short="Seed fuzz corpus from golden files.", topic="testing"), self.proj, None)
con.execute("UPDATE lessons SET folded_into='fuzz', status='applied', effect='field-note' WHERE id=?", (lid,))
con.commit(); con.close()
from sisi import cycle
base = cycle.base_version()
for _ in range(20):
out = self.sisi("lessons", "show", str(lid))
self.assertEqual(out.returncode, 0, out.stdout)
con = retro.connect()
st = dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()); con.close()
self.assertEqual(st["status"], "applied") # retirement deferred while the round is open
doc = {"version": 1, "base": base, "summary": "keep",
"notes": [{"lesson": lid, "action": "set-short", "short": "Seed fuzz corpus from golden files.", "topic": "testing"},
{"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"},
{"lesson": lid, "action": "set-scope", "scope": "core"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class DueAndBacklogTests(ScopeCase):
def test_tool_lessons_do_not_make_cycle_due_by_headings(self):
con = retro.connect()
for i in range(10):
retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="tool wait %d at step 2 of the run" % i, cause="no cache existed for that step",
change="Make sisi cache transcript scans between gate decisions number %d and reuse them always" % i,
when=WHEN, short="Cache transcript scans.", topic="sisi itself"), self.proj, None)
con.commit(); con.close()
from sisi import cycle
st = cycle.due_state()
self.assertFalse(any("loose lesson headings" in r for r in st["reasons"]), st["reasons"])
out = self.sisi("backlog").stdout
self.assertIn("cap", out.lower())
def test_applied_tool_lesson_not_not_built_in_digest(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="tool wait at step 2 of the run today", cause="no cache existed for that step",
change="Make sisi cache transcript scans between gate decisions and reuse them",
when=WHEN, short="Cache transcript scans.", topic="sisi itself"), self.proj, None)
con.commit(); con.close()
self.assertEqual(self.sisi("lessons", "set", str(lid), "--status", "applied").returncode, 0)
out = self.sisi("lessons", "digest").stdout
self.assertNotIn("not built yet", out)
self.assertIn("built", out)
self.assertNotIn("#%d" % lid, self.sisi("backlog").stdout)
class CycleScopeTests(ScopeCase):
def test_cycle_refuses_folding_project_lesson_into_entry(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="rule", target=None,
moment="export broke at step 2 in this repo", cause="rows joined by hand here",
change="Use a quoting writer for delimited exports in this project",
when=WHEN, short="Use a quoting writer here.", topic="data files"), self.proj, None)
con.execute("UPDATE lessons SET scope='project', project=? WHERE id=?", (scope.project_id(self.proj), lid))
con.commit(); con.close()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "x",
"notes": [{"lesson": lid, "action": "fold-into-rule", "into": "know-done"},
{"lesson": lid, "action": "set-short", "short": "Use a quoting writer here.", "topic": "data files"}]}
p = os.path.join(self.tmp, "cyc2.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("project", r.stdout)
class CleanupRevertTests(ScopeCase):
def test_set_scope_project_moves_and_revert_restores(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="rule", target=None,
moment="export broke at step 2 in acme-widgets today", cause="rows joined by hand here",
change="Use a quoting writer for delimited exports in this project",
when=WHEN, short="Use a quoting writer here.", topic="data files"), self.proj, None)
con.commit(); con.close()
store.append("quarantine", store.stamp({"text": "use the left control key here"}))
from sisi import cycle
base = cycle.base_version()
brief = self.sisi("cycle", "--now").stdout
self.assertIn("Scope cleanup", brief)
self.assertIn(self.proj, brief)
doc = {"version": 1, "base": base, "summary": "cleanup",
"notes": [{"lesson": lid, "action": "set-scope", "scope": "project",
"project": scope.project_id(self.proj)}],
"learn": [{"text": "use the left control key here", "action": "set-scope",
"scope": "project", "project": scope.project_id(self.proj)}]}
p = os.path.join(self.tmp, "cleanup.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn("characters ->", r.stdout)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0); con.close()
self.assertEqual(store.read("quarantine"), [])
from sisi import handover
self.assertEqual(len(handover.load_pile()), 2)
self.assertNotIn("Use a quoting writer here", self.sisi("lessons", "digest").stdout)
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 1); con.close()
self.assertEqual(len(store.read("quarantine")), 1)
self.assertEqual(handover.load_pile(), [])
if __name__ == "__main__":
unittest.main()
+11 -8
View File
@@ -81,14 +81,17 @@ class StoreTests(SisiCase):
with open(os.path.join(self.data, name)) as f: # what the person taught sisi is personal data
return [json.loads(l) for l in f]
def test_learn_appends_with_context(self):
self.assertEqual(self.sisi("learn", "--scope", "everywhere", "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
self.sisi("learn", "--scope", "everywhere", "second")
recs = self.read("learn.jsonl")
self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
self.assertEqual(recs[0]["cwd"], self.proj)
self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9"))
self.assertIn("ts", recs[0])
def test_learn_records_a_statement(self):
r = self.sisi("learn", "--scope", "user", "always record the statement plainly")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("always record the statement plainly", self.sisi("oracle").stdout)
recs = self.read("learnings.jsonl")
self.assertEqual(len(recs), 1)
self.assertTrue(recs[0]["owner_statement"])
def test_empty_learn_rejected(self):
self.assertNotEqual(self.sisi("learn").returncode, 0)
self.assertFalse(os.path.exists(os.path.join(self.data, "learnings.jsonl")))
def test_oracle_prints_file(self):
r = self.sisi("oracle")
-371
View File
@@ -1,371 +0,0 @@
import json, os, random, shutil, time, unittest
from support import *
from sisi import contract as C, deep as D, gate, gitutil, verify as V
from test_verifiers import LibCase, vfile, BODY_V
def deepc(id, cmd="true", timeout_s=3600, **kw):
return dict(check(id, cmd, rung=2, timeout_s=timeout_s, **kw), tier="deep")
class TierContractTests(SisiCase):
def errs(self, c):
return C.validate(c)
def test_fast_default_and_limit(self):
self.assertEqual(self.errs(contract([check("a", "true", timeout_s=60)])), [])
e = self.errs(contract([check("a", "true", timeout_s=61)]))
self.assertTrue(any("deep" in x and "61" in x for x in e), e)
self.assertTrue(self.errs(contract([check("a", "true")], [check("i", "true", timeout_s=900)]))) # invariants too
self.assertEqual(self.errs(contract([check("a", "true"), deepc("d")])), []) # deep may be long
def test_bad_tier_value(self):
self.assertTrue(self.errs(contract([dict(check("a", "true"), tier="slow")])))
def test_fast_limit_is_configurable(self):
os.makedirs(self.state)
json.dump({"verify": {"fast_limit_s": 10}}, open(os.path.join(self.state, "config.json"), "w"))
self.assertTrue(self.errs(contract([check("a", "true", timeout_s=30)])))
def test_sum_over_gate_budget_is_a_warning_only(self):
c = contract([check("a%d" % i, "true", timeout_s=50) for i in range(3)])
self.assertEqual(self.errs(c), [])
self.assertTrue(C.warnings(c))
self.assertFalse(C.warnings(contract([check("a", "true"), deepc("d"), deepc("e")]))) # deep not counted
def test_check_command_prints_warning_and_ok(self):
self.write_contract(contract([check("a%d" % i, "true", timeout_s=50) for i in range(3)]))
r = self.sisi("contract", "check")
self.assertEqual(r.returncode, 0)
self.assertIn("warning", r.stdout)
self.write_contract(contract([check("a", "true", timeout_s=999)]))
r = self.sisi("contract", "check")
self.assertEqual(r.returncode, 1)
self.assertIn("deep", r.stdout)
def test_skeleton_shows_fast_and_deep_placeholders(self):
self.sisi("contract", "init")
c = json.load(open(os.path.join(self.proj, ".sisi", "contract.json")))
self.assertEqual([x.get("tier", "fast") for x in c["checks"]], ["fast", "deep"])
self.assertTrue(all("PLACEHOLDER" in x["claim"] for x in c["checks"]))
self.assertEqual(C.validate(c), [])
self.assertTrue(C.is_unedited_skeleton(c))
class VerifyTierTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.fast, self.dp = os.path.join(self.tmp, "fast"), os.path.join(self.tmp, "deep")
self.write_contract(contract([check("f", "echo x >> %s" % self.fast), deepc("d", "echo x >> %s" % self.dp)]))
def ran(self, p):
return os.path.exists(p)
def test_default_fast_only_deep_only_all(self):
self.assertEqual(self.sisi("verify").returncode, 0)
self.assertTrue(self.ran(self.fast) and not self.ran(self.dp))
os.remove(self.fast)
self.assertEqual(self.sisi("verify", "--deep").returncode, 0)
self.assertTrue(self.ran(self.dp) and not self.ran(self.fast))
os.remove(self.dp)
self.assertEqual(self.sisi("verify", "--all").returncode, 0)
self.assertTrue(self.ran(self.dp) and self.ran(self.fast))
def test_records_carry_tier_and_fingerprint(self):
self.sisi("verify", "--all")
fp = gitutil.fingerprint(self.proj, [os.path.join(self.proj, ".sisi", "contract.json")])
self.assertTrue(fp)
recs = self.results()
self.assertEqual({r["tier"] for r in recs}, {"fast", "deep"})
self.assertEqual({r["fp"] for r in recs}, {fp})
def test_state_lifecycle_and_line(self):
st = lambda: self.sisi("verify", "--state").stdout.strip()
self.assertTrue(st().startswith("deep checks: never-run (1 item)"), st())
self.sisi("verify", "--deep")
self.assertTrue(st().startswith("deep checks: fresh-pass (1 item, last run"), st())
self.assertIn("on the current tree", st())
with open(os.path.join(self.proj, "new.txt"), "w") as f:
f.write("change\n")
self.assertTrue(st().startswith("deep checks: stale-pass"), st())
self.assertIn("older tree", st())
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
self.sisi("verify", "--deep")
self.assertTrue(st().startswith("deep checks: failed"), st())
self.assertIn("failing: d", st())
def test_every_mode_ends_with_state_line(self):
for mode in ([], ["--deep"], ["--all"]):
out = self.sisi("verify", *mode).stdout
self.assertIn("deep checks:", out.strip().splitlines()[-1], mode)
def test_state_json_and_no_deep_items(self):
d = json.loads(self.sisi("verify", "--state", "--json").stdout)
self.assertEqual((d["state"], d["items"]), ("never-run", 1))
self.write_contract(contract([check("f", "true")]))
self.assertIn("none", self.sisi("verify", "--state").stdout)
self.assertNotIn("deep checks: ", self.sisi("verify").stdout.replace("deep checks: none", ""))
def test_failed_deep_exit_code_and_modes_conflict(self):
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
self.assertEqual(self.sisi("verify", "--deep").returncode, 1)
self.assertEqual(self.sisi("verify").returncode, 0) # fast mode ignores deep
self.assertEqual(self.sisi("verify", "--deep", "--all").returncode, 1)
self.assertEqual(self.sisi("verify", "--background").returncode, 1) # needs --deep
class BackgroundTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.counter = os.path.join(self.tmp, "count")
self.go = os.path.join(self.tmp, "go") # the deep check waits for this file, so "running" is deterministic
self.write_contract(contract([check("f", "true"), deepc(
"d", "echo x >> %s; i=0; while [ ! -f %s ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i+1)); done" % (self.counter, self.go))]))
def release(self):
open(self.go, "w").close()
def wait_state(self, want, timeout=15):
t = time.time()
while time.time() - t < timeout:
s = self.sisi("verify", "--state").stdout
if s.startswith("deep checks: " + want):
return s
time.sleep(0.2)
self.fail("never reached %s; last: %s" % (want, s))
def test_detached_run_records_after_parent_exits(self):
r = self.sisi("verify", "--deep", "--background")
self.assertEqual(r.returncode, 0) # returned although the check is still waiting for `go`
log = r.stdout.split("log: ")[1].split()[0]
self.assertTrue(log.startswith(self.state))
self.assertTrue(self.sisi("verify", "--state").stdout.startswith("deep checks: running"))
lock = json.load(open(os.path.join(self.state, "locks", os.listdir(os.path.join(self.state, "locks"))[0])))
self.assertEqual(os.getpgid(lock["pid"]), lock["pid"]) # own process group
self.release()
self.wait_state("fresh-pass") # the parent is long gone by now
deeprecs = [x for x in self.results() if x["tier"] == "deep"]
self.assertEqual([(x["check"], x["status"]) for x in deeprecs], [("d", "passed")])
self.assertTrue(deeprecs[0]["fp"])
self.assertTrue(os.path.exists(log))
self.assertFalse(os.listdir(os.path.join(self.state, "locks"))) # lock released
def test_second_request_while_running_says_so_and_exits_0(self):
self.sisi("verify", "--deep", "--background")
t = time.time()
while not os.path.exists(self.counter) and time.time() - t < 15: # the worker has started its check
time.sleep(0.05)
r = self.sisi("verify", "--deep", "--background")
self.assertEqual(r.returncode, 0)
self.assertIn("already running", r.stdout)
with open(os.path.join(self.proj, "edit.txt"), "w") as f:
f.write("x")
r = self.sisi("verify", "--deep", "--background") # tree changed: reported, not killed or restarted
self.assertIn("older tree", r.stdout)
self.assertIn("running", self.sisi("verify", "--state").stdout)
self.release()
self.wait_state("stale-pass") # finished run was against the older tree
self.assertEqual(len(open(self.counter).read().split()), 1)
def test_foreground_deep_respects_the_lock(self):
self.sisi("verify", "--deep", "--background")
r = self.sisi("verify", "--deep")
self.assertEqual(r.returncode, 0)
self.assertIn("already running", r.stdout)
self.release()
self.wait_state("fresh-pass")
def test_stale_lock_from_dead_process_is_ignored(self):
p = D._lock_path(self.proj)
os.makedirs(os.path.dirname(p))
json.dump({"pid": 2 ** 22 + 12345, "start": "1", "fp": None, "ts": time.time()}, open(p, "w"))
self.assertNotIn("running", self.sisi("verify", "--state").stdout)
self.release()
self.assertEqual(self.sisi("verify", "--deep").returncode, 0)
class GateDeepTests(SisiCase):
sid = "gd"
def setUp(self):
super().setUp()
self.git_init()
self.path = os.path.join(self.proj, ".sisi", "contract.json")
def gate(self, sid=None):
return gate.decide({"session_id": sid or self.sid, "cwd": self.proj})
def hook(self):
return self.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj}))
def fp(self):
return V.tree_fp(self.proj, self.path)
def set_deep(self, ok, fp="current"):
c = json.load(open(self.path))
res = [{"tier": "deep", "id": x["id"], "status": "passed" if ok else "failed", "tail": "" if ok else "kaboom-deep"}
for x in D.deep_items(c)]
D.save_state(self.proj, c["id"], self.fp() if fp == "current" else "older", res, [x["id"] for x in D.deep_items(c)])
def edit(self, t="x"):
with open(os.path.join(self.proj, "w.txt"), "a") as f:
f.write(t + "\n")
def test_pending_deep_allows_and_tells_the_model_once(self):
self.write_contract(contract([check("f", "true"), deepc("d", "sleep 100")]))
t = time.time()
r = self.hook()
self.assertLess(time.time() - t, 5) # never waits for deep items
out = json.loads(r.stdout)
ctx = out["hookSpecificOutput"]
self.assertEqual(ctx["hookEventName"], "Stop")
self.assertIn("not yet", ctx["additionalContext"])
self.assertIn("never-run", ctx["additionalContext"])
self.assertIn("deep", out["systemMessage"])
self.assertNotIn("decision", out)
self.assertEqual(self.hook().stdout, "") # same tree: said once, no loop
def test_stale_pass_notifies_fresh_pass_is_silent(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.set_deep(True)
self.assertEqual(self.hook().stdout, "")
self.edit()
self.assertIn("stale-pass", json.loads(self.hook().stdout)["hookSpecificOutput"]["additionalContext"])
def test_deep_failure_on_current_tree_blocks_with_tail_and_strikes(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.set_deep(False)
a, msg = self.gate()
self.assertEqual(a, "block")
self.assertIn("kaboom-deep", msg)
self.assertEqual([self.gate()[0] for _ in range(2)], ["block", "block"]) # unchanged tree keeps blocking
a, msg = self.gate()
self.assertEqual(a, "allow")
self.assertIn("UNVERIFIED", msg)
def test_deep_failure_on_older_tree_does_not_block(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.set_deep(False, fp="older")
self.assertEqual(self.gate()[0], "allow")
def test_deep_failure_arriving_after_an_allow_is_noticed_on_unchanged_tree(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.assertEqual(self.gate()[0], "allow")
self.assertEqual(self.gate()[0], "allow") # short-circuit
self.set_deep(False) # a background run finished and failed
self.assertEqual(self.gate()[0], "block")
def test_deep_rerun_that_passes_unblocks_unchanged_tree(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.set_deep(False)
self.assertEqual(self.gate()[0], "block")
self.set_deep(True)
self.assertEqual(self.gate()[0], "allow")
def test_fast_failure_still_blocks_regardless_of_deep(self):
self.write_contract(contract([check("f", "false"), deepc("d")]))
self.set_deep(True)
self.assertEqual(self.gate()[0], "block")
def test_running_deep_is_not_a_block(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
ok, _ = D.acquire(self.proj, self.fp())
self.assertTrue(ok)
self.addCleanup(D.release, self.proj)
self.set_deep(False) # an old failure while a new run is in progress
self.assertEqual(self.gate()[0], "allow")
def test_property_deep_never_blocks_by_itself_and_current_failure_always_does(self):
seeds = [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]
for seed in seeds:
rng = random.Random(seed)
for n in range(6 * ITERS):
deeps = [deepc("d%d" % i, rng.choice(["true", "false", "sleep 100"]), timeout_s=rng.choice([60, 3600, 86400]))
for i in range(rng.randint(1, 3))]
c = contract([check("f", "true")] + ([human("h")] if rng.random() < 0.3 else []), [])
c["checks"] += deeps
self.write_contract(c)
self.edit("%d-%d" % (seed, n)) # new tree for each case
mode = rng.choice(["unrun", "running", "pass-fresh", "pass-stale", "fail-fresh", "fail-stale"])
shutil.rmtree(os.path.join(self.state, "deep"), ignore_errors=True)
shutil.rmtree(os.path.join(self.state, "locks"), ignore_errors=True)
if mode == "running":
D.acquire(self.proj, self.fp())
elif mode != "unrun":
self.set_deep(mode.startswith("pass"), "current" if mode.endswith("fresh") else "older")
sid = "prop-%d-%d" % (seed, n)
with self.subTest(seed=seed, n=n, mode=mode):
a, msg = self.gate(sid)
if mode == "fail-fresh":
self.assertEqual(a, "block")
self.assertEqual([self.gate(sid)[0] for _ in range(2)], ["block", "block"])
self.assertEqual(self.gate(sid)[0], "allow") # 3-strike release
else:
self.assertEqual(a, "allow")
D.release(self.proj)
class TickDeepTests(SisiCase):
def tick(self):
return self.sisi("tick", stdin=json.dumps({"session_id": "t", "cwd": self.proj, "source": "startup"})).stdout
def setUp(self):
super().setUp()
self.git_init()
def test_line_for_not_fresh_states_silent_when_fresh_or_untrusted(self):
# Session start no longer prints deep-check state; `sisi verify --state` owns it.
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.assertEqual(self.tick(), "")
self.sisi("verify", "--deep")
self.assertEqual(self.tick(), "")
with open(os.path.join(self.proj, "n.txt"), "w") as f:
f.write("x")
self.assertEqual(self.tick(), "")
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
self.sisi("verify", "--deep")
self.assertEqual(self.tick(), "")
self.write_contract(contract([check("f", "true"), deepc("d")]), trusted=False)
os.remove(os.path.join(self.data, "trusted.json"))
self.assertEqual(self.tick(), "")
def test_still_fast(self):
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.tick()
best = 9
for _ in range(5):
t = time.perf_counter()
self.tick()
best = min(best, time.perf_counter() - t)
__import__('support').skip_timing_if_busy(self)
self.assertLess(best, 0.2)
class StatusLintTests(LibCase):
def test_status_lists_recent_contracts(self):
self.git_init()
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.sisi("verify")
out = self.sisi("status").stdout
self.assertIn("recent contracts:", out)
self.assertRegex(out, r"t\s+fast: pass\s+deep: never-run")
self.sisi("verify", "--deep")
self.assertRegex(self.sisi("status").stdout, r"deep: fresh-pass")
def test_lint_warns_on_long_untiered_example(self):
def body(extra):
return BODY_V.replace("## As a contract check\ntext", '## As a contract check\n```json\n{"id": "x", "timeout_s": %s%s}\n```' % extra)
self.put("prove/slow.md", vfile("slow", body=body(("3600", ""))))
self.put("prove/ok.md", vfile("ok", body=body(("3600", ', "tier": "deep"'))))
self.put("prove/quick.md", vfile("quick", body=body(("60", ""))))
r = self.sisi("verifiers", "lint")
self.assertEqual(r.returncode, 0, r.stdout)
warn = [l for l in r.stdout.splitlines() if "no \"tier\": \"deep\"" in l]
self.assertEqual(len(warn), 1)
self.assertIn("slow.md", warn[0])
if __name__ == "__main__":
unittest.main()
-210
View File
@@ -1,210 +0,0 @@
"""Three tiers (core, user, project): round-trips, migration of `everywhere`, the sisi-name
exemption, promote from the clone, export, and exact cycle revert with tiers."""
import json, os, shutil, subprocess, unittest
from support import *
from sisi import paths, retro, scope, store
from unittest import mock
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
PATTERN = "Build the obvious thing instead of using what the environment already provides"
def retro_cli(case, tier, **kw):
f = dict(aim="verified", moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change_kind="rule", change="Write delimited files with a quoting writer so fields survive",
when=WHEN, pattern=PATTERN, short="Use a quoting writer for delimited exports.",
topic="data files")
f.update(kw)
args = ["retro", "--scope", tier]
for k in ("aim", "moment", "cause", "change_kind", "change", "when", "pattern", "short", "topic"):
args += ["--" + k.replace("_", "-"), f[k]]
return case.sisi(*args)
class TierTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def test_tier_decisions_round_trip(self):
for tier in ("core", "user"):
r = retro_cli(self, tier, moment="export %s broke on a quoted field at step 3" % tier,
change="Write delimited files with a quoting writer so %s fields survive" % tier)
if tier == "user":
self.assertIn(r.returncode, (0, 4), r.stdout) # 4 = similar lesson kept as sighting
if r.returncode == 4:
r = self.sisi("retro", "--new", "--scope", "user", "--aim", "verified",
"--moment", "export user broke on a quoted field at step 3",
"--cause", "rows were joined by hand instead of with a quoting writer",
"--change-kind", "rule",
"--change", "Write delimited files with a quoting writer so user fields survive",
"--when", WHEN, "--pattern", PATTERN,
"--short", "Use a quoting writer for delimited exports.",
"--topic", "data files")
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
try:
tiers = [scope.tier_of(r[0]) for r in con.execute("SELECT scope FROM lessons ORDER BY id")]
finally:
con.close()
self.assertEqual(tiers, ["core", "user"])
for tier, text in (("core", "sisi should anticipate what is needed from what was already said"),
("user", "always ask questions as options with a recommendation")):
r = self.sisi("learn", "--scope", tier, text)
self.assertEqual(r.returncode, 0, r.stdout)
recs = store.read("learn")
self.assertEqual([r["scope"] for r in recs], ["core", "user"])
out = self.sisi("oracle").stdout
self.assertIn("always ask questions as options", out)
self.assertIn("sisi should anticipate", out) # core, until the product carries it
def test_missing_scope_text_asks_the_two_questions(self):
r = self.sisi("learn", "always show options")
self.assertEqual(r.returncode, 2)
self.assertIn("all projects where sisi may be used", r.stdout)
self.assertIn("every user who installs sisi", r.stdout)
def test_statement_naming_sisi_is_accepted_as_core_inside_sisi_repo(self):
d = os.path.join(self.tmp, "sisi")
os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
r = self.sisi("learn", "--scope", "core",
"sisi should anticipate what I need from what I already said", cwd=d)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(store.read("learn")[0]["scope"], "core")
def test_everywhere_migrates_to_unscoped_tier_and_still_delivers(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(
aim="verified", change_kind="rule", target=None,
moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so fields survive",
when=WHEN, short="Use a quoting writer.", topic="data files",
scope="user", pattern=PATTERN), self.proj, None)
con.execute("UPDATE lessons SET scope='everywhere' WHERE id=?", (lid,))
con.commit(); con.close()
con = retro.connect() # migration on open
try:
v = con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0]
finally:
con.close()
self.assertEqual(v, "unscoped-tier")
self.assertIn("Use a quoting writer", retro.tick_block(self.proj))
brief = self.sisi("cycle", "--now").stdout
self.assertIn("tier", brief.lower())
def test_digest_groups_core_user_and_project_counts(self):
r = retro_cli(self, "core")
self.assertEqual(r.returncode, 0, r.stdout)
self.sisi("learn", "--scope", "user", "always ask questions as options with a recommendation")
out = self.sisi("lessons", "digest").stdout
self.assertIn("## In sisi itself, for every user", out)
self.assertIn("## How you want work done", out)
self.assertIn("waiting to be promoted", out)
class PromoteTierTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.src = os.path.join(self.tmp, "src")
for d in ("bin", "sisi", "canon"):
os.makedirs(os.path.join(self.src, d))
open(os.path.join(self.src, "bin", "sisi"), "w").write("#!/bin/sh\n")
open(os.path.join(self.src, "sisi", "cli.py"), "w").write("# cli\n")
shutil.copy(os.path.join(REPO, "canon", "core.md"), os.path.join(self.src, "canon", "core.md"))
os.makedirs(os.path.join(self.data), exist_ok=True)
_p = mock.patch.object(paths, "REPO", self.src) # run from the clone
_p.start()
self.addCleanup(_p.stop)
def core_lesson_folded_to_rule(self):
r = retro_cli(self, "core")
self.assertEqual(r.returncode, 0, r.stdout)
d = os.path.join(self.data, "overlay", "rules")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "quoting-writer.md"), "w") as f:
f.write("## Write delimited files with a quoting writer\n\n"
"Write delimited files with a quoting writer so embedded delimiters and "
"newlines survive.\n\nWhy: hand-joined rows break on real data.\n")
con = retro.connect()
try:
con.execute("UPDATE lessons SET folded_into='rule:quoting-writer' WHERE id=1")
con.commit()
finally:
con.close()
def test_promote_lists_core_items(self):
self.assertEqual(retro_cli(self, "core").returncode, 0)
out = self.sisi("promote").stdout
self.assertIn("lesson:1", out)
def test_promote_from_clone_edits_product_and_drops_personal_copy(self):
self.core_lesson_folded_to_rule()
overlay_file = os.path.join(self.data, "overlay", "rules", "quoting-writer.md")
self.assertTrue(os.path.exists(overlay_file))
r = self.sisi("promote", "lesson:1") # dry run: product untouched
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertNotIn("quoting-writer", open(os.path.join(self.src, "canon", "core.md")).read())
r = self.sisi("promote", "lesson:1", "--apply")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
core = open(os.path.join(self.src, "canon", "core.md")).read()
self.assertIn("quoting writer so embedded delimiters", core)
self.assertFalse(os.path.exists(overlay_file)) # dropped only after the product has it
con = retro.connect()
try:
self.assertTrue(con.execute("SELECT promoted FROM lessons WHERE id=1").fetchone()[0])
finally:
con.close()
self.assertNotIn("lesson:1", self.sisi("promote").stdout)
def test_export_contains_no_history_or_names(self):
self.assertEqual(retro_cli(self, "core").returncode, 0)
self.sisi("learn", "--scope", "core", "sisi should use what the host already provides")
p = os.path.join(self.tmp, "contrib.md")
r = self.sisi("promote", "--export", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
text = open(p).read()
self.assertIn("Write delimited files with a quoting writer", text)
self.assertIn("sisi should use what the host already provides", text)
self.assertNotIn("the export broke on a quoted field", text) # the moment (history)
self.assertNotIn("rows were joined by hand", text) # the cause (history)
self.assertNotIn(self.tmp, text)
def test_cycle_set_scope_to_core_and_exact_revert(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(
aim="verified", change_kind="rule", target=None,
moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so fields survive",
when=WHEN, short="Use a quoting writer.", topic="data files",
pattern=PATTERN), self.proj, None)
con.commit(); con.close()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "tier it",
"notes": [{"lesson": lid, "action": "set-scope", "scope": "core"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
self.assertEqual(con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0], "core")
finally:
con.close()
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
self.assertEqual(con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0],
"unscoped-tier")
finally:
con.close()
if __name__ == "__main__":
unittest.main()