Universal lessons with project handover; whole-document edits; worker discovery and routing
ci / tests (macos-latest, python 3.10) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.10) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s

Lessons and statements carry a required scope; project items leave the shared
store for a per-project handover pile filed into that project's own docs.
Every learning round ends with a whole-document edit with traced lessons.
sisi workers / route / delegate discover tools, choose the most affordable
adequate worker and record results in the personal store; the host tool's own
subagents come first, the command-line runner is the fallback.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 08:59:21 -07:00
1 parent dad13062a1
commit ba84772acf
33 files changed
+4623 -125

No files matched your search

+25
View File
@@ -8,12 +8,37 @@ All notable changes to this project are recorded here. The format follows
### Changed
- Request-time delivery no longer hands over a recipe on a weak match or for a question that names
no work; reading lessons can no longer stale a learning round; the due test counts only lessons a
round can act on.
- `sisi install` updates extension files written by earlier versions instead of refusing them.
- The name now expands to "sisi is still improving"; the earlier expansion is retired.
- The always-loaded rulebook budget is raised to the largest size vendor guidance supports; growth
still requires shortening elsewhere.
### Added
- Lessons and `sisi learn` statements now carry a scope (`--scope everywhere|project`, required).
Universal lessons are refused when their delivered text names the current project; their history
may name it freely. Project-scoped items leave the shared store for a per-project handover pile
(`sisi handover`) and are filed into that project's own documentation or work list.
- A learning round now ends with a whole-document edit: each rulebook, recipe and technique
document with unintegrated notes is rewritten as a proper document or marked reviewed with a
reason; every folded lesson must be traced to the text that carries it, so nothing can be lost.
`sisi done ID --trace` and `sisi lessons show ID` print where each lesson lives.
- Rule 7 of the rulebook is rewritten as short grouped instructions.
- Dynamic workers (`sisi workers`, `sisi route`, `sisi delegate`): the agent tools and models on
the machine are discovered and cached (refreshed during normal use, never scheduled), work is
routed to the most affordable usable worker by pure arithmetic over a judged delegation ledger
(flat-rate allowance before per-use price, load spread in proportion to allowance left, thin
records explored on low-difficulty work, reviews sent to a different maker, "contributor"
models never chosen), and one brief can be run unattended with limit and login failures —
recognised from output text, including failures reported with a success exit status — recorded
as unavailability and retried on the next choice. Judgements are recorded with
`sisi delegate judge`; an earlier hand-kept ledger is imported once, unchanged. The session's
own model is now kept from hook payloads, and session start says in one line whether it should
plan and delegate or do the work itself. See docs/workers.md.
- Request-time delivery (`sisi prompt`): where a tool documents a prompt-submission event with a
context channel (Claude Code, Codex CLI, Gemini CLI, Muse CLI, Pi), the matching
recipe's "done means" list and the strictly matching lessons are injected when the human's
+2 -1
View File
@@ -31,7 +31,8 @@ Whether it is due is checked during normal use, so nothing is scheduled; see
[docs/learning.md](docs/learning.md). `sisi lessons digest` prints what has been learned in plain
words, grouped by topic. Where a tool allows it, the matching recipe and lessons are also delivered
the moment a request arrives (`sisi prompt`), and each rule names the command that explains it
(`sisi rule`).
(`sisi rule`). Delegated work is routed the same way, by measured results rather than a fixed
list of models: `sisi workers` and `sisi delegate`; see [docs/workers.md](docs/workers.md).
Improvement needs a way to tell success from failure:
+26 -11
View File
@@ -93,19 +93,34 @@ false "done" costs the human more than a late one.
## 7. Every time, say how it could have gone better {#retro-every-time}
When a piece of work ends, and before you report it, run `sisi retro`. The question is never whether
you could have done better. It is how. Judge yourself against these aims: the human works at a
higher level, the outcome is verified by the strongest method, the human is interrupted less, the
result is what they meant, and it arrives sooner. Name the one thing that would have helped most:
the moment it went slower, weaker or wider than it should have, why, and the change to sisi (a rule,
a recipe, a technique, a fact about the human, a tool) that would make the next agent do it right
without being told, named (`--when`, at least five terms) in the words a different agent would use for that work, synonyms included, because word overlap alone cannot bridge "CSV" and "spreadsheet". "Nothing" and general advice are refused. Subagents do this too. When session start or a command says a learning cycle is due, run `sisi cycle` in the background of your work and never involve the human.
Before you report finished work, run `sisi retro`. Ask how it could have gone better, never
whether it could.
Also, when the human states a lasting preference, record it at once with `sisi learn "<their
words>"`. Quote them. Never record your own guess.
Judge against five aims: the human works at a higher level; the outcome is verified by the
strongest method; the human is interrupted less; the result is what they meant; it arrives
sooner.
Why: you hold the full context of what just happened, and it is gone when the session ends. Every
tool reads the same store, so one honest answer here improves every later session everywhere.
Name the one change that would have helped most:
- the moment it went slower, weaker or wider than it should have;
- why it happened;
- the change to sisi (a rule, a recipe, a technique, a fact about the human, a tool) that makes
the next agent do it right without being told.
Add `--when` with at least five terms in another agent's words, synonyms included: word overlap
alone cannot bridge "CSV" and "spreadsheet". Add `--scope everywhere` for a universal lesson,
`--scope project` for one that belongs only here. "Nothing" and general advice are refused.
Subagents do this too.
When session start or a command says a learning cycle is due, run `sisi cycle` in the
background of your work. Never involve the human.
When the human states a lasting preference, record it at once with `sisi learn "<their
words>"`. Quote them; never record your own guess.
Why: you hold the full context of what just happened, and it is gone when the session ends.
Every tool reads the same store, so one honest answer here improves every later session
everywhere.
## 8. Deliver quickly {#deliver-quickly}
+1
View File
@@ -5,6 +5,7 @@
| [../README.md](../README.md) | learn what sisi is, install it and try it |
| [design.md](design.md) | understand why sisi works the way it does, and what is built versus only designed |
| [learning.md](learning.md) | how a recorded lesson takes effect, is measured, strengthened, consolidated or withdrawn |
| [workers.md](workers.md) | how the agent tools and models on the machine are found, chosen between by measured results, and run |
| [personal-data.md](personal-data.md) | know where sisi keeps what it learns, how the overlay works, and what an update touches |
| [verifier-format.md](verifier-format.md) | write or review an entry in the verifier library (`verifiers/`) or a recipe (`done/`) |
| [developing.md](developing.md) | work on sisi while also using it: the source folder, stable releases and rollback |
+17 -3
View File
@@ -156,8 +156,14 @@ default the agent is proceeding on. Work that does not depend on it continues. `
queue. An answer that differs from the default re-opens only the nodes that used it.
**Delegation records.** A person who already delegates work to cheaper models may keep a ledger of outcomes.
The design folds such a ledger and its routing table into the shared store. Built so far, sisi only reads an optional
ledger file, to match delegations with sessions when it builds the task set.
The design folds such a ledger and its routing table into the shared store. Built: the worker layer
([workers.md](workers.md)) discovers the agent tools and models installed on the machine, imports such a
ledger once into the shared store, and routes work by pure arithmetic over the judged record — the most
affordable usable worker that is good enough, with load spread in proportion to the allowance each plan has
left and reviews sent to a different maker. `sisi delegate` runs one brief unattended through a per-tool
driver and leaves the run waiting for a judgement. No model is preferred in code, and nothing refreshes on a
schedule: discovery is re-read during normal use when the stored copy is old or after a failure. What is not
built on top of it is the conductor above: framing, splitting and closing a tree of work.
## Part 3: learning that compounds
@@ -296,6 +302,13 @@ Built and covered by tests:
into the product.
- The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates,
check statistics, scoreboard.
- The worker layer: discovery of the installed agent tools and their models (`sisi workers`), the delegation
ledger in the shared store with a one-time lossless import of the earlier hand-kept ledger, unavailability
kept apart from judged quality, choice by measured results (`sisi route`), and unattended runs with
judgement (`sisi delegate`). The session's model is kept from hook payloads, strength comes from the record
plus a stored prior with source and date (no ranking shipped in code), and session start says whether the
session should plan and delegate or work itself. Stored price and strength tables are ready for a later
research refresh; that refresh, and any driver for a host with its own delegation interface, are not built.
Designed, not built:
@@ -326,7 +339,8 @@ resumes without redoing closed nodes (to be model-checked, then tested).
## Decisions
1. Delegation tooling is folded into sisi in the design; only the optional ledger read is built.
1. Delegation tooling is folded into sisi: discovery, the ledger, the choice rule and unattended runs are
built (see [workers.md](workers.md)); the conductor that frames and splits whole products is not.
2. The end-of-turn gate is on by default. Each check has a time limit, and after three send-backs in a row the
agent is let through with the result marked unverified. One setting turns the gate off.
3. Session text may be read by any provider the user already uses as a worker, never by a model whose id marks it
+127 -11
View File
@@ -9,7 +9,28 @@ what "done" means, verifying, or being sent back by the gate.
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. It also names, with `--when` (at
that would make the next agent do it right without being told. Every lesson, and every
`sisi learn` statement, has a scope (`--scope everywhere|project` is required; a missing scope is
refused with a paragraph saying what each means). **Scope: lessons are universal, or they leave.**
`everywhere` is for a lesson that holds in any project, stated in general terms; `project` is for
a fact about this one project, and it 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 when scoped
`everywhere`, 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 word `sisi` alone is exempt
in tool lessons, which are changes to sisi itself). 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 scopes existed are `unscoped`: they keep being delivered as before until a
learning round scopes them (below), and printed headings count the short line when present.
`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
@@ -47,8 +68,10 @@ what "done" means, verifying, or being sent back by the gate.
"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 (matched on stems, so "tag" meets "tagging"); trivial messages (a bare yes or
no, a slash command, a short question) and unmatched requests inject nothing at all. These
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
@@ -74,11 +97,37 @@ what "done" means, verifying, or being sent back by the gate.
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.
## Project facts are handed over, not kept (`sisi handover`)
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 cycle (`sisi cycle`)
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 loose list stays short
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
@@ -102,16 +151,37 @@ states the short and topic limits, and requires a `set-short` entry for each lis
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 unscoped lesson and `sisi learn` statement, with the repository each
was recorded in where known, and requires a scope decision for each: a note
`{"lesson": A, "action": "set-scope", "scope": "everywhere|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`). 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. A learn statement about how the owner wants all work done (how to ask
questions, spending limits, no scheduled jobs) is universal; a statement about one product's
design is project. A file containing only the required set-short/set-scope 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",
"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",
"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)",
"entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", "scope": "everywhere|project (set-scope)", "project": "id (set-scope)",
"reason": "why it stays a draft (keep-as-draft)"}],
"learn": [{"text": "the exact learn statement", "action": "set-scope", "scope": "everywhere|project", "project": "id, when project"}],
"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}]}
@@ -153,6 +223,40 @@ deliveries, send-backs each, median time, and recurrences of the lessons it touc
deliveries got worse after at least 10 of them is flagged, and the next brief says to revert or repair
it first.
Every round ends with a whole-document edit. The things agents read are documents — the
rulebook, 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.
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.
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
@@ -179,13 +283,18 @@ sent back twice.
`sisi lessons digest` is for the human, not for agents. Its first line says how much has been
learned in one sentence, and its last line says how to see a lesson in full (`sisi lessons show
ID`), with the lesson number on every line. Preferences recorded with `sisi learn` appear first,
ID`), with the lesson number on every line. Universal items come first; items waiting to be
filed in their projects appear only as a count per project (run `sisi handover` inside that
project to see them). Preferences recorded with `sisi learn` appear first,
in the person's own words, under "What you said" when any are stored. Short lines are grouped
under their topic headings, ordered by how much each topic holds, most first. After every line
comes its state in plain words — in the rulebook; attached to a kind of work; a loose note; or a
change to sisi itself, not built yet — plus "seen N times" only when a lesson has been seen more
than once. Lessons without a short line go last, under "Not yet summarized", cut at a word
boundary. Retired, withdrawn and superseded lessons are left out unless `--all` is given.
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.
## Is it getting better?
@@ -220,6 +329,13 @@ reach 21/21 (20 of them already in part one; one — a request sharing a single
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:
+108
View File
@@ -0,0 +1,108 @@
# Workers: discovery, choice and delegation
sisi finds the agent command-line tools on the machine, keeps a judged record of work given to
them, and chooses the most affordable worker that is good enough for each new piece of work. No
list of preferred models is shipped in code, and nothing is scheduled: information refreshes when
a command runs and the stored copy is old, or after a failure.
## The commands
- `sisi workers` prints, in plain words, each tool found on `PATH`, the models it lists, whether
it is usable now and why not (not logged in, limit reached until a stated time), the allowance
left where the tool itself reports one, and the price where one is known. A tool with no model
listing command is shown as "models learned by use": the record names its models as they are
used. `sisi workers --refresh` reads the tools again instead of using the stored copy.
- `sisi route --kind K --difficulty N [--review-of W] [--explain]` prints the worker the record
chooses for a kind of task (such as `search`, `impl`, `tests`, `review`) at a difficulty of 1, 2
or 3. It is plain arithmetic over the record; no model is called. `--explain` also prints why
each other candidate was passed over. `--review-of W` chooses a reviewer from a different maker
than the author `W`, peer review style.
- `sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]`
runs the brief unattended on the chosen worker in the given folder, writes the full transcript
to a file under the state folder, and prints only the worker's final report, the transcript path
and the command that records the judgement.
- `sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review
[--minutes N]` records how a run turned out and how strongly it was checked. That judgement is
what later choices learn from. A run nobody judged is listed by `sisi workers` and named at
session start.
- `sisi delegate amend ID` marks a judged result that later proved wrong, so it stops counting as
a success.
## How the choice is made
In order: a model whose id contains "contributor" is never chosen, because those tiers train on
prompts. A worker marked unavailable is skipped until its retry time, as is a flat-rate plan whose
allowance is known to be spent. For a review, the author's maker is skipped while another maker
is available.
A worker counts as proven for a kind and difficulty after enough judged attempts (one threshold
constant in code) with an accepted rate at or above the bar, where accepted means accepted and not
later found wrong. Above the lowest difficulty, proven workers come first. At the lowest
difficulty, workers with a thin record stay in the pool, so low-stakes work is what gathers their
first attempts. A worker with enough attempts and a rate below the bar is passed over while
anything else remains.
Cheapest means: a flat-rate plan with allowance left and no recent failure comes before anything
billed per use, because one more task on it costs nothing extra. Per-use workers order by their
known price. An unknown price is treated as the most expensive of its class until it is learned;
`--explain` says so rather than inventing a number.
Work is then spread, not drained: within one price tier and price, the worker that has taken the
least work relative to the allowance it has left goes first. Every delegation is recorded, so the
choice rotates as work is done, yet is deterministic for one fixed record. Ties break on the
worker id.
On a fresh install the record is empty and no prices are known, so every worker is thin and
unpriced: the first usable worker in id order is chosen, with flat-rate allowance winning where a
tool reports it. Each judgement then shapes the next choice. That is the whole bootstrap; there is
no shipped roster to fall back on.
## Failures that are not bad work
Some tools report a limit or a missing login with a success exit status, so failure is recognised
from the output text, never from the exit status alone. A limit, login, missing tool or outage is
recorded as unavailability, with a retry time that grows on repeat failures, and the same brief is
tried on the next choice at once. Unavailability never counts against a worker's quality. A worker
that ran and did poor work is a different thing: that is a rejected judgement.
sisi never passes a flag that switches off a tool's approvals or sandbox unless the config
explicitly allows it for that tool (`workers.allow_bypass`). When a run times out, the message
says it may be stalled on such a decision and names that setting.
## The main thread
Hook payloads carry the session's model; sisi keeps it with the session record. Model strength
comes from the judged record where it is thick enough, otherwise from a stored prior table in
which every figure carries its source and date. No ranking ships in code: with no prior and no
record, the strength of a model is stated as unknown.
At session start, one plain line follows from that: a session whose model is among the strongest
available on the machine is told to plan, delegate with `sisi delegate` and judge; a weaker one is
told to do the work itself, and told once which stronger models are available. A session another
agent started (a subagent, or a worker run by `sisi delegate`) is told nothing about delegating.
## What is stored, and the seams left open
In the personal data folder: `workers.json` (discovery, with the time it was read),
`delegations.jsonl` (the ledger: runs, judged attempts, amendments), `worker-availability.json`
(unavailable workers and retry times), and two tables that start empty:
- `worker-prices.json`: `{"models": {"<model or worker>": {"plan": "flat" or "per-use",
"cost_per_million_tokens": number, "maker": name, "source": text, "date": "YYYY-MM-DD"}},
"tools": {"<tool>": entries of the same shape}}`.
- `model-strength.json`: `{"models": {"<model or worker>": {"score": number from 0 to 100,
"source": text, "date": "YYYY-MM-DD"}}}`.
A ledger kept by the earlier hand-written orchestrator is imported once, without changing the
original, when its path is named by the `ledger` config key or the `SISI_LEDGER` environment
variable; `sisi workers` reports how many rows came in.
Settings live under a `workers` key in the config: `refresh_after_s` (how old discovery may get
before a command refreshes it), `timeout_s` (how long one delegated run may take), and
`allow_bypass` (per tool, whether approval- or sandbox-switching flags may be passed; off unless
named).
Deliberately not built in this slice, with the tables above ready for them: refreshing prices and
published benchmark scores by web research into those tables; using a cheap fast model to classify
tasks, match lessons or draft review plans; a driver for hosts that delegate through their own
interface rather than a command line; and removing the prose orchestrator this replaces.
+27 -8
View File
@@ -366,9 +366,26 @@ def _header_of(content):
return content.split(b"\n", 1)[0].rstrip(b"\r")
def _is_generated(data, content):
"""Ours only when the first line is exactly the header line the generator writes."""
return data is not None and _header_of(data) == _header_of(content)
GENERATED_MARKER = b"sisi:generated"
def _is_generated(data, content, p=None):
"""Ours when the first line is exactly the current header, or carries the stable
`sisi:generated` marker in its first line (what earlier sisi versions wrote; their
header wording differed), or the recorded install manifest's sha for this path
matches the file's bytes. A marker anywhere else in the file proves nothing."""
if data is None:
return False
if _header_of(data) == _header_of(content) or GENERATED_MARKER in _header_of(data):
return True
if p is not None:
try:
ent = wiring._mload().get("files", {}).get(p) or {}
sha = ent.get("sha256")
return bool(sha) and hashlib.sha256(data).hexdigest() == sha
except Exception:
return False
return False
def generated_state(p, content):
@@ -376,7 +393,7 @@ def generated_state(p, content):
data, err = wiring._read_file(p)
if err or data is None:
return "absent"
if not _is_generated(data, content):
if not _is_generated(data, content, p):
return "foreign"
return "current" if data == content else "stale"
@@ -392,7 +409,7 @@ def write_generated(m, p, content, notes, label):
if err:
notes.append("%s: %s; not touched" % (label, err))
return False
if data is not None and not _is_generated(data, content):
if data is not None and not _is_generated(data, content, p):
notes.append("%s: %s exists and is not ours; not touched" % (label, p))
return False
if data == content:
@@ -411,7 +428,7 @@ def remove_generated(m, p, notes, label, content):
if err:
notes.append("%s: %s not touched (%s)" % (label, p, err))
return
if data is None or not _is_generated(data, content):
if data is None or not _is_generated(data, content, p):
return
ent = m["files"].get(p)
known = (ent.get("sha256") if ent else None) or hashlib.sha256(content).hexdigest()
@@ -420,10 +437,12 @@ def remove_generated(m, p, notes, label, content):
return
if ent is not None and ent["backup"]:
orig = wiring._read(os.path.join(wiring._idir(), "backups", ent["backup"]))
if orig is not None:
if orig is not None and not _is_generated(orig, content, p):
wiring._write(p, orig)
notes.append("%s: restored %s" % (label, p))
return
# a backup that is itself a sisi-generated file (an older version) is not restored:
# uninstall removes the generated file rather than resurrecting the old one
if os.path.islink(p):
notes.append("%s: %s is a symlink; left alone" % (label, p))
return
@@ -435,7 +454,7 @@ def plan_generated_ops(p, content):
data, err = wiring._read_file(p)
if err:
return [{"kind": "skip", "reason": err + "; not touched", "fatal": False}]
if data is not None and not _is_generated(data, content):
if data is not None and not _is_generated(data, content, p):
return [{"kind": "skip", "reason": "%s exists and is not ours; not touched" % p, "fatal": False}]
if data == content:
return []
+36 -6
View File
@@ -31,7 +31,7 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT
learned changes to rules, verifiers and recipes; each one a commit in your personal repo
sisi audit inventory of standing instructions per tool
sisi retro --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"]
sisi retro --scope everywhere|project --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"]
(or --json - with the same keys on stdin)
end of every piece of work: HOW it could have gone better; --when (at least
5 terms, synonyms included) is how a later agent with different words finds it;
@@ -53,17 +53,32 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
sisi improve is it getting better? lessons, recurrence, send-backs, time, rulebook size
sisi note TEXT (older; prefer retro) record something that went wrong
sisi propose TEXT (older; prefer retro) suggest a rule change
sisi learn TEXT record a human-stated preference (quarantined until verified)
sisi learn --scope everywhere|project TEXT
record a human-stated preference (quarantined until verified);
--scope is required: everywhere for how all work should be done,
project for a fact about this project (handed over to it)
sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]
project items waiting to be filed in this project's own docs or
work list; done confirms one is filed (the named file must contain
its key text) and removes it from the pile
sisi oracle print what the human wants (oracle.md in the personal folder)
sisi status verification statistics from the store
sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks
sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]
list ways to know work is correct, by section
sisi verifiers show ID one entry in full, and whether its tool is installed here
sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it
sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work
sisi verifiers doctor | lint which tools are installed; validate the library
sisi done [ID] recipes: which checks make a kind of work done
sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe
sisi done for "<work>" best-matching recipe
sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, and delegations waiting for a judgement
sisi route --kind K --difficulty N [--review-of W] [--explain]
the most affordable usable worker for this kind and difficulty, by the judged record alone; --explain says why, and why the rest were passed over
sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]
run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command
sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]
record your judgement of a delegation run, so the next choice learns from it
sisi delegate amend ID mark a judged delegation that later proved wrong
sisi version | --version print the product version (the VERSION file in the product folder)
sisi help this text
@@ -425,8 +440,14 @@ def main(argv):
if cmd == "audit":
from . import audit
return audit.main(args)
if cmd in ("note", "propose", "learn"):
return cmd_store({"note": "notes", "propose": "proposals", "learn": "quarantine"}[cmd], args)
if cmd == "learn":
from . import scope
return scope.cmd_learn(args)
if cmd == "handover":
from . import handover
return handover.main(args)
if cmd in ("note", "propose"):
return cmd_store({"note": "notes", "propose": "proposals"}[cmd], args)
if cmd == "retro":
from . import retro
return retro.cmd_retro(args)
@@ -455,6 +476,15 @@ def main(argv):
if cmd == "done":
from . import verifiers
return verifiers.done_main(args)
if cmd == "workers":
from . import workers
return workers.cmd_workers(args)
if cmd == "route":
from . import workers
return workers.cmd_route(args)
if cmd == "delegate":
from . import workers
return workers.cmd_delegate(args)
rc = _learn_cli(cmd, args)
if rc is not None:
return rc
+442 -28
View File
@@ -15,14 +15,16 @@ A cycle file (what the agent writes, what `sisi cycle apply` checks) is one JSON
"when": "csv, tsv, spreadsheet, tabular data, import, parse (optional; sets the lesson's when-terms)"}],
"enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30},
{"lesson": 4, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}]}
"require_kind": "parsing", "max_rung": 2}],
"documents": [{"doc": "recipe:<id>", "action": "rewrite|reviewed", "text": "...", "trace": [...]}],
"rule_order": ["every rule id once"]}
Every part is optional except version and base. Apply is one commit in the personal repository under
the personal-data lock; a stale base (another cycle or lesson landed since the brief) refuses cleanly.
Each applied cycle records the exact bytes it changed, so revert restores them byte for byte.
"""
import base64, difflib, hashlib, json, os, re, shlex, shutil, time
from . import overlay, paths, pdata, retro, store
from . import documents, overlay, paths, pdata, retro, store
class CycleError(Exception):
@@ -30,7 +32,7 @@ class CycleError(Exception):
ACTIONS = ("merge", "fold-into-rule", "fold-into-entry", "retire", "withdraw", "keep",
"set-when", "create-entry", "keep-as-draft", "set-short")
"set-when", "create-entry", "keep-as-draft", "set-short", "set-scope")
# Total characters of lesson text (change+moment+cause) the brief prints in full. Over this,
# lessons are truncated and the brief says to run `sisi lessons show ID` for the full text.
BRIEF_TEXT_BUDGET = 6000
@@ -107,13 +109,18 @@ def due_state(con=None):
return {"due": False, "reasons": [], "counter": [0, 0]}
try:
last = retro.get_meta(con, "last_cycle_ts") or ""
since = con.execute("SELECT count(*) FROM lessons WHERE created>?", (last,)).fetchone()[0]
# only what a round can act on counts: tool lessons (backlog, closed when built) and
# project-scoped items (handed over to their project) never make a cycle due
since = con.execute("SELECT count(*) FROM lessons WHERE created>? AND change_kind<>'tool' "
"AND COALESCE(scope,'unscoped')<>'project'", (last,)).fetchone()[0]
pending = con.execute(
"SELECT count(*) FROM lessons WHERE status IN ('open','applied') AND "
"SELECT count(*) FROM lessons WHERE status IN ('open','applied') AND change_kind<>'tool' "
"AND COALESCE(scope,'unscoped')<>'project' AND "
"(COALESCE(needs_cycle,0)=1 OR (COALESCE(strength,1)>=3 AND check_json IS NULL))").fetchone()[0]
notes_chars = retro.notes_chars(con)
loose = [dict(r) for r in con.execute(
"SELECT * FROM lessons WHERE status IN ('open','applied') AND folded_into IS NULL ORDER BY id")]
"SELECT * FROM lessons WHERE status IN ('open','applied') AND folded_into IS NULL "
"AND change_kind<>'tool' AND COALESCE(scope,'unscoped')<>'project' ORDER BY id")]
headings_chars = sum(len(retro.loose_heading(r)) + 1 for r in loose)
counter = [con.execute("SELECT COALESCE(max(id),0) FROM lessons").fetchone()[0],
con.execute("SELECT COALESCE(max(id),0) FROM occurrences").fetchone()[0]]
@@ -193,7 +200,8 @@ def _announce_save(data):
# occurrence counters (count, last_seen) and new lessons do NOT count: reading a lesson or a
# lesson arriving must never stale a brief (gaps 2 and 3).
_RELEVANT = ("aim", "change_kind", "target", "moment", "cause", "change", "status", "strength",
"folded_into", "effect", "when_terms", "check_json", "needs_cycle", "short", "topic")
"folded_into", "effect", "when_terms", "check_json", "needs_cycle", "short", "topic",
"scope", "project")
def _snapshot(con):
@@ -217,8 +225,20 @@ def _snapshot(con):
cyc = sorted(os.listdir(cycles_dir()))
except OSError:
cyc = []
learn_unscoped = []
try:
for rec in store.read("quarantine"):
if rec.get("scope") not in ("everywhere", "project") and (rec.get("text") or "").strip():
learn_unscoped.append({"text": rec.get("text"), "cwd": rec.get("cwd")})
except Exception:
pass
try:
docs_required = documents.required_documents(con)
except Exception:
docs_required = []
return {"lessons": lessons, "files": files, "rules": rules, "enforced": enf,
"last_cycle_ts": retro.get_meta(con, "last_cycle_ts") or "", "cycles": cyc}
"last_cycle_ts": retro.get_meta(con, "last_cycle_ts") or "", "cycles": cyc,
"learn_unscoped": learn_unscoped, "documents": docs_required}
def _save_snapshot(base, snap):
@@ -322,6 +342,11 @@ def cycle_records():
def _scan_files():
"""{data-relative path: bytes} for overlay/ and notes/ (everything a cycle may touch)."""
out = {}
for rel in ("handover.json", "learn-quarantine.jsonl"):
p = paths.data_file(rel)
if os.path.exists(p):
with open(p, "rb") as f:
out[rel] = f.read()
for root in ("overlay", os.path.relpath(paths.notes_dir(), paths.data())
if paths.notes_dir().startswith(paths.data() + os.sep) else None):
if not root:
@@ -422,15 +447,31 @@ Shape (all but version/base optional; full detail: `sisi cycle help`):
"rules": [{"id": "rule-id", "title": "Title", "body": "text ending with Why: ...", "action": "add|replace",
"shortens": "rule-id: what text is removed/shortened (required when the rulebook would grow in characters)"}],
"disable_rules": ["rule-id"],
"notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short",
"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",
"into": "id or [ids] (folds; entry folds append a field note)", "merged_into": 4,
"note": "text to append instead of the lesson change (for splitting one lesson)",
"when": "at least 5 terms (sets when-terms; alone with action set-when)",
"short": "one plain sentence, at most 140 characters (set-short)", "topic": "1 to 3 lower-case words, at most 30 characters (set-short)",
"entry_kind": "recipe|verifier", "entry_text": "full file text (create-entry)",
"scope": "everywhere|project (set-scope)", "project": "project id (set-scope to project)",
"reason": "why it stays a draft (keep-as-draft)"}],
"learn": [{"text": "<the exact learn statement>", "action": "set-scope", "scope": "everywhere|project",
"project": "project id (when project)"}],
"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}]}"""
{"lesson": 4, "type": "contract-requirement", "when": "parser", "require_kind": "parsing", "max_rung": 2}],
"documents": [{"doc": "recipe:<id>|verifier:<id>|rulebook", "action": "rewrite", "text": "<full new text>",
"trace": [{"lesson": 3, "fragment": "exact sentence in the new text"},
{"lesson": 4, "disposition": "moved", "to": "recipe:<id>", "fragment": "..."},
{"lesson": 5, "disposition": "merged", "merged_with": 3, "fragment": "..."},
{"lesson": 6, "disposition": "retired", "reason": "..."}],
"rule_merges": [{"from": "old-rule-id", "into": "surviving-rule-id"}],
"shortens": "what existing rule text gets shorter (rulebook, when it would grow)"},
{"doc": "verifier:<id>", "action": "reviewed", "reason": "why its structure is already right"}],
"rule_order": ["every rule id exactly once, in reading order (numbers follow it; ids stay stable)"]}
Every document the brief lists under whole-document review needs one documents entry; a rewrite
must trace every lesson folded into it, and nothing folded may be lost.
A file containing only the required set-short/set-scope entries (for lessons and learn statements) is
acceptable when nothing else is ready to fold: that is a cleanup-only round, and it is a good round."""
HELP_TEXT = """sisi cycle help: the full cycle file format (the brief is the short form)
@@ -444,7 +485,11 @@ File: write ONE JSON file at the scratch path the brief prints, then:
sisi cycle --now same: start a round on demand, even when none is due
Top level: {"version": 1 (required), "base": "<from the brief, required>", "summary": "one line",
"rules": [...], "disable_rules": [...], "notes": [...], "enforced": [...]} - all else optional.
"rules": [...], "disable_rules": [...], "notes": [...], "learn": [...], "enforced": [...],
"documents": [...], "rule_order": [...]} - all else optional, except the documents entries the
brief requires (below).
A file containing only the required set-short/set-scope entries is acceptable when nothing else
is ready to fold (a cleanup-only round).
The file covers only the lessons listed in its brief. Lessons recorded since the brief are left
for the next cycle and do not make the apply fail. Reading (`sisi lessons show ID`, `sisi done`,
`sisi verifiers show`) never stales the base: it covers only lesson content/status, rules, notes
@@ -497,6 +542,16 @@ Notes - one object per decision; the same lesson may appear several times (split
be combined with other actions on the same lesson. When the lesson is already
folded into an entry, its default field-note bullet is rewritten to the short
form; a bullet that came from an explicit `note` is left alone.
set-scope {"lesson": A, "action": "set-scope", "scope": "everywhere|project",
"project": "<project id, required when project>"} - decides where a lesson
belongs. everywhere requires its delivered text (change, short, when) to be
universal: naming the project it came from is refused, though its moment and
cause (its history) may name it freely. project moves the lesson out of the
global store into that project's handover pile (`sisi handover` there); it is
never folded into the rulebook or the general recipe/technique notes. Every
unscoped lesson in the brief needs one; lessons this file retires, withdraws or
merges away are exempt. Project-scoped lessons cannot be folded into a rule or
an entry, created into an entry, or enforced in a cycle.
keep {"lesson": A, "action": "keep"} - leave it; clears its waiting flag.
retire leave the active notes. Only when fully folded and quiet: folded into a rule,
entry or enforced check, listed/read at least 20 times, and 0 recurrences after
@@ -507,6 +562,15 @@ Notes - one object per decision; the same lesson may appear several times (split
re-learned. Tool lessons: cannot be done in a cycle (they are changes to sisi
itself) - leave them in `sisi backlog` untouched, except merging a duplicate.
Learn statements - the equivalent for `sisi learn` statements ("learn" at the top level):
{"text": "<the exact statement>", "action": "set-scope", "scope": "everywhere|project",
"project": "<project id, when project>"} - every unscoped statement in the brief needs one.
project moves it to that project's handover pile, out of the global store. Decide by what the
statement is about: how the owner wants all work done is universal (for example "always ask
questions as options with a recommendation" or "never set up scheduled jobs or timers"), while
a fact about one product's design is project (for example "this product's settings page keeps
advanced options behind one toggle" or "this app uses the left control key for search").
Enforced checks - write none for lessons below strength 3. One per strength-3 NEEDS A CHECK:
command: {"lesson": 3, "type": "command", "cmd": "program + args that exist here",
"expect": {"exit": 0} (integer exit code required; runs only in trusted projects),
@@ -517,6 +581,40 @@ Enforced checks - write none for lessons below strength 3. One per strength-3 NE
"max_rung": 2 (optional, 1-6: the required check must be at this rung or stronger)}
Complete examples are the two objects above.
Documents - every round ends with a whole-document edit. The things agents read are documents:
the rulebook ("rulebook"), each recipe ("recipe:<id>") and each technique ("verifier:<id>").
The brief prints, for every document that has appended field notes, whose personal copy no
longer matches the product text it was made from (a re-merge), or that has had no
whole-document review for the configured number of rounds, its full current text and the
lessons folded into it. Existing field-note files are listed this way until rewritten; until
then they keep being shown as before.
{"doc", "action": "reviewed", "reason"} - the structure is already right; say why in one line.
{"doc", "action": "rewrite", "text", "trace"} - the full new text, written as a proper
document by the editorial standard in the brief: one instruction per bullet or sentence; most
important first; related instructions under one heading; no duplicates; imperative, concrete,
plain words; each rule keeps its Why; exceptions beside what they qualify; no history.
A folded lesson becomes part of the document's own text where it belongs (in a recipe: Done
means, Checks, or Common false finishes), never a dated appended bullet. The personal version
lives in the overlay and records the product hash it was derived from.
trace: one entry per lesson folded into the document or already traced into it. Nothing may
be lost: {"lesson", "fragment"} - the exact sentence or bullet in the new text that carries
it (whitespace-normalised; it must occur); {"lesson", "disposition": "moved", "to", "fragment"}
- it lives in that other document now, as that fragment there; {"lesson", "disposition":
"merged", "merged_with", "fragment"} - both lessons point at the same fragment; {"lesson",
"disposition": "retired", "reason"} - only under the retirement rule for retire above.
The trace map is stored beside the document, not in the text agents load; `sisi lessons
show ID`, `sisi rule N` and `sisi done ID --trace` print where a lesson lives.
A rewrite is refused when: the rulebook would pass its line or character budget; a rule lacks
its heading with id, its Why, or its generated More line; a recipe or technique fails the
library lint; a line stays over the house width after wrapping; a bullet over the configured
length ends more than one sentence; or the text holds a dated journal-style bullet. For the
rulebook, every existing rule id must survive or be named in "rule_merges"
({"from", "into"}) with the survivor present, and any growth needs "shortens" as for rules.
"rule_order" (top level, or the order of a rulebook rewrite) reorders the book: it names
every rule id exactly once; ids stay stable, numbers follow the order, and stored data
refers to rules by id, never by number. `sisi cycle status` shows, per rewritten document,
recurrences of its lessons before and after the rewrite, and flags a rewrite followed by more.
Learned-notes limit: counts length(change) of active strength-1 loose learned notes only
(limit 4000 characters). It still counts `change`, not `short`: it is about lesson content not
yet folded. Delivery budgets for printed headings (session start, the other-lessons list) count
@@ -559,6 +657,23 @@ def brief_text():
missing_short = [r for r in rows if r["status"] in retro.ACTIVE
and (not str(r.get("short") or "").strip() or not str(r.get("topic") or "").strip())]
topics_in_use = _topics_in_use(con)
unscoped = [r for r in rows if r["status"] in retro.ACTIVE
and retro._get(r, "scope") in (None, "", "unscoped")]
unscoped_repos = {}
for r in unscoped:
o = con.execute("SELECT repo, cwd FROM occurrences WHERE lesson_id=? ORDER BY id LIMIT 1", (r["id"],)).fetchone()
unscoped_repos[r["id"]] = (o[0] or o[1]) if o else None
try:
docs_required = documents.required_documents(con)
docs_folded = {d["doc"]: documents.folded_lesson_ids(con, d["kind"], d["id"])
for d in docs_required}
except Exception:
docs_required, docs_folded = [], {}
from . import scope as _scope_mod
learn_unscoped = []
for _lrec in store.read("quarantine"):
if _lrec.get("scope") not in _scope_mod.SCOPES and (_lrec.get("text") or "").strip():
learn_unscoped.append(_lrec)
finally:
con.close()
from . import verifiers as V
@@ -657,6 +772,67 @@ def brief_text():
"Topics already in use: " + (", ".join(topics_in_use) if topics_in_use else "(none yet)"),
"Lessons lacking a short line or topic: " +
(", ".join("#%d" % r["id"] for r in missing_short) if missing_short else "(none)"), ""]
if unscoped or learn_unscoped:
out += ["", "Scope cleanup (backfill): every item below was recorded before scopes existed. "
"Give each a set-scope (lessons: {\"lesson\": A, \"action\": \"set-scope\", \"scope\": "
"\"everywhere|project\", \"project\": \"<id, when project>\"}; learn statements: a "
"\"learn\" entry, see `sisi cycle help`). Scoping to a project moves the item out of "
"the global store into that project's handover pile. A lesson whose instruction is "
"universal stays global even when its history (moment, cause) names a project. A file "
"containing only the required set-short/set-scope entries is acceptable when nothing "
"else is ready to fold (a cleanup-only round; `sisi cycle --now` starts one now).",
"For learn statements: how the owner wants all work done is universal (\"always ask "
"questions as options with a recommendation\"; \"never set up scheduled jobs\"); a fact "
"about one product's design is project (\"this product's settings page keeps advanced "
"options behind one toggle\"; \"this app uses the left control key for search\")."]
for r in unscoped:
out.append(" lesson #%d recorded in %s: %s" % (r["id"], unscoped_repos.get(r["id"]) or "(unknown repository)",
" ".join(str(r.get("change") or "").split())[:120]))
for rec in learn_unscoped:
pid = ""
try:
if rec.get("cwd"):
pid = " (project id there: %s)" % _scope_mod.project_id(rec["cwd"])
except Exception:
pass
out.append(" learn statement recorded in %s%s: %r" % (rec.get("cwd") or "(unknown repository)", pid,
" ".join(str(rec["text"]).split())[:120]))
out.append("")
out += ["", "Documents for whole-document review (every round ends with a whole-document edit):",
"Editorial standard - "
+ " ".join(documents.EDITORIAL_STANDARD),
"For each document below your file needs a documents entry: a rewrite (the full new "
"text, with each folded lesson integrated where it belongs and a trace entry giving "
"the exact fragment that carries it - or a moved/merged/retired disposition), or a "
"reviewed entry with a one-line reason why its structure is already right. "
"`sisi cycle check` refuses a file that skips a listed document, a rewrite that "
"leaves a lesson untraced, and any text that fails the structure checks (budgets, "
"headings and Why, the library lint, the %d-character house width after wrapping, "
"run-on bullets, dated journal bullets). A document is listed when it has appended "
"field notes, when its personal copy no longer matches the product text it was made "
"from (re-merge it), or when it has had no whole-document review for %d rounds."
% (overlay.HOUSE_WIDTH, documents.review_every_rounds())]
if not docs_required:
out.append(" (none this round)")
_rows_by_id = {r["id"]: r for r in rows}
for _d in docs_required:
out.append("")
out.append("Document %s - %s" % (_d["doc"], "; ".join(_d["reasons"])))
for _lid in docs_folded.get(_d["doc"], []):
_r = _rows_by_id.get(_lid)
if _r:
out.append(" lesson #%d folded here: %s (full text: sisi lessons show %d)"
% (_lid, " ".join(str(_r.get("change") or "").split()), _lid))
if _r.get("short"):
out.append(" short: %s" % " ".join(str(_r["short"]).split()))
if _d["kind"] != "rulebook":
_notes = retro.notes_for(_d["id"])
if _notes:
out.append(" appended field notes (integrate these, do not copy the dates):")
out += [" " + _l for _l in _notes.splitlines()]
out.append(" ----- %s: current text -----" % _d["doc"])
out += documents.effective_text(_d["kind"], _d["id"]).rstrip("\n").split("\n")
out.append(" ----- end of %s -----" % _d["doc"])
out += ["Do this, in order:",
"1. Fold each loose lesson into the recipe/entry whose applies-to (above) fits its kind of "
"work, or lift several into one general rule. fold-into-entry appends a field note (see help). "
@@ -665,7 +841,8 @@ def brief_text():
"2. Merge only lessons requesting the same change (not just the same topic), into the older "
"or more general one; the survivor keeps its text and occurrence count. Superseded, retired "
"and withdrawn lessons need no action.",
"3. Tool lessons (kind tool) cannot be done in a cycle: leave them in `sisi backlog` untouched, except merging a duplicate.",
"3. Tool lessons (kind tool) cannot be done in a cycle: leave them in `sisi backlog` untouched, except merging a duplicate. When a tool lesson's change has been built, close it outside the cycle file with `sisi lessons set ID --status applied`; it then leaves the backlog and the digest stops calling it not built yet.",
"3b. Project-scoped lessons cannot be folded into the rulebook or the general recipe/technique notes in a cycle, and unscoped items each need a set-scope above (scoping to a project moves the item to that project's handover pile).",
"4. Rules: keep id and Why, format per help; name in `shortens` which existing rule text gets shorter or is replaced whenever a rule is added or the book would grow in characters.",
"5. For each NEEDS A CHECK lesson write one enforced check (help has fields and examples); none below strength 3.",
"6. For every lesson listed above as lacking a short line or topic, add a set-short (it may sit "
@@ -673,6 +850,10 @@ def brief_text():
"7. Retire only what is fully folded and quiet (folded, at least 20 listed/read, 0 recurrences "
"after first listed) - folding now does not make it quiet, so fold and keep, retire next cycle. "
"Withdraw what made things worse. set-when only sets when-terms. Keep the rest.",
"8. End with the whole-document edit above: for every listed document, rewrite it as a "
"proper document by the editorial standard (lessons integrated into its own sections, "
"each traced to the fragment that carries it) or mark it reviewed with a reason. "
"Nothing folded may be lost: moved, merged and retired lessons are named as such.",
"Every changed rule keeps its id and ends with its Why. Never ask the human anything.", "", FORMAT_DOC]
return "\n".join(out) + "\n"
@@ -707,6 +888,13 @@ def _lesson_ids_in(doc):
for k in ("lesson", "merged_into"):
if isinstance(e.get(k), int):
ids.add(e[k])
for e in doc.get("documents") or []:
if isinstance(e, dict):
for t in e.get("trace") or []:
if isinstance(t, dict):
for k in ("lesson", "merged_with"):
if isinstance(t.get(k), int):
ids.add(t[k])
return ids
@@ -786,16 +974,79 @@ def static_validate(doc, con):
if rid not in base_rule_ids | over_ids:
errs.append("no rule %s to disable.%s" % (rid, _suggest(rid, base_rule_ids | over_ids)))
kinds = {}
scopes = {}
try:
kinds = {r[0]: r[1] for r in con.execute("SELECT id, change_kind FROM lessons")}
scopes = {r[0]: (r[1] or "unscoped") for r in con.execute("SELECT id, scope FROM lessons")}
except Exception:
pass
from . import scope as _scmod
for e in doc.get("notes") or []:
if not isinstance(e, dict):
continue
lid, act = e.get("lesson"), e.get("action")
if scopes.get(lid) == "project" and act in ("fold-into-rule", "fold-into-entry", "create-entry"):
errs.append("lesson %s: project-scoped items can never be folded into the rulebook or the "
"general recipe/technique notes in a cycle" % lid)
if act == "set-scope":
if e.get("scope") not in _scmod.SCOPES:
errs.append("lesson %s: set-scope needs scope everywhere|project" % lid)
elif e["scope"] == "project" and not (e.get("project") or "").strip():
errs.append("lesson %s: set-scope to project needs \"project\" naming the project id" % lid)
elif e["scope"] == "everywhere" and isinstance(lid, int) and lid in kinds:
try:
row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()
occ = con.execute("SELECT repo FROM occurrences WHERE lesson_id=? ORDER BY id LIMIT 1", (lid,)).fetchone()
origin = occ[0] if occ and occ[0] and os.path.isdir(occ[0]) else os.getcwd()
reason = _scmod.universal_refusal(
[e.get("short") or (row["change"] if row else ""), row["change"] if row else "",
e.get("when") or (row["when_terms"] if row else "")], origin, kind=kinds.get(lid))
if reason:
errs.append("lesson %s: cannot set-scope everywhere: %s; rewrite it in general "
"terms or scope it to its project" % (lid, reason))
except Exception:
pass
for e in doc.get("enforced") or []:
if isinstance(e, dict) and scopes.get(e.get("lesson")) == "project":
errs.append("lesson %s: project-scoped items can never be folded into the rulebook or the "
"general recipe/technique notes in a cycle" % e.get("lesson"))
learn_recs = []
try:
learn_recs = store.read("quarantine")
except Exception:
pass
unscoped_learn = [r for r in learn_recs if r.get("scope") not in _scmod.SCOPES and (r.get("text") or "").strip()]
covered_learn = set()
for e in doc.get("learn") or []:
if not isinstance(e, dict) or e.get("action") != "set-scope":
errs.append("each learn entry needs action set-scope: %r" % (e,))
continue
covered_learn.add(e.get("text"))
if e.get("scope") not in _scmod.SCOPES:
errs.append("learn %r: set-scope needs scope everywhere|project" % (e.get("text"),))
elif e["scope"] == "project" and not (e.get("project") or "").strip():
errs.append("learn %r: set-scope to project needs \"project\" naming the project id" % (e.get("text"),))
elif not any(r.get("text") == e.get("text") for r in unscoped_learn):
errs.append("learn %r: no unscoped learn statement with that exact text" % (e.get("text"),))
elif e["scope"] == "everywhere":
origin = next((r.get("cwd") for r in unscoped_learn if r.get("text") == e.get("text")), None)
if origin and os.path.isdir(origin):
reason = _scmod.universal_refusal([e.get("text")], origin)
if reason:
errs.append("learn %r: cannot set-scope everywhere: %s" % (e.get("text"), reason))
if isinstance(doc, dict) and doc.get("base"):
old = _load_snapshot(doc["base"])
if old and isinstance(old.get("learn_unscoped"), list):
for rec in old["learn_unscoped"]:
if rec.get("text") and rec["text"] not in covered_learn:
errs.append("learn statement %r: missing set-scope - add {\"text\": ..., \"action\": "
"\"set-scope\", \"scope\": \"everywhere|project\"}" % (rec["text"],))
for e in doc.get("notes") or []:
if not isinstance(e, dict) or e.get("action") not in ACTIONS:
errs.append("each note needs an action in %s: %r" % (", ".join(ACTIONS), e))
continue
lid = e.get("lesson")
if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when", "set-short"):
if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when", "set-short", "set-scope"):
errs.append("lesson %s: tool lessons cannot be done in a cycle (they change sisi itself); "
"leave them in `sisi backlog` untouched, except merging a duplicate" % lid)
if e["action"] == "set-short":
@@ -888,6 +1139,39 @@ def static_validate(doc, con):
errs.append("lesson %d: missing set-short (%s) - the brief listed this lesson as needing "
"a short line; add {\"lesson\": %d, \"action\": \"set-short\", \"short\": \"...\", \"topic\": \"...\"}"
% (lid, " and ".join(need), lid))
# Every active lesson that was unscoped in the brief needs a set-scope here (same exemption
# as set-short: lessons this file retires, withdraws or merges away are exempt).
if isinstance(doc, dict) and doc.get("base"):
old = _load_snapshot(doc["base"])
if old and isinstance(old.get("lessons"), dict):
notes_list = [e for e in doc.get("notes") or [] if isinstance(e, dict)]
scoped_ids = {e.get("lesson") for e in notes_list if e.get("action") == "set-scope"}
exempt = {e.get("lesson") for e in notes_list if e.get("action") in ("retire", "withdraw", "merge")}
for lid_s, v in old["lessons"].items():
if not isinstance(v, dict) or v.get("status") not in retro.ACTIVE:
continue
if v.get("scope") not in (None, "", "unscoped"):
continue
try:
lid = int(lid_s)
except ValueError:
continue
if lid in exempt or lid in scoped_ids:
continue
errs.append("lesson %d: missing set-scope - the brief listed this lesson as unscoped; add "
"{\"lesson\": %d, \"action\": \"set-scope\", \"scope\": \"everywhere|project\"}"
% (lid, lid))
# Whole-document entries: every document the brief listed needs a rewrite or a reviewed
# entry, and a rewrite must trace every lesson folded into it (see sisi.documents).
required_docs = None
if isinstance(doc, dict) and doc.get("base"):
old = _load_snapshot(doc["base"])
if old and isinstance(old.get("documents"), list):
required_docs = old["documents"]
try:
errs.extend(documents.validate_documents(doc, con, required_docs))
except Exception as ex:
errs.append("documents: %s" % ex)
return errs
@@ -961,6 +1245,9 @@ def _apply_writes(doc, con):
if sets:
con.execute("UPDATE lessons SET %s WHERE id=?" % ", ".join(sets), vals + [lid])
retro.rewrite_notes_for_lesson(con, lid)
elif act == "set-scope":
con.execute("UPDATE lessons SET scope=?, project=? WHERE id=?",
(e.get("scope"), (e.get("project") or None) if e.get("scope") == "project" else None, lid))
elif act == "keep-as-draft":
con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,))
elif act == "set-when":
@@ -971,7 +1258,43 @@ def _apply_writes(doc, con):
con.execute("UPDATE lessons SET status='withdrawn', needs_cycle=0 WHERE id=?", (lid,))
else: # keep
con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,))
return sorted(touched)
# project-scoped lessons leave the global store for their project's handover pile
from . import handover as _ho
for e in doc.get("notes") or []:
if isinstance(e, dict) and e.get("action") == "set-scope" and e.get("scope") == "project":
_ho.move_lesson(con, e["lesson"], e.get("project"))
docs_changed = documents.apply_documents(doc, con, touched)
_apply_learn(doc)
return sorted(touched), docs_changed
def _apply_learn(doc):
"""Apply the learn set-scope entries: everywhere stamps the statement; project moves it
out of the global store into that project's handover pile."""
entries = [e for e in doc.get("learn") or [] if isinstance(e, dict)]
if not entries:
return
from . import handover as _ho
recs = store.read("quarantine")
by_text = {e.get("text"): e for e in entries}
kept = []
for rec in recs:
e = by_text.get(rec.get("text"))
if e is None or rec.get("scope") in ("everywhere", "project"):
kept.append(rec)
elif e.get("scope") == "project":
_ho.move_learn(rec, e.get("project"))
else:
rec = dict(rec, scope="everywhere")
rec.pop("project", None)
kept.append(rec)
p = store.file_path("quarantine")
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
for rec in kept:
f.write(json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n")
os.replace(tmp, p)
def apply_file(path):
@@ -996,7 +1319,7 @@ def apply_file(path):
before_chars = before_m.get("rulebook_chars")
prev_last = retro.get_meta(con, "last_cycle_ts")
try:
touched = _apply_writes(doc, con)
touched, docs_changed = _apply_writes(doc, con)
# create-entry files must pass the existing library lint
from . import verifiers as _V
for e in doc.get("notes") or []:
@@ -1008,8 +1331,11 @@ def apply_file(path):
% (into, "; ".join(bad)))
con.commit()
built = overlay.build_canon()
has_replace = any(e.get("action") == "replace" for e in doc.get("rules") or [])
has_shortens = any(e.get("shortens") for e in doc.get("rules") or []) or bool(doc.get("disable_rules"))
_doc_entries = [e for e in doc.get("documents") or [] if isinstance(e, dict)]
has_replace = any(e.get("action") == "replace" for e in doc.get("rules") or []) or \
any(e.get("doc") == "rulebook" and e.get("action") == "rewrite" for e in _doc_entries)
has_shortens = any(e.get("shortens") for e in doc.get("rules") or []) or bool(doc.get("disable_rules")) or \
any(e.get("shortens") for e in _doc_entries) or bool(doc.get("rule_order"))
if before_chars is not None and built["chars"] > before_chars and not has_shortens:
raise CycleError("the rulebook would grow from %d to %d characters (and %d to %d lines). "
"A cycle must not increase the characters unless its rules name in "
@@ -1034,15 +1360,21 @@ def apply_file(path):
cid = "cycle-%04d" % (int(cid.split("-")[1]) + 1)
ts = store.now()
rec = {"id": cid, "ts": ts, "summary": doc.get("summary") or "", "base": doc["base"],
"touched": touched, "before": before_m, "after": measures(con),
"touched": touched, "documents_changed": sorted(docs_changed),
"document_lessons": docs_changed,
"before": before_m, "after": measures(con),
"lessons_before": [before_rows[i] for i in touched if i in before_rows],
"changed_files": changed, "prev_last_cycle_ts": prev_last, "reverted": None}
os.makedirs(cycles_dir(), exist_ok=True)
pdata.write_text(os.path.join("cycles", cid + ".json"), json.dumps(rec, indent=1, sort_keys=True) + "\n")
retro.set_meta(con, "last_cycle_ts", ts)
con.commit()
try:
os.unlink(os.path.join(paths.state(), "cycle-bases", doc["base"] + ".json"))
except OSError:
pass # the round is closed now; its snapshot no longer defers retirement
retro.export_jsonl()
specs = ["overlay", "lessons.jsonl", "cycles"]
specs = ["overlay", "lessons.jsonl", "cycles", "handover.json", "learn-quarantine.jsonl"]
if paths.notes_dir().startswith(paths.data() + os.sep):
specs.append(os.path.relpath(paths.notes_dir(), paths.data()))
if pdata._commit("cycle %s: %s" % (cid, rec["summary"] or "consolidation"), specs) is None \
@@ -1054,9 +1386,7 @@ def apply_file(path):
for rel, b in _scan_files().items() if before_files.get(rel) != b} |
{rel: base64.b64encode(b).decode() for rel, b in before_files.items()})
for row in before_rows.values():
cols = [c for c in retro.LESSON_COLS if c != "id"]
con.execute("UPDATE lessons SET %s WHERE id=?" % ",".join(c + "=?" for c in cols),
[row.get(c) for c in cols] + [row["id"]])
_restore_lesson_row(con, row)
if prev_last is None:
con.execute("DELETE FROM meta WHERE key='last_cycle_ts'")
else:
@@ -1072,6 +1402,20 @@ def apply_file(path):
con.close()
def _restore_lesson_row(con, row):
"""Put a lesson row back exactly, recreating it when the cycle moved it to the handover pile."""
cols = [c for c in retro.LESSON_COLS if c in row]
have = [r[1] for r in con.execute("PRAGMA table_info(lessons)")]
cols = [c for c in cols if c in have]
if con.execute("SELECT 1 FROM lessons WHERE id=?", (row["id"],)).fetchone():
sets = [c for c in cols if c != "id"]
con.execute("UPDATE lessons SET %s WHERE id=?" % ",".join(c + "=?" for c in sets),
[row.get(c) for c in sets] + [row["id"]])
else:
con.execute("INSERT INTO lessons(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))),
[row.get(c) for c in cols])
def revert_cycle(cid=None):
"""Undo one cycle exactly: the bytes it changed and the lesson rows it touched. Only the newest
cycle that has not been reverted can go, so the undo can be exact."""
@@ -1088,9 +1432,7 @@ def revert_cycle(cid=None):
with pdata.lock():
_restore_changed(rec.get("changed_files") or {})
for row in rec.get("lessons_before") or []:
cols = [c for c in retro.LESSON_COLS if c != "id" and c in row]
con.execute("UPDATE lessons SET %s WHERE id=?" % ",".join(c + "=?" for c in cols),
[row.get(c) for c in cols] + [row["id"]])
_restore_lesson_row(con, row)
prev = rec.get("prev_last_cycle_ts")
if prev is None:
con.execute("DELETE FROM meta WHERE key='last_cycle_ts'")
@@ -1102,7 +1444,7 @@ def revert_cycle(cid=None):
rec = dict(rec, reverted=store.now())
pdata.write_text(os.path.join("cycles", rec["id"] + ".json"),
json.dumps(rec, indent=1, sort_keys=True) + "\n")
specs = ["overlay", "lessons.jsonl", "cycles"]
specs = ["overlay", "lessons.jsonl", "cycles", "handover.json", "learn-quarantine.jsonl"]
if paths.notes_dir().startswith(paths.data() + os.sep):
specs.append(os.path.relpath(paths.notes_dir(), paths.data()))
pdata._commit("cycle revert %s" % rec["id"], specs)
@@ -1117,6 +1459,36 @@ def _fmt_med(m):
return delivery.fmt_s(m) if m is not None else "-"
def _doc_recurrences(rec):
"""{doc: (before, after)} -- recurrences (sightings past each lesson's first) of the lessons
a rewritten document carries, before and after the rewrite landed."""
out = {}
per_doc = rec.get("document_lessons") or {}
if not per_doc:
return out
con = _connect_if()
if con is None:
return out
ts = rec.get("ts") or ""
try:
for key, ids in sorted(per_doc.items()):
before = after = 0
for lid in ids or []:
occ = [r[0] for r in con.execute(
"SELECT ts FROM occurrences WHERE lesson_id=? ORDER BY id", (lid,))]
for i, t in enumerate(occ):
if i == 0:
continue # the first sighting made the lesson; later ones are recurrences
if t < ts:
before += 1
else:
after += 1
out[key] = (before, after)
finally:
con.close()
return out
def status_lines():
recs = cycle_records()
if not recs:
@@ -1130,6 +1502,11 @@ def status_lines():
out.append(" since: %d deliveries, %s send-backs each, median %s, %d recurrence(s) of touched lessons"
% (a["deliveries"], a["send_backs_per_delivery"], _fmt_med(a["median_seconds"]),
a["recurrences_of_touched"]))
for key, (before, after) in sorted(_doc_recurrences(r).items()):
flag = " MORE RECURRENCES AFTER THE REWRITE - revert or repair" \
if not r.get("reverted") and after > before else ""
out.append(" document %s rewritten: %d recurrence(s) of its lessons before, %d after%s"
% (key, before, after, flag))
return out
@@ -1260,12 +1637,46 @@ def check_file(path):
extra += " short=%r" % e["short"][:60]
if e.get("topic"):
extra += " topic=%r" % e["topic"][:60]
if e.get("scope"):
extra += " scope=%s%s" % (e["scope"], (" project=%s" % e["project"]) if e.get("project") else "")
out.append(" lesson %s: %s%s" % (e.get("lesson"), e.get("action"), extra))
for e in doc.get("learn") or []:
out.append(" learn %r: set-scope %s%s" % (str(e.get("text"))[:60], e.get("scope"),
(" project=%s" % e["project"]) if e.get("project") else ""))
for e in doc.get("enforced") or []:
out.append(" lesson %s: enforced %s %s" % (e.get("lesson"), e.get("type"),
e.get("cmd") or ("when=%s require_kind=%s" % (e.get("when"), e.get("require_kind")))))
for e in doc.get("documents") or []:
if e.get("action") == "rewrite":
traced = ", ".join("#%s" % t.get("lesson") for t in e.get("trace") or []
if isinstance(t, dict)) or "-"
out.append(" document %s: rewrite (%d characters; lessons traced: %s)"
% (e.get("doc"), len(e.get("text") or ""), traced))
else:
out.append(" document %s: reviewed (%s)" % (e.get("doc"), e.get("reason") or ""))
if doc.get("rule_order"):
out.append(" rule order: %s" % ", ".join(doc["rule_order"]))
# predicted rulebook size with the rules applied in memory
try:
cand_doc = documents.candidate_rulebook(doc)
if cand_doc is not None:
lines, chars = overlay.size(cand_doc)
out.append(" rulebook: %s lines, %s characters -> %d lines, %d characters "
"(budgets %d lines, %d characters)"
% (before["rulebook_lines"], before.get("rulebook_chars"), lines, chars,
overlay.MAX_LINES, overlay.MAX_CHARS))
_entries = [e for e in doc.get("documents") or [] if isinstance(e, dict)]
has_shortens = any(e.get("shortens") for e in doc.get("rules") or []) \
or bool(doc.get("disable_rules")) or any(e.get("shortens") for e in _entries) \
or bool(doc.get("rule_order"))
if chars > overlay.MAX_CHARS or lines > overlay.MAX_LINES:
raise CycleError("the rulebook would be %d lines and %d characters; budgets are %d and %d"
% (lines, chars, overlay.MAX_LINES, overlay.MAX_CHARS))
if before.get("rulebook_chars") is not None and chars > before["rulebook_chars"] and not has_shortens:
raise CycleError("the rulebook would grow from %d to %d characters; add `shortens` naming "
"which existing rule text gets shorter or is replaced"
% (before["rulebook_chars"], chars))
return out
pre, rules = overlay.effective()
by_id = {r["id"]: dict(r) for r in rules}
order = [r["id"] for r in rules]
@@ -1338,8 +1749,11 @@ def cmd_cycle(args):
print("usage: sisi cycle apply FILE")
return 2
rec = apply_file(args[1])
print("applied %s: %s (rulebook %s lines; committed to the personal repository)"
% (rec["id"], rec["summary"] or "consolidation", rec["after"]["rulebook_lines"]))
print("applied %s: %s (rulebook %s lines, %s characters -> %s lines, %s characters; "
"committed to the personal repository)"
% (rec["id"], rec["summary"] or "consolidation",
rec["before"]["rulebook_lines"], rec["before"].get("rulebook_chars"),
rec["after"]["rulebook_lines"], rec["after"].get("rulebook_chars")))
return 0
if sub == "revert":
rec = revert_cycle(args[1] if len(args) > 1 else None)
+790
View File
@@ -0,0 +1,790 @@
"""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.
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.
"""
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+`.*$")
def _cfg(key, default):
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):
return "rulebook" if kind == "rulebook" else "%s:%s" % (kind, id)
def parse_doc_key(key):
if key == "rulebook":
return "rulebook", "rulebook"
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
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
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 _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()
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")]
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)
folded = folded_lesson_ids(con, kind, id)
traced = {int(k) for k in trace_entries(kind, id) if str(k).isdigit()}
covered = set((reviews.get(key) or {}).get("covered") or [])
unintegrated = [i for i in folded if i not in traced and i not in covered]
reasons = []
if unintegrated:
reasons.append("appended field notes not yet integrated into the document's own text"
if kind != "rulebook" else
"lessons folded into rules are not yet traced to the text that carries them")
stale = _stale_reason(kind, id)
if stale:
reasons.append(stale)
eligible = kind == "rulebook" or bool(folded) or bool(traced) or _personal_exists(kind, id)
last = int((reviews.get(key) or {}).get("round") or 0)
if eligible and rounds >= every and rounds - last >= every:
reasons.append("no whole-document review for %d rounds" % (rounds - last))
if reasons:
out.append({"doc": key, "kind": kind, "id": id, "reasons": reasons,
"lessons": unintegrated})
return out
# ---- structure checks ---------------------------------------------------------
def _bullets(text):
"""Joined bullet texts (a bullet plus its indented continuation lines)."""
out, cur = [], None
for line in text.split("\n"):
if re.match(r"^\s*[-*]\s+", line):
if cur is not None:
out.append(cur)
cur = line.strip()
elif cur is not None and line.startswith(" ") and line.strip():
cur += " " + line.strip()
elif cur is not None:
out.append(cur)
cur = None
if cur is not None:
out.append(cur)
return out
def _sentence_count(text):
t = re.sub(r"`[^`]*`", " ", text) # code spans are not prose
t = re.sub(r"https?://\S+", " ", t)
return len(re.findall(r"[.!?]+(?=\s+[A-Z0-9\"']|\s*$)", t))
def wrap_text(text, width=overlay.HOUSE_WIDTH):
"""Wrap prose paragraphs and bullets to the house width. Front matter, code fences,
indented code, tables and headings are left alone."""
lines = text.split("\n")
out, i, fence, front = [], 0, False, bool(lines and lines[0].strip() == "---")
while i < len(lines):
line = lines[i]
if front:
out.append(line)
if i > 0 and line.strip() == "---":
front = False
i += 1
continue
if line.strip().startswith("```"):
fence = not fence
out.append(line); i += 1; continue
if fence or not line.strip() or line.startswith((" ", "\t", "|", "#")):
out.append(line); i += 1; continue
m = re.match(r"^(\s*)([-*]|\d+\.)\s+(.*)$", line)
if m:
indent, marker, rest = m.groups()
parts = [rest]
i += 1
while i < len(lines) and lines[i].startswith(" ") and lines[i].strip() \
and not re.match(r"^\s*[-*]\s+", lines[i]):
parts.append(lines[i].strip()); i += 1
joined = " ".join(parts)
sub = indent + " " * (len(marker) + 1)
wrapped = textwrap.wrap(joined, width=width, initial_indent="%s%s " % (indent, marker),
subsequent_indent=sub, break_long_words=False,
break_on_hyphens=False)
out.extend(wrapped or ["%s%s " % (indent, marker)])
continue
parts = [line.strip()]
i += 1
while i < len(lines) and lines[i].strip() and not lines[i].startswith((" ", "\t", "|", "#")) \
and not re.match(r"^\s*([-*]|\d+\.)\s+", lines[i]) \
and not lines[i].strip().startswith("```"):
parts.append(lines[i].strip()); i += 1
out.extend(textwrap.wrap(" ".join(parts), width=width, break_long_words=False,
break_on_hyphens=False) or [""])
return "\n".join(out)
def _long_line_problems(text):
wrapped = wrap_text(text)
out, fence, front = [], False, wrapped.startswith("---")
for n, line in enumerate(wrapped.split("\n"), 1):
if front:
if n > 1 and line.strip() == "---":
front = False
continue
if line.strip().startswith("```"):
fence = not fence
continue
if fence or line.startswith((" ", "\t", "|")):
continue
if len(line) > overlay.HOUSE_WIDTH:
out.append("line %d is %d characters after wrapping (house width %d)"
% (n, len(line), overlay.HOUSE_WIDTH))
return out
def _entry_lint_problems(kind, text, doc_id):
"""The library lint for one candidate entry, mirroring `verifiers.lint()`."""
from . import contract as C, verifiers as V
tmp = tempfile.NamedTemporaryFile("w", suffix=".md", prefix=(doc_id or "entry") + "-",
delete=False, encoding="utf-8")
try:
tmp.write(text); tmp.close()
# parse under the entry's own file name so the id-equals-stem check means something
named = os.path.join(os.path.dirname(tmp.name), (doc_id or "entry") + ".md")
os.replace(tmp.name, named)
e = V.parse(named)
finally:
for p in (tmp.name, os.path.join(os.path.dirname(tmp.name), (doc_id or "entry") + ".md")):
try:
os.unlink(p)
except OSError:
pass
out = list(e["problems"])
h = e["header"]
if not h:
return out or ["no header block"]
keys, heads = (V.V_KEYS, V.V_HEADINGS) if kind == "verifier" else (V.D_KEYS, V.D_HEADINGS)
for k in keys:
if k not in h or (not h[k] and k != "detect"):
out.append("missing or empty %r" % k)
if doc_id and h.get("id") and h["id"] != doc_id:
out.append("header id %r must equal the document id %r" % (h["id"], doc_id))
for m in V._missing_headings(e["body"], heads):
out.append("body lacks the heading %r" % m)
if kind == "verifier":
if not re.fullmatch(r"[1-6]", h.get("rung", "")):
out.append("rung must be an integer 1-6")
if h.get("section") and h["section"] not in V.SECTIONS:
out.append("unknown section %r" % h["section"])
if h.get("cost") and h["cost"] not in V.COSTS:
out.append("cost must be one of %s" % ", ".join(V.COSTS))
if h.get("ran_here") and h["ran_here"] not in ("yes", "no"):
out.append("ran_here must be yes or no")
for k in V._list(h.get("kinds")):
if k != "any" and k not in C.KINDS:
out.append("unknown kind %r" % k)
else:
known = {x["id"] for x in V.load_verifiers()} | set(overlay.disabled("verifier"))
fake = dict(e, body=e["body"])
for i in dict.fromkeys(V.cited_ids(fake)):
if i not in known:
out.append("Checks cites unknown verifier id %r" % i)
return out
def rulebook_problems(text):
out = []
pre, rules = overlay.parse_rules(text)
headings = [l for l in text.split("\n") if l.startswith("## ")]
if len(headings) != len(rules):
out.append("the rulebook text does not parse into rules")
seen = set()
for line, r in zip(headings, rules):
if not overlay.ID_TAIL.search(line):
out.append("rule heading %r lacks its {#id}" % line[:60])
if r["id"] in seen:
out.append("duplicate rule id %r" % r["id"])
seen.add(r["id"])
if not any(p.lstrip().startswith("Why:") for p in r["body"].split("\n\n")):
out.append("rule %s lacks its Why paragraph" % r["id"])
cand = candidate_render(pre, rules)
lines, chars = overlay.size(cand)
if lines > overlay.MAX_LINES or chars > overlay.MAX_CHARS:
out.append("the rulebook would be %d lines and %d characters; the budgets are %d lines "
"and %d characters" % (lines, chars, overlay.MAX_LINES, overlay.MAX_CHARS))
for n in range(1, len(rules) + 1):
if overlay.more_line(n) not in cand:
out.append("rule %d lacks its generated `More: sisi rule %d` line" % (n, n))
return out
def candidate_render(pre, rules):
try:
head = overlay.render().splitlines()[0]
except Exception:
head = "<!-- candidate rulebook -->"
parts = [head]
if (pre or "").strip():
parts.append(pre)
for n, r in enumerate(rules, 1):
body = "\n".join(l for l in r["body"].split("\n") if not MORE_LINE.match(l.strip()))
parts.append("## %d. %s {#%s}\n\n%s\n%s" % (n, r["title"], r["id"], body.strip("\n"),
overlay.more_line(n)))
return "\n\n".join(parts) + "\n"
def structure_problems(kind, text, doc_id=None):
"""Mechanical refusals for a rewritten document. Empty means the structure is acceptable.
The bullet test is deliberately simple: one bullet, once it passes the configured length
(default %d characters), may not end more than one sentence.""" % DEFAULT_MAX_BULLET_CHARS
out = []
for n, line in enumerate(text.split("\n"), 1):
if DATED_BULLET.match(line):
out.append("line %d is a dated journal-style bullet; integrate it into the "
"document's own text instead" % n)
limit = max_bullet_chars()
for b in _bullets(text):
if len(b) > limit and _sentence_count(b) > 1:
out.append("a bullet of %d characters holds %d sentences; one instruction per "
"bullet (limit %d characters): %r" % (len(b), _sentence_count(b), limit, b[:60]))
out.extend(_long_line_problems(text))
if kind == "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\", \"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\", \"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)
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 == "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)
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
+222
View File
@@ -0,0 +1,222 @@
"""Project handover pile: project-scoped items leave the global store.
Scoping a lesson or a `sisi learn` statement to a project moves it here: a pile in
the personal store, keyed by project id, kept only until an agent files it in that
project's own design documentation or work list and confirms with
`sisi handover done ID --where PATH`. After confirmation the item is gone from
every global listing; a small filed log (id, project, path, date) keeps the trace,
and the personal store's git history keeps the rest.
"""
import json, os
from . import paths, scope, store
def pile_path():
return paths.data_file("handover.json")
def filed_path():
return paths.data_file("handover-filed.jsonl")
def load_pile():
try:
with open(pile_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, list) else []
except (OSError, ValueError):
return []
def save_pile(items):
os.makedirs(os.path.dirname(pile_path()), exist_ok=True)
tmp = pile_path() + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
json.dump(items, f, indent=1, sort_keys=True, ensure_ascii=False)
f.write("\n")
os.replace(tmp, pile_path())
def _next_hid(items):
n = len(items)
try:
with open(filed_path(), encoding="utf-8") as f:
n += sum(1 for _ in f)
except OSError:
pass
return "h%d" % (n + 1)
def add_item(item):
items = load_pile()
item = dict(item)
item.setdefault("hid", _next_hid(items))
item.setdefault("date", store.now())
items.append(item)
save_pile(items)
return item
def for_project(pid):
return [it for it in load_pile() if it.get("project") == pid]
def counts_by_project():
out = {}
for it in load_pile():
out[it.get("project") or ""] = out.get(it.get("project") or "", 0) + 1
return out
def notice(cwd):
"""The session-start / request-time line inside the owning project only."""
try:
items = for_project(scope.project_id(cwd))
except Exception:
return ""
if not items:
return ""
return ("sisi: %d item(s) recorded by sisi belong to this project. File each in this project's own "
"design documentation or work list (wherever this project keeps them; if it has neither, create "
"a short section in its main agent instructions file or a docs file), then confirm each with "
"`sisi handover done ID --where PATH`. `sisi handover` lists them in full."
% len(items))
def _norm(t):
return " ".join(str(t or "").split()).lower()
def move_lesson(con, lesson_id, pid):
"""Copy a lesson (with its occurrences, the historical example) into the pile and remove
it from the delivered global data. Returns the pile item, or None."""
r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone()
if r is None:
return None
d = dict(r)
occ = [dict(o) for o in con.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (lesson_id,))]
item = {"kind": "lesson", "lesson_id": d["id"], "project": pid,
"date": d.get("created") or store.now(),
"aim": d.get("aim"), "change_kind": d.get("change_kind"), "target": d.get("target"),
"change": d.get("change"), "short": d.get("short"), "when": d.get("when_terms"),
"moment": d.get("moment"), "cause": d.get("cause"),
"occurrences": [{"ts": o.get("ts"), "repo": o.get("repo"), "cwd": o.get("cwd"),
"tool": o.get("tool"), "session": o.get("session"), "moment": o.get("moment")}
for o in occ]}
con.execute("DELETE FROM impressions WHERE lesson_id=?", (lesson_id,))
con.execute("DELETE FROM sightings WHERE lesson_id=?", (lesson_id,))
# the occurrence rows stay: they are the history of the work itself (and what satisfies
# the retro gate for that session), not delivered lesson data
con.execute("DELETE FROM lessons WHERE id=?", (lesson_id,))
return add_item(item)
def move_learn(rec, pid):
item = {"kind": "learn", "project": pid, "date": rec.get("ts") or store.now(),
"text": rec.get("text"), "cwd": rec.get("cwd"),
"occurrences": [{"ts": rec.get("ts"), "repo": rec.get("cwd"), "tool": rec.get("tool")}]}
return add_item(item)
def _find(items, ident):
for it in items:
if str(ident) in (str(it.get("hid")), str(it.get("lesson_id") or "")):
return it
return None
def _key_text(it):
if it.get("kind") == "learn":
return it.get("text") or ""
return it.get("change") or it.get("short") or ""
def _item_lines(it):
out = ["%s %s recorded %s project %s" % (it.get("hid"), it.get("kind"), (it.get("date") or "")[:10],
scope.project_label(it.get("project") or ""))]
if it.get("kind") == "learn":
out.append(' what the owner said: "%s"' % " ".join(str(it.get("text") or "").split()))
else:
out.append(" lesson #%s (%s/%s): %s" % (it.get("lesson_id"), it.get("aim"), it.get("change_kind"),
" ".join(str(it.get("change") or "").split())))
if it.get("short"):
out.append(" short: %s" % it["short"])
if it.get("moment"):
out.append(" where it came from: %s (cause: %s)" % (" ".join(str(it["moment"]).split()),
" ".join(str(it.get("cause") or "").split())))
for o in it.get("occurrences") or []:
out.append(" - %s repo %s tool %s" % ((o.get("ts") or "")[:10], o.get("repo") or o.get("cwd") or "-",
o.get("tool") or "-"))
return out
def main(argv):
argv = list(argv)
if argv and argv[0] == "done":
if len(argv) < 2:
print("usage: sisi handover done ID --where PATH [--quote FRAGMENT]")
return 2
ident = argv[1]
where, quote, i = None, None, 2
while i < len(argv):
if argv[i] == "--where" and i + 1 < len(argv):
where = argv[i + 1]; i += 2
elif argv[i] == "--quote" and i + 1 < len(argv):
quote = argv[i + 1]; i += 2
else:
print("usage: sisi handover done ID --where PATH [--quote FRAGMENT]")
return 2
if not where:
print("sisi handover: --where PATH is required (the file in this project you filed it in)")
return 2
items = load_pile()
it = _find(items, ident)
if it is None:
print("sisi handover: no waiting item %r (`sisi handover` lists them)" % ident)
return 1
cwd = os.getcwd()
root = scope.project_id(cwd)
# the file must be in this project
ap = where if os.path.isabs(where) else os.path.join(cwd, where)
ap = os.path.realpath(ap)
from . import gitutil
groot = gitutil.root(cwd)
base = os.path.realpath(groot) if groot else os.path.realpath(cwd)
if not (ap == base or ap.startswith(base + os.sep)):
print("sisi handover: %s is not inside this project (%s); nothing was filed" % (where, base))
return 1
if not os.path.isfile(ap):
print("sisi handover: %s does not exist in this project; nothing was filed" % where)
return 1
try:
with open(ap, encoding="utf-8") as f:
content = f.read()
except OSError as e:
print("sisi handover: cannot read %s: %s" % (where, e))
return 1
need = quote if quote is not None else _key_text(it)
if _norm(need) not in _norm(content):
print("sisi handover: refused: %s does not contain the item's key text (%r). File it there "
"first, or pass --quote with a quoted fragment of the item that the file does contain."
% (where, " ".join(str(need).split())[:120]))
return 1
save_pile([x for x in items if x is not it])
rec = {"hid": it.get("hid"), "kind": it.get("kind"), "lesson_id": it.get("lesson_id"),
"project": it.get("project"), "where": ap, "date": store.now()}
os.makedirs(os.path.dirname(filed_path()), exist_ok=True)
with open(filed_path(), "a", encoding="utf-8") as f:
f.write(json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n")
print("filed %s in %s; removed from the handover pile" % (ident, where))
return 0
if argv not in ([], ["--all"]):
print("usage: sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]")
return 2
items = load_pile() if argv == ["--all"] else for_project(scope.project_id(os.getcwd()))
if not items:
print("nothing waiting to be filed" + (" here" if argv != ["--all"] else ""))
return 0
for it in items:
for line in _item_lines(it):
print(line)
return 0
+3
View File
@@ -65,6 +65,9 @@ def normalize(tool, d):
prompt = _s(d, "prompt", "user_prompt", "userPrompt")
if prompt:
out["prompt"] = prompt
model = _s(d, "model", "model_id", "modelId")
if model:
out["model"] = model
cwd = _s(d, "cwd")
if not cwd and isinstance(d.get("workspace_roots"), list):
roots = [r for r in d["workspace_roots"] if isinstance(r, str) and r]
+9
View File
@@ -4,6 +4,8 @@ Files, all under <personal>/overlay/:
rules/<id>.md a rule: `## Title` then the body. Same id as a base rule = replaces it; new id = adds one.
rules/disabled.txt ids of rules switched off (one per line)
rules/order.txt order of added rules (ids, one per line); base rules keep the base order
rules/full-order.txt whole-book reading order from a whole-document round (ids; numbers follow it)
traces/ where each folded lesson lives in a rewritten document (never agent-loaded)
verifiers/<section>/<id>.md a verifier in the library's own format (replaces the product's of that id, or adds)
verifiers/disabled.txt ids of verifiers switched off
done/<id>.md a recipe in the library's own format (replace or add)
@@ -187,6 +189,13 @@ def effective():
for i in dict.fromkeys(order + rest):
if i not in off:
out.append(dict(over[i], origin="added"))
# A whole-document round may reorder the whole book: rules/full-order.txt then names every
# rule in reading order. Ids stay stable; numbers follow this order, and anything stored
# refers to rules by id (`rule:<id>`), never by number.
full = _lines(paths.overlay_dir("rules", "full-order.txt"))
if full:
rank = {i: n for n, i in enumerate(full)}
out.sort(key=lambda r: rank.get(r["id"], len(rank)))
return pre, out
+8
View File
@@ -115,6 +115,14 @@ def _commit(msg, pathspecs):
if not ok: # a pathspec that matches nothing makes git add refuse them all: add what exists one by one
for s in pathspecs:
git("add", "-A", "--", s, check=False)
# A pathspec whose files were all deleted before ever being tracked (an emptied notes
# folder, say) matches nothing in the index either, and git commit refuses it: commit
# only the pathspecs that actually staged something.
staged = git("diff", "--cached", "--name-only", check=False).stdout.splitlines()
pathspecs = [s for s in pathspecs
if any(f == s or f.startswith(s.rstrip("/") + "/") for f in staged)]
if not pathspecs:
return None
spec = ["--"] + list(pathspecs)
else:
git("add", "-A")
+50 -11
View File
@@ -14,6 +14,24 @@ _TRIVIAL = {"yes", "no", "y", "n", "ok", "okay", "sure", "yep", "nope", "thanks"
"go ahead", "do it", "continue", "stop", "wait", "hi", "hello"}
_WORK_STEMS = {"fix", "chang", "add", "build", "updat", "remov", "implement", "writ", "creat",
"refactor", "renam", "delet", "introduc", "migrat", "upgrad", "design", "develop",
"ship", "publish", "tag", "releas", "mak", "set", "install", "convert", "speed"}
_QUESTION_START = {"should", "can", "could", "would", "is", "are", "do", "does", "did", "why", "what",
"how", "whether", "when", "where", "who", "which", "will", "shall", "may"}
def _is_question_without_work(t):
"""A question to the agent that names no work (no fix/build/change/...): the agent just answers."""
low = " ".join(t.lower().split())
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)}
return not (stems & _WORK_STEMS)
def is_trivial(text):
"""A message no recipe or lesson can help with: empty, a slash command, a bare yes/no, or a short
question. A wrong injection on every message is worse than none."""
@@ -29,6 +47,8 @@ def is_trivial(text):
return True
if t.endswith("?") and len(words) <= 7: # a short question: the agent just answers it
return True
if _is_question_without_work(t):
return True
return False
@@ -45,21 +65,33 @@ def _best_recipe(query):
def stems_of(text):
return {retro._stem(x) for x in V._words(text.replace("-", " "))}
generic = retro.COMMON | {retro._stem(w) for w in
("agent agents tool tools interface surface command commands function functions "
"program system name names description descriptions user users thing things "
"way ways step steps example examples".split())}
scored = []
for r in V.usable(V.load_recipes()):
s, primary = 0.0, set()
for text, w in ((r["title"], 3.0), (r["applies_to"], 3.0), (r["id"].replace("-", " "), 3.0), (r["body"], 0.2)):
s, primary, anchored = 0.0, set(), set()
for text, w, is_anchor in ((r["title"], 3.0, True), (r["applies_to"], 3.0, False),
(r["id"].replace("-", " "), 3.0, False), (r["body"], 0.2, False)):
hit = toks & stems_of(text)
s += w * len(hit)
if w > 1.0:
primary |= hit - retro.COMMON # generic words (new, fix, change) never carry a match alone
primary |= hit - generic # generic words (new, fix, change, agent, tool) never carry a match
if is_anchor:
anchored |= hit - generic
if s > 0:
scored.append((len(primary), s, r))
scored.append((len(primary), len(anchored), s, r))
if not scored:
return None
scored.sort(key=lambda x: (-x[0], -x[1], x[2]["id"]))
primary, s, best = scored[0]
return best if primary >= 2 and s >= RECIPE_MIN_SCORE else None
scored.sort(key=lambda x: (-x[0], -x[1], -x[2], x[3]["id"]))
# the strict floor lessons use: two distinct non-generic terms, at least one of them in the
# recipe's own title (its topic, not merely its id), and the score floor; the best
# candidate that clears it wins
for nprimary, nanchored, s, best in scored:
if nprimary >= 2 and nanchored >= 1 and s >= RECIPE_MIN_SCORE:
return best
return None
def _done_means(recipe, retro):
@@ -76,8 +108,14 @@ def _done_means(recipe, retro):
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)."""
notice = ""
try:
from . import handover
notice = handover.notice(os.getcwd())
except Exception:
notice = ""
if is_trivial(query):
return ""
return notice
from . import retro
recipe = _best_recipe(query)
targets = (recipe["id"],) if recipe else ()
@@ -92,9 +130,10 @@ def build_context(query, session=None):
% (row["id"], retro.heading_text(row, 120), row["id"]))
ids.append(row["id"])
if not recipe and not lesson_lines:
return ""
lines = ["sisi: for this request (from earlier agents' lessons and the recipe library; "
"information to weigh, not commands):"]
return notice
lines = [notice] if notice else []
lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; "
"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)
+148 -18
View File
@@ -96,7 +96,8 @@ def db_path():
NEW_LESSON_COLS = (("strength", "INTEGER DEFAULT 1"), ("triggers", "TEXT"), ("effect", "TEXT"),
("applied_at", "TEXT"), ("folded_into", "TEXT"), ("needs_cycle", "INTEGER DEFAULT 0"),
("check_json", "TEXT"), ("change_fp", "TEXT"), ("promoted_shown", "INTEGER DEFAULT 0"),
("when_terms", "TEXT"), ("short", "TEXT"), ("topic", "TEXT"))
("when_terms", "TEXT"), ("short", "TEXT"), ("topic", "TEXT"),
("scope", "TEXT"), ("project", "TEXT"))
def connect():
@@ -154,7 +155,7 @@ def _backfill(con):
# ---- the committed dump ------------------------------------------------------
LESSON_COLS = ("id", "created", "aim", "change_kind", "target", "moment", "cause", "change", "status", "count", "last_seen",
"strength", "triggers", "effect", "applied_at", "folded_into", "needs_cycle", "check_json", "change_fp",
"promoted_shown", "when_terms", "short", "topic")
"promoted_shown", "when_terms", "short", "topic", "scope", "project")
OCC_COLS = ("id", "lesson_id", "ts", "session", "tool", "cwd", "repo", "moment", "fp", "delivery_s")
IMP_COLS = ("id", "lesson_id", "ts", "session", "place", "occ_count")
SIGHT_COLS = ("id", "lesson_id", "ts", "session", "moment")
@@ -553,8 +554,29 @@ def sightings_count(con, lesson_id):
return 0
def _round_open(lesson_id):
"""A learning round is open for this lesson when a brief snapshot on record still shows it
active. Automatic retirement is deferred then, so reading lessons during a round (which
counts showings) can never stale the round's base."""
try:
d = os.path.join(paths.state(), "cycle-bases")
for name in os.listdir(d):
if not name.endswith(".json"):
continue
with open(os.path.join(d, name), encoding="utf-8") as f:
snap = json.load(f)
v = (snap.get("lessons") or {}).get(str(lesson_id)) or {}
if v.get("status") in ACTIVE:
return True
except Exception:
pass
return False
def _maybe_retire(con, lesson_id):
"""Shown 20 times with no recurrence since first shown, and folded into a rule or an entry: leave the notes."""
if _round_open(lesson_id):
return # deferred while a learning round is open; reading must not stale it
r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone()
if r and r["status"] in ACTIVE and r["folded_into"] and shown_count(con, lesson_id) >= RETIRE_SHOWS \
and recurrences_after_shown(con, r) == 0:
@@ -598,8 +620,11 @@ def new_lesson(con, f, cwd, fp):
topic = (f.get("topic") or "").strip() or None
# tolerate stores predating short/topic: only insert columns that exist
cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")]
extra_cols = [c for c in ("short", "topic") if c in cols]
extra_vals = [short if c == "short" else topic for c in extra_cols]
extra_cols = [c for c in ("short", "topic", "scope", "project") if c in cols]
_scope_vals = {"short": short, "topic": topic,
"scope": (f.get("scope") or "unscoped"),
"project": (f.get("project") or None)}
extra_vals = [_scope_vals[c] for c in extra_cols]
base_cols = ("created, aim, change_kind, target, moment, cause, change, status, count, last_seen,"
" strength, triggers, change_fp, when_terms")
all_cols = base_cols + (", " + ", ".join(extra_cols) if extra_cols else "")
@@ -622,7 +647,8 @@ def notes_chars(con):
try:
return con.execute(
"SELECT COALESCE(sum(length(change)),0) FROM lessons WHERE status IN ('open','applied') "
"AND COALESCE(strength,1)=1 AND folded_into IS NULL AND COALESCE(effect,'')='learned-note'"
"AND COALESCE(strength,1)=1 AND folded_into IS NULL AND COALESCE(effect,'')='learned-note' "
"AND COALESCE(scope,'unscoped')<>'project' AND change_kind<>'tool'"
).fetchone()[0]
except Exception:
return con.execute(
@@ -723,6 +749,11 @@ def apply_effect(con, lesson_id):
r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone()
if not r or r["status"] not in ACTIVE or r["applied_at"]:
return r["effect"] if r else None
if _get(r, "scope") == "project":
# project facts never write into the shared recipe/verifier notes
con.execute("UPDATE lessons SET effect='learned-note', applied_at=? WHERE id=?",
(store.now(), lesson_id))
return "learned-note"
eff = effect_for(r["change_kind"], r["target"], r["change"])
folded = None
if eff == "field-note":
@@ -854,8 +885,14 @@ LIMIT = 1200
def tick_block(cwd, n=8, session=None):
notice = ""
try:
from . import handover
notice = handover.notice(cwd)
except Exception:
notice = ""
if not os.path.exists(db_path()):
return ""
return notice
con = connect()
try:
ensure_effects(con)
@@ -865,9 +902,12 @@ def tick_block(cwd, n=8, session=None):
FROM lessons l WHERE l.status IN ('open','applied')
ORDER BY COALESCE(l.strength,1) DESC, here DESC, l.count DESC, l.last_seen DESC LIMIT 60""", (repo,)))
out, total, ids = [], len(HEADER) + 1, []
from . import scope as _scope
for r in rows:
if len(out) >= n:
break
if not _scope.row_visible(r, cwd):
continue
src = _get(r, "short") or r["change"]
t = safe_line(src, repo)
if not t:
@@ -882,7 +922,8 @@ def tick_block(cwd, n=8, session=None):
con.close()
if out:
record_shown(ids, "tick", session)
return (HEADER + "\n" + "\n".join(out)) if out else ""
block = (HEADER + "\n" + "\n".join(out)) if out else ""
return "\n".join(x for x in (notice, block) if x)
# ---- delivery at the moment it matters --------------------------------------
@@ -925,6 +966,8 @@ def _score_all(query, extra="", con=None):
finally:
if own:
con.close()
from . import scope as _scope
rows = [r for r in rows if _scope.row_visible(r, os.getcwd())]
q, qx = _stems(query), _stems(extra)
if not (q or qx) or not rows:
return []
@@ -1129,7 +1172,7 @@ def backlog_rows(con=None):
con = connect()
try:
return [dict(r) for r in con.execute(
"SELECT * FROM lessons WHERE change_kind='tool' AND status IN ('open','applied') "
"SELECT * FROM lessons WHERE change_kind='tool' AND status='open' "
"ORDER BY count DESC, created ASC, id ASC")]
finally:
if own:
@@ -1141,7 +1184,7 @@ def _parse(argv):
f, flags, i = {}, set(), 0
names = {"--aim": "aim", "--moment": "moment", "--cause": "cause", "--change-kind": "change_kind",
"--change": "change", "--target": "target", "--same-as": "same_as", "--when": "when",
"--short": "short", "--topic": "topic"}
"--short": "short", "--topic": "topic", "--scope": "scope", "--project": "project"}
while i < len(argv):
a = argv[i]
if a in names:
@@ -1181,7 +1224,7 @@ def cmd_retro(argv, stdin=None):
if k == "new":
if v:
flags.add("new")
elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as", "when", "short", "topic"):
elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as", "when", "short", "topic", "scope", "project"):
f.setdefault(k, str(v))
for k in list(f):
f[k] = f[k].strip()
@@ -1193,6 +1236,20 @@ def cmd_retro(argv, stdin=None):
print(" - " + e)
print("Answer how it could have gone better, concretely: see `sisi help` and canon rule 7.")
return 2
if not same:
from . import scope as _scope
sc = f.get("scope")
if sc not in _scope.SCOPES:
print(_scope.MISSING_SCOPE)
return 2
if sc == "everywhere":
reason = _scope.universal_refusal(
[f.get("change"), f.get("short"), f.get("when")], os.getcwd(), kind=f.get("change_kind"))
if reason:
print(_scope.refusal_text(reason))
return 2
else:
f["project"] = _scope.project_id(os.getcwd())
cwd = os.getcwd()
con = connect()
try:
@@ -1242,9 +1299,18 @@ def cmd_retro(argv, stdin=None):
count = row["count"]
applied = bool(applied) or (row["effect"] == "field-note" and count == 1)
needs_short = not (_get(row, "short") and str(_get(row, "short")).strip()) or not (_get(row, "topic") and str(_get(row, "topic")).strip())
handed = None
if not same and f.get("scope") == "project":
from . import handover
handed = handover.move_lesson(con, lid, f.get("project"))
con.commit()
finally:
con.close()
sync("lessons: retro recorded for lesson #%d" % lid)
if handed:
print("recorded for this project: lesson #%d is in the handover pile (%s), not in the global "
"lessons; `sisi handover` here lists it in full" % (lid, handed.get("hid")))
return 0
print("recorded: lesson #%d, seen %d time%s%s" % (lid, count, "" if count == 1 else "s", "; applied to notes/" if applied else ""))
if needs_short:
print("sisi: this lesson has no short line yet; the next learning round will write one (run `sisi cycle --now` to start it now).")
@@ -1264,10 +1330,23 @@ def _lesson_line(r):
heading_text(r, 100))
def _entry_title(entry_id):
"""The human title of a recipe/verifier entry, or the id in plain words."""
try:
from . import verifiers as V
for e in list(V.load_recipes()) + list(V.load_verifiers()):
if e.get("id") == entry_id and e.get("title"):
return e["title"]
except Exception:
pass
return str(entry_id).replace("-", " ")
def plain_state(r):
"""A lesson's state in plain words for the human digest (no internal labels)."""
if _get(r, "change_kind") == "tool":
return "change to sisi itself, not built yet"
return "change to sisi itself, built" if _get(r, "status") == "applied" \
else "change to sisi itself, not built yet"
folded = _get(r, "folded_into") or ""
if folded.startswith("rule:") or folded == "enforced" or _get(r, "check_json"):
return "in the rulebook"
@@ -1276,11 +1355,11 @@ def plain_state(r):
if first.startswith("draft:"):
first = first[6:]
if first:
return "attached to %s work" % first
return "attached to %s work" % _entry_title(first)
if _get(r, "effect") == "field-note":
target = _get(r, "target")
if target:
return "attached to %s work" % target
return "attached to %s work" % _entry_title(target)
return "loose note"
@@ -1301,10 +1380,22 @@ def digest_lines(include_all=False, con=None):
try:
for rec in store.read("quarantine"):
t = " ".join(str(rec.get("text") or "").split())
if t:
if t and rec.get("scope") != "project":
said.append(t)
except Exception:
said = []
# any project-scoped rows still in the store (recorded before handover, not yet moved)
# are not global lessons: the digest names only how many wait to be filed, per project
from . import scope as _scope, handover as _ho
waiting = dict(_ho.counts_by_project())
uni_rows = []
for r in rows:
if _scope.row_scope(r) == "project":
pid = r.get("project") or ""
waiting[pid] = waiting.get(pid, 0) + 1
else:
uni_rows.append(r)
rows = uni_rows
summarized = [r for r in rows if (r.get("short") or "").strip() and (r.get("topic") or "").strip()]
_summ_ids = {r["id"] for r in summarized}
pending = [r for r in rows if r["id"] not in _summ_ids]
@@ -1339,6 +1430,12 @@ def digest_lines(include_all=False, con=None):
line += "; seen %d times" % r["count"]
out.append(line + ")")
out.append("")
if waiting:
out.append("## Waiting to be filed in their projects")
for pid in sorted(waiting):
out.append("- %d item(s) waiting to be filed in %s (run `sisi handover` inside that project)"
% (waiting[pid], _scope.project_label(pid) if pid else "an unknown project"))
out.append("")
out.append("To see one lesson in full, run `sisi lessons show ID` with the lesson number in place of ID.")
return out
@@ -1369,11 +1466,31 @@ def cmd_lessons(argv):
r["strength"] or 1, r["effect"] or "-", r["folded_into"] or "-",
listed_count(con, r["id"]), read_count(con, r["id"]),
recurrences_after_shown(con, r), sightings_count(con, r["id"])))
print("moment: %s\ncause : %s\nchange: %s" % (r["moment"], r["cause"], r["change"]))
from . import scope as _scope
_sc = _scope.row_scope(r)
print("scope : %s%s" % (_sc, (" (%s)" % _get(r, "project")) if _sc == "project" else
" (not yet scoped; a learning round will ask)" if _sc == "unscoped" else ""))
print("change: %s" % r["change"])
print("short : %s" % (_get(r, "short") or "- (none yet; a learning cycle can write one)"))
print("topic : %s" % (_get(r, "topic") or "-"))
print("when : %s" % (r["when_terms"] or "- (none recorded; a cycle can add terms)"))
print("\noccurrences:")
try:
from . import documents as _docs
for _key, _t in _docs.traces_for_lesson(r["id"]):
_disp = _t.get("disposition") or "carried"
if _disp == "moved":
print("lives : moved to %s as %r" % (_t.get("to"), _t.get("fragment")))
elif _disp == "merged":
print("lives : in %s, merged with lesson #%s as %r" % (_key, _t.get("merged_with"), _t.get("fragment")))
elif _disp == "retired":
print("lives : retired from %s (%s)" % (_key, _t.get("reason")))
else:
print("lives : in %s as %r" % (_key, _t.get("fragment")))
except Exception:
pass
print("\nWhere this came from (historical example)")
print("moment: %s\ncause : %s" % (r["moment"], r["cause"]))
print("occurrences:")
for o in con.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (r["id"],)):
print(" %s session %s tool %s repo %s\n %s" % (o["ts"], o["session"] or "?", o["tool"] or "?", o["repo"], o["moment"]))
record_shown([r["id"]], "lessons-show") # opening a lesson in full counts as showing it
@@ -1531,7 +1648,20 @@ def cmd_backlog(argv):
if not rows:
print("the backlog is empty: no open tool lessons")
return 0
cap = 1500 # the backlog's own heading cap, separate from the loose-lessons budget
total, printed = 0, 0
print("sisi backlog: %d tool lesson(s), most seen first (its own cap is %d heading characters; "
"built ones leave the list with `sisi lessons set ID --status applied`)" % (len(rows), cap))
for r in rows:
print("#%-4d x%-3d s%d shown %-3d %s" % (r["id"], r["count"], r["strength"] or 1, shown[r["id"]],
heading_text(r, 110)))
line = "#%-4d x%-3d s%d shown %-3d %s" % (r["id"], r["count"], r["strength"] or 1, shown[r["id"]],
heading_text(r, 110))
if total + len(line) + 1 > cap and printed:
break
print(line)
total += len(line) + 1
printed += 1
if printed < len(rows):
print("- ... and %d more not listed (backlog headings take %d characters, cap %d; "
"`sisi lessons --kind tool` lists them all)" % (len(rows) - printed,
sum(len(heading_text(r, 110)) + 8 for r in rows), cap))
return 0
+261
View File
@@ -0,0 +1,261 @@
"""Choosing a worker: pure arithmetic over the delegation record. No model call, no file access.
A candidate is a plain dict: worker (canonical id), tool, model, maker, plan ("flat", "per-use" or
None), cost (a comparable per-use price or None), allowance_pct_left (0..100 or None), usable,
reason (why not usable), and aliases (every spelling the record may use for this worker).
The rule, in order:
1. Never a model whose id contains "contributor" (those tiers train on prompts).
2. Never a worker marked unavailable whose retry time is still ahead, nor one whose flat
allowance is known to be spent.
3. For a review, never the author's maker while another maker is available.
4. Among the rest, a worker is proven for a kind and difficulty with MIN_ATTEMPTS judged attempts
and an accepted rate of at least MIN_ACCEPTED_RATE (accepted and not later found wrong). Above
difficulty 1, proven workers are preferred; at difficulty 1, workers with a thin record stay in
the pool so they gather attempts on low-stakes work. A worker proven bad (enough attempts, rate
below the bar) is passed over whenever anything else remains.
5. Cheapest first: a flat-rate plan with allowance left costs nothing more per task, so it comes
before anything billed per use; per-use workers order by their known price; an unknown price is
treated as the most expensive until learned.
6. Load balancing: within the same price tier and price, the worker that has taken the least work
relative to its remaining allowance goes first (recorded uses divided by allowance left, an
unknown allowance counting as half). Because every delegation is recorded, the choice rotates
as work is done, yet stays deterministic for one fixed record. Ties break on the worker id.
On a fresh install the record is empty and no prices are known, so every candidate is thin and
priced unknown: the first in worker-id order among the usable ones is chosen, and each judged
result from then on shapes the next choice.
"""
import re
MIN_ATTEMPTS = 8 # below this, a worker's record for a kind and difficulty is thin
MIN_ACCEPTED_RATE = 0.6 # "good enough" among workers with at least MIN_ATTEMPTS attempts
UNKNOWN_ALLOWANCE = 50.0 # allowance weight when a tool reports none
STRONG_BAND = 10.0 # strength points from the best still counts as among the strongest
_MAKER_ALIASES = {"haiku": "claude", "sonnet": "claude", "opus": "claude", "fable": "claude"}
def maker_of(name):
"""A best-effort maker from a worker or model id: the first word of the model part.
Stored tables may state a maker explicitly; those win wherever a candidate carries one."""
s = str(name or "").strip().lower()
if not s:
return ""
model = s.rsplit("/", 1)[-1]
token = re.split(r"[-_:. ]", model)[0] or model
return _MAKER_ALIASES.get(token, token)
def _alias_map(candidates):
m = {}
for c in candidates:
for a in [c.get("worker"), c.get("model")] + list(c.get("aliases") or []):
if a:
m.setdefault(str(a).lower(), c["worker"])
return m
def _availability_keys(c):
keys = {str(x).lower() for x in [c.get("worker"), c.get("tool"), c.get("model")] + list(c.get("aliases") or []) if x}
for v in (c.get("worker") or "", c.get("model") or ""):
if "/" in v:
keys.add(v.split("/", 1)[0].lower())
return keys
def _down_entry(c, availability, now):
keys = _availability_keys(c)
for k, e in (availability or {}).items():
if not isinstance(e, dict):
continue
if str(k).lower() in keys and float(e.get("retry_at") or 0) > now:
return e
return None
def candidate_stats(candidates, records):
"""{canonical worker: counted facts} from judged attempts, amendments and runs."""
aliases = _alias_map(candidates)
amended = {r.get("id") for r in records if r.get("kind") == "amend"}
stats = {}
for c in candidates:
stats[c["worker"]] = {"uses": 0, "by_cell": {}}
for r in records:
w = aliases.get(str(r.get("worker") or "").lower())
if w is None:
continue
if r.get("kind") == "run":
stats[w]["uses"] += 1
elif r.get("kind") == "attempt":
stats[w]["uses"] += 1
cell = stats[w]["by_cell"].setdefault(
(r.get("type") or r.get("task_kind"), r.get("difficulty")), {"n": 0, "good": 0})
cell["n"] += 1
if r.get("outcome") == "accepted" and r.get("id") not in amended:
cell["good"] += 1
return stats
def _price_tier(c):
if c.get("plan") == "flat":
return 0
if c.get("plan") == "per-use" or c.get("cost") is not None:
return 1
return 2
def _cell(stats, worker, kind, difficulty):
return stats.get(worker, {}).get("by_cell", {}).get((kind, difficulty), {"n": 0, "good": 0})
def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=()):
"""Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker"}.
`passed_over` is [(worker, plain reason)] covering every candidate not chosen."""
now = float(now or 0)
exclude = {str(x) for x in exclude}
stats = candidate_stats(candidates, records)
passed = []
eligible = []
for c in candidates:
w = c["worker"]
if w in exclude:
passed.append((w, "already tried in this delegation"))
continue
if "contributor" in str(c.get("model") or w).lower():
passed.append((w, "its id contains 'contributor', a tier that trains on prompts"))
continue
down = _down_entry(c, availability, now)
if down is not None:
passed.append((w, "unavailable (%s) until its retry time" % (down.get("reason") or "down")))
continue
if not c.get("usable", True):
passed.append((w, c.get("reason") or "not usable now"))
continue
if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0:
passed.append((w, "its flat-rate allowance is spent"))
continue
eligible.append(c)
author_maker = ""
if review_of:
target = str(review_of).lower()
author = next((c for c in candidates
if target in {str(x).lower() for x in [c.get("worker"), c.get("model")] + list(c.get("aliases") or []) if x}), None)
author_maker = (author.get("maker") if author else None) or maker_of(review_of)
for c in eligible:
c.setdefault("maker", maker_of(c.get("model") or c["worker"]))
if any((c.get("maker") or maker_of(c.get("model") or c["worker"])) != author_maker for c in eligible):
rest = []
for c in eligible:
if (c.get("maker") or maker_of(c.get("model") or c["worker"])) == author_maker:
passed.append((c["worker"], "same maker as the author (%s); a review needs another maker" % author_maker))
else:
rest.append(c)
eligible = rest
def rate(c):
cell = _cell(stats, c["worker"], kind, difficulty)
return (cell["good"] / cell["n"]) if cell["n"] else None
def proven_good(c):
cell = _cell(stats, c["worker"], kind, difficulty)
return cell["n"] >= MIN_ATTEMPTS and rate(c) is not None and rate(c) >= MIN_ACCEPTED_RATE
def proven_bad(c):
cell = _cell(stats, c["worker"], kind, difficulty)
return cell["n"] >= MIN_ATTEMPTS and rate(c) is not None and rate(c) < MIN_ACCEPTED_RATE
pool = list(eligible)
if difficulty and difficulty > 1:
good = [c for c in eligible if proven_good(c)]
if good:
for c in eligible:
if c not in good:
cell = _cell(stats, c["worker"], kind, difficulty)
passed.append((c["worker"],
"record too thin for this difficulty (%d of %d attempts) while a proven worker is available"
% (cell["n"], MIN_ATTEMPTS) if cell["n"] < MIN_ATTEMPTS
else "accepted rate below the bar for this kind and difficulty"))
pool = good
if pool:
bad = [c for c in pool if proven_bad(c)]
if bad and len(bad) < len(pool):
for c in bad:
passed.append((c["worker"], "accepted rate below the bar over %d attempts"
% _cell(stats, c["worker"], kind, difficulty)["n"]))
pool = [c for c in pool if c not in bad]
def load_ratio(c):
left = c.get("allowance_pct_left")
weight = float(left) if left else UNKNOWN_ALLOWANCE
return stats.get(c["worker"], {}).get("uses", 0) / max(weight, 1.0)
def key(c):
r = rate(c)
return (_price_tier(c),
float(c["cost"]) if c.get("cost") is not None else float("inf"),
load_ratio(c),
-(r if r is not None else -1.0),
c["worker"])
pool.sort(key=key)
choice = pool[0] if pool else None
if choice is not None:
for c in pool[1:]:
if _price_tier(c) > _price_tier(choice) or (c.get("cost") is not None and choice.get("cost") is not None
and float(c["cost"]) > float(choice["cost"])):
reason = "more expensive than the choice (per-use price or unknown price counts as most expensive)"
elif load_ratio(c) > load_ratio(choice):
reason = "load balancing: it has taken more work relative to the allowance it has left"
else:
r, cr = rate(c), rate(choice)
reason = ("lower measured accepted rate for this kind and difficulty"
if r is not None and cr is not None and r < cr else
"equal on price and load; the choice came first in worker-id order")
passed.append((c["worker"], reason))
return {"choice": choice, "passed_over": passed, "stats": stats, "author_maker": author_maker,
"load_ratios": {c["worker"]: load_ratio(c) for c in candidates}}
def explain_choice(result, kind, difficulty):
"""Plain lines for `--explain`, from a choose() result."""
choice = result["choice"]
lines = []
if choice is None:
lines.append("no usable worker for kind %s at difficulty %s" % (kind, difficulty))
else:
cell = _cell(result["stats"], choice["worker"], kind, difficulty)
if choice.get("plan") == "flat":
price = "a flat-rate plan with allowance left, so one more task costs nothing extra"
elif choice.get("cost") is not None:
price = "the cheapest known per-use price among the workers that are good enough"
elif choice.get("plan") == "per-use":
price = "billed per use; no cheaper flat-rate worker is usable"
else:
price = "price unknown, treated as most expensive until learned; nothing priced cheaper is usable"
if cell["n"] >= MIN_ATTEMPTS:
record = "%d judged attempts for this kind and difficulty, %d accepted" % (cell["n"], cell["good"])
elif cell["n"]:
record = "a thin record (%d of %d attempts for this kind and difficulty)" % (cell["n"], MIN_ATTEMPTS)
else:
record = "no judged attempts yet for this kind and difficulty"
lines.append("chose %s: %s; %s; load so far is %s recorded use(s) against the allowance it has left, "
"the lowest in its price tier, so work spreads instead of draining one plan"
% (choice["worker"], price, record, result["stats"].get(choice["worker"], {}).get("uses", 0)))
if result.get("author_maker"):
lines.append("it is from a different maker than the author (%s)" % result["author_maker"])
groups, order = {}, []
for worker, reason in result["passed_over"]:
if reason not in groups:
groups[reason] = []
order.append(reason)
groups[reason].append(worker)
for reason in order:
names = groups[reason]
shown = ", ".join(names[:12])
if len(names) > 12:
shown += " (and %d more)" % (len(names) - 12)
lines.append("passed over %s: %s" % (shown, reason))
return lines
+12 -7
View File
@@ -103,7 +103,8 @@ def _folded_lessons(rule_id):
con = retro.connect()
try:
return [dict(r) for r in con.execute(
"SELECT * FROM lessons WHERE folded_into=? ORDER BY id", (rule_id,))]
"SELECT * FROM lessons WHERE folded_into=? OR folded_into=? ORDER BY id",
(rule_id, "rule:" + rule_id))]
finally:
con.close()
except Exception:
@@ -156,12 +157,16 @@ def _detail(n, rule):
print(" - #%d (%s, seen %d times): %s (full text: `sisi lessons show %d`)"
% (r["id"], date or "undated", r["count"] or 0,
retro.heading_text(r, 140), r["id"]))
examples = [r for r in lessons if (r.get("moment") or "").strip()]
if examples:
print("\nExamples (what actually happened):")
for r in examples[:3]:
print(" - %s (lesson %d; `sisi lessons show %d`)"
% (retro.word_cut(r["moment"], 160), r["id"], r["id"]))
try:
from . import documents as _docs
for _key, _t in _docs.traces_for_lesson(r["id"]):
if _t.get("fragment"):
print(" carried in %s by: %r" % (_key, _t["fragment"]))
except Exception:
pass
if (r.get("moment") or "").strip():
print(" Where this came from (historical example): %s"
% retro.word_cut(r["moment"], 160))
else:
print("\nLessons folded into this rule: none yet.")
return 0
+232
View File
@@ -0,0 +1,232 @@
"""Lesson scope: everywhere or one project.
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 they name the current project. History (moment, cause, occurrences) may name
the project freely and is never checked.
"""
import os, re, subprocess
from . import gitutil
SCOPES = ("everywhere", "project")
MISSING_SCOPE = (
"sisi: --scope is required: use --scope everywhere for a lesson that holds in any project, stated in "
"general terms so a different project can use it, or --scope project for a fact about this project only, "
"which is kept with this project and shown only here. To make a project fact universal, restate it in "
"general terms: 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'). The moment and cause may name this project either way: they stay as its history.")
# 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
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))
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
def visible(scope_value, project_value, cwd=None):
"""Legacy (unscoped) and everywhere items show everywhere; project items only at home."""
if scope_value in (None, "", "unscoped"):
return True
if scope_value == "everywhere":
return True
if 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 v or "unscoped"
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. A tool lesson
(a change to sisi itself) may say 'sisi': that word alone is exempt there.
"""
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 kind == "tool" and 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 lesson scoped everywhere 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." % reason)
def cmd_learn(argv):
"""`sisi learn [--scope everywhere|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
elif a.startswith("--scope="):
scope_value = a.split("=", 1)[1]; i += 1
else:
text_parts.append(a); i += 1
text = " ".join(text_parts).strip()
if not text:
print("usage: sisi learn --scope everywhere|project TEXT")
return 1
if scope_value not in SCOPES:
print(MISSING_SCOPE)
return 2
cwd = os.getcwd()
if scope_value == "everywhere":
reason = universal_refusal([text], cwd)
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 (quarantined until verified); it will be handed over to this "
"project at session start (`sisi handover` lists it)")
return 0
store.append("quarantine", store.stamp(rec))
try:
from . import cli
cli._commit_personal(store.file_path("quarantine"),
"learn: %s" % " ".join(text.split())[:60])
except Exception:
pass
print("recorded (quarantined until verified)")
return 0
+24
View File
@@ -95,6 +95,14 @@ def main(args=()):
if payload.get("source", "startup") == "startup" or not store.load_session(sid):
rec = {"session_id": sid, "cwd": cwd, "started": store.now(), "tool": store.tool(),
"source": payload.get("source"), "blocks": 0}
if isinstance(payload.get("model"), str) and payload["model"]:
rec["model"] = payload["model"]
try:
from . import workers as _W
if _W.is_subagent_payload(payload):
rec["subagent"] = True
except Exception:
pass
if isinstance(payload.get("transcript_path"), str):
rec["transcript_path"] = payload["transcript_path"]
# Attribution starts here: the gate reads only transcript bytes after this offset.
@@ -124,6 +132,22 @@ def main(args=()):
if line:
sys.stdout.write("sisi: %s\n" % line)
_export_session(sid)
try:
sess = rec or store.load_session(sid)
model = payload.get("model") if isinstance(payload.get("model"), str) else sess.get("model")
if model and sess.get("model") != model:
sess["model"] = model
store.save_session(sid, sess)
if model and not sess.get("orch_line_shown"):
from . import workers as _W
lines = _W.session_lines(model, payload)
for ln in lines:
sys.stdout.write(ln + "\n")
if lines:
sess["orch_line_shown"] = True
store.save_session(sid, sess)
except Exception as e:
store.log_error("tick-workers", e)
try:
from . import cycle
note = cycle.due_notice(session=sid if isinstance(sid, str) else None)
+15 -1
View File
@@ -316,14 +316,21 @@ def _print_drafts(query):
def cmd_show(args):
trace = "--trace" in args
args = [a for a in args if a != "--trace"]
if not args:
print("usage: sisi verifiers show ID")
print("usage: sisi verifiers show ID [--trace]")
return 1
e = _find(usable(load_verifiers()), args[0])
if not e:
print("no verifier with id %r (see `sisi verifiers`)" % args[0])
return 1
_show(e, True)
if trace:
from . import documents as _docs
print("")
for line in _docs.trace_lines("verifier", e["id"]):
print(line)
_print_lessons("%s %s %s" % (e["id"], e["title"], e["answers"]), "verifiers-show")
return 0
@@ -548,6 +555,8 @@ def main(args):
# ---- done recipes ----------------------------------------------------------
def done_main(args):
trace = "--trace" in args
args = [a for a in args if a != "--trace"]
rs = usable(load_recipes())
if args and args[0] == "for":
desc = " ".join(args[1:]).strip()
@@ -590,6 +599,11 @@ def done_main(args):
print("== %s: %s ==%s\napplies to: %s\n" % (r["id"], r["title"], origin_tag(r), r["applies_to"]))
print(r["body"].strip("\n"))
_print_notes(r["id"])
if trace:
from . import documents as _docs
print("")
for line in _docs.trace_lines("recipe", r["id"]):
print(line)
_print_lessons("%s %s %s" % (r["id"].replace("-", " "), r["title"], r["applies_to"]),
"done-show", loose=True, targets=(r["id"],))
return 0
+1053
View File
File diff suppressed because it is too large. Load diff
+26 -3
View File
@@ -52,8 +52,29 @@ class ShortCase(LibCase):
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": "everywhere"})
have.add(e["lesson"])
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)
@@ -165,7 +186,7 @@ class DigestTests(ShortCase):
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("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)
@@ -190,7 +211,7 @@ class DigestTests(ShortCase):
def test_digest_shows_what_you_said_first(self):
self.seed_digest()
self.assertEqual(self.sisi("learn", "Always", "show", "the", "options.").returncode, 0)
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)
@@ -292,7 +313,9 @@ class BulletTests(ShortCase):
# 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"}]}
"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)
+289
View File
@@ -0,0 +1,289 @@
"""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="everywhere", short="Seed the corpus from golden files.", topic="parsing")
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()
+29
View File
@@ -258,6 +258,35 @@ class ByteExactTests(SafetyBase):
self.assertEqual(open(p, "rb").read(), edited)
class OldGeneratedTests(SafetyBase):
OLD_PI = (b"// sisi:generated by `sisi install` -- runs `sisi tick` at session start and `sisi gate` before the session settles. Remove with `sisi uninstall`.\n"
b"import { execFile } from \"node:child_process\";\nconst OLD = true;\n")
def test_old_pi_extension_updated_by_install_and_dry_run(self):
os.makedirs(self.path(".pi", "agent", "extensions"))
p = self.path(".pi/agent/extensions/sisi.ts")
self.put(".pi/agent/extensions/sisi.ts", self.OLD_PI)
r = self.sisi("install", "--dry-run")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("is not ours", r.stdout)
self.assertEqual(open(p, "rb").read(), self.OLD_PI) # dry run changes nothing
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertNotEqual(open(p, "rb").read(), self.OLD_PI)
self.assertIn(b"sisi:generated", open(p, "rb").read().split(b"\n", 1)[0])
wiring.uninstall()
self.assertFalse(os.path.exists(p))
def test_old_marker_only_in_body_still_refused(self):
os.makedirs(self.path(".pi", "agent", "extensions"))
mine = b"// my extension\nexport const X = 'sisi:generated';\n"
self.put(".pi/agent/extensions/sisi.ts", mine)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".pi/agent/extensions/sisi.ts"), "rb").read(), mine)
wiring.uninstall()
class FailOpenCommandTests(SafetyBase):
def test_hook_command_fails_open_without_launcher(self):
repo = os.path.join(self.tmp, "repo-copy")
+28 -7
View File
@@ -66,10 +66,13 @@ class LearningCase(LibCase):
con.close()
notes = list(doc.get("notes") or [])
covered = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-short"}
scoped = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"}
exempt = {e.get("lesson") for e in notes if isinstance(e, dict)
and e.get("action") in ("retire", "withdraw", "merge")}
extra = []
for r in rows:
if r["id"] not in scoped and r["id"] not in exempt:
extra.append({"lesson": r["id"], "action": "set-scope", "scope": "everywhere"})
if r["id"] in covered or r["id"] in exempt:
continue
if (r.get("short") or "").strip() and (r.get("topic") or "").strip():
@@ -84,6 +87,21 @@ class LearningCase(LibCase):
doc["notes"] = notes + extra
except Exception:
pass
# 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)
@@ -475,8 +493,9 @@ class CycleApplyTests(LearningCase):
b = self.mk(change="Session two lesson about widget caching", moment="s2 wait at step 2")
base = cycle.base_version() # both sessions read the same brief
_ss = lambda lid: {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}
doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b)]}
doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b)]}
_sc = lambda lid: {"lesson": lid, "action": "set-scope", "scope": "everywhere"}
doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b)]}
doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b)]}
paths_ = []
for i, d in enumerate((doc1, doc2)):
p = os.path.join(self.tmp, "two-%d.json" % i)
@@ -758,7 +777,7 @@ class MatchingCorpusTests(LearningCase):
self.assertEqual(wrong, [], "part one must stay empty for should-not requests")
def test_csv_lesson_reaches_the_next_agent_three_ways(self):
r = self.sisi("retro", "--new", "--aim", "verified",
r = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011",
"--cause", "the importer was only tested with three hand-written rows",
"--change-kind", "rule", "--when", CSV_WHEN,
@@ -827,13 +846,13 @@ class MatchingCorpusTests(LearningCase):
self.assertIn("#%d" % lid, out)
def test_unconfirmed_duplicate_sighting_is_recorded(self):
first = self.sisi("retro", "--new", "--aim", "verified",
first = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "the parser server waited 90 seconds in step 4 of the nightly job",
"--cause", "no readiness probe existed before the browser step",
"--change-kind", "rule", "--when", PARSER_WHEN, "--change", PARSER_CHANGE)
self.assertEqual(first.returncode, 0, first.stdout)
lid = int(first.stdout.split("lesson #")[1].split(",")[0])
dup = self.sisi("retro", "--aim", "verified",
dup = self.sisi("retro", "--scope", "everywhere", "--aim", "verified",
"--moment", "again the parser server waited 90 seconds in step 9 of the nightly job",
"--cause", "still no readiness probe before the browser step at all",
"--change-kind", "rule", "--when", PARSER_WHEN,
@@ -844,7 +863,7 @@ class MatchingCorpusTests(LearningCase):
self.assertEqual(retro.sightings_count(con, lid), 1)
con.close()
self.assertIn("1 unconfirmed sighting(s)", self.sisi("lessons", "show", str(lid)).stdout)
as_new = self.sisi("retro", "--new", "--aim", "verified",
as_new = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "again the parser server waited 90 seconds in step 9 of the nightly job",
"--cause", "still no readiness probe before the browser step at all",
"--change-kind", "rule", "--when", PARSER_WHEN,
@@ -968,7 +987,7 @@ class ImproveFromUseTests(LearningCase):
def test_sisi_improves_from_use_end_to_end(self):
"""The purpose itself: a lesson from session A reaches session B doing the same kind of work,
its showing is recorded, and recurrence after fresh showings strengthens it until a cycle is due."""
a = self.sisi("retro", "--new", "--aim", "verified",
a = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified",
"--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011",
"--cause", "the importer was only tested with three hand-written rows",
"--change-kind", "rule", "--when", CSV_WHEN,
@@ -1051,6 +1070,7 @@ class CycleGapTests(LearningCase):
doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}])
# cycle_doc recomputes base; rebuild with the original base
d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"},
{"lesson": lid, "action": "set-scope", "scope": "everywhere"},
{"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]}
p = os.path.join(self.tmp, "g2.json")
with open(p, "w") as f:
@@ -1076,6 +1096,7 @@ class CycleGapTests(LearningCase):
base = cycle.base_version()
self.mk(change="Brand new parser lesson arriving mid cycle", moment="new wait at step 5")
d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"},
{"lesson": lid, "action": "set-scope", "scope": "everywhere"},
{"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]}
p = os.path.join(self.tmp, "g3.json")
with open(p, "w") as f:
+6 -6
View File
@@ -551,8 +551,8 @@ 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", "never", "ask", "twice")
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
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",
"--change", "write the failing test first and show it fail with `pytest -k new`")
@@ -588,7 +588,7 @@ class ExportImportTests(PersonalCase):
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", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
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",
"--change", "write the failing test first and show it fail with `pytest -k new`")
@@ -632,7 +632,7 @@ def LessonRows():
class LessonDumpTests(PersonalCase):
RETRO = ["--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
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",
"--change", "write the failing test first and show it fail with `pytest -k new`"]
@@ -659,7 +659,7 @@ class LessonDumpTests(PersonalCase):
self.assertEqual(len(self.git_log()), n + 1)
def test_learn_and_note_are_personal_and_committed(self):
self.ok("learn", "Always", "use", "options")
self.ok("learn", "--scope", "everywhere", "Always", "use", "options")
self.assertIn("learn: Always use options", self.git_log()[0])
self.assertIn("learn-quarantine.jsonl", pdata.git("ls-files").stdout)
self.assertFalse(os.path.exists(os.path.join(self.state, "learn-quarantine.jsonl")))
@@ -738,7 +738,7 @@ class ProductIsReadOnlyTests(PersonalCase):
gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False})
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",),
("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"),
("learn", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
("learn", "--scope", "everywhere", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
("contract", "init", "--goal", "g"), ("verify",), ("migrate",), ("update",),
("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)]
for c in cmds:
+56
View File
@@ -153,5 +153,61 @@ class LabelledMatchingTests(PromptCase):
self.assertIn("sisi done release", self.ctx("cut a new release and tag it"))
class RecipeFloorLabelledTests(SisiCase):
"""Long real-style multi-part requests and plain questions. Expected is a recipe id or None."""
CASES = [
("Please change the brand text everywhere it appears: the product is now called sisi is still improving in the help text, the README, the docs and the version banner, and update any tests that pin the old name; do not change behaviour, commands or file layout, just the words users see, and check nothing else still says the old name", None),
("Should lessons be universal, or can a lesson mention the project it came from?", None),
("Rename the exported brand string in the CLI help, the man page draft and the docs index to the new product name, keep every command name and flag exactly as it is, and make the tests that assert the old wording pass with the new wording", None),
("Fix the bug where the parser crashes on an empty file, a reported defect: reproduce it with a failing test first, find the cause in the tokeniser, fix only that, and run the whole suite to show nothing else changed", "bugfix"),
("Build a new command-line tool that runs from a shell with arguments and standard output, converting delimited files to JSON: flags for input and output, clear errors and exit codes for bad input, help text that matches behaviour, and tests for empty and huge inputs", "cli-tool"),
("Change the web settings page in the browser app to add a dark mode toggle, check the interface in a real browser at phone and desktop sizes, keep keyboard use working and do not move anything else on the page", "web-ui-change"),
("Upgrade the HTTP client library to the next major version, read its changelog for behaviour changes, pin it in the lockfile and make the whole suite pass from a clean checkout without weakening tests", "dependency-upgrade"),
("Performance work on the export job: make it faster and lighter on resource use, take a measured baseline first on the same inputs, speed up the hot loop, show identical outputs afterwards and report before and after latency timings with a spread", "performance-work"),
("Migrate the stored records to the new schema: every record in a realistic copy must survive, counts must match before and after by an independent check, old files must still load and running it twice must be safe", "data-migration"),
("Fix the security vulnerability where user input reaches the shell command, an injection weakness: reproduce it with an attack-shaped exploit test, fix the root cause everywhere the pattern occurs and keep legitimate behaviour unchanged", "security-fix"),
("Add an MCP server that AI agents call to search the catalogue: each tool needs a clear name and description, validated inputs, small structured outputs, and real agent tasks to prove agents pick the right tool", "agent-tool-surface"),
("Write the release: tag the version, make the manifest, tag and changelog agree, build the package from a clean checkout and check a fresh machine can install and upgrade it", "release"),
("Refactoring the billing module: change the structure of the code to remove the duplicated rounding logic without changing what it does, capture the current outputs and public interface first, compare afterwards and show performance did not get worse", "refactor"),
("Change the build configuration and CI workflow so the tests run on every push, run it in the real CI system, and show the new step fails when it should and secrets are not in the logs", "config-or-infra-change"),
]
QUESTIONS = [
"Should lessons always be universal, or can they name a project?",
"Why did the last learning round get refused as stale?",
"What does the recipe for releasing actually require in full?",
"Can a lesson mention a file name and still apply everywhere?",
"How does request-time delivery decide which recipe to hand over?",
"Is it better to fold this lesson into a rule or into an entry?",
"Whether we keep project facts with the project or in the general notes?",
"Do you think the backlog should have its own size limit?",
]
def test_labelled_requests(self):
from sisi import prompt as P
hits = false_matches = 0
for text, want in self.CASES:
got = P._best_recipe(text)
got_id = got["id"] if got else None
if got_id == want:
hits += 1
elif got_id is not None:
false_matches += 1
self.assertEqual(got_id, want, "%r -> %r (want %r)" % (text[:60], got_id, want))
self.assertGreaterEqual(len(self.CASES), 12)
def test_questions_get_nothing(self):
from sisi import prompt as P
for q in self.QUESTIONS:
self.assertEqual(P.build_context(q), "", q)
self.assertGreaterEqual(len(self.QUESTIONS), 8)
def test_reconstructed_failures(self):
from sisi import prompt as P
brand, question = self.CASES[0][0], self.CASES[1][0]
self.assertIsNone(P._best_recipe(brand))
self.assertNotEqual((P._best_recipe(question) or {}).get("id"), "bugfix")
self.assertEqual(P.build_context(question), "")
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -10,7 +10,7 @@ GOOD = dict(aim="verified",
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",
target="parser-or-codec")
scope="everywhere", target="parser-or-codec")
def argv(f):
@@ -265,7 +265,7 @@ class SimilarityAndSameAsTests(RetroCase):
def test_dissimilar_lesson_accepted_directly(self):
self.retro()
other = dict(aim="speed", change_kind="tool", target="",
other = dict(aim="speed", change_kind="tool", target="", scope="everywhere",
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",
+277
View File
@@ -0,0 +1,277 @@
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")
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("everywhere", 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-scope", "scope": "everywhere"}]}
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()
+3 -2
View File
@@ -83,8 +83,9 @@ class StoreTests(SisiCase):
def test_note_propose_learn_append_with_context(self):
for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn-quarantine.jsonl")):
self.assertEqual(self.sisi(cmd, "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
self.sisi(cmd, "second")
extra = ["--scope", "everywhere"] if cmd == "learn" else []
self.assertEqual(self.sisi(cmd, *(extra + ["first", "entry"]), env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
self.sisi(cmd, *(extra + ["second"]))
recs = self.read(fn)
self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
self.assertEqual(recs[0]["cwd"], self.proj)
+269
View File
@@ -0,0 +1,269 @@
import json, os, random, stat, time, unittest
from support import *
FAKE_CODEX = """#!/bin/sh
case "$1 $2" in
"debug models") echo '{"models":[{"slug":"alpha-1"},{"slug":"alpha-contributor-x"}]}' ;;
"exec "*) echo '{"type":"error","error":{"type":"provider.go-limit","message":"monthly usage limit reached","status":429,"retryAfterMs":60000}}' ;;
*) echo 'codex help' ;;
esac
exit 0
"""
FAKE_MUSE = """#!/bin/sh
case "$1" in
exec)
if [ "$2" = "--list-models" ]; then echo "beta-1"; echo "beta-2"; exit 0; fi
echo "worker final report: done ok" ;;
usage) echo '{"allowance":{"tier":"flat plan","weekly":{"usedPercent":25},"window":{"usedPercent":10}}}' ;;
*) echo 'muse help' ;;
esac
exit 0
"""
FAKE_CURSOR = """#!/bin/sh
echo "Error: Authentication required. Run 'agent login' to sign in" >&2
exit 0
"""
FAKE_CLAUDE = """#!/bin/sh
echo "claude final report"
exit 0
"""
class WorkerCase(SisiCase):
def setUp(self):
super().setUp()
self.bindir = os.path.join(self.tmp, "bin")
os.makedirs(self.bindir)
for name, body in (("codex", FAKE_CODEX), ("muse", FAKE_MUSE), ("cursor-agent", FAKE_CURSOR),
("claude", FAKE_CLAUDE)):
p = os.path.join(self.bindir, name)
with open(p, "w") as f:
f.write(body)
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
def env(self, **kw):
return dict(PATH=self.bindir, **kw)
def write_data(self, name, obj):
os.makedirs(self.data, exist_ok=True)
with open(os.path.join(self.data, name), "w") as f:
json.dump(obj, f)
def brief(self):
p = os.path.join(self.proj, "brief.md")
open(p, "w").write("You are a worker. Do the toy task and report back.\n")
return p
class DiscoveryTests(WorkerCase):
def test_workers_lists_tools_models_and_reasons(self):
r = self.sisi("workers", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("codex", r.stdout)
self.assertIn("alpha-1", r.stdout)
self.assertIn("beta-1", r.stdout)
self.assertIn("allowance left", r.stdout) # muse usage reported 75% weekly left
self.assertIn("cursor-agent", r.stdout)
self.assertIn("not logged in", r.stdout.lower())
self.assertIn("models learned by use", r.stdout) # tools with no listing command
def test_discovery_is_cached_in_personal_store(self):
self.sisi("workers", env=self.env())
cache = json.load(open(os.path.join(self.data, "workers.json")))
self.assertIn("checked", cache)
tools = {t["name"]: t for t in cache["tools"]}
self.assertIn("alpha-1", tools["codex"]["models"])
self.assertFalse(tools["cursor-agent"]["usable"])
class LedgerImportTests(WorkerCase):
def test_existing_ledger_imported_once_losslessly(self):
src = os.path.join(self.tmp, "orch-log.jsonl")
rows = [
{"kind": "attempt", "id": "abc123", "ts": 1700000000, "project": "p", "type": "impl",
"difficulty": 2, "worker": "beta-1", "outcome": "accepted", "check": "tests",
"minutes": 3, "tokens": None, "retry_of": None, "note": "keep me", "extra": [1, 2]},
{"kind": "attempt", "id": "def456", "ts": 1700000100, "project": "p", "type": "impl",
"difficulty": 2, "worker": "beta-1", "outcome": "rejected", "check": "read",
"minutes": 4, "tokens": 9, "retry_of": "abc123", "note": None},
{"kind": "amend", "id": "abc123", "ts": 1700000200, "note": "later wrong"},
]
with open(src, "w") as f:
for row in rows:
f.write(json.dumps(row) + "\n")
before = open(src).read()
r = self.sisi("workers", env=self.env(SISI_LEDGER=src))
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("imported 3 rows", r.stdout)
self.assertEqual(open(src).read(), before, "the original ledger must not be modified")
got = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
self.assertEqual(len(got), 3)
for want, have in zip(rows, got):
for k, v in want.items():
self.assertEqual(have.get(k), v, k)
# a second run imports nothing more
self.sisi("workers", env=self.env(SISI_LEDGER=src))
got2 = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
self.assertEqual(len(got2), 3)
class RouteTests(WorkerCase):
def test_route_explains_and_skips_contributor_and_logged_out(self):
r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("contributor-x", r.stdout.splitlines()[0])
self.assertIn("contributor", r.stdout) # named as passed over
self.assertIn("cursor-agent", r.stdout)
def test_route_review_picks_another_maker(self):
r = self.sisi("route", "--kind", "review", "--difficulty", "1", "--review-of", "codex/alpha-1",
"--explain", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("alpha", r.stdout.splitlines()[0])
class DelegateTests(WorkerCase):
def test_limit_with_success_exit_is_unavailability_and_retries_next(self):
r = self.sisi("delegate", "--kind", "impl", "--difficulty", "2", "--brief", self.brief(),
"--worker", "codex/alpha-1", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("worker final report: done ok", r.stdout) # fell through to muse
self.assertIn("sisi delegate judge", r.stdout)
avail = json.load(open(os.path.join(self.data, "worker-availability.json")))
self.assertTrue(any("alpha" in k or k == "codex" for k in avail), avail)
entries = list(avail.values())
self.assertEqual(entries[0]["reason"], "limit")
self.assertGreater(entries[0]["retry_at"], time.time())
# the limit failure is not recorded as bad work
recs = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
attempts = [x for x in recs if x.get("kind") == "attempt"]
self.assertEqual(attempts, [])
runs = [x for x in recs if x.get("kind") == "run"]
self.assertEqual(len(runs), 1)
self.assertTrue(os.path.isfile(runs[0]["transcript"]))
def test_unjudged_run_shows_then_judge_records_attempt(self):
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(),
"--worker", "muse/beta-1", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
w = self.sisi("workers", env=self.env())
self.assertIn("waiting for a judgement", w.stdout)
recs = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
run = [x for x in recs if x.get("kind") == "run"][0]
j = self.sisi("delegate", "judge", run["id"], "--outcome", "accepted", "--check", "tests",
"--minutes", "2", env=self.env())
self.assertEqual(j.returncode, 0, j.stderr)
recs = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
attempts = [x for x in recs if x.get("kind") == "attempt"]
self.assertEqual(len(attempts), 1)
self.assertEqual(attempts[0]["type"], "read")
self.assertEqual(attempts[0]["check"], "tests")
w2 = self.sisi("workers", env=self.env())
self.assertNotIn("waiting for a judgement", w2.stdout)
def test_no_bypass_flag_is_passed(self):
marker = os.path.join(self.tmp, "argv.txt")
p = os.path.join(self.bindir, "muse")
open(p, "w").write("#!/bin/sh\necho \"$@\" > %s\ncase \"$1\" in exec) [ \"$2\" = \"--list-models\" ] && echo beta-1 && exit 0;; esac\necho ok-report\n" % marker)
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(),
"--worker", "muse/beta-1", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
argv = open(marker).read()
for bad in ("--yolo", "--disable-approval", "--disable-sandbox", "bypass", "dangerously"):
self.assertNotIn(bad, argv)
class SessionModelTests(WorkerCase):
def seed_strength(self, scores):
self.write_data("model-strength.json", {"models": {
m: {"score": s, "source": "test fixture", "date": "2000-01-01"} for m, s in scores.items()}})
self.write_data("workers.json", {"checked": time.time(), "tools": [
{"name": "muse", "usable": True, "models": ["beta-1", "beta-2"]},
{"name": "codex", "usable": True, "models": ["alpha-1"]}]})
def tick(self, payload):
return self.sisi("tick", stdin=json.dumps(payload))
def test_hookio_keeps_model(self):
from sisi import hookio
n = hookio.normalize("codex", {"session_id": "s", "cwd": "/w", "model": "alpha-1"})
self.assertEqual(n.get("model"), "alpha-1")
def test_tick_stores_model_and_strong_line(self):
self.seed_strength({"beta-1": 95, "alpha-1": 60})
r = self.tick({"session_id": "strong-1", "cwd": self.proj, "source": "startup", "model": "beta-1"})
self.assertEqual(r.returncode, 0, r.stderr)
rec = json.load(open(os.path.join(self.state, "sessions", "strong-1.json")))
self.assertEqual(rec.get("model"), "beta-1")
self.assertIn("sisi delegate", r.stdout)
self.assertIn("strongest", r.stdout)
def test_tick_weak_line_names_stronger(self):
self.seed_strength({"beta-1": 95, "alpha-1": 60})
r = self.tick({"session_id": "weak-1", "cwd": self.proj, "source": "startup", "model": "alpha-1"})
self.assertIn("do the work yourself", r.stdout)
self.assertIn("beta-1", r.stdout)
def test_tick_subagent_gets_no_delegation_line(self):
self.seed_strength({"beta-1": 95})
r = self.tick({"session_id": "sub-1", "cwd": self.proj, "source": "startup",
"model": "beta-1", "agent_id": "agent-7"})
self.assertNotIn("sisi delegate", r.stdout)
self.assertNotIn("do the work yourself", r.stdout)
def test_tick_unknown_strength_says_so(self):
r = self.tick({"session_id": "unk-1", "cwd": self.proj, "source": "startup", "model": "mystery-9"})
self.assertIn("unknown", r.stdout.lower())
class RoutingPropertyTests(unittest.TestCase):
def test_choice_invariants_over_generated_records(self):
from sisi import routing
rng = random.Random(20261123)
makers = ["alpha", "beta", "gamma"]
for _ in range(200 * ITERS):
cands, records, avail = [], [], {}
now = 1000000.0
for i in range(rng.randint(0, 7)):
maker = rng.choice(makers)
model = "%s-m%d%s" % (maker, i, "-contributor-z" if rng.random() < 0.15 else "")
w = "tool%d/%s" % (i, model)
cands.append({"worker": w, "tool": "tool%d" % i, "model": model, "maker": maker,
"plan": rng.choice(["flat", "per-use", None]),
"cost": rng.choice([None, 1.0, 5.0, 20.0]),
"allowance_pct_left": rng.choice([None, 0, 40, 90]),
"usable": True, "aliases": [w, model]})
if rng.random() < 0.3:
avail[w] = {"reason": "limit", "retry_at": now + 3600, "fails": 1}
for _ in range(rng.randint(0, 12)):
records.append({"kind": "attempt", "id": "r%d" % rng.randint(0, 10 ** 6),
"type": "impl", "difficulty": rng.choice([1, 2, 3]),
"worker": w, "outcome": rng.choice(["accepted", "rejected"]),
"check": "tests", "ts": now - 100})
author = rng.choice(cands)["worker"] if cands and rng.random() < 0.5 else None
a = routing.choose(cands, records, avail, "impl", rng.choice([1, 2, 3]),
review_of=author, now=now)
b = routing.choose(cands, records, avail, "impl", 2, review_of=author, now=now)
again = routing.choose(cands, records, avail, "impl", 2, review_of=author, now=now)
self.assertEqual((b["choice"] or {}).get("worker"), (again["choice"] or {}).get("worker"),
"choice must be deterministic for the same record")
if a["choice"] is None:
continue
w = a["choice"]["worker"]
self.assertNotIn("contributor", w)
self.assertNotIn(w, avail, "never picks an unavailable worker")
if author:
author_maker = next(c["maker"] for c in cands if c["worker"] == author)
others = [c for c in cands if c["maker"] != author_maker
and "contributor" not in c["worker"] and c["worker"] not in avail
and not (c["plan"] == "flat" and c["allowance_pct_left"] == 0)]
if others:
self.assertNotEqual(a["choice"]["maker"], author_maker)
if __name__ == "__main__":
unittest.main()