From e5b603486bbe6b307cfb39351a9501bdc5b81a10 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 03:16:06 -0700 Subject: [PATCH] Shorter README with nothing that goes stale; honest rulebook budget; complete cycle instructions README cut by about 40 percent, with tests that refuse version numbers, counts, years and a word ceiling. The rulebook budget now counts characters as well as lines. Folded lessons no longer count as loose notes, reading a lesson no longer invalidates a cycle, and the cycle brief answers the twenty gaps the first real cycle reported. Adds `sisi cycle check`. Co-Authored-By: Claude Fable 5.2 --- CONTRIBUTING.md | 14 +- README.md | 311 +++++++++------------- docs/design.md | 8 +- docs/harnesses.md | 9 +- docs/learning.md | 49 +++- docs/verifier-format.md | 4 +- sisi/cli.py | 8 +- sisi/cycle.py | 573 +++++++++++++++++++++++++++++++++------- sisi/overlay.py | 42 ++- sisi/retro.py | 20 +- tests/test_learning.py | 244 +++++++++++++++++ tests/test_public.py | 61 +++++ 12 files changed, 1026 insertions(+), 317 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f682b4e..9e7c79e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,9 +7,9 @@ Thanks for looking. sisi is small on purpose; this page says how to change it sa python3 tests/run_parallel.py # every test file in its own process, side by side python3 -W ignore::ResourceWarning -m unittest discover -s tests # the same tests, one at a time bin/sisi verifiers lint - bin/sisi verify # runs the same two checks through sisi's own contract (.sisi/contract.json) + bin/sisi verify # runs sisi's own contract (.sisi/contract.json) -Side by side the suite takes well under a minute on an idle machine; one at a time, a minute or two. Tests never touch your real home folder: they point `SISI_HOME` and `SISI_STATE` +Tests never touch your real home folder: they point `SISI_HOME` and `SISI_STATE` at temporary directories, and a test fails at once if a path resolves outside them. Set `SISI_TEST_ITERS=10` to run the property tests with more iterations. @@ -19,8 +19,14 @@ A pull request should pass all three. If you fix a bug, add a test that fails wi - Standard library only. No third-party packages, no build step, no install step beyond cloning. This is what lets the tool run unchanged in any tool's hook, on any machine with Python. -- Python 3.9 or newer (see the README for how that was determined). Do not use syntax or library calls that need a - newer version. +- Python 3.9 or newer. Do not use syntax or library calls that need a newer version. The minimum + was set by reading the code, not by running old interpreters: every Python file parses with + `ast.parse(..., feature_version=(3, 8))`, and there are no `match` statements, `X | Y` types or + walrus operators. The newest standard library features in use, `shutil.copytree(..., + dirs_exist_ok=True)` and `sys.pycache_prefix`, were added in 3.8; the stated minimum is 3.9 + because 3.8 is end of life and the CI runners in use do not offer it. Which versions and systems + CI proves is stated in `.github/workflows/ci.yml`; read that file rather than trusting a list + here. - Hooks (`sisi tick`, `sisi gate`) must stay fast and must fail open: anything that goes wrong inside sisi lets the agent through and is logged. - sisi never writes into the product folder at run time. Anything it writes goes to the personal data folder or diff --git a/README.md b/README.md index d02839a..cf923cf 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,73 @@ # sisi: self-improving superintelligence -**The purpose of sisi is that your AI agents get better at working for you on every single turn, in every tool, -without you doing anything.** Each piece of work ends with the agent recording how it could have gone better. -That lesson goes into one store that every agent in every tool reads, so the next turn, in any tool, starts -smarter than the last one. Lessons that keep recurring are strengthened until the mistake cannot happen again. +**Your AI agents get better at working for you on every turn, in every tool, automatically, just by +being used. There is nothing to schedule or maintain.** Each piece of work ends with the agent +recording how it could have gone better. That lesson goes into one store that every agent in every +tool reads, so a later turn in any tool can start from it. A lesson that recurs after being shown is +strengthened until an enforced check stops the mistake. -The direction it pushes is fixed: you state an outcome at a higher and higher level (a function, then a module, -then a product) and get it back correct, complete, verified by the strongest method available, and fast, with -fewer and fewer interruptions. +The direction is fixed: state an outcome at a higher level and get it back correct, complete, +verified by the strongest method available and fast, with fewer interruptions. An agent writes +down how success will be checked, runs those checks before saying it is done, and is sent back +when they fail. -To improve, an agent first has to know whether it succeeded. So sisi also makes an agent write down how success -will be checked, run those checks before it says it is done, and get sent back when they fail. It is a rulebook -and a small command-line tool, plain Python with no dependencies. What it learns about you is kept outside the -clone, so updating never loses it. +sisi is a shared rulebook and a small command-line tool in plain Python with no dependencies. What +it learns about you is kept outside the clone, so updating never loses it. -**How far along this is.** The name states the goal, not the present. Today every turn is checked, measured and -ends with a recorded lesson; each lesson takes effect at once (a field note, a draft recipe, a learned note or -a backlog item), is offered to later agents when they start that kind of work (strong matches in full, the rest as one-line -headings the agent chooses from), and is strengthened when the same problem recurs -after being shown — up to an enforced check the gate runs. Consolidation (`sisi cycle`) folds lessons into the -rulebook without growing it, and `sisi improve` reports whether any of this is working. There is nothing to -schedule: it all runs from normal use. See [Status](#status) for exactly what works, and -[docs/learning.md](docs/learning.md) for the loop in plain words. What is not yet shown: that this makes agents -measurably better over weeks of real use. `sisi improve` exists to answer that, and it needs use to have data. - -## Why it exists - -- **Agents report "done" without proof.** The definition of done is usually a sentence in an instruction file. - Nothing makes the agent write it as something runnable, and nothing stops it ending a turn when a check fails. -- **Each tool learns separately.** A lesson learned in one tool is lost to the others, and instructions drift apart - across `CLAUDE.md`, `AGENTS.md` and friends. -- **The work takes too long.** Nobody measures the time from a request to a result that is actually verified, so - nobody can tell whether a change to the instructions helped. +The name states the goal, not the present. What is not yet shown is that this makes agents +measurably better over weeks of real use. `sisi improve` reports the counted evidence for that +question, and it needs real use to have data. ## How it works -- **A contract per piece of work.** `.sisi/contract.json` in the project lists the checks that decide success, - each with the claim it supports, a command, the result expected and its rung (below). It can also list - invariants (what must not get worse), assumptions and open questions. The agent drafts it from the request. -- **A ladder of checks.** Each check is rated by how strong the evidence is: 1 proof, model checking or the type - system; 2 property-based tests, fuzzing, comparison with a reference; 3 example tests; 4 golden files and - snapshots, including screenshots; 5 a rubric scored by an independent judge; 6 the human. The rulebook tells the - agent to use the highest rung that is feasible, and sets a minimum rung for kinds of claim that need it - (concurrency, parsing, money, state machines, data migration). -- **An end-of-turn gate.** A hook calls `sisi verify` when the agent tries to finish. If a check fails or did not - run, the agent is sent back with the failures. If a large change has no contract, it is sent back to write one. - Small edits pass. After three send-backs in a row the agent is let through and the result is marked unverified, - so a broken check cannot trap a session. Today this blocks in Claude Code, Codex, Gemini CLI, Copilot CLI, - Qwen Code and Pi, and sends the agent back with a follow-up message in Cursor (see the table below). -- **A retrospective after each piece of work.** `sisi retro` records how the work could have gone better, against - five aims: the human could have worked at a higher level, a stronger check was possible, the human was - interrupted more than needed, the result was not what they meant, it took longer than it had to. Retros become - shared lessons (`sisi lessons`), which every tool reads. -- **Time to delivery.** Each time the gate lets a turn end, sisi records the time since the human's last typed - message, how many times it sent the agent back, and how long the checks took. `sisi time` compares the last 7 - days with the 7 before. -- **One shared store.** The rulebook, lessons, results and settings are written once and read by every tool, which - are connected by reference (an import line or a symlink), never by copy. +`sisi retro` ends each piece of work by recording how it could have gone better: the moment, the +cause, and the change that would make a later agent do it right without being told, in the words a +different agent would use for that work. The lesson takes effect in your personal store at once and +is offered to later agents starting matching work. If the problem recurs after a lesson has been +shown, it is strengthened: a note, a candidate rule, then an enforced check the gate runs. +`sisi cycle` consolidates lessons into rules and library entries without growing the rulebook. +Whether it is due is checked during normal use, so nothing is scheduled; see +[docs/learning.md](docs/learning.md). + +Improvement needs a way to tell success from failure: + +- **A contract of executable checks.** `.sisi/contract.json` lists the checks that decide success, + each with its claim, a command, the result expected and its rung, plus invariants (what must not + get worse), assumptions and open questions. The agent drafts it from the request. +- **A ladder of six rungs.** Rung 1 proof, model checking or the type system; rung 2 + property-based testing, fuzzing or comparison with a reference; rung 3 examples; rung 4 golden + files and snapshots, including screenshots; rung 5 a rubric scored by an independent judge; rung + 6 the human. Use the highest feasible rung; some claim kinds have a minimum (concurrency, + parsing, money, state machines, data migration). +- **An end-of-turn gate.** A hook runs `sisi verify` when the agent tries to finish. A failing or + unrun check sends it back, a large change with no contract sends it back to write one, and small + edits pass. After repeated send-backs it is let through marked unverified, so a broken check + cannot trap a session. +- **Time to delivery.** When the gate lets a turn end, sisi records how long the verified result + took and how often the agent was sent back. `sisi time` reports it. +- **One shared store.** Rulebook, lessons, results and settings are written once and read by every + tool, connected by reference (an import line or a symlink), never by copy. ## Quick start -Requirements: Python 3.9 or newer (see "Python versions" below), and `git`. Linux and macOS are what the tests and -CI are meant to cover; Windows is not supported (the code imports `fcntl`). +Requirements: Python 3.9 or newer, and `git`, on Linux or macOS. Windows is not supported (the code +imports `fcntl`). The minimum Python version is proved by CI; the reasoning is in +[CONTRIBUTING.md](CONTRIBUTING.md). git clone https://github.com/swaits/sisi.git cd sisi - bin/sisi install # wire sisi into the tools it finds; backs up every file it edits - bin/sisi doctor # shows what is wired in each tool + bin/sisi install --dry-run + bin/sisi install + bin/sisi doctor -`sisi install` links `bin/sisi` as `~/.local/bin/sisi`; make sure that folder is on your `PATH`, or call -`bin/sisi` from the clone. It edits your tools' global instruction files only by adding an import line, and -`sisi uninstall` restores every file you have not edited since exactly as it was, and removes only its own -entries from a file you have edited. `sisi install --dry-run` shows every change first and makes none. It skips any tool whose configuration folder does not exist. +The dry run prints every change and makes none. Install backs up every file it edits, adds only an +import line, a link, hook entries or a generated plugin, and skips a missing configuration folder. +It links the command as `~/.local/bin/sisi`; make sure that folder is on your `PATH`, or call +`bin/sisi` from the clone. `sisi doctor` shows what is wired and anything you must still do. -Now a first contract. Change to one of your own projects (not the sisi clone), where `sisi contract init --goal "slugify() turns titles into URL slugs"` creates a -skeleton whose placeholder check fails until you replace it. Replace it with a real check. Here, for a small -function and a test next to it: +For a first contract, change to one of your own projects and run +`sisi contract init --goal "slugify() turns titles into URL slugs"`. That skeleton's placeholder +check fails until you replace it. For a small function with a test next to it: { "id": "slugify", @@ -96,158 +88,107 @@ function and a test next to it: "questions": [] } -Then: +Trimmed output: $ sisi verify - ID KIND RUNG TIER STATUS SECS - examples general 3 fast passed 0.1 - + ... OK -`sisi verify` exits 0 when every check passes, 1 when one fails, 2 when there is no contract and 3 when the -project is not trusted (see Security). With the hook installed you do not run it yourself: the agent writes the -contract, and the gate runs it at the end of each turn. +`sisi verify` succeeds only when every check passes; `sisi help` lists the other exit meanings. +With a hook wired you do not run it yourself: the agent writes the contract and the gate runs it. -## Which tools are supported +## Supported tools -| Tool | Rulebook loaded | Lessons at session start | End-of-turn enforcement | How verified | -|---|---|---|---|---| -| Claude Code | yes | yes | blocks | ran end to end | -| Codex CLI | yes | yes | blocks | built from documentation; session-start hook fired live | -| Gemini CLI | yes | yes | blocks | built from documentation | -| GitHub Copilot CLI | yes | yes | blocks | ran end to end | -| Qwen Code | yes | yes | blocks | built from documentation; session-start hook fired live | -| Pi | yes | yes | blocks | built from documentation; extension loaded and tick ran live | -| Cursor | no (no confirmed global file) | yes | sends a follow-up | built from documentation | -| OpenCode | yes | no | unknown | built from documentation; plugin load verified live | -| Muse Code | yes (via the Claude/Codex files) | no | unknown | not built | -| Antigravity | via the shared Gemini file | no | unknown | not built | -| Windsurf | pointer file | no | none | built from documentation | -| Cline | yes | no | none | built from documentation | -| Kiro | yes | no | none | built from documentation | -| Zed | yes | no | none | built from documentation | -| Goose | yes | no | none | built from documentation | -| Amp | yes | no | none | built from documentation | -| Grok CLI | yes | no | none | ran end to end (`grok inspect` lists the file as global) | -| Crush | yes | no | none | built from documentation | -| Aider | yes (via `read:` in an existing `~/.aider.conf.yml`) | no | none | built from documentation | -| T3 Code | via provider | via provider | via provider | host app; nothing to wire | -| Orca | via provider | via provider | via provider | host app; nothing to wire | +Enforcement is what happens at the end of a turn; evidence is how the wiring was checked. +`sisi doctor` gives the live state on your machine. Per-tool detail, limits and steps you must +take are in [docs/harnesses.md](docs/harnesses.md). -This table comes from `sisi doctor` and the wiring code (`sisi/wiring.py`, `sisi/adapters.py`); per-tool limits -and any step you must take yourself are in [docs/harnesses.md](docs/harnesses.md). Where there is no gate, the -rulebook still tells the agent to write and run a contract, but nothing enforces it. `sisi install` is skipped -for a tool whose configuration folder is missing, and `sisi install --dry-run` prints exactly what would be -created, edited (with diffs) or skipped while changing nothing. The uninstall guarantee: a file you have not -edited since install is restored byte for byte (or removed, if sisi created it); a file you have edited since -install keeps your edits, with only sisi's own entries removed and every other byte left as it was; a file -sisi cannot edit with certainty is skipped and reported, never rewritten, and a generated plugin or extension -you edited is left alone entirely. Agent skills linked into `~/.agents/skills` are supported by the wiring but -the product ships none yet. +| Tool | Enforcement | Evidence | +|---|---|---| +| Claude Code | blocks | ran end to end | +| Codex CLI | blocks | documentation; session-start hook fired live | +| Gemini CLI | blocks | documentation | +| GitHub Copilot CLI | blocks | ran end to end | +| Pi | blocks | documentation; extension loaded, tick ran live | +| Qwen Code | blocks | documentation; session-start hook fired live | +| Cursor (no confirmed global rulebook file) | sends a follow-up | documentation | +| Aider (existing config file only) | rulebook only | documentation | +| Amp | rulebook only | documentation | +| Cline | rulebook only | documentation | +| Crush | rulebook only | documentation | +| Goose | rulebook only | documentation | +| Grok CLI | rulebook only | verified with `grok inspect` | +| Kiro | rulebook only | documentation | +| Windsurf (pointer file) | rulebook only | documentation | +| Zed | rulebook only | documentation | +| Antigravity (through the shared Gemini file) | unknown | nothing wired separately | +| Muse Code (through Claude Code or Codex files) | unknown | nothing wired directly | +| OpenCode | unknown | documentation; plugin loading verified live | +| Orca | through its provider | host app; nothing to wire | +| T3 Code | through its provider | host app; nothing to wire | + +Where there is no gate, the rulebook still tells the agent to write and run a contract, but nothing +enforces it. ## The verifier library -sisi ships 140 verification techniques in ten sections (design, prove, many-inputs, concurrency, test-quality, -regression, real-world, safety, intent, completeness) and 20 recipes that say what "done" means for a kind of -work (a bug fix, a new library, a data migration, a web UI change, and so on). Each technique has a minimal -example, the exact command, what passing looks like, and a JSON check to paste into a contract. Agents query it -instead of inventing a check from memory: +sisi ships verification techniques and recipes that say what "done" means for a kind of work, such +as a bug fix or a data migration. Each technique gives an example, the exact command, what passing +looks like, and a check to paste into a contract. `sisi verifiers` and `sisi done` list them, so +agents query them instead of inventing a check. Trimmed output: $ sisi verifiers for "a parser that must not crash on hostile input" 1. hostile-input-from-schema rung 2 cost medium installed: no - Does every call my API or tool accepts survive wrong, missing, huge and strange arguments with a clean error and no crash? 2. klee rung 1 cost high installed: no - Which inputs make this C program crash, overflow or break an assert, found by exploring its paths? - 3. afl-plus-plus rung 2 cost medium installed: no - Can any input make this native program or library crash, hang or trip a sanitizer? - 4. atheris rung 2 cost medium installed: no - Can any input make this Python code raise an exception it should not, hang, or crash the interpreter? - $ sisi done for "bug fix" # prints the full recipe for that kind of work +Matching is by word overlap, weighted toward the question each entry answers, so phrase the claim +as a doubt and read the top results rather than trusting the first. `sisi verifiers show ID` prints +an entry in full, `sisi verifiers doctor` reports installed tools, and `sisi done for "bug fix"` +prints a recipe. Format and quality bar: [docs/verifier-format.md](docs/verifier-format.md). -The chooser is keyword matching over each entry's header, so phrase the claim the way you would phrase a doubt, and -read the top few results rather than trusting the first. `sisi verifiers show ID` prints one entry in full, and -`sisi verifiers doctor` says which of the tools are installed on your machine. Format and quality bar: -[docs/verifier-format.md](docs/verifier-format.md). Most entries were run on the author's machine; the rest were checked against the -tools' documentation. Each header says which (`verified: ran | docs | memory`). +## Where data lives, updating and uninstalling -## Where data lives, and updating +- **The product** is the clone: code, base rulebook, library and defaults. It is never written at + run time. +- **What sisi learns for you** lives in `~/.local/share/sisi` (or `$SISI_DATA`), a local git + repository that is never pushed. +- **Scratch** that can be rebuilt lives in `~/.local/state/sisi` (or `$SISI_STATE`). -| Place | Where | What | -|---|---|---| -| Product | the clone | code, base rulebook, verifier library, recipes, defaults. Never written at run time. | -| Personal data | `~/.local/share/sisi` (or `$SISI_DATA`) | lessons, learned changes to rules (an overlay), your preferences, settings, trusted projects. A local git repository with every change committed, never pushed. | -| Scratch | `~/.local/state/sisi` (or `$SISI_STATE`) | rebuildable: transcript index, locks, logs, results | - -`sisi update` fast-forwards the clone (`git fetch` then a fast-forward merge; it refuses if you have local -changes), takes a backup of your personal data, migrates its format if needed, reapplies your overlay to the new -rulebook and rebuilds it. If the product changed a rule you had replaced, your version is kept and queued for a -re-test. `sisi export` and `sisi import` move personal data to another machine as one archive. More: +`sisi update` replaces only the product, after backing up your personal data, and reapplies what +you learned. `sisi status` shows the live state; the layout is in [docs/personal-data.md](docs/personal-data.md). -## Uninstalling +`sisi uninstall` removes the import line, hooks and links. A file you have not edited since install +is restored byte for byte. A file you edited keeps your edits and loses only sisi's entries. A file +sisi cannot edit with certainty is skipped and reported. Personal data and scratch are left for you +to delete. The exact guarantee is in [docs/harnesses.md](docs/harnesses.md). - sisi uninstall +## Designed but not built -removes the import line, hooks and links. A file not edited since install is restored byte for byte; a file you -edited keeps your edits and loses only sisi's entries. Your personal data and -scratch folders are left alone; delete them yourself if you want them gone. Then delete the clone. +[docs/design.md](docs/design.md) separates what is built from what is not. The main missing pieces: -## Status - -An early release. `sisi --version` prints the version, and [CHANGELOG.md](CHANGELOG.md) lists what changed. - -Works today, with tests: - -- Contracts, `sisi verify` (fast and deep tiers), the trust mechanism, the end-of-turn gate and session-start hook. -- Wiring for every tool in the table above: blocking gates in Claude Code, Codex, Gemini CLI, Copilot CLI, - Qwen Code and Pi; a follow-up gate in Cursor; rulebook-only links elsewhere; an OpenCode plugin whose - enforcement is unproven (see [docs/harnesses.md](docs/harnesses.md)); and `sisi doctor`, `audit`. -- The verifier library and recipes, with `sisi verifiers lint`. -- Retros, lessons, quarantined preferences, time to delivery, personal data, overlay, update, export and import, - releases and rollback. -- The learning loop that acts on lessons: immediate effects (field notes, draft recipes, learned notes, - `sisi backlog`), delivery at the matching moment, the strength ladder (note, candidate rule, enforced check), - consolidation (`sisi cycle`, with exact revert) and `sisi improve`. No scheduler: due-ness is a counter - checked at session start, at the end of each turn and in `sisi retro`, `sisi verify` and `sisi done for`. - Plain-words tour: [docs/learning.md](docs/learning.md). -- A data layer that reads past Claude Code transcripts into a local database and builds a task set, escape - candidates, per-check statistics and a weekly scoreboard (`sisi harvest`, `tasks`, `escapes`, `checks`, - `scoreboard`; these are not listed in `sisi help`). - -Designed but not built (see [docs/design.md](docs/design.md)): - -- The build conductor: `sisi build ""` turning a statement into verified work, and the question queue - (`sisi inbox`). Neither command exists. -- Replay experiments on a task set before a learned change ships, and the taste judge and playbooks. Learned - changes currently ship first (personal overlay only) and are judged by measured deliveries afterwards, with - exact revert and withdrawal as the safety net; the data layer above is groundwork for the replay version. -- Proven end-to-end enforcement in OpenCode, and harvest of transcripts from tools other than Claude Code. - -Not verified: whether Codex and OpenCode obey the rulebook as well as Claude Code does. - -### Python versions - -The minimum is Python 3.9. This was determined by reading, not by running old interpreters. Every Python file parses -with `ast.parse(..., feature_version=(3, 8))`, and a search found no `match` statements, no `X | Y` types and no -walrus operators. The newest standard-library features in use are `shutil.copytree(..., dirs_exist_ok=True)` and -`sys.pycache_prefix`, both added in 3.8. The stated minimum is 3.9 because 3.8 is end of life and current macOS runners do not -offer it. The test suite was run here on Python 3.11 and 3.14 and passes. CI runs the tests on Linux and macOS with Python 3.10, 3.11 and 3.13, and with 3.9 on macOS (the -newest Ubuntu image no longer offers 3.9). +- The build conductor (`sisi build ""`) and its question queue (`sisi inbox`). + Neither command exists. +- Replay experiments on a task set before a learned change ships, a separate coach run, brief + templates and playbooks. Learned changes instead ship to your overlay first and are judged by + measured deliveries, with exact revert as the safety net. +- The taste judge (a model judging at rung 5), a git-survival signal, transcript harvest beyond + Claude Code, and proven end-to-end enforcement in OpenCode, reported by `sisi doctor` as unknown. ## Security -sisi runs commands that come from a project's contract. A contract in a project you did not write is untrusted -until you read it and run `sisi contract trust`; until then `sisi verify` refuses and the gate runs nothing. sisi -does not sandbox what a trusted contract runs. See [SECURITY.md](SECURITY.md), which also says how to report a -problem privately. +sisi runs commands from a project contract, so a contract you did not write is untrusted until you +read it and run `sisi contract trust`; until then `sisi verify` refuses and the gate runs nothing. +sisi does not sandbox what a trusted contract runs. See [SECURITY.md](SECURITY.md), including how +to report a problem privately. ## Contributing -Tests, the standard-library-only rule, the verifier entry format and what belongs in the product versus your own -overlay are in [CONTRIBUTING.md](CONTRIBUTING.md). A change log is in [CHANGELOG.md](CHANGELOG.md), and all docs are -indexed in [docs/README.md](docs/README.md). +Running the tests, the standard-library-only rule, the library entry format, and what belongs in +the product rather than your own overlay are in [CONTRIBUTING.md](CONTRIBUTING.md). For the release +you have, run `sisi --version`; changes between releases are in [CHANGELOG.md](CHANGELOG.md), and +all docs are indexed in [docs/README.md](docs/README.md). ## Licence -MIT. Copyright (c) 2026 Stephen Waits. See [LICENSE](LICENSE). +MIT. Copyright (c) Stephen Waits. See [LICENSE](LICENSE). diff --git a/docs/design.md b/docs/design.md index 71ff20e..e39239f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -156,7 +156,7 @@ 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. Today sisi only reads an optional +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. ## Part 3: learning that compounds @@ -220,7 +220,7 @@ that favours flat-rate plans first, then the cheaper models. Other things the loop would improve, besides rules: recipes are tightened whenever a bug gets past a passing set of checks; techniques are ranked by how often they catch real failures; checks that never fail are flagged -(`sisi checks` does this today); new models are scored on the task set before routing changes. +(`sisi checks` does this); new models are scored on the task set before routing changes. **Owning the instruction surface.** `sisi audit` lists every source of instructions each tool loads (instruction files, plugins, skills) and reports where they contradict the rulebook. Contradictions the loop @@ -255,7 +255,7 @@ replaced, the person's version stays and the item is queued for re-testing again Personal data carries a format version, and `sisi update` migrates it after taking a backup. One folder means one thing to back up or copy to another machine (`sisi export`, `sisi import`). Results and -session records stay in scratch for now and are included in the export. Nothing personal is ever placed in the +session records stay in scratch and are included in the export. Nothing personal is ever placed in the product, so the product can be published. Any agent in any tool reads through the files or the CLI and writes through the CLI: @@ -325,7 +325,7 @@ 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 exists today. +1. Delegation tooling is folded into sisi in the design; only the optional ledger read is built. 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 diff --git a/docs/harnesses.md b/docs/harnesses.md index 30a4655..0f1dbef 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -25,8 +25,9 @@ Wiring is always by reference: an import line, a symlink to the generated rulebo shell hook command first checks the sisi launcher still exists, so deleting the sisi folder without uninstalling makes hooks exit silently instead of erroring on every turn. The per-tool translation between each tool's hook JSON and the gate lives in `sisi/hookio.py`; the adapters live in -`sisi/adapters.py`; the textual JSON editing lives in `sisi/hookjson.py`. Hooks fail open: any error -lets the agent finish. +`sisi/adapters.py`; the textual JSON editing lives in `sisi/hookjson.py`. Install also links any +skills shipped under `canon/skills` into `~/.agents/skills`; `sisi doctor` reports the linked +state. Hooks fail open: any error lets the agent finish. ## Claude Code @@ -179,7 +180,7 @@ Code-compatible configuration; whether sisi's Claude hooks fire under Grok is no Rulebook symlink at `~/.config/crush/CRUSH.md` (or `$XDG_CONFIG_HOME/crush/CRUSH.md`, honoured as `crush dirs` confirms; one of Crush's default global context paths, confirmed from the binary's own -configuration schema). Crush hooks currently support only `PreToolUse`, which is not a turn gate, so +configuration schema). Crush hooks support only `PreToolUse`, which is not a turn gate, so sisi wires no hooks. Revisit when its session/turn hook events ship. ## Aider @@ -198,6 +199,6 @@ hooks. There is nothing T3- or Orca-specific to wire; wire the providers and bot ## Not wired -Roo Code was discontinued (2026-05-15) and gets no wiring; any remaining installs still read project +Roo Code was discontinued and gets no wiring; any remaining installs still read project `AGENTS.md`. Agents beyond the list above that read a project `AGENTS.md` (Factory, Warp, Junie and similar) are covered by the project file, with no per-tool wiring and no gate. diff --git a/docs/learning.md b/docs/learning.md index 4a7891c..1060895 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -47,17 +47,17 @@ what "done" means, verifying, or being sent back by the gate. 5. **Recurring lessons get stronger.** Each lesson has a strength: 1 (a note), 2 (a candidate rule), 3 (enforced). A recurrence after at least two showings since the last promotion moves it up one step — each step needs its own fresh evidence. A strength-2 lesson - becomes a real rule only through consolidation (below), because the rulebook has a hard budget of - 120 lines and must not grow. A strength-3 lesson needs a check the gate can run; a folded lesson + becomes a real rule only through consolidation (below), because the rulebook has hard budgets of + 120 lines and 7,200 characters and must not grow. A strength-3 lesson needs a check the gate can run; a folded lesson shown 20 times with no recurrence is retired from the notes (it stays in history); a lesson that still recurs at strength 3 is withdrawn, and the same wording will not be learned again. 6. **Consolidation happens in a cycle**, run by whichever agent is working — see below. ## The cycle (`sisi cycle`) -Consolidation is due when 5 or more lessons have been recorded since the last cycle, or a lesson is -waiting to move up a step, or the learned notes pass their size limit, or more than 30 lessons are -still loose (or their one-line headings pass the 1,500-character budget) — the loose list stays short +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 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 @@ -71,24 +71,47 @@ lessons that say the same thing; lift specific lessons into one general rule; fo entry it belongs to; say which existing rule text gets shorter so the book does not grow; write checks for strength-3 lessons). The agent answers with one JSON file: +The brief names the scratch path to write it to, lists every valid rule, recipe and verifier id +(with each recipe's one-line applies-to and the rule number-to-id map), shows full lesson text when +it fits its stated text budget (otherwise it says to run `sisi lessons show ID`), and puts the full +format behind `sisi cycle help`. `sisi cycle check FILE` (or `--dry-run`) validates and prints +exactly what would change, changing nothing. + ```json {"version": 1, "base": "", "summary": "one line", - "rules": [{"id": "rule-id", "title": "Title", "body": "text, ending with Why: ...", "action": "add|replace"}], + "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", - "into": "rule or entry id", "merged_into": 4, - "when": "at least 5 terms (optional; sets the lesson's when-terms)"}], + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft", + "into": "rule/entry id or [ids]", "merged_into": 4, "note": "split text (optional)", + "when": "at least 5 terms (optional)", "entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", + "reason": "why it stays a draft (keep-as-draft)"}], "enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30}, {"lesson": 4, "type": "contract-requirement", "when": "parser", "require_kind": "parsing", "max_rung": 2}]} ``` +`fold-into-entry` appends a dated field-note bullet (the lesson's change, or `note`) to +`notes/.md` and marks the lesson applied; `into` may be a list, and two notes for one lesson +with different `note` text split a compound lesson. `create-entry` creates a personal recipe or +verifier entry in the overlay, lint-checked; `keep-as-draft` keeps it as a draft with a reason. +`set-when` only sets when-terms. Merge only lessons requesting the same change, into the older or +more general one, which keeps its text and count; the other becomes superseded and needs no action. +Tool lessons cannot be done in a cycle: they stay in `sisi backlog`, except merging a duplicate. +Retire only what is fully folded and quiet (folded, at least 20 listed/read, no recurrences after +first listing); folding in this cycle does not make it quiet. The learned-notes limit counts only +`length(change)` of active strength-1 loose learned notes: folded lessons no longer count, which +is why folding (or merging, retiring, withdrawing, enforcing) reduces it. + `sisi cycle apply FILE` checks the file before writing anything: every lesson id exists, the base version is still current, changed rules keep their id and their Why, named `sisi` commands and -enforced programs exist, and the resulting rulebook is inside the budget and no longer than before -unless a rule was replaced. The base version plus the personal-data lock means two sessions -consolidating at once cannot overwrite each other: the second apply is refused and told to read a -fresh brief. A successful apply is one commit in your personal repository, with before-and-after +enforced programs exist, and the resulting rulebook is inside both budgets (120 lines and 7,200 +characters) and no longer in characters than before unless `shortens` names what was removed. +Rules are re-wrapped to 100 characters on apply. The base version covers only what a cycle may +change (lesson content and status, rules, notes, enforced checks), not listed/read counters, and +lessons recorded since the brief are left for the next cycle; a stale refusal names exactly what +changed. The base version plus the personal-data lock means two sessions consolidating at once +cannot overwrite each other: the second apply is refused and told to read a fresh brief. A successful apply is one commit in your personal repository, with before-and-after measurements. `sisi cycle revert` undoes the newest applied cycle exactly (the changed files byte for byte, and the lesson rows it touched). `sisi cycle status` shows each cycle with what happened since: deliveries, send-backs each, median time, and recurrences of the lessons it touched. A cycle whose diff --git a/docs/verifier-format.md b/docs/verifier-format.md index 3824f6e..c65dc42 100644 --- a/docs/verifier-format.md +++ b/docs/verifier-format.md @@ -34,8 +34,8 @@ verified: docs - `answers`: the question, in plain words, that a passing run answers. This is what the chooser matches on, so write it the way an agent would phrase its doubt. -- `rung`: 1 proof, model checking or types; 2 property tests, fuzzing, - differential, mutation; 3 example tests; 4 golden files and snapshots; +- `rung`: 1 proof, model checking or types; 2 property-based testing, fuzzing, + differential, mutation; 3 examples; 4 golden files and snapshots; 5 judged rubric; 6 human. - `languages`: comma list, or `any`. - `kinds`: any of general, concurrency, parsing, money, state-machine, diff --git a/sisi/cli.py b/sisi/cli.py index e6f9f36..6385107 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -22,7 +22,7 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co sisi update fast-forward the product clone, then back up, migrate and rebuild personal data sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it sisi build-canon regenerate the effective rulebook (base rules + your overlay) - sisi canon cost size of what is always loaded: rulebook lines and characters, lessons block maximum + sisi canon cost size of what is always loaded: rulebook lines and characters against both budgets, lessons block maximum 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 @@ -36,9 +36,11 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co sisi lessons [filters] | show ID | set ID --status S | apply ID | export [FILE] | import FILE the shared lessons from retros (--aim --kind --status --repo --top --json) sisi backlog tool lessons: changes to sisi itself, most seen first - sisi cycle [due|apply FILE|revert [ID]|status] + sisi cycle [due|apply FILE|check FILE|--dry-run FILE|revert [ID]|status|help] consolidate lessons into rules, entries and enforced checks (no - scheduler: due-ness is a counter checked during normal use) + scheduler: due-ness is a counter checked during normal use); + check/--dry-run prints what would change, changing nothing; + help prints the full cycle file format 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 diff --git a/sisi/cycle.py b/sisi/cycle.py index 4551289..eae1d36 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -19,7 +19,7 @@ Every part is optional except version and base. Apply is one commit in the perso 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, hashlib, json, os, re, shlex, shutil, time +import base64, difflib, hashlib, json, os, re, shlex, shutil, time from . import overlay, paths, pdata, retro, store @@ -28,7 +28,11 @@ class CycleError(Exception): pass -ACTIONS = ("merge", "fold-into-rule", "fold-into-entry", "retire", "withdraw", "keep") +ACTIONS = ("merge", "fold-into-rule", "fold-into-entry", "retire", "withdraw", "keep", + "set-when", "create-entry", "keep-as-draft") +# 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 # ---- enforced lessons (overlay/enforced.json, checked like floors) ---------- @@ -106,9 +110,7 @@ def due_state(con=None): pending = con.execute( "SELECT count(*) FROM lessons WHERE status IN ('open','applied') AND " "(COALESCE(needs_cycle,0)=1 OR (COALESCE(strength,1)>=3 AND check_json IS NULL))").fetchone()[0] - notes_chars = con.execute( - "SELECT COALESCE(sum(length(change)),0) FROM lessons WHERE status IN ('open','applied') " - "AND COALESCE(strength,1)=1").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")] headings_chars = sum(len(retro.loose_heading(r)) + 1 for r in loose) @@ -184,38 +186,117 @@ def _announce_save(data): # ---- base version and cycle records ------------------------------------------ +# Only what a cycle may change counts toward the base: lesson content and status (aim, kind, +# target, moment, cause, change, status, strength, folded_into, effect, when-terms, check), +# the rulebook, field/draft notes and enforced checks. Listed/read counters (impressions), +# 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") + + +def _snapshot(con): + lessons = {} + for r in con.execute("SELECT * FROM lessons ORDER BY id"): + d = dict(r) + lessons[str(d["id"])] = {k: d.get(k) for k in _RELEVANT} + files = {} + for rel, b in _scan_files().items(): + files[rel] = hashlib.sha256(b).hexdigest()[:16] + try: + rules = overlay.render() + except Exception: + rules = "" + try: + with open(enforced_path(), "rb") as f: + enf = f.read().decode("utf-8", "replace") + except OSError: + enf = "" + try: + cyc = sorted(os.listdir(cycles_dir())) + except OSError: + cyc = [] + return {"lessons": lessons, "files": files, "rules": rules, "enforced": enf, + "last_cycle_ts": retro.get_meta(con, "last_cycle_ts") or "", "cycles": cyc} + + +def _save_snapshot(base, snap): + try: + d = os.path.join(paths.state(), "cycle-bases") + os.makedirs(d, exist_ok=True) + with open(os.path.join(d, base + ".json"), "w", encoding="utf-8") as f: + json.dump(snap, f, sort_keys=True) + except OSError: + pass + + +def _load_snapshot(base): + try: + with open(os.path.join(paths.state(), "cycle-bases", base + ".json"), encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else None + except (OSError, ValueError): + return None + + def base_version(con=None): - """A fingerprint of everything a cycle may change. The brief prints it; apply refuses a stale one, - which is how two sessions consolidating at once cannot overwrite each other.""" + """A fingerprint of everything a cycle may change (see _RELEVANT). The brief prints it; apply + refuses a stale one, which is how two sessions consolidating at once cannot overwrite each other.""" own = con is None if own: con = retro.connect() try: - h = hashlib.sha256() - for line in retro.dump_lines(con): - h.update(line.encode("utf-8") + b"\n") - try: - h.update(overlay.render().encode("utf-8")) - except Exception: - pass - try: - with open(enforced_path(), "rb") as f: - h.update(f.read()) - except OSError: - pass - # an applied cycle changes the base even when it only re-states a lesson, so a second - # session working from the same brief is refused instead of silently overwriting it - h.update((retro.get_meta(con, "last_cycle_ts") or "").encode("utf-8")) - try: - h.update(",".join(sorted(os.listdir(cycles_dir()))).encode("utf-8")) - except OSError: - pass - return h.hexdigest()[:16] + snap = _snapshot(con) + h = hashlib.sha256(json.dumps(snap, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:16] + _save_snapshot(h, snap) + return h finally: if own: con.close() +def _check_base(doc_base, con): + """[] when the base is current, or differs only by lessons that arrived since the brief. + Otherwise one precise line per changed thing (never 'likely another cycle landed').""" + if doc_base == base_version(con): + return [] + old = _load_snapshot(doc_base) + if old is None: + return ["stale base %s: it does not match the current base %s and no brief with that base " + "is on record. Run `sisi cycle` again and copy its base version" % (doc_base, base_version(con))] + cur = _snapshot(con) + errs, new_only = [], True + for lid, ov in sorted(old["lessons"].items(), key=lambda kv: int(kv[0])): + cv = cur["lessons"].get(lid) + if cv is None: + errs.append("lesson #%s was removed since the brief" % lid) + new_only = False + continue + diffs = [k for k in _RELEVANT if ov.get(k) != cv.get(k)] + if diffs: + errs.append("lesson #%s changed since the brief (%s: %s -> %s)" + % (lid, ", ".join(diffs), + ", ".join("%s=%r" % (k, ov.get(k)) for k in diffs[:2]), + ", ".join("%s=%r" % (k, cv.get(k)) for k in diffs[:2]))) + new_only = False + if old.get("last_cycle_ts") != cur.get("last_cycle_ts") or old.get("cycles") != cur.get("cycles"): + added = [c for c in cur.get("cycles", []) if c not in old.get("cycles", [])] + errs.append("another cycle landed since the brief (%s)" % (", ".join(added) or "cycle record changed")) + new_only = False + if old.get("rules") != cur.get("rules"): + errs.append("the rulebook changed since the brief") + new_only = False + if old.get("enforced") != cur.get("enforced"): + errs.append("the enforced checks changed since the brief") + new_only = False + # Note/overlay files are not listed separately: a cycle that changed one also changed the + # lesson or rule above, and a new lesson's own field note must not stale the brief. + if new_only: + return [] # only lessons recorded since the brief: they are left for the next cycle + return ["stale base %s (now %s): %s. Nothing was applied; run `sisi cycle` again" + % (doc_base, base_version(con), "; ".join(errs))] + + def cycles_dir(): return paths.data_file("cycles") @@ -290,9 +371,13 @@ def measures(con): lines = overlay.size(overlay.render())[0] except Exception: lines = None + try: + chars = overlay.size(overlay.render())[1] + except Exception: + chars = None return {"lessons": con.execute("SELECT count(*) FROM lessons").fetchone()[0], "active": con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied')").fetchone()[0], - "by_status_strength": rows, "rulebook_lines": lines, + "by_status_strength": rows, "rulebook_lines": lines, "rulebook_chars": chars, "deliveries_so_far": _delivery_measures(store.read("deliveries"))} @@ -330,17 +415,109 @@ def flagged(rec): # ---- the brief ----------------------------------------------------------------- -FORMAT_DOC = """Write ONE JSON file, then run `sisi cycle apply FILE`. Shape (all but version/base optional): - {"version": 1, "base": "", "summary": "one line", - "rules": [{"id": "rule-id", "title": "Title", "body": "rule text ending with a Why: ... paragraph", - "action": "add" or "replace"}], +FORMAT_DOC = """Write ONE JSON file at the path printed in the brief, then `sisi cycle check FILE`, then `sisi cycle apply FILE`. +Shape (all but version/base optional; full detail: `sisi cycle help`): + {"version": 1, "base": "", "summary": "one line", + "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", - "into": "rule id or verifier/recipe id (for folds)", "merged_into": 4, - "when": "csv, tsv, spreadsheet, tabular data, import, parse (optional; at least 5 terms, sets when-terms)"}], - "enforced": [{"lesson": 3, "type": "command", "cmd": "a real command", "expect": {"exit": 0}, "timeout_s": 30}, - {"lesson": 4, "type": "contract-requirement", "when": "parser", - "require_kind": "parsing", "max_rung": 2}]}""" + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft", + "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)", + "entry_kind": "recipe|verifier", "entry_text": "full file text (create-entry)", + "reason": "why it stays a draft (keep-as-draft)"}], + "enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30}, + {"lesson": 4, "type": "contract-requirement", "when": "parser", "require_kind": "parsing", "max_rung": 2}]}""" + +HELP_TEXT = """sisi cycle help: the full cycle file format (the brief is the short form) + +File: write ONE JSON file at the scratch path the brief prints, then: + sisi cycle check FILE validate and print exactly what would change, changing nothing + (also: sisi cycle --dry-run FILE) + sisi cycle apply FILE apply it (one commit in the personal repository) + sisi cycle revert [ID] undo the newest applied cycle exactly + sisi cycle status past cycles and what happened since + +Top level: {"version": 1 (required), "base": "", "summary": "one line", + "rules": [...], "disable_rules": [...], "notes": [...], "enforced": [...]} - all else optional. +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 +and enforced checks, not listed/read counters. A stale refusal names exactly what changed. + +Rules - format: {"id", "title", "body", "action": "add|replace", "shortens": "..."}. + Body: prose paragraphs wrapped at 100 characters (apply re-wraps for you), ending with a + paragraph starting "Why:". Keep the id and the Why when replacing. Title is the heading text. + Budget: at most 120 lines AND at most 7200 characters, and a cycle must not increase the + characters unless it names in "shortens" which existing rule text gets shorter or is replaced + (required whenever a rule is added or the book would grow in characters); never past the budget. + Rule numbers in lessons ("rule 5") mean the numbered list in the brief, which maps number to id. + +Notes - one object per decision; the same lesson may appear several times (split, or fold+set-when): + merge {"lesson": A, "action": "merge", "merged_into": B} - only when A and B request + the SAME change (not merely the same topic). Merge the newer/ narrower into the + older or more general one (B). A becomes superseded; B keeps its own text and + its occurrence count unchanged. Superseded lessons need no further action. + fold-into-rule {"lesson": A, "action": "fold-into-rule", "into": "rule-id" or ["id", ...]} + The lesson is marked folded into that rule; its strength rises to at least 2. + fold-into-entry {"lesson": A, "action": "fold-into-entry", "into": "id" or ["id", ...], + "note": "optional text"} - appends one field-note bullet to notes/.md: + "- YYYY-MM-DD: (aim: ; seen + times; lesson )", and marks the lesson applied / field-note / + folded_into=. To split a compound lesson, use two notes objects with the + same lesson, different `into` and different `note` text each. + create-entry {"lesson": A, "action": "create-entry", "into": "new-id", + "entry_kind": "recipe|verifier", "entry_text": ""} + Creates a personal recipe or verifier entry in the overlay from the lesson, + validated by the existing library lint (docs/verifier-format.md). Use it when a + lesson asks for a recipe/entry that does not exist (e.g. "Add a recipe 'x'"). + If a full, lint-clean entry is too large for this cycle, use keep-as-draft + instead and say why; do not fold into a poor-matching existing entry. + keep-as-draft {"lesson": A, "action": "keep-as-draft", "reason": "why"} - keeps it as a draft + recipe note (shown by `sisi done for` when its words match), nothing else. + set-when {"lesson": A, "action": "set-when", "when": "at least 5 terms"} - only sets + the lesson's when-terms; nothing else changes. + 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 + first being listed. Folding in this cycle does not make it quiet: fold now, + keep it, and retire it in a later cycle once it is quiet. (sisi also retires + such lessons itself at 20 showings.) + withdraw it made things worse or keeps recurring at strength 3; same wording is not + 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. + +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), + "timeout_s": 30 (seconds, optional)} + contract-requirement: {"lesson": 4, "type": "contract-requirement", + "when": "word in the contract goal/claims that triggers it", + "require_kind": "general|concurrency|parsing|money|state-machine|migration|ui", + "max_rung": 2 (optional, 1-6: the required check must be at this rung or stronger)} + Complete examples are the two objects above. + +Learned-notes limit: counts length(change) of active strength-1 loose learned notes only +(limit 4000 characters). Folded, strengthened, retired, withdrawn and tool-backlog lessons do +not count. fold-into-entry, fold-into-rule, merge, retire, withdraw and writing an enforced +check all reduce it; keep and set-when do not. +""" + +def cycle_file_path(): + return os.path.join(paths.state(), "cycle.json") + + +def _into_list(e): + v = e.get("into") + if v is None: + return [] + return list(v) if isinstance(v, list) else [v] + + +def _suggest(bad, valid): + close = difflib.get_close_matches(str(bad), sorted(valid), n=3, cutoff=0.4) + return (" Closest valid: %s." % ", ".join(close)) if close else "" def brief_text(): @@ -359,6 +536,13 @@ def brief_text(): before = measures(con) finally: con.close() + from . import verifiers as V + try: + _, eff_rules = overlay.effective() + except Exception: + eff_rules = [] + recipes = [e for e in V.load_recipes() if e["header"]] + vers = [e for e in V.load_verifiers() if e["header"]] out = ["sisi learning cycle: consolidation brief", ""] bad = [r for r in cycle_records() if flagged(r)] if bad: @@ -367,47 +551,87 @@ def brief_text(): out += [" %s (%s): %s" % (r["id"], r.get("ts"), r.get("summary") or "") for r in bad] + [""] out += ["Due: " + ("; ".join(st["reasons"]) if st["due"] else "not due by the counters; a cycle may still help"), "Base version (copy into your file): %s" % base, - "Rulebook: %s lines, budget %d. It must not grow: a rule enters only by shortening or " - "replacing existing text." % (before["rulebook_lines"], overlay.MAX_LINES), "", - "Lessons (id, status, kind, strength, occurrences, listed, read, recurrences-after-listed, effect):"] + "Write your file to: %s then `sisi cycle check FILE`, then `sisi cycle apply FILE`. " + "Full format: `sisi cycle help`." % cycle_file_path(), + "This file covers only the lessons below; lessons recorded since are left for the next " + "cycle and do not fail the apply. Reading lessons (`sisi lessons show ID`) does not stale the base.", + "Rulebook: %s lines (budget %d), %s characters (budget %d). It must not grow in " + "characters unless `shortens` names what is removed; never past either budget. " + "Rules are re-wrapped to 100 chars on apply." + % (before["rulebook_lines"], overlay.MAX_LINES, before.get("rulebook_chars"), overlay.MAX_CHARS), + "Learned notes: %d of %d characters counted (active strength-1 loose learned notes " + "only, length of each lesson's change; folded/strengthened/tool lessons do not count). " + "fold-into-entry, fold-into-rule, merge, retire, withdraw and enforced checks reduce it." + % (st.get("notes_chars", 0), retro.NOTES_LIMIT_CHARS), "", + "Rules (number = what 'rule 5' means; choose folds by this list, full text in %s):" % paths.generated()] + for i, r in enumerate(eff_rules, 1): + out.append(" %d. %s - %s" % (i, r["id"], r["title"])) + out.append("Recipes (fold by reading applies-to, not by word matching):") + for e in sorted(recipes, key=lambda x: x["id"]): + out.append(" %s - %s" % (e["id"], (e.get("applies_to") or e.get("title") or "")[:110])) + out.append("Verifier entries (valid fold/create targets): " + + ", ".join(sorted(e["id"] for e in vers))) + out += ["", "Lessons (change chars = its size toward the notes limit when loose):"] + active_text = sum(len(r["change"] or "") + len(r["moment"] or "") + len(r["cause"] or "") + for r in rows if r["status"] in retro.ACTIVE) + if active_text > BRIEF_TEXT_BUDGET: + out.append("Lesson text beyond the brief's %d-character text budget is truncated; run " + "`sisi lessons show ID` for the full text of any lesson." % BRIEF_TEXT_BUDGET) + remaining = [BRIEF_TEXT_BUDGET] for r in rows: - out.append("#%-4d %-10s %-9s s%d x%-3d listed %-3d read %-3d rec %-3d %-13s %s" + out.append("#%-4d %-10s %-9s s%d x%-3d listed %-3d read %-3d rec %-3d %-13s change %d chars" % (r["id"], r["status"], r["change_kind"], r["strength"] or 1, r["count"], listed[r["id"]], - readn[r["id"]], rec[r["id"]], r["effect"] or "-", " ".join(r["change"].split())[:160])) + readn[r["id"]], rec[r["id"]], r["effect"] or "-", len(r["change"] or ""))) + if r["status"] not in retro.ACTIVE: + out.append(" (history; no action needed) change: %s" % " ".join((r["change"] or "").split())[:120]) + continue + need = len(r["change"] or "") + len(r["moment"] or "") + len(r["cause"] or "") + full = need <= remaining[0] + remaining[0] -= need if full else 0 + def show(label, text, _full=full, _id=r["id"]): + t = " ".join((text or "").split()) + if _full: + out.append(" %s: %s" % (label, t)) + else: + out.append(" %s: %s [truncated - `sisi lessons show %d` for the full text]" % (label, t[:200], _id)) + if full: + show("change", r["change"]) + show("moment", r["moment"]) + show("cause", r["cause"]) + else: + t = " ".join((r["change"] or "").split()) + out.append(" change: %s [truncated - `sisi lessons show %d` for the full text, moment and cause]" % (t[:160], r["id"])) + if full: + out.append(" when: %s" % (r["when_terms"] or "MISSING - add at least 5 terms with set-when or any note's when")) + elif not r["when_terms"]: + out.append(" when: MISSING - add at least 5 terms with set-when or any note's when") + out.append(" target: %s folded_into: %s" % (r["target"] or "-", r["folded_into"] or "-")) if listed[r["id"]] >= 5 and readn[r["id"]] == 0 and rec[r["id"]] > 0 and r["status"] in retro.ACTIVE: - out.append(" LISTED %d TIMES, NEVER READ, STILL RECURS: its heading is not earning a " - "read - rewrite the start of its change and its when-terms" % listed[r["id"]]) - out.append(" moment: %s" % " ".join((r["moment"] or "").split())[:160]) - out.append(" when: %s" % (r["when_terms"] or "MISSING - add at least 5 terms (synonyms included) " - "in your cycle file, or this lesson is found only by its own wording")) + out.append(" LISTED %d TIMES, NEVER READ, STILL RECURS: rewrite the start of its change and its when-terms" % listed[r["id"]]) if sight[r["id"]]: - out.append(" plus %d unconfirmed sighting(s) sisi matched to this lesson itself " - "(merge candidates: the agent never confirmed with --same-as)" % sight[r["id"]]) + out.append(" plus %d unconfirmed sighting(s) (merge candidates)" % sight[r["id"]]) if (r["strength"] or 1) >= 3 and not r["check_json"] and r["status"] in retro.ACTIVE: - out.append(" NEEDS A CHECK: this lesson is at strength 3. Write one below (a command and " - "expected result, or a contract requirement).") - out += ["", "Current rulebook (what every agent loads):", "-" * 60] - try: - out.append(overlay.render().rstrip("\n")) - except Exception as e: - out.append("(cannot render: %s)" % e) + out.append(" NEEDS A CHECK: strength 3 - write one enforced check (see `sisi cycle help`). " + "Write no enforced check for lessons below strength 3.") + out += ["", "Current rulebook (what every agent loads): %s lines, %s characters; full text at %s" + % (before["rulebook_lines"], before.get("rulebook_chars"), paths.generated()), ""] missing = [r["id"] for r in rows if r["status"] in retro.ACTIVE and not r["when_terms"]] if missing: - out += ["", "Lessons with no when-terms yet (found only by their own wording until you add terms): " - + ", ".join("#%d" % i for i in missing)] - out += ["-" * 60, "", "Do this, in order:", - "1. First, shrink the loose list: fold each lesson into the recipe for its kind of work (or its " - "verifier entry), or lift several into one general rule, so they leave the loose list. The recipe " - "is the strongest route to the next agent, because `sisi done for` already maps a request to a " - "kind of work; a loose note depends on the asking agent spotting its heading, a folded one does " - "not (notes: fold-into-entry, fold-into-rule).", - "2. Merge lessons that say the same thing (notes: merge, with merged_into), including any pair an " - "unconfirmed sighting points at.", - "3. When lifting lessons into a rule (rules: add/replace), name which existing rule text gets " - "shorter or is replaced so the book stays the same size.", - "4. For each strength-3 lesson marked NEEDS A CHECK, write the check (enforced). Prefer a contract " - "requirement; a command must name a program that exists here and runs only in trusted projects.", - "5. Retire what is fully folded and quiet; withdraw what made things worse; keep the rest.", + out += ["Lessons with no when-terms yet: " + ", ".join("#%d" % i for i in missing), ""] + 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). " + "For a lesson naming a recipe/entry that does not exist, use create-entry with a lint-clean " + "file, or keep-as-draft with a reason if that is too large for this cycle - never fold into a poor match.", + "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.", + "4. Rules: keep id and Why, format per help; name in `shortens` which existing rule text gets shorter or is replaced whenever a rule is added or the book would grow in characters.", + "5. For each NEEDS A CHECK lesson write one enforced check (help has fields and examples); none below strength 3.", + "6. Retire only what is fully folded and quiet (folded, at least 20 listed/read, 0 recurrences " + "after first listed) - folding now does not make it quiet, so fold and keep, retire next cycle. " + "Withdraw what made things worse. set-when only sets when-terms. Keep the rest.", "Every changed rule keeps its id and ends with its Why. Never ask the human anything.", "", FORMAT_DOC] return "\n".join(out) + "\n" @@ -454,10 +678,8 @@ def static_validate(doc, con): errs.append("version must be 1") if not doc.get("base"): errs.append("missing base: copy the base version printed by `sisi cycle` (it proves which state you read)") - elif doc["base"] != base_version(con): - errs.append("stale base %s: the lessons or rulebook changed since the brief (base is now %s), " - "likely another cycle landed. Nothing was applied; run `sisi cycle` again" - % (doc["base"], base_version(con))) + else: + errs.extend(_check_base(doc["base"], con)) have = {r[0] for r in con.execute("SELECT id FROM lessons")} for lid in sorted(_lesson_ids_in(doc) - have): errs.append("no lesson with id %d" % lid) @@ -486,22 +708,59 @@ def static_validate(doc, con): errs.append("rule %s: %s" % (rid, ex)) for rid in doc.get("disable_rules") or []: if rid not in base_rule_ids | over_ids: - errs.append("no rule %s to disable" % rid) + errs.append("no rule %s to disable.%s" % (rid, _suggest(rid, base_rule_ids | over_ids))) + kinds = {} + try: + kinds = {r[0]: r[1] for r in con.execute("SELECT id, change_kind FROM lessons")} + except Exception: + pass 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 - if e["action"] == "merge" and (not isinstance(e.get("merged_into"), int) or e.get("merged_into") == e.get("lesson")): - errs.append("lesson %s: merge needs merged_into naming a different lesson" % e.get("lesson")) - if e["action"] in ("fold-into-rule", "fold-into-entry") and not e.get("into"): - errs.append("lesson %s: %s needs into" % (e.get("lesson"), e["action"])) + lid = e.get("lesson") + if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when"): + 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"] == "merge" and (not isinstance(e.get("merged_into"), int) or e.get("merged_into") == lid): + errs.append("lesson %s: merge needs merged_into naming a different lesson" % lid) + if e["action"] in ("fold-into-rule", "fold-into-entry", "create-entry") and not _into_list(e): + errs.append("lesson %s: %s needs into" % (lid, e["action"])) if e.get("when") is not None and len(retro.parse_when(e.get("when"))) < 5: - errs.append("lesson %s: when needs at least 5 terms (synonyms included)" % e.get("lesson")) - if e["action"] == "fold-into-entry" and e.get("into"): + errs.append("lesson %s: when needs at least 5 terms (synonyms included)" % lid) + if e["action"] == "set-when" and len(retro.parse_when(e.get("when"))) < 5: + errs.append("lesson %s: set-when needs when with at least 5 terms" % lid) + if e["action"] == "keep-as-draft" and not (e.get("reason") or "").strip(): + errs.append("lesson %s: keep-as-draft needs a reason" % lid) + if e["action"] == "fold-into-rule": + valid = base_rule_ids | over_ids + for into in _into_list(e): + if into not in valid: + errs.append("lesson %s: no rule with id %r to fold into.%s" % (lid, into, _suggest(into, valid))) + if e["action"] == "fold-into-entry": from . import verifiers as V ids = {x["id"] for x in V.load_verifiers() if x["header"]} | {x["id"] for x in V.load_recipes() if x["header"]} - if e["into"] not in ids: - errs.append("lesson %s: no verifier or recipe with id %r to fold into" % (e.get("lesson"), e["into"])) + for into in _into_list(e): + if into not in ids: + errs.append("lesson %s: no verifier or recipe with id %r to fold into.%s " + "If the lesson asks for a new one, use create-entry, or keep-as-draft with a reason" + % (lid, into, _suggest(into, ids))) + if e["action"] == "create-entry": + if e.get("entry_kind") not in ("recipe", "verifier"): + errs.append("lesson %s: create-entry needs entry_kind recipe or verifier" % lid) + elif not (e.get("entry_text") or "").strip(): + errs.append("lesson %s: create-entry needs entry_text (the full file, see docs/verifier-format.md)" % lid) + else: + for into in _into_list(e): + try: + from . import verifiers as V + existing = {x["id"] for x in (V.load_verifiers() if e["entry_kind"] == "verifier" else V.load_recipes()) if x["header"]} + if into in existing: + errs.append("lesson %s: %s %r already exists; fold into it instead of create-entry" % (lid, e["entry_kind"], into)) + else: + overlay._put_entry(e["entry_kind"], e["entry_text"], into, False) + except Exception as ex: + errs.append("lesson %s: create-entry %r: %s" % (lid, into, ex)) from . import contract as C for e in doc.get("enforced") or []: if not isinstance(e, dict): @@ -530,7 +789,8 @@ def _apply_writes(doc, con): """Write the validated cycle: rule files, disables, enforced checks, lesson updates. Caller holds the lock.""" touched = set() for e in doc.get("rules") or []: - r = overlay.parse_rule_file("## %s\n\n%s\n" % (e["title"], e["body"]), e["id"]) + body = overlay.wrap_rule_body(e["body"]) + r = overlay.parse_rule_file("## %s\n\n%s\n" % (e["title"], body), e["id"]) overlay._write("rules/%s.md" % e["id"], overlay.rule_text(r)) if e.get("action") == "replace": overlay._set_base("rule", e["id"], overlay.base_hash("rule", e["id"])) @@ -566,16 +826,29 @@ def _apply_writes(doc, con): ("lesson:%d" % e["merged_into"], lid)) con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (e["merged_into"],)) elif act == "fold-into-rule": + intos = _into_list(e) con.execute("UPDATE lessons SET folded_into=?, needs_cycle=0, " "promoted_shown=CASE WHEN COALESCE(strength,1)<2 THEN " "(SELECT count(*) FROM impressions WHERE lesson_id=?) ELSE promoted_shown END, " "strength=max(COALESCE(strength,1),2) WHERE id=?", - ("rule:" + e["into"], lid, lid)) + (",".join("rule:" + x for x in intos), lid, lid)) elif act == "fold-into-entry": r = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone() - retro._append_note(e["into"] + ".md", e["into"], r) + intos = _into_list(e) + for into in intos: + retro._append_note(into + ".md", into, r, note_text=e.get("note")) con.execute("UPDATE lessons SET status='applied', effect='field-note', folded_into=?, needs_cycle=0, " - "applied_at=COALESCE(applied_at,?) WHERE id=?", (e["into"], store.now(), lid)) + "applied_at=COALESCE(applied_at,?) WHERE id=?", (",".join(intos), store.now(), lid)) + elif act == "create-entry": + for into in _into_list(e): + _id, rel, _mine = overlay._put_entry(e["entry_kind"], e["entry_text"], into, False) + overlay._write(rel, e["entry_text"] if e["entry_text"].endswith("\n") else e["entry_text"] + "\n") + con.execute("UPDATE lessons SET status='applied', effect='field-note', folded_into=?, needs_cycle=0, " + "applied_at=COALESCE(applied_at,?) WHERE id=?", (",".join(_into_list(e)), store.now(), lid)) + elif act == "keep-as-draft": + con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,)) + elif act == "set-when": + pass # when-terms were already set above; set-when does nothing else elif act == "retire": con.execute("UPDATE lessons SET status='retired', needs_cycle=0 WHERE id=?", (lid,)) elif act == "withdraw": @@ -604,16 +877,34 @@ def apply_file(path): before_rows = {r["id"]: dict(r) for r in con.execute("SELECT * FROM lessons")} before_m = measures(con) before_lines = before_m["rulebook_lines"] + before_chars = before_m.get("rulebook_chars") prev_last = retro.get_meta(con, "last_cycle_ts") try: touched = _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 []: + if isinstance(e, dict) and e.get("action") == "create-entry": + for into in _into_list(e): + bad = [x for x in _V.lint() if os.path.basename(x.split(":")[0]) == into + ".md"] + if bad: + raise CycleError("create-entry %r does not pass `sisi verifiers lint`: %s" + % (into, "; ".join(bad))) con.commit() built = overlay.build_canon() has_replace = any(e.get("action") == "replace" for e in doc.get("rules") or []) - if built["lines"] > overlay.MAX_LINES: - raise CycleError("the rulebook would be %d lines; the budget is %d. Shorten or replace " - "another rule first" % (built["lines"], overlay.MAX_LINES)) - if before_lines is not None and built["lines"] > before_lines and not has_replace: + has_shortens = any(e.get("shortens") for e in doc.get("rules") or []) or bool(doc.get("disable_rules")) + 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 " + "`shortens` which existing rule text gets shorter or is replaced; it " + "would grow, so add `shortens` or shorten existing text instead" + % (before_chars, built["chars"], before_lines or 0, built["lines"])) + if built["lines"] > overlay.MAX_LINES or built["chars"] > overlay.MAX_CHARS: + raise CycleError("the rulebook would be %d lines and %d characters; the budgets are %d lines " + "and %d characters. Shorten or replace another rule first" + % (built["lines"], built["chars"], overlay.MAX_LINES, overlay.MAX_CHARS)) + if before_lines is not None and built["lines"] > before_lines and not has_replace and not has_shortens: raise CycleError("the rulebook would grow from %d to %d lines. It may grow only when a " "rule is replaced (and never past %d); shorten existing text instead" % (before_lines, built["lines"], overlay.MAX_LINES)) @@ -788,7 +1079,7 @@ def improve_text(): else: lines.append("deliveries: send-backs each %s this week, %s before; median time %s this week, %s before" % (sb(cur, cur_rows), sb(prev, prev_rows), _fmt_med(cur["median_s"]), _fmt_med(prev["median_s"]))) - lines.append("rulebook: %s lines of %d allowed" % (m["rulebook_lines"], overlay.MAX_LINES)) + lines.append("rulebook: %s lines of %d allowed, %s characters of %d allowed" % (m["rulebook_lines"], overlay.MAX_LINES, m.get("rulebook_chars"), overlay.MAX_CHARS)) st = due_state() lines.append("next cycle: " + ("due now (%s); run `sisi cycle`" % st["reasons"][0] if st["due"] else "not due")) lines.append("Not measured: whether the work itself is what the human meant. That still rests on the " @@ -815,9 +1106,101 @@ def improve_line(): return "learning : n/a" +def check_file(path): + """Validate FILE and print exactly what would change, changing nothing. Returns lines.""" + try: + with open(path, encoding="utf-8") as f: + doc = json.load(f) + except (OSError, ValueError) as e: + raise CycleError("cannot read %s: %s" % (path, e)) + con = retro.connect() + try: + retro.ensure_effects(con) + errs = static_validate(doc, con) + if errs: + raise CycleError("refused, nothing would be applied:\n" + "\n".join(" - " + e for e in errs)) + before = measures(con) + out = ["check ok: %s would apply as follows (nothing was changed):" % path, + " summary: %s" % (doc.get("summary") or "")] + for e in doc.get("rules") or []: + out.append(" rule %s: %s %r (shortens: %s)" % (e.get("id"), e.get("action"), e.get("title"), e.get("shortens") or "-")) + for rid in doc.get("disable_rules") or []: + out.append(" disable rule: %s" % rid) + for e in doc.get("notes") or []: + extra = "" + if _into_list(e): + extra = " into %s" % ", ".join(_into_list(e)) + if e.get("merged_into"): + extra = " into lesson %s" % e["merged_into"] + if e.get("note"): + extra += " note=%r" % e["note"][:60] + if e.get("when"): + extra += " when=%r" % e["when"][:60] + if e.get("reason"): + extra += " reason=%r" % e["reason"][:60] + if e.get("entry_kind"): + extra += " entry_kind=%s" % e["entry_kind"] + out.append(" lesson %s: %s%s" % (e.get("lesson"), e.get("action"), extra)) + for e in doc.get("enforced") or []: + out.append(" lesson %s: enforced %s %s" % (e.get("lesson"), e.get("type"), + e.get("cmd") or ("when=%s require_kind=%s" % (e.get("when"), e.get("require_kind"))))) + # predicted rulebook size with the rules applied in memory + try: + pre, rules = overlay.effective() + by_id = {r["id"]: dict(r) for r in rules} + order = [r["id"] for r in rules] + for rid in doc.get("disable_rules") or []: + by_id.pop(rid, None) + if rid in order: + order.remove(rid) + for e in doc.get("rules") or []: + wrapped = overlay.wrap_rule_body(e["body"]) + if e["id"] in by_id: + by_id[e["id"]].update(title=e["title"], body=wrapped) + else: + by_id[e["id"]] = {"id": e["id"], "title": e["title"], "body": wrapped} + order.append(e["id"]) + parts = [overlay.render().splitlines()[0] if overlay.render().splitlines() else ""] + if pre.strip(): + parts.append(pre) + for n, rid in enumerate(order, 1): + if rid in by_id: + parts.append("## %d. %s {#%s}\n\n%s" % (n, by_id[rid]["title"], rid, by_id[rid]["body"])) + cand = "\n\n".join(parts) + "\n" + lines, chars = overlay.size(cand) + 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)) + has_shortens = any(e.get("shortens") for e in doc.get("rules") or []) or bool(doc.get("disable_rules")) + 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)) + except CycleError: + raise + except Exception: + pass + return out + finally: + con.close() + + def cmd_cycle(args): sub = args[0] if args else "brief" try: + if sub in ("help", "--help", "-h"): + print(HELP_TEXT, end="") + return 0 + if sub in ("check", "--dry-run"): + if len(args) != 2: + print("usage: sisi cycle check FILE (or sisi cycle --dry-run FILE)") + return 2 + for line in check_file(args[1]): + print(line) + return 0 if sub == "due": st = due_state() if st["due"]: @@ -846,7 +1229,7 @@ def cmd_cycle(args): for line in status_lines(): print(line) return 0 - print("usage: sisi cycle [due|apply FILE|revert [ID]|status] (no argument prints the brief)") + print("usage: sisi cycle [due|apply FILE|check FILE|--dry-run FILE|revert [ID]|status|help] (no argument prints the brief)") return 2 except CycleError as e: print("sisi cycle: %s" % e) diff --git a/sisi/overlay.py b/sisi/overlay.py index cbf47a0..596e4d6 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -19,6 +19,12 @@ import contextlib, hashlib, json, os, re, sys, tempfile, time from . import paths MAX_LINES = 120 +# Character budget as well as lines: the base rulebook renders to 6,525 characters in 120 lines. +# Wrapping games (fewer, longer lines) must not load more text into every session, so the honest +# measure is characters. 7,200 allows modest headroom (about 10%) for a short replacement while +# still refusing any real growth. +MAX_CHARS = 7200 +HOUSE_WIDTH = 100 KINDS = ("rule", "verifier", "recipe") ID_TAIL = re.compile(r"\s*\{#([A-Za-z0-9][A-Za-z0-9_-]*)\}\s*$") NUM = re.compile(r"^\d+\.\s+") @@ -88,6 +94,30 @@ def rule_text(r): return "## %s\n\n%s\n" % (r["title"], r["body"]) +def wrap_rule_body(body, width=HOUSE_WIDTH): + """Re-wrap rule prose to the house width, preserving paragraphs, bullets and code fences.""" + import textwrap + out, in_fence = [], False + for line in (body or "").split("\n"): + if line.strip().startswith("```"): + in_fence = not in_fence + out.append(line) + continue + if in_fence or not line.strip(): + out.append(line) + continue + stripped = line.lstrip() + indent = "" + if stripped.startswith(("- ", "* ")): + indent = " " + elif re.match(r"^\d+\.\s", stripped): + indent = " " + wrapped = textwrap.wrap(line, width=width, subsequent_indent=indent, + break_long_words=False, break_on_hyphens=False) + out.extend(wrapped or [""]) + return "\n".join(out).strip("\n") + + def _read(p): with open(p, encoding="utf-8") as f: return f.read() @@ -196,10 +226,11 @@ def build_canon(strict=False): from . import pdata text = render() lines, chars = size(text) - over = lines > MAX_LINES + over = lines > MAX_LINES or chars > MAX_CHARS if over and strict: - raise OverlayError("the rulebook would be %d lines; the budget is %d. Shorten or replace another rule first " - "(`sisi canon cost` shows the size)" % (lines, MAX_LINES)) + raise OverlayError("the rulebook would be %d lines and %d characters; the budgets are %d lines and %d " + "characters. Shorten or replace another rule first (`sisi canon cost` shows the size)" + % (lines, chars, MAX_LINES, MAX_CHARS)) pdata.ensure() p = paths.generated() os.makedirs(os.path.dirname(p), exist_ok=True) @@ -240,6 +271,7 @@ def cost(): except OSError: lines = chars = None return {"rulebook_lines": lines, "rulebook_chars": chars, "rulebook_budget_lines": MAX_LINES, + "rulebook_budget_chars": MAX_CHARS, "lessons_block_max_chars": retro.LIMIT, "lessons_block_max_lines": 1 + 8} @@ -247,8 +279,8 @@ def cost_line(c=None): c = c or cost() if c["rulebook_lines"] is None: return "rulebook not generated yet (run `sisi build-canon`); lessons block at most %d characters" % c["lessons_block_max_chars"] - return "rulebook %d lines (budget %d), %d characters; session-start lessons block at most %d characters, %d lines" % ( - c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], c["lessons_block_max_chars"], c["lessons_block_max_lines"]) + return "rulebook %d lines (budget %d), %d characters (budget %d); session-start lessons block at most %d characters, %d lines" % ( + c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], c.get("rulebook_budget_chars", MAX_CHARS), c["lessons_block_max_chars"], c["lessons_block_max_lines"]) # ---- library overlay (verifiers, recipes) --------------------------------------- diff --git a/sisi/retro.py b/sisi/retro.py index f96c0d1..8744051 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -537,7 +537,22 @@ def new_lesson(con, f, cwd, fp): return lid -def _append_note(kind_file, target, r, draft=False): +def notes_chars(con): + """Characters counted toward the learned-notes limit: length(change) of active, strength-1, + still-loose learned notes only. Folded lessons (into a rule, entry, draft or enforced check), + tool backlog lessons and strengthened lessons do not count: folding is what reduces this.""" + 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'" + ).fetchone()[0] + except Exception: + 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").fetchone()[0] + + +def _append_note(kind_file, target, r, draft=False, note_text=None): d = paths.notes_dir() os.makedirs(d, exist_ok=True) p = os.path.join(d, kind_file) @@ -548,7 +563,8 @@ def _append_note(kind_file, target, r, draft=False): if draft: f.write("No recipe with this id exists yet. These notes are shown by `sisi done for` when their " "words match, until a cycle turns them into a recipe or folds them elsewhere.\n\n") - f.write("- %s: %s (aim: %s; seen %d times; lesson %d)\n" % (store.now()[:10], " ".join(r["change"].split()), r["aim"], r["count"], r["id"])) + text = note_text if note_text is not None else r["change"] + f.write("- %s: %s (aim: %s; seen %d times; lesson %d)\n" % (store.now()[:10], " ".join(text.split()), r["aim"], r["count"], r["id"])) return p diff --git a/tests/test_learning.py b/tests/test_learning.py index 09ee441..b9f67c5 100644 --- a/tests/test_learning.py +++ b/tests/test_learning.py @@ -980,5 +980,249 @@ class ImproveFromUseTests(LearningCase): self.assertEqual(self.lesson(lid)["strength"], 3) +RECIPE_TEXT = """--- +id: curated-record-change +title: Editing a curated record +applies_to: Editing a sourced record in a curated dataset. +--- + +## Done means +- The record is edited and its source is cited. + +## Checks +- Show the edited record matches its source. + +## Common false finishes +- Editing without checking the source. +""" + + +class CycleGapTests(LearningCase): + def test_gap01_brief_full_text_and_show_hint(self): + lid = self.mk(change="Parser readiness probes beat fixed sleeps for servers always", + moment="the parser server waited at step 4") + out = cycle.brief_text() + self.assertIn("Parser readiness probes beat fixed sleeps", out) + self.assertIn("sisi lessons show ID", out) # reading instruction present + old = cycle.BRIEF_TEXT_BUDGET + cycle.BRIEF_TEXT_BUDGET = 10 + try: + out2 = cycle.brief_text() + finally: + cycle.BRIEF_TEXT_BUDGET = old + self.assertIn("`sisi lessons show %d`" % lid, out2) + self.assertIn("text budget", out2) + + def test_gap02_reading_does_not_stale_base_and_stale_is_precise(self): + lid = self.mk() + base = cycle.base_version() + self.sisi("lessons", "show", str(lid)) # a read: counters only + retro.record_shown([lid], "done-for", "s") + doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}]) + # cycle_doc recomputes base; rebuild with the original base + d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}]} + p = os.path.join(self.tmp, "g2.json") + with open(p, "w") as f: + json.dump(d, f) + self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) + # now a real change stales a fresh brief, precisely + lid2 = self.mk(change="Second parser readiness lesson for stale check", moment="second wait at step 2") + base2 = cycle.base_version() + con = retro.connect() + con.execute("UPDATE lessons SET status='retired' WHERE id=?", (lid2,)) + con.commit(); con.close() + d2 = {"version": 1, "base": base2, "summary": "x", "notes": [{"lesson": lid2, "action": "keep"}]} + p2 = os.path.join(self.tmp, "g2b.json") + with open(p2, "w") as f: + json.dump(d2, f) + r = self.sisi("cycle", "apply", p2) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("lesson #%d changed" % lid2, r.stdout) + self.assertNotIn("likely another cycle", r.stdout) + + def test_gap03_new_lesson_does_not_block_apply(self): + lid = self.mk() + base = cycle.base_version() + self.mk(change="Brand new parser lesson arriving mid cycle", moment="new wait at step 5") + d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}]} + p = os.path.join(self.tmp, "g3.json") + with open(p, "w") as f: + json.dump(d, f) + self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) + + def test_gap04_create_entry_and_keep_as_draft(self): + lid = self.mk(change_kind="recipe", target="curated-record-change", + change="Add a recipe 'curated-record-change' for editing a sourced record in a curated dataset") + doc = self.cycle_doc(notes=[{"lesson": lid, "action": "create-entry", "into": "curated-record-change", + "entry_kind": "recipe", "entry_text": RECIPE_TEXT}]) + r = self.sisi("cycle", "apply", doc) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertTrue(os.path.exists(paths.overlay_dir("done", "curated-record-change.md"))) + from sisi import verifiers as V + self.assertIn("curated-record-change", [e["id"] for e in V.load_recipes()]) + lid2 = self.mk(change="A draft-only parser readiness lesson", moment="draft wait at step 2") + bad = self.sisi("cycle", "apply", self.cycle_doc( + notes=[{"lesson": lid2, "action": "keep-as-draft"}])) + self.assertEqual(bad.returncode, 1) + self.assertIn("needs a reason", bad.stdout) + self.assertIn("create-entry", cycle.brief_text()) + self.assertIn("keep-as-draft", cycle.HELP_TEXT) + + def test_gap05_fold_into_entry_appends_field_note(self): + lid = self.mk(change="Parser recipes need a readiness probe before server work", + moment="server wait at step 3") + doc = self.cycle_doc(notes=[{"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec"}]) + self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) + text = open(os.path.join(self.notes, "parser-or-codec.md")).read() + self.assertIn("readiness probe", text) + self.assertIn("lesson %d" % lid, text) + self.assertIn("field-note bullet", cycle.HELP_TEXT) + + def test_gap06_into_list_and_split(self): + self.put("prove/other.md", vfile("other")) + lid = self.mk(change="Compound parser lesson about probes and fuzz corpus seeding", + moment="compound wait at step 3") + doc = self.cycle_doc(notes=[ + {"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec", "note": "Use a readiness probe before parser server work"}, + {"lesson": lid, "action": "fold-into-entry", "into": "fuzz", "note": "Seed the fuzz corpus from golden files"}]) + r = self.sisi("cycle", "apply", doc) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn("readiness probe", open(os.path.join(self.notes, "parser-or-codec.md")).read()) + self.assertIn("Seed the fuzz corpus", open(os.path.join(self.notes, "fuzz.md")).read()) + lid2 = self.mk(change="Multi target parser readiness lesson", moment="multi wait at step 2") + doc2 = self.cycle_doc(notes=[{"lesson": lid2, "action": "fold-into-entry", "into": ["parser-or-codec", "fuzz"]}]) + self.assertEqual(self.sisi("cycle", "apply", doc2).returncode, 0) + + def test_gap07_unknown_id_suggests_closest_and_brief_lists_ids(self): + lid = self.mk() + r = self.sisi("cycle", "apply", self.cycle_doc( + notes=[{"lesson": lid, "action": "fold-into-entry", "into": "parser-or-code"}])) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("Closest valid", r.stdout) + self.assertIn("parser-or-codec", r.stdout) + out = cycle.brief_text() + self.assertIn("parser-or-codec", out) + self.assertIn("fuzz", out) + + def test_gap08_brief_gives_recipe_applies_to(self): + out = cycle.brief_text() + self.assertIn("applies-to", out) + # a real recipe's applies_to line from the library + from sisi import verifiers as V + rec = [e for e in V.load_recipes() if e["id"] == "parser-or-codec"][0] + self.assertIn(rec["applies_to"][:40], out) + + def test_gap09_tool_lesson_refused_in_cycle(self): + lid = self.mk(change_kind="tool", change="Make sisi cycle print faster for large stores") + r = self.sisi("cycle", "apply", self.cycle_doc( + notes=[{"lesson": lid, "action": "fold-into-entry", "into": "fuzz"}])) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("tool lessons cannot be done in a cycle", r.stdout) + self.assertIn("sisi backlog", cycle.brief_text()) + + def test_gap10_merge_keeps_survivor_text_and_count(self): + a = self.mk(change="Parser readiness probes beat fixed sleeps for servers", moment="merge a at step 1") + b = self.mk(change="Fixed sleeps waste time for parser servers", moment="merge b at step 2") + before = self.lesson(a) + doc = self.cycle_doc(notes=[{"lesson": b, "action": "merge", "merged_into": a}]) + self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) + after = self.lesson(a) + self.assertEqual((after["change"], after["count"]), (before["change"], before["count"])) + self.assertEqual(self.lesson(b)["status"], "superseded") + self.assertIn("SAME change", cycle.HELP_TEXT) + self.assertIn("Superseded", cycle.HELP_TEXT) + + def test_gap11_retire_definition_in_brief_and_help(self): + self.assertIn("fully folded and quiet", cycle.brief_text()) + self.assertIn("20", cycle.HELP_TEXT) + self.assertIn("does not make it quiet", cycle.HELP_TEXT) + + def test_gap12_set_when_only(self): + lid = self.mk() + doc = self.cycle_doc(notes=[{"lesson": lid, "action": "set-when", "when": PARSER_WHEN}]) + self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) + l = self.lesson(lid) + self.assertIn("readiness probe", l["when_terms"]) + self.assertEqual(l["status"], "open") + + def test_gap14_shortens_required_when_book_grows(self): + pre, base = overlay.base_rules() + title = next(r["title"] for r in base if r["id"] == "know-done") + long_body = ("Before work, write a contract. " * 40) + "\n\nWhy: a request says what is wanted." + doc = self.cycle_doc(rules=[{"id": "know-done", "title": title, "body": long_body, "action": "replace"}]) + r = self.sisi("cycle", "apply", doc) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("shortens", r.stdout) + doc2 = self.cycle_doc(rules=[{"id": "know-done", "title": title, "body": long_body, "action": "replace", + "shortens": "know-done: the old preamble is removed"}]) + # with shortens it may still fail the hard char budget, but not for missing shortens + r2 = self.sisi("cycle", "check", doc2) + if r2.returncode != 0: + self.assertNotIn("add `shortens`", r2.stdout) + + def test_gap15_char_budget_rewrap_and_canon_cost(self): + self.sisi("build-canon") + self.assertIn("characters (budget %d)" % overlay.MAX_CHARS, self.sisi("canon", "cost").stdout) + pre, base = overlay.base_rules() + title = next(r["title"] for r in base if r["id"] == "know-done") + body = ("Before non-trivial work write a contract listing the checks that decide success " + "and draft it yourself from the request and the project in front of you today.\n\n" + "Why: a request says what is wanted, rarely how success is measured.") + doc = self.cycle_doc(rules=[{"id": "know-done", "title": title, "body": body, "action": "replace"}]) + self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) + gen = open(paths.generated()).read() + section = gen.split("Know how you will know you are done")[1].split("## 2.")[0] + self.assertTrue(all(len(l) <= 101 for l in section.splitlines()), [l for l in section.splitlines() if len(l) > 101][:3]) + self.assertTrue(all(len(l) <= 101 for l in open(paths.overlay_dir("rules", "know-done.md")).read().splitlines())) + + def test_gap16_rule_numbers_map_to_ids(self): + out = cycle.brief_text() + self.assertIn("1. know-done", out) + self.assertIn("rule 5", out) + + def test_gap17_enforced_help_fields_and_examples(self): + out = self.sisi("cycle", "help").stdout + self.assertIn("contract-requirement", out) + self.assertIn("require_kind", out) + self.assertIn("max_rung", out) + self.assertIn("below strength 3", out) + self.assertIn("timeout_s", out) + + def test_gap18_notes_chars_exclude_folded(self): + ids = [self.mk(change="Loose parser readiness lesson number %d with enough text to count here" % i, + moment="loose wait %d at step 2" % i) for i in range(3)] + before = cycle.due_state()["notes_chars"] + self.assertGreater(before, 0) + doc = self.cycle_doc(notes=[{"lesson": ids[0], "action": "fold-into-entry", "into": "parser-or-codec"}]) + self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) + after = cycle.due_state()["notes_chars"] + self.assertLess(after, before) + self.assertIn("do not count", cycle.brief_text()) + + def test_gap19_brief_names_cycle_file_path(self): + out = cycle.brief_text() + self.assertIn(cycle.cycle_file_path(), out) + self.assertIn("sisi cycle check FILE", out) + + def test_gap20_help_is_detailed_and_brief_points_to_it(self): + self.assertIn("sisi cycle help", cycle.brief_text()) + out = self.sisi("cycle", "help").stdout + self.assertIn("create-entry", out) + self.assertIn("fold-into-entry", out) + + def test_also_cycle_check_dry_run_changes_nothing(self): + lid = self.mk() + before = self.overlay_bytes() + doc = self.cycle_doc(notes=[{"lesson": lid, "action": "retire"}]) + for args in (("cycle", "check", doc), ("cycle", "--dry-run", doc)): + r = self.sisi(*args) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn("nothing was changed", r.stdout) + self.assertIn("retire", r.stdout) + self.assertEqual(self.overlay_bytes(), before) + self.assertEqual(self.lesson(lid)["status"], "open") + self.assertEqual(cycle.cycle_records(), []) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_public.py b/tests/test_public.py index c6ff016..ec65e4e 100644 --- a/tests/test_public.py +++ b/tests/test_public.py @@ -38,6 +38,34 @@ _ALLOWED_HOME_USERS = {"alice", "bob", "user", "you", "name", "username", "examp HOME_RE = re.compile(r"(? %s" % (doc, target)) +class NoStaleValues(unittest.TestCase): + def test_readme_has_no_stale_values(self): + text = open(os.path.join(REPO, "README.md"), encoding="utf-8").read() + self.assertEqual(_stale_value_findings(text, "README.md"), [], + "hardcoded values that will go stale in the README") + + def test_docs_have_no_stale_values(self): + rels = ["CONTRIBUTING.md", "SECURITY.md"] + rels += [os.path.join("docs", n) for n in sorted(os.listdir(os.path.join(REPO, "docs"))) + if n.endswith(".md")] + findings = [] + for rel in rels: + findings += _stale_value_findings(_text(rel), rel, allow_version_evidence=True) + self.assertEqual(findings, [], "hardcoded values that will go stale in the docs") + + def test_readme_word_count_stays_under_ceiling(self): + words = len(open(os.path.join(REPO, "README.md"), encoding="utf-8").read().split()) + self.assertLessEqual(words, README_WORD_CEILING, + "README has %d words, ceiling %d; cut or raise it deliberately" + % (words, README_WORD_CEILING)) + + def test_the_stale_scan_can_fail(self): + bad = _stale_value_findings( + "Version 0.1.0 had 140 verification techniques and 20 recipes in 2026; today it grows.", + "sample") + self.assertGreaterEqual(len(bad), 5, bad) + self.assertTrue(_stale_value_findings("checked on Foo v1.2.3", "sample")) + allowed = "Python 3.9 or newer; rung 1, rung 2, rung 3, rung 4, rung 5, rung 6." + self.assertEqual(_stale_value_findings(allowed, "sample"), []) + evidence = "no delivery could be confirmed on Foo v1.2.3 in headless runs" + self.assertEqual(_stale_value_findings(evidence, "sample", allow_version_evidence=True), []) + + if __name__ == "__main__": unittest.main()