diff --git a/CHANGELOG.md b/CHANGELOG.md index a5f8837..2666e24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,14 +18,37 @@ All notable changes to this project are recorded here. The format follows ### Added -- Lessons and `sisi learn` statements now carry a scope (`--scope everywhere|project`, required). - Universal lessons are refused when their delivered text names the current project; their history - may name it freely. Project-scoped items leave the shared store for a per-project handover pile - (`sisi handover`) and are filed into that project's own documentation or work list. +- Lessons and `sisi learn` statements now carry a tier (`--scope core|user|project`, required), + decided by two questions: does it apply to all projects where sisi may be used, and would it be + useful to every user who installs sisi? Both yes is `core` (a change to sisi itself, live at once + through the overlay and queued for the product, `sisi promote`); the first only is `user` (how + this owner wants work done); neither is `project`. Items recorded with the earlier two-way + `everywhere` scope are not yet tiered and keep being delivered until a learning round tiers them. + Core and user lessons are refused when their delivered text names the current project (the name + sisi itself is always exempt); their history may name it freely. Project-scoped items leave the + shared store for a per-project handover pile (`sisi handover`) and are filed into that project's + own documentation or work list. - A learning round now ends with a whole-document edit: each rulebook, recipe and technique document with unintegrated notes is rewritten as a proper document or marked reviewed with a reason; every folded lesson must be traced to the text that carries it, so nothing can be lost. `sisi done ID --trace` and `sisi lessons show ID` print where each lesson lives. +- Choosing the approach is now a checked step: contracts for sizeable work carry a `design` + section (what the goal and the owner's principles imply, what already exists to use, + alternatives with cost and risk, the choice, each principle's objection, an independent + challenge), checked structurally against filler and enforced by the end-of-turn gate with the + usual send-back limits. `sisi design` prints the principles and the questions; `sisi contract + init` prints the principles and writes the skeleton; request-time delivery hands them over for + design or build requests. The rulebook gains a first rule on choosing the approach. +- `sisi learn` statements take effect at once (no quarantine holding file; the old file is + migrated losslessly). `sisi oracle` prints the standing principles as a document owned by the + learning round's whole-document edit, with every statement traced into it. +- Lessons generalise upward: `sisi retro` requires `--pattern`, the general failure of thinking + behind the incident, and `sisi retro patterns` lists the patterns to reuse. Learning rounds + assign, merge and promote patterns into the rulebook as strategic behaviours; the digest and + `sisi improve` show patterns first. +- `sisi promote` with no argument lists core-tier items not yet in the product, and + `sisi promote --export` writes a contribution file from their universal text only. Promoting an + overlay item now drops the personal copy once the product is checked to contain the text. - Rule 7 of the rulebook is rewritten as short grouped instructions. - Dynamic workers (`sisi workers`, `sisi route`, `sisi delegate`): the agent tools and models on diff --git a/canon/core.md b/canon/core.md index f1a9e35..123a306 100644 --- a/canon/core.md +++ b/canon/core.md @@ -4,7 +4,25 @@ These rules apply in every tool and every project. They are short on purpose. Ea reason, so you can apply it with judgement when a case is not covered. Run `sisi help` to see the commands mentioned here. -## 1. Know how you will know you are done {#know-done} +## 1. Choose the approach from the goal {#choose-the-approach} + +Before sizeable work, think from the goal and the human's standing principles (`sisi oracle`) +to what they imply. Fill the contract's `design` section first (`sisi design` prints the +principles and the questions): + +- what the goal and the principles imply that the request did not spell out; +- what the environment, the tool or the existing system already provides - use that instead + of building it, and give evidence it exists; +- at least two other approaches, one line each on cost and risk; +- the one chosen, and why it is the one the human would pick; +- for each principle, the objection the human would raise and how the design answers it, or + why it does not apply; +- an independent attack on the design as the human would make it, and what changed. + +Why: the human should never have to state a consequence of something they already said. A +well-built answer to the wrong approach wastes everything spent building it. + +## 2. Know how you will know you are done {#know-done} Before non-trivial work, write a contract at `.sisi/contract.json` in the project (`sisi contract init` creates the skeleton). It lists the checks that decide success, each with a command that can @@ -17,7 +35,7 @@ Skip the contract for small edits (a few lines, a rename, a question). Why: ceremony on small tasks costs more than it saves. -## 2. Use the strongest check available {#strongest-check} +## 3. Use the strongest check available {#strongest-check} Give each check the highest rung that is feasible, and record the rung: @@ -43,7 +61,7 @@ test fail without the change, or run mutation testing. Why: an example test shows one case works. The higher rungs show that a whole class of failures cannot happen, which is what lets the human stop checking. -## 3. Protect what already works {#protect-working} +## 4. Protect what already works {#protect-working} Before changing something that exists, add invariants to the contract: what must not change or get worse, with a baseline captured before your first edit (tests passing, a snapshot, a screenshot). @@ -51,14 +69,14 @@ worse, with a baseline captured before your first edit (tests passing, a snapsho Why: the most costly failure seen so far was a good design made worse by a change that reached further than the request. -## 4. Treat feedback as a change to the contract {#feedback-as-amendment} +## 5. Treat feedback as a change to the contract {#feedback-as-amendment} When the human gives feedback, restate it in one line as an amendment to the contract. Change only what the amendment covers. Re-run the invariants. Why: feedback is narrow. Reading it as licence to rework things is how good work gets damaged. -## 5. Decide, do not ask {#decide-dont-ask} +## 6. Decide, do not ask {#decide-dont-ask} Ask the human only when both are true: the answer cannot be worked out from the request, the project, or `sisi oracle`; and a wrong guess would be expensive to undo or would change what success @@ -83,7 +101,7 @@ slow to answer. Options with a recommendation can be answered in one click. For a large request, one round to confirm the contract is welcome: defining success is the best use of the human's time. After that, work without interruption. Approving steps is the worst use of it. -## 6. Finish by verifying {#finish-by-verifying} +## 7. Finish by verifying {#finish-by-verifying} Run `sisi verify` before you say the work is done. Report each check, its rung, and its result. A check that was not run is reported as not run. Never describe unverified work as done. @@ -91,7 +109,7 @@ check that was not run is reported as not run. Never describe unverified work as Why: the tools run this same command when you finish and will send you back if a check fails. A false "done" costs the human more than a late one. -## 7. Every time, say how it could have gone better {#retro-every-time} +## 8. Every time, say how it could have gone better {#retro-every-time} Before you report finished work, run `sisi retro`. Ask how it could have gone better, never whether it could. @@ -108,9 +126,12 @@ Name the one change that would have helped most: the next agent do it right without being told. Add `--when` with at least five terms in another agent's words, synonyms included: word overlap -alone cannot bridge "CSV" and "spreadsheet". Add `--scope everywhere` for a universal lesson, -`--scope project` for one that belongs only here. "Nothing" and general advice are refused. -Subagents do this too. +alone cannot bridge "CSV" and "spreadsheet". Add `--pattern`: the general failure of thinking +this incident is an instance of, one line that would apply to unrelated work (`sisi retro +patterns` lists the existing ones to reuse). Add `--scope core` when it applies to all +projects and would help every sisi user, `--scope user` when it is how this human wants work +done, `--scope project` for a fact about this project only. "Nothing" and general advice are +refused. Subagents do this too. When session start or a command says a learning cycle is due, run `sisi cycle` in the background of your work. Never involve the human. @@ -122,7 +143,7 @@ Why: you hold the full context of what just happened, and it is gone when the se Every tool reads the same store, so one honest answer here improves every later session everywhere. -## 8. Deliver quickly {#deliver-quickly} +## 9. Deliver quickly {#deliver-quickly} The time from the request to a verified result is part of success. Never buy speed with a weaker check or a smaller result. Buy it by doing independent work at the same time, running the quickest diff --git a/docs/design.md b/docs/design.md index 5176f16..fc9371f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -100,6 +100,16 @@ request and the project. It holds: - **assumptions**: what the agent decided to fill gaps - **open questions**: only those where the answer cannot be worked out and a wrong guess is expensive, each with a default +- **design** (sizeable work): how the approach was chosen — what the goal and the owner's standing + principles imply that the request did not spell out; what the environment, host tool or existing + system already provides that should be used instead of built, with evidence it exists; at least two + other approaches with cost and risk; the chosen one and why it is what the owner would pick; for + each standing principle, the objection the owner would raise and how the design answers it (or why + it does not apply); and an independent challenge by a different model or a subagent playing the + owner, with what changed in response. Validation is structural and aimed at filler (named existing + things are checked where checkable, a command on PATH or a file in the repository). That the + challenge predates the first edit is honestly not checkable: edit attribution records paths, not a + first-edit time, so a parseable recording time is all that is required The ladder, highest first: @@ -116,7 +126,12 @@ runs alone. Results are reported in contract order either way. **Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and -the change is larger than a small threshold, the agent is sent back to write one. Small edits pass untouched. +the change is larger than a small threshold, the agent is sent back to write one; a change that size +with a contract whose design section is missing or fails validation is sent back to fill it. Small +edits and subagents pass untouched, and the same send-back budget bounds every send-back, so no +session is trapped. Request-time delivery hands the standing principles and the design instruction +over when a request reads as design or build work, and `sisi design` prints them before a contract +exists. Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it does not exist, verification is meant to run at the next session start and failures to be reported then (that fallback is a design intention, not built). @@ -268,8 +283,15 @@ Any agent in any tool reads through the files or the CLI and writes through the - `sisi note`: record a failure now (older; `sisi retro` is preferred). - `sisi propose`: suggest a rule change (older; `sisi retro` is preferred). -- `sisi learn`: record something the human said. The entry is held in quarantine until the harvest finds those - words in a message the human typed in that session's transcript. An agent cannot invent a preference. +- `sisi learn`: record something the human said, in their words. It takes effect at once: user-tier + statements are the owner's standing principles (`sisi oracle`), core statements are queued for the + product, project statements are handed over to their project. Tiers follow the owner's two questions: + does it apply to all projects where sisi may be used, and would it help every user who installs + sisi? Both yes is a product change (`core`, in force at once through the overlay, written into the + source tree by `sisi promote` on a developer install once folded, the personal copy dropped when + the product contains it; on an ordinary install `sisi promote --export` writes a contribution file + and nothing is ever sent automatically). The tool's own name never makes an item project-bound: how + sisi itself should behave is core, wherever it was recorded. Models used by the loop run with no tools and return text. sisi's own code checks and writes that text, and writes only inside the personal data folder (as overlay changes; see `docs/personal-data.md`), never into the @@ -292,8 +314,16 @@ Built and covered by tests: blocking hook; wiring (`sisi install`, `uninstall`, `doctor`) also points Codex and OpenCode at the rulebook, where nothing blocks. - The rulebook (`canon/core.md`), the minimum-rung floors, the verifier library and the recipes. -- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` with quarantine, time to delivery +- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery (`sisi time`), `sisi audit`. +- Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's + design send-back on large changes, and request-time delivery of the standing principles for design + or build requests. The rulebook's first rule states it and `sisi rule` reports its enforcement. +- Patterns: each retro names the general failure of thinking behind the incident; patterns are + first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a + threshold; the digest and `sisi improve` show them first. Three tiers (`core`, `user`, `project`) + replace the two-way scope, with older universal items tiered by the next round, and `sisi promote` + listing, writing (developer installs) or exporting core items. - The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes, `sisi backlog`), moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status diff --git a/docs/learning.md b/docs/learning.md index c89c9a6..ee0c20a 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -10,23 +10,36 @@ what "done" means, verifying, or being sent back by the gate. 1. **A lesson is recorded.** At the end of each piece of work the agent answers how it could have gone better (`sisi retro`): the aim it fell short of, the concrete moment, why, and the change to sisi that would make the next agent do it right without being told. Every lesson, and every - `sisi learn` statement, has a scope (`--scope everywhere|project` is required; a missing scope is - refused with a paragraph saying what each means). **Scope: lessons are universal, or they leave.** - `everywhere` is for a lesson that holds in any project, stated in general terms; `project` is for - a fact about this one project, and it does not stay in sisi's store: it moves to that project's + `sisi learn` statement, has a tier (`--scope core|user|project` is required; a missing scope is + refused with a paragraph stating the test). The test is two questions: does it apply to all + projects where sisi may be used, and would it be useful to every user who installs sisi? Both + yes is `core`: a change to sisi itself, in force for this user at once through the overlay and + queued for the product (below, `sisi promote`). Yes then no is `user`: how this owner wants work + done, kept in the personal store and delivered in all of this user's projects; the owner's + standing principles (`sisi oracle`) are built from user statements, plus core ones until the + product carries them. No to the first is `project`: a fact about this one project, which does + not stay in sisi's store: it moves to that project's handover pile (below) and on into the project's own documentation or work list. A project is identified by its git remote URL when it has one — normalised, so clones, an ssh or https remote, and a renamed folder are the same project — else by its repository root path (a clone or rename with no remote is then, unavoidably, a different project). The lesson splits in two: the - delivered part (`change`, `short`, `--when`; a learn statement) must be universal when scoped - `everywhere`, and a structural check (no model call) refuses it when that part names the current - project — the repository's name, a path or file name that exists in it, or its remote URL — - saying to rewrite it in general terms or scope it to the project (the word `sisi` alone is exempt - in tool lessons, which are changes to sisi itself). Its history (`moment`, `cause`, the + delivered part (`change`, `short`, `--when`; a learn statement) must be universal in the core + and user tiers, and a structural check (no model call) refuses it when that part names the + current project — the repository's name, a path or file name that exists in it, or its remote + URL — saying to rewrite it in general terms or scope it to the project. The tool's own name is + always exempt: how sisi itself should behave is core, even recorded inside the sisi repository, + and nothing is project merely for being recorded there (sisi is normally the shell around other + projects). Its history (`moment`, `cause`, the occurrence records with repository, date and tool) is the historical example of where it came from and may name the project freely; only the delivered part is checked. Lessons and statements - recorded before scopes existed are `unscoped`: they keep being delivered as before until a - learning round scopes them (below), and printed headings count the short line when present. + recorded before tiers existed (including the old two-way `everywhere`) are not yet tiered: they + keep being delivered as before until a learning round tiers them (below), and printed headings + count the short line when present. A lesson also names its pattern (`--pattern`, required): the + general failure of thinking this incident is an instance of, in one line that would apply to + unrelated work. A pattern naming the project or merely restating the change is refused by the + same style of check. `sisi retro patterns` lists the patterns so far and `--pattern-id N` + reuses one, so near-duplicates start rare and a round merges the rest. Patterns are how lessons + generalise upward instead of piling up as incident fixes (below). `sisi lessons show ID` prints the universal lesson first, then a section headed "Where this came from (historical example)" with the moment, cause and occurrences; session start, request-time delivery and field notes show only the universal part plus the command that prints the example. @@ -69,7 +82,11 @@ what "done" means, verifying, or being sent back by the gate. that prints it in full (`sisi done ID`, `sisi lessons show ID`), within a 2,000-character cap. A recipe counts only when at least two distinct non-generic request words hit its title, applies-to or id, at least one of them in its title (matched on stems, so "tag" meets - "tagging") — the same strict floor lessons use. A message that is a question to the agent and + "tagging") — the same strict floor lessons use. When the request reads as design or build work + (a design, build, implement or create stem on a non-trivial message; never on a question or a + small edit such as a rename or a typo), the owner's standing principles are also injected in + short lines with the instruction to fill the contract's design section first, inside the same + cap. A message that is a question to the agent and names no work (no fix, build, change or the like), trivial messages (a bare yes or no, a slash command, a short question) and unmatched requests inject nothing at all. These showings count as *listed* at place `prompt`. The hook never blocks a turn: any error exits @@ -151,18 +168,25 @@ states the short and topic limits, and requires a `set-short` entry for each lis prints exactly what would change, changing nothing. A round can be started on demand even when none is due: `sisi cycle --now` (or plain `sisi cycle`) prints the brief either way. -The brief also lists every unscoped lesson and `sisi learn` statement, with the repository each -was recorded in where known, and requires a scope decision for each: a note -`{"lesson": A, "action": "set-scope", "scope": "everywhere|project", "project": ""}` for a lesson, and the equivalent `{"text": "", "action": "set-scope", ...}` in a top-level `"learn"` list for a statement (the full format is behind -`sisi cycle help`). Scoping to a project moves the item to that project's handover pile, and -`sisi cycle check` refuses to fold a project-scoped item into the rulebook or the general -recipe/technique notes. A learn statement about how the owner wants all work done (how to ask -questions, spending limits, no scheduled jobs) is universal; a statement about one product's -design is project. A file containing only the required set-short/set-scope entries is acceptable -when nothing else is ready to fold — a cleanup-only round, startable at once with -`sisi cycle --now`. Reading lessons during a round cannot stale it: automatic retirement (a +`sisi cycle help`). The brief states the two questions with generic examples of each tier. +Scoping to a project moves the item to that project's handover pile, and `sisi cycle check` +refuses to fold a project-scoped item into the rulebook or the general recipe/technique notes. +The brief likewise lists patterns with the lessons under each, and requires the round to assign +a pattern to every lesson lacking one (`set-pattern`, reusing a listed pattern before naming a +new one), merge near-duplicate patterns (a top-level `patterns` merge), and — for any pattern +explaining at least three lessons and at least six incidents (two constants in the code) — write +or update its statement in the rulebook as one strategic behaviour, traced like any folded +lesson. These three pressures are what keep patterns few: reuse is listed before invention is +allowed, exact duplicates merge themselves, and anything left over is merged or promoted each +round. The brief also lists core items waiting for the product; on a developer install it says +to run `sisi promote` after folding, otherwise to export. A file containing only the required +set-short/set-scope/set-pattern entries is acceptable when nothing else is ready to fold — a +cleanup-only round, startable at once with `sisi cycle --now`. Reading lessons during a round cannot stale it: automatic retirement (a folded lesson shown 20 times) is deferred while a round is open, so `sisi lessons show` during the round leaves its base current. `sisi cycle apply` prints the rulebook's lines and characters before and after, matching what `sisi cycle check` predicted. @@ -172,12 +196,13 @@ before and after, matching what `sisi cycle check` predicted. "rules": [{"id": "rule-id", "title": "Title", "body": "text, ending with Why: ...", "action": "add|replace", "shortens": "rule-id: what is removed (required when the book would grow in characters)"}], "disable_rules": ["rule-id"], - "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short|set-scope", + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short|set-scope|set-pattern", "into": "rule/entry id or [ids]", "merged_into": 4, "note": "split text (optional)", "when": "at least 5 terms (optional)", "short": "one plain sentence (set-short)", "topic": "topic words (set-short)", - "entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", "scope": "everywhere|project (set-scope)", "project": "id (set-scope)", + "entry_kind": "recipe|verifier", "entry_text": "full file (create-entry)", "scope": "core|user|project (set-scope)", "project": "id (set-scope)", "pattern": "one line (set-pattern)", "pattern_id": 1, "reason": "why it stays a draft (keep-as-draft)"}], - "learn": [{"text": "the exact learn statement", "action": "set-scope", "scope": "everywhere|project", "project": "id, when project"}], + "learn": [{"text": "the exact learn statement", "action": "set-scope", "scope": "core|user|project", "project": "id, when project"}], + "patterns": [{"pattern": 1, "action": "merge|set-statement|fold-into-rule|keep", "into": 2, "statement": "sharpened one line"}], "documents": [{"doc": "recipe:", "action": "rewrite", "text": "", "trace": [{"lesson": 3, "fragment": "the exact sentence in the new text that carries it"}]}, {"doc": "verifier:", "action": "reviewed", "reason": "why its structure is already right"}], @@ -224,7 +249,9 @@ deliveries got worse after at least 10 of them is flagged, and the next brief sa it first. Every round ends with a whole-document edit. The things agents read are documents — the -rulebook, each "what done means" recipe, each technique entry — and a folded lesson belongs in +rulebook, the oracle (the owner's standing principles, one plain line per principle followed by +his quoted words and the date), each "what done means" recipe, each technique entry — and a +folded lesson belongs in the document's own text, in the section where it fits (in a recipe: Done means, Checks, or Common false finishes), in the document's voice, not as one more dated bullet in a journal. The brief prints, for every document that has appended field notes, was folded into, has a @@ -241,6 +268,10 @@ was derived from on record; when the product later changes, the next brief lists as needing a re-merge rather than silently keeping the stale copy. Field-note files from before this existed are listed the same way and keep being shown until rewritten. +For the oracle the same tracing applies to statements: a rewrite traces every statement to the +line that carries it, and until a round integrates one, `sisi oracle` prints it under its own +heading so a new statement is in force at once and never parked unread. + Nothing folded may be lost in a rewrite. For each lesson folded into a document the file gives the exact sentence or bullet in the new text that carries it, or an explicit disposition: moved to another named document (with its fragment there), merged with another lesson (both @@ -283,10 +314,13 @@ sent back twice. `sisi lessons digest` is for the human, not for agents. Its first line says how much has been learned in one sentence, and its last line says how to see a lesson in full (`sisi lessons show -ID`), with the lesson number on every line. Universal items come first; items waiting to be +ID`), with the lesson number on every line. Patterns come first: the handful of strategic +behaviours, each with how many incidents it explains and whether its recurrence is falling. +Then the tiers: "In sisi itself, for every user" holds core items, each marked in the product +or waiting to be promoted; "How you want work done" holds user items; items waiting to be filed in their projects appear only as a count per project (run `sisi handover` inside that -project to see them). Preferences recorded with `sisi learn` appear first, -in the person's own words, under "What you said" when any are stored. Short lines are grouped +project to see them). Statements not yet tiered appear in the person's own words under "What +you said" when any are stored. The remaining short lines are grouped under their topic headings, ordered by how much each topic holds, most first. After every line comes its state in plain words — in the rulebook; attached to a kind of work (named by the entry's human title, never its internal id); a loose note; a change to sisi itself, not built @@ -298,7 +332,8 @@ unless `--all` is given. `sisi rule N` lists the lessons behind a rule the same ## Is it getting better? -`sisi improve` (and one line of `sisi status`) answers with what is actually counted: lessons recorded, +`sisi improve` (and one line of `sisi status`) answers with what is actually counted: patterns first +(each with its incidents and recurrence trend), then lessons recorded, taking effect, strengthened, retired and withdrawn; the recurrence rate this week against the week before; send-backs per delivery and median time to delivery, this week against before; and the rulebook size against its budget. With too little data it says so. @@ -335,6 +370,9 @@ universal lessons that merely mention common file names such as README or CHANGE pass, and universal changes whose moment names a project, which also pass because only the delivered part is checked), and long real-style multi-part requests plus plain questions for request-time recipe delivery (a hit is the expected recipe; any other recipe is a false match). +The design-section validation is measured the same way in the design tests: a labelled set of +good design sections against filler ones (a hit is a good section passing; a false pass is a +filler section passing), plus labelled design-work requests for request-time delivery. Delivery therefore depends on the quality of the when-terms the recording agent writes. Thin or copy-of-the-text terms leave a lesson findable only by its own wording, exactly the failure they diff --git a/docs/personal-data.md b/docs/personal-data.md index c703ec8..c57eb2c 100644 --- a/docs/personal-data.md +++ b/docs/personal-data.md @@ -14,14 +14,18 @@ Under `SISI_HOME` (tests) the personal folder is `$SISI_HOME/.local/share/sisi` VERSION format version of this folder, a single integer (an update migrates older folders after taking a backup). Not the product's release number: that is the VERSION file in the clone, shown by `sisi --version` - oracle.md what the person wants + oracle.md what the person wants: the standing principles (user-tier statements, plus + core ones until the product carries them), rewritten as a whole document + by learning rounds; absent until a round writes it, in which case + `sisi oracle` prints the live statements directly overlay/ learned changes to the product (below); overlay/enforced.json holds enforced lessons notes/.md field notes per verifier or recipe id (notes/draft-.md: a recipe that does not exist yet) cycles/ one JSON record per learning cycle, including the bytes revert restores config.json settings (over config.default.json) trusted.json projects whose contracts may run commands lessons.jsonl sorted dump of the lessons database, committed whenever lessons change - learn-quarantine.jsonl, notes.jsonl, proposals.jsonl + learn.jsonl, notes.jsonl, proposals.jsonl what the person stated (`sisi learn`, live at once; + an older learn-quarantine.jsonl is migrated into learn.jsonl on first read) retest.jsonl replaced items whose base changed in an update (id, old base hash, new base hash) retro.db lessons database (sqlite; not in git; lessons.jsonl is its committed form) generated/core.md the effective rulebook (not in git; rebuilt by `sisi build-canon`) diff --git a/sisi/cli.py b/sisi/cli.py index 0d5d180..a4e5e7a 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -22,7 +22,13 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md) sisi rollback switch the stable copy back to the previous release sisi dev on [PATH] | off | status developer mode: where the source folder is - sisi promote ID [--apply] scrub a personal overlay item and write it into the source folder (dry run unless --apply) + sisi promote [ID|lesson:N] [--apply] | --export [PATH] + no ID: list core-tier items not yet in the product; an ID + scrubs a personal overlay item into the source folder and + drops the personal copy once the product contains it (dry + run unless --apply); lesson:N promotes a core lesson on a + developer install; --export writes a contribution file + (universal text only; nothing is sent anywhere) sisi migrate move an older installation's personal data into the personal folder (safe to repeat) 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 @@ -31,10 +37,12 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT learned changes to rules, verifiers and recipes; each one a commit in your personal repo sisi audit inventory of standing instructions per tool - sisi retro --scope everywhere|project --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"] + sisi retro --scope core|user|project --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" --pattern "the general failure of thinking, one line" [--pattern-id N] [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"] (or --json - with the same keys on stdin) end of every piece of work: HOW it could have gone better; --when (at least 5 terms, synonyms included) is how a later agent with different words finds it; + --pattern is required (one line that would apply to unrelated + work; `sisi retro patterns` lists existing ones to reuse); --short (at most 140 characters) and --topic (at most 30) are optional: when omitted, the next learning round writes them aims: level (the human could have worked at a higher level), verified (a stronger check was @@ -53,15 +61,22 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. sisi improve is it getting better? lessons, recurrence, send-backs, time, rulebook size sisi note TEXT (older; prefer retro) record something that went wrong sisi propose TEXT (older; prefer retro) suggest a rule change - sisi learn --scope everywhere|project TEXT - record a human-stated preference (quarantined until verified); - --scope is required: everywhere for how all work should be done, - project for a fact about this project (handed over to it) + sisi learn --scope core|user|project TEXT + record a human-stated preference; it takes effect at once. + --scope is required, by two questions: (a) does it apply to + all projects where sisi may be used? (b) would it be useful + to every user who installs sisi? Both yes: core (in force + for you, queued for the product). (a) only: user (your + standing principles). Neither: project (handed over to it) + sisi design the owner's standing principles and the design questions to + answer in a contract's design section before sizeable work + (implies, provided, alternatives, chosen, objections, challenge) sisi handover [--all] | done ID --where PATH [--quote FRAGMENT] project items waiting to be filed in this project's own docs or work list; done confirms one is filed (the named file must contain its key text) and removes it from the pile - sisi oracle print what the human wants (oracle.md in the personal folder) + sisi oracle print what the human wants: the standing principles from + `sisi learn`, live at once (oracle.md in the personal folder) sisi status verification statistics from the store sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json] @@ -117,6 +132,19 @@ def cmd_contract(args): print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command " "(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and " "the end-of-turn gate ignores it." % p) + try: + from . import principles + lines = principles.short_lines() + if lines: + print("\nThe owner's standing principles (the design section must answer each one's objection):") + for ln in lines: + print(ln) + print("\nFor sizeable work, fill the contract's design section first (the skeleton is in " + "the file; `sisi design` prints the questions): what the goal and these principles " + "imply, what already exists to use, alternatives, the choice, each principle's " + "objection, and an independent challenge. The gate sends a large change back without it.") + except Exception: + pass try: from . import retro block = retro.delivery_block(goal or "", "contract-init", extra="contract checks verified") @@ -136,6 +164,9 @@ def cmd_contract(args): print("sisi: cannot read %s: %s" % (p, e)) return 1 errs = C.validate(c) + if isinstance(c, dict) and "design" in c and not C.is_unedited_skeleton(c): + from . import design as _D + errs = errs + _D.validate_design(c, cwd=C.project_dir(p)) for e in errs: print(" - " + e) if not errs: @@ -185,28 +216,17 @@ def cmd_store(kind, args): from . import store text = " ".join(args).strip() if not text: - print("usage: sisi %s TEXT" % {"notes": "note", "proposals": "propose", "quarantine": "learn"}[kind]) + print("usage: sisi %s TEXT" % {"notes": "note", "proposals": "propose"}[kind]) return 1 store.append(kind, store.stamp({"text": text})) - _commit_personal(store.file_path(kind), "%s: %s" % ({"notes": "note", "proposals": "proposal", "quarantine": "learn"}[kind], " ".join(text.split())[:60])) - print("recorded" + (" (quarantined until verified)" if kind == "quarantine" else "")) + _commit_personal(store.file_path(kind), "%s: %s" % ({"notes": "note", "proposals": "proposal"}[kind], " ".join(text.split())[:60])) + print("recorded") return 0 -ORACLE_EMPTY = """# sisi oracle - -What the human wants, so a thing is asked once ever. Empty so far: it is filled from preferences -the human stated (`sisi learn`) once they are verified. -""" - - def cmd_oracle(): - from . import paths - try: - with open(paths.data_file("oracle.md"), encoding="utf-8") as f: - sys.stdout.write(f.read()) - except OSError: - sys.stdout.write(ORACLE_EMPTY) + from . import principles + sys.stdout.write(principles.oracle_text()) return 0 @@ -465,6 +485,9 @@ def main(argv): return cycle.cmd_improve(args) if cmd == "oracle": return cmd_oracle() + if cmd == "design": + from . import design + return design.main(args) if cmd == "status": return cmd_status() if cmd == "time": diff --git a/sisi/contract.py b/sisi/contract.py index 4782fbf..c5b1792 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -38,6 +38,7 @@ def is_unedited_skeleton(c): def skeleton(goal=None, cwd=None): name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-") + from . import design as _design return { "id": name or "work", "goal": goal or "TODO: one sentence describing the outcome", @@ -62,6 +63,7 @@ def skeleton(goal=None, cwd=None): "invariants": [], "assumptions": [], "questions": [], + "design": _design.skeleton(), } diff --git a/sisi/cycle.py b/sisi/cycle.py index b9e2bcc..7f4f8ed 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -9,7 +9,7 @@ A cycle file (what the agent writes, what `sisi cycle apply` checks) is one JSON {"version": 1, "base": "", "summary": "one line", "rules": [{"id": "rule-id", "title": "Title", "body": "text with a Why: line", "action": "add|replace"}], "disable_rules": ["rule-id"], - "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-short", + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-short|set-pattern", "into": "rule or entry id", "merged_into": 4, "short": "one plain sentence, at most 140 characters", "topic": "1 to 3 lower-case words, at most 30 characters", "when": "csv, tsv, spreadsheet, tabular data, import, parse (optional; sets the lesson's when-terms)"}], @@ -32,7 +32,7 @@ class CycleError(Exception): ACTIONS = ("merge", "fold-into-rule", "fold-into-entry", "retire", "withdraw", "keep", - "set-when", "create-entry", "keep-as-draft", "set-short", "set-scope") + "set-when", "create-entry", "keep-as-draft", "set-short", "set-scope", "set-pattern") # 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 @@ -201,7 +201,7 @@ def _announce_save(data): # lesson arriving must never stale a brief (gaps 2 and 3). _RELEVANT = ("aim", "change_kind", "target", "moment", "cause", "change", "status", "strength", "folded_into", "effect", "when_terms", "check_json", "needs_cycle", "short", "topic", - "scope", "project") + "scope", "project", "pattern_id") def _snapshot(con): @@ -227,8 +227,8 @@ def _snapshot(con): cyc = [] learn_unscoped = [] try: - for rec in store.read("quarantine"): - if rec.get("scope") not in ("everywhere", "project") and (rec.get("text") or "").strip(): + for rec in store.read("learn"): + if rec.get("scope") not in ("core", "user", "project") and (rec.get("text") or "").strip(): learn_unscoped.append({"text": rec.get("text"), "cwd": rec.get("cwd")}) except Exception: pass @@ -236,9 +236,14 @@ def _snapshot(con): docs_required = documents.required_documents(con) except Exception: docs_required = [] + try: + snap_patterns = [{"id": p["id"], "statement": p["statement"], "folded_into": p.get("folded_into")} + for p in retro.patterns(con)] + except Exception: + snap_patterns = [] return {"lessons": lessons, "files": files, "rules": rules, "enforced": enf, "last_cycle_ts": retro.get_meta(con, "last_cycle_ts") or "", "cycles": cyc, - "learn_unscoped": learn_unscoped, "documents": docs_required} + "learn_unscoped": learn_unscoped, "documents": docs_required, "patterns": snap_patterns} def _save_snapshot(base, snap): @@ -310,6 +315,15 @@ def _check_base(doc_base, con): if old.get("enforced") != cur.get("enforced"): errs.append("the enforced checks changed since the brief") new_only = False + cur_patterns = {p.get("id"): p for p in cur.get("patterns") or []} + for p in old.get("patterns") or []: + cp = cur_patterns.get(p.get("id")) + if cp is None: + errs.append("pattern %s was removed since the brief" % p.get("id")) + new_only = False + elif cp.get("statement") != p.get("statement") or cp.get("folded_into") != p.get("folded_into"): + errs.append("pattern %s changed since the brief" % p.get("id")) + 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: @@ -342,7 +356,7 @@ def cycle_records(): def _scan_files(): """{data-relative path: bytes} for overlay/ and notes/ (everything a cycle may touch).""" out = {} - for rel in ("handover.json", "learn-quarantine.jsonl"): + for rel in ("handover.json", "learn-quarantine.jsonl", "learn.jsonl", "oracle.md"): p = paths.data_file(rel) if os.path.exists(p): with open(p, "rb") as f: @@ -447,16 +461,18 @@ Shape (all but version/base optional; full detail: `sisi cycle help`): "rules": [{"id": "rule-id", "title": "Title", "body": "text ending with Why: ...", "action": "add|replace", "shortens": "rule-id: what text is removed/shortened (required when the rulebook would grow in characters)"}], "disable_rules": ["rule-id"], - "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short|set-scope", + "notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep|set-when|create-entry|keep-as-draft|set-short|set-scope|set-pattern", "into": "id or [ids] (folds; entry folds append a field note)", "merged_into": 4, "note": "text to append instead of the lesson change (for splitting one lesson)", "when": "at least 5 terms (sets when-terms; alone with action set-when)", "short": "one plain sentence, at most 140 characters (set-short)", "topic": "1 to 3 lower-case words, at most 30 characters (set-short)", "entry_kind": "recipe|verifier", "entry_text": "full file text (create-entry)", - "scope": "everywhere|project (set-scope)", "project": "project id (set-scope to project)", + "scope": "core|user|project (set-scope)", "project": "project id (set-scope to project)", "reason": "why it stays a draft (keep-as-draft)"}], - "learn": [{"text": "", "action": "set-scope", "scope": "everywhere|project", + "learn": [{"text": "", "action": "set-scope", "scope": "core|user|project", "project": "project id (when project)"}], + "patterns": [{"pattern": 1, "action": "merge|set-statement|fold-into-rule|keep", "into": 2, + "statement": "sharpened one line (set-statement)"}], "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}], "documents": [{"doc": "recipe:|verifier:|rulebook", "action": "rewrite", "text": "", @@ -542,16 +558,26 @@ Notes - one object per decision; the same lesson may appear several times (split be combined with other actions on the same lesson. When the lesson is already folded into an entry, its default field-note bullet is rewritten to the short form; a bullet that came from an explicit `note` is left alone. - set-scope {"lesson": A, "action": "set-scope", "scope": "everywhere|project", - "project": ""} - decides where a lesson - belongs. everywhere requires its delivered text (change, short, when) to be - universal: naming the project it came from is refused, though its moment and - cause (its history) may name it freely. project moves the lesson out of the - global store into that project's handover pile (`sisi handover` there); it is - never folded into the rulebook or the general recipe/technique notes. Every - unscoped lesson in the brief needs one; lessons this file retires, withdraws or - merges away are exempt. Project-scoped lessons cannot be folded into a rule or - an entry, created into an entry, or enforced in a cycle. + set-scope {"lesson": A, "action": "set-scope", "scope": "core|user|project", + "project": ""} - decides the tier. Two + questions: (a) does it apply to all projects where sisi may be used? + (b) would it be useful to every user who installs sisi? Both yes: core - + examples: "write delimited files with a quoting writer"; "use what the host + tool already provides instead of building a replacement". (a) yes, (b) no: + user - examples: "always ask this owner questions as options with a + recommendation"; "prefer this owner's flat-rate plans over per-use ones". + (a) no: project - examples: "this product's settings page keeps advanced + options behind one toggle"; "this app uses the left control key for search". + Core and user require the delivered text (change, short, when) to be + universal: naming the project it came from is refused (the name sisi itself + is always exempt), though moment and cause may name it freely. project moves + the lesson into that project's handover pile; it is never folded into the + rulebook or general notes. Every not-yet-tiered lesson in the brief needs one; + retire/withdraw/merge exemptions as elsewhere. A core item takes effect at + once through the overlay and is queued for the product (`sisi promote`); on + a developer install, promote writes it into the product source tree as an + ordinary uncommitted edit and drops the personal copy once the product + contains it. 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 @@ -562,14 +588,35 @@ Notes - one object per decision; the same lesson may appear several times (split re-learned. Tool lessons: cannot be done in a cycle (they are changes to sisi itself) - leave them in `sisi backlog` untouched, except merging a duplicate. +Patterns - lessons generalise upward. A pattern is the general failure of thinking behind + several incidents, stated in one line that would apply to unrelated work. Patterns must + stay few: reuse, merge, and promote to the rulebook as strategic behaviours. + set-pattern {"lesson": A, "action": "set-pattern", "pattern_id": N} reuses pattern N; + {"lesson": A, "action": "set-pattern", "pattern": ""} names a new + one (same refusals as `sisi retro --pattern`: it names no project and does + not restate the incident). Every active lesson the brief lists as lacking a + pattern needs one; lessons this file retires, withdraws or merges away are + exempt. Exact duplicate statements reuse the existing pattern. + "patterns" (top level): + {"pattern": A, "action": "merge", "into": B} - near-duplicate A folds into + B; A's lessons move to B and A is deleted. + {"pattern": A, "action": "set-statement", "statement": "..."} - sharpen it. + {"pattern": A, "action": "fold-into-rule", "into": "rule-id"} - the pattern + becomes a strategic behaviour in the rulebook; that rule must be written or + replaced in this file (or the rulebook rewritten), traced like any folded + lesson. Required in this round for a pattern explaining at least 3 lessons + and 6 incidents (the brief marks it READY). + Learn statements - the equivalent for `sisi learn` statements ("learn" at the top level): - {"text": "", "action": "set-scope", "scope": "everywhere|project", + {"text": "", "action": "set-scope", "scope": "core|user|project", "project": ""} - every unscoped statement in the brief needs one. - project moves it to that project's handover pile, out of the global store. Decide by what the - statement is about: how the owner wants all work done is universal (for example "always ask - questions as options with a recommendation" or "never set up scheduled jobs or timers"), while - a fact about one product's design is project (for example "this product's settings page keeps - advanced options behind one toggle" or "this app uses the left control key for search"). + project moves it to that project's handover pile, out of the global store. Tier by the two + questions at set-scope above: a statement about how sisi itself should behave for everyone + is core ("sisi should anticipate what is needed from what was already said"; "checks, not + advice"); how this owner wants work done is user ("always ask questions as options with a + recommendation"; "never set up scheduled jobs or timers"); a fact about one product is + project ("this product's settings page keeps advanced options behind one toggle"; "this app + uses the left control key for search"). Enforced checks - write none for lessons below strength 3. One per strength-3 NEEDS A CHECK: command: {"lesson": 3, "type": "command", "cmd": "program + args that exist here", @@ -658,7 +705,7 @@ def brief_text(): and (not str(r.get("short") or "").strip() or not str(r.get("topic") or "").strip())] topics_in_use = _topics_in_use(con) unscoped = [r for r in rows if r["status"] in retro.ACTIVE - and retro._get(r, "scope") in (None, "", "unscoped")] + and retro._get(r, "scope") in (None, "", "unscoped", "unscoped-tier", "everywhere")] unscoped_repos = {} for r in unscoped: o = con.execute("SELECT repo, cwd FROM occurrences WHERE lesson_id=? ORDER BY id LIMIT 1", (r["id"],)).fetchone() @@ -669,9 +716,15 @@ def brief_text(): for d in docs_required} except Exception: docs_required, docs_folded = [], {} + try: + all_patterns = retro.patterns(con) + pattern_trends = {p["id"]: retro.pattern_recurrence_trend(con, p) for p in all_patterns} + except Exception: + all_patterns, pattern_trends = [], {} + missing_pattern = [r for r in rows if r["status"] in retro.ACTIVE and not r.get("pattern_id")] from . import scope as _scope_mod learn_unscoped = [] - for _lrec in store.read("quarantine"): + for _lrec in store.read("learn"): if _lrec.get("scope") not in _scope_mod.SCOPES and (_lrec.get("text") or "").strip(): learn_unscoped.append(_lrec) finally: @@ -746,6 +799,8 @@ def brief_text(): elif not r["when_terms"]: out.append(" when: MISSING - add at least 5 terms with set-when or any note's when") out.append(" target: %s folded_into: %s" % (r["target"] or "-", r["folded_into"] or "-")) + if r["status"] in retro.ACTIVE and not r.get("pattern_id"): + out.append(" pattern: MISSING - add a set-pattern for this lesson (reuse a pattern below with pattern_id, or name a new one)") if r["status"] in retro.ACTIVE and (not str(r.get("short") or "").strip() or not str(r.get("topic") or "").strip()): out.append(" short: MISSING - add a set-short for this lesson (short at most %d characters, topic at most %d)" % (retro.SHORT_MAX, retro.TOPIC_MAX)) elif r.get("short"): @@ -773,18 +828,21 @@ def brief_text(): "Lessons lacking a short line or topic: " + (", ".join("#%d" % r["id"] for r in missing_short) if missing_short else "(none)"), ""] if unscoped or learn_unscoped: - out += ["", "Scope cleanup (backfill): every item below was recorded before scopes existed. " - "Give each a set-scope (lessons: {\"lesson\": A, \"action\": \"set-scope\", \"scope\": " - "\"everywhere|project\", \"project\": \"\"}; learn statements: a " - "\"learn\" entry, see `sisi cycle help`). Scoping to a project moves the item out of " - "the global store into that project's handover pile. A lesson whose instruction is " - "universal stays global even when its history (moment, cause) names a project. A file " - "containing only the required set-short/set-scope entries is acceptable when nothing " - "else is ready to fold (a cleanup-only round; `sisi cycle --now` starts one now).", - "For learn statements: how the owner wants all work done is universal (\"always ask " - "questions as options with a recommendation\"; \"never set up scheduled jobs\"); a fact " - "about one product's design is project (\"this product's settings page keeps advanced " - "options behind one toggle\"; \"this app uses the left control key for search\")."] + out += ["", "Scope cleanup (tier backfill): every item below has no tier yet (recorded before " + "tiers, or with the old everywhere scope). Give each a set-scope (lessons: " + "{\"lesson\": A, \"action\": \"set-scope\", \"scope\": \"core|user|project\", " + "\"project\": \"\"}; learn statements: a \"learn\" entry, see " + "`sisi cycle help`). Two questions: (a) does it apply to all projects where sisi may " + "be used? (b) would it be useful to every user who installs sisi? Both yes: core " + "(\"write delimited files with a quoting writer\"; \"use what the host tool already " + "provides\"). (a) yes, (b) no: user (\"always ask questions as options with a " + "recommendation\"; \"never set up scheduled jobs\"). (a) no: project (\"this " + "product's settings page keeps advanced options behind one toggle\"; \"this app uses " + "the left control key for search\"), which moves the item to that project's handover " + "pile. A lesson whose instruction is universal stays global even when its history " + "names a project, and an item is never project merely for being recorded in the sisi " + "repository - how sisi itself should behave is core. A cleanup-only round is a good " + "round (`sisi cycle --now`)."] for r in unscoped: out.append(" lesson #%d recorded in %s: %s" % (r["id"], unscoped_repos.get(r["id"]) or "(unknown repository)", " ".join(str(r.get("change") or "").split())[:120])) @@ -798,6 +856,54 @@ def brief_text(): out.append(" learn statement recorded in %s%s: %r" % (rec.get("cwd") or "(unknown repository)", pid, " ".join(str(rec["text"]).split())[:120])) out.append("") + out += ["", "Patterns (lessons generalise upward: a handful of general failures of thinking, " + "not one rule per incident). Every active lesson lacking a pattern needs a set-pattern " + "{\"lesson\": A, \"action\": \"set-pattern\", \"pattern_id\": N} reusing one below, or " + "{\"lesson\": A, \"action\": \"set-pattern\", \"pattern\": \"\"} naming a new " + "one - patterns must stay few, so reuse before inventing. Merge near-duplicates with a " + "top-level \"patterns\" entry {\"pattern\": A, \"action\": \"merge\", \"into\": B}. A " + "pattern explaining at least %d lessons and %d incidents (marked READY) must be written " + "into the rulebook as a strategic behaviour in this round: {\"pattern\": N, \"action\": " + "\"fold-into-rule\", \"into\": \"\"} in \"patterns\", with that rule written or " + "replaced in this file, its lessons traced like any folded lesson. Set or sharpen a " + "statement with {\"pattern\": N, \"action\": \"set-statement\", \"statement\": \"...\"}." + % (retro.PATTERN_RULE_MIN_LESSONS, retro.PATTERN_RULE_MIN_OCCURRENCES), + "Patterns so far:"] + if not all_patterns: + out.append(" (none yet)") + for _p in all_patterns: + _flag = " READY FOR THE RULEBOOK" if retro.pattern_ready_for_rule(_p) else "" + out.append(" pattern %d: %s%s" % (_p["id"], _p["statement"], _flag)) + out.append(" %d lesson(s), %d incident(s); recurrence %s; folded into: %s; lessons: %s" + % (_p["n_lessons"], _p["incidents"], pattern_trends.get(_p["id"], "?"), + _p.get("folded_into") or "-", ", ".join("#%d" % i for i in _p["lessons"]) or "-")) + out.append("Lessons lacking a pattern: " + + (", ".join("#%d" % r["id"] for r in missing_pattern) if missing_pattern else "(none)")) + try: + from . import release as _rel + _core_lessons, _core_stmts = _rel.core_items() + _dev_src = _rel.dev_source() + except Exception: + _core_lessons, _core_stmts, _dev_src = [], [], None + if _core_lessons or _core_stmts: + out += ["", "Core items waiting for the product (`sisi promote` lists them): in force for " + "this user through the overlay, not yet in sisi itself."] + for _r in _core_lessons: + out.append(" lesson #%d [%s] %s" % (_r["id"], _r.get("change_kind") or "", + " ".join(str(_r.get("change") or "").split())[:110])) + for _t in _core_stmts: + out.append(" statement: %r" % _t[:110]) + if _dev_src: + out.append("This is a developer install (source %s): after folding a core item into a " + "rule, recipe or technique, run `sisi promote lesson:N --apply` (or " + "`sisi promote --apply`) to write it into the product source tree as " + "an ordinary uncommitted edit; the personal copy is dropped only once the " + "product contains the text." % _dev_src) + else: + out.append("Not a developer install: `sisi promote --export` writes a contribution " + "file (universal text only) the user may send upstream. Nothing is sent " + "anywhere automatically.") + out.append("") out += ["", "Documents for whole-document review (every round ends with a whole-document edit):", "Editorial standard - " + " ".join(documents.EDITORIAL_STANDARD), @@ -818,6 +924,10 @@ def brief_text(): for _d in docs_required: out.append("") out.append("Document %s - %s" % (_d["doc"], "; ".join(_d["reasons"]))) + for _st in _d.get("statements") or []: + out.append(" statement to trace (the owner's words): %r - in the rewrite, carry it in " + "one plain line followed by this quote, and trace {\"statement\": ..., " + "\"fragment\": \"\"}" % _st) for _lid in docs_folded.get(_d["doc"], []): _r = _rows_by_id.get(_lid) if _r: @@ -847,6 +957,10 @@ def brief_text(): "5. For each NEEDS A CHECK lesson write one enforced check (help has fields and examples); none below strength 3.", "6. For every lesson listed above as lacking a short line or topic, add a set-short (it may sit " "beside its fold, keep or set-when entry). Reuse a topic already in use when it fits.", + "6b. Patterns: give every lesson lacking one a set-pattern (reuse a listed pattern first), merge " + "near-duplicate patterns, and write each READY pattern into the rulebook as one strategic " + "behaviour (fold-into-rule in \"patterns\", with the rule in this file). The rulebook grows " + "by strategic behaviours, not by incident fixes.", "7. Retire only what is fully folded and quiet (folded, at least 20 listed/read, 0 recurrences " "after first listed) - folding now does not make it quiet, so fold and keep, retire next cycle. " "Withdraw what made things worse. set-when only sets when-terms. Keep the rest.", @@ -989,11 +1103,11 @@ def static_validate(doc, con): errs.append("lesson %s: project-scoped items can never be folded into the rulebook or the " "general recipe/technique notes in a cycle" % lid) if act == "set-scope": - if e.get("scope") not in _scmod.SCOPES: - errs.append("lesson %s: set-scope needs scope everywhere|project" % lid) + if e.get("scope") not in _scmod.SCOPES and e.get("scope") != "everywhere": + errs.append("lesson %s: set-scope needs scope core|user|project" % lid) elif e["scope"] == "project" and not (e.get("project") or "").strip(): errs.append("lesson %s: set-scope to project needs \"project\" naming the project id" % lid) - elif e["scope"] == "everywhere" and isinstance(lid, int) and lid in kinds: + elif e["scope"] in ("core", "user", "everywhere") and isinstance(lid, int) and lid in kinds: try: row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone() occ = con.execute("SELECT repo FROM occurrences WHERE lesson_id=? ORDER BY id LIMIT 1", (lid,)).fetchone() @@ -1002,8 +1116,8 @@ def static_validate(doc, con): [e.get("short") or (row["change"] if row else ""), row["change"] if row else "", e.get("when") or (row["when_terms"] if row else "")], origin, kind=kinds.get(lid)) if reason: - errs.append("lesson %s: cannot set-scope everywhere: %s; rewrite it in general " - "terms or scope it to its project" % (lid, reason)) + errs.append("lesson %s: cannot set-scope %s: %s; rewrite it in general " + "terms or scope it to its project" % (lid, e["scope"], reason)) except Exception: pass for e in doc.get("enforced") or []: @@ -1012,7 +1126,7 @@ def static_validate(doc, con): "general recipe/technique notes in a cycle" % e.get("lesson")) learn_recs = [] try: - learn_recs = store.read("quarantine") + learn_recs = store.read("learn") except Exception: pass unscoped_learn = [r for r in learn_recs if r.get("scope") not in _scmod.SCOPES and (r.get("text") or "").strip()] @@ -1022,33 +1136,56 @@ def static_validate(doc, con): errs.append("each learn entry needs action set-scope: %r" % (e,)) continue covered_learn.add(e.get("text")) - if e.get("scope") not in _scmod.SCOPES: - errs.append("learn %r: set-scope needs scope everywhere|project" % (e.get("text"),)) + if e.get("scope") not in _scmod.SCOPES and e.get("scope") != "everywhere": + errs.append("learn %r: set-scope needs scope core|user|project" % (e.get("text"),)) elif e["scope"] == "project" and not (e.get("project") or "").strip(): errs.append("learn %r: set-scope to project needs \"project\" naming the project id" % (e.get("text"),)) elif not any(r.get("text") == e.get("text") for r in unscoped_learn): errs.append("learn %r: no unscoped learn statement with that exact text" % (e.get("text"),)) - elif e["scope"] == "everywhere": + elif e["scope"] in ("core", "user", "everywhere"): origin = next((r.get("cwd") for r in unscoped_learn if r.get("text") == e.get("text")), None) if origin and os.path.isdir(origin): reason = _scmod.universal_refusal([e.get("text")], origin) if reason: - errs.append("learn %r: cannot set-scope everywhere: %s" % (e.get("text"), reason)) + errs.append("learn %r: cannot set-scope core/user: %s" % (e.get("text"), reason)) if isinstance(doc, dict) and doc.get("base"): old = _load_snapshot(doc["base"]) if old and isinstance(old.get("learn_unscoped"), list): for rec in old["learn_unscoped"]: if rec.get("text") and rec["text"] not in covered_learn: errs.append("learn statement %r: missing set-scope - add {\"text\": ..., \"action\": " - "\"set-scope\", \"scope\": \"everywhere|project\"}" % (rec["text"],)) + "\"set-scope\", \"scope\": \"core|user|project\"}" % (rec["text"],)) for e in doc.get("notes") or []: if not isinstance(e, dict) or e.get("action") not in ACTIONS: errs.append("each note needs an action in %s: %r" % (", ".join(ACTIONS), e)) continue lid = e.get("lesson") - if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when", "set-short", "set-scope"): + if kinds.get(lid) == "tool" and e["action"] not in ("merge", "keep", "keep-as-draft", "set-when", "set-short", "set-scope", "set-pattern"): errs.append("lesson %s: tool lessons cannot be done in a cycle (they change sisi itself); " "leave them in `sisi backlog` untouched, except merging a duplicate" % lid) + if e["action"] == "set-pattern": + _have_pats = {} + try: + _have_pats = {p["id"]: p for p in retro.patterns(con)} + except Exception: + pass + if e.get("pattern_id") is not None: + if e["pattern_id"] not in _have_pats: + errs.append("lesson %s: set-pattern names pattern %r, which does not exist " + "(see the patterns listed in the brief)" % (lid, e.get("pattern_id"))) + elif (e.get("pattern") or "").strip(): + try: + row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone() + occ = con.execute("SELECT repo FROM occurrences WHERE lesson_id=? ORDER BY id LIMIT 1", (lid,)).fetchone() + origin = occ[0] if occ and occ[0] and os.path.isdir(occ[0]) else os.getcwd() + reason = retro.pattern_refusal(e["pattern"], row["change"] if row else "", origin, + row["moment"] if row else None) + if reason: + errs.append("lesson %s: %s" % (lid, reason)) + except Exception: + pass + else: + errs.append("lesson %s: set-pattern needs pattern (a new one-line statement) or pattern_id (an existing one)" % lid) if e["action"] == "set-short": if e.get("short") is None and e.get("topic") is None: errs.append("lesson %s: set-short needs a short line and/or a topic" % lid) @@ -1150,7 +1287,7 @@ def static_validate(doc, con): for lid_s, v in old["lessons"].items(): if not isinstance(v, dict) or v.get("status") not in retro.ACTIVE: continue - if v.get("scope") not in (None, "", "unscoped"): + if v.get("scope") not in (None, "", "unscoped", "unscoped-tier", "everywhere"): continue try: lid = int(lid_s) @@ -1159,8 +1296,81 @@ def static_validate(doc, con): if lid in exempt or lid in scoped_ids: continue errs.append("lesson %d: missing set-scope - the brief listed this lesson as unscoped; add " - "{\"lesson\": %d, \"action\": \"set-scope\", \"scope\": \"everywhere|project\"}" + "{\"lesson\": %d, \"action\": \"set-scope\", \"scope\": \"core|user|project\"}" % (lid, lid)) + # Patterns: top-level merges / statements / rule folds, every lesson lacking a pattern at + # the brief needs one, and a pattern past the threshold must reach the rulebook this round. + try: + _pats_now = {p["id"]: p for p in retro.patterns(con)} + except Exception: + _pats_now = {} + _pat_folded = set() + for e in doc.get("patterns") or []: + if not isinstance(e, dict) or not isinstance(e.get("pattern"), int): + errs.append("each patterns entry needs a pattern id: %r" % (e,)) + continue + pid, act = e["pattern"], e.get("action") + if pid not in _pats_now: + errs.append("pattern %s: no such pattern" % pid) + continue + if act == "merge": + if not isinstance(e.get("into"), int) or e["into"] == pid or e["into"] not in _pats_now: + errs.append("pattern %s: merge needs into naming a different existing pattern" % pid) + elif act == "set-statement": + if not (e.get("statement") or "").strip(): + errs.append("pattern %s: set-statement needs a statement" % pid) + else: + _r = retro.pattern_refusal(e["statement"], "__different__", os.getcwd()) + if _r: + errs.append("pattern %s: %s" % (pid, _r)) + elif act == "fold-into-rule": + _pat_folded.add(pid) + valid = base_rule_ids | over_ids + for into in _into_list(e): + if into not in valid: + errs.append("pattern %s: no rule with id %r to fold into.%s" % (pid, into, _suggest(into, valid))) + _rule_ids_in_file = {r.get("id") for r in doc.get("rules") or [] if isinstance(r, dict)} + _rb_rewrite = any(isinstance(x, dict) and x.get("doc") == "rulebook" and x.get("action") == "rewrite" + for x in doc.get("documents") or []) + if not (_rule_ids_in_file & set(_into_list(e))) and not _rb_rewrite: + errs.append("pattern %s: folding it into a rule needs that rule written or replaced in " + "this file (or a rulebook rewrite), so the statement actually lands" % pid) + elif act == "keep": + pass + else: + errs.append("pattern %s: action must be merge, set-statement, fold-into-rule or keep" % pid) + if isinstance(doc, dict) and doc.get("base"): + old = _load_snapshot(doc["base"]) + if old and isinstance(old.get("lessons"), dict): + notes_list = [e for e in doc.get("notes") or [] if isinstance(e, dict)] + patterned = {e.get("lesson") for e in notes_list if e.get("action") == "set-pattern"} + exempt = {e.get("lesson") for e in notes_list if e.get("action") in ("retire", "withdraw", "merge")} + exempt |= {e.get("lesson") for e in notes_list + if e.get("action") == "set-scope" and e.get("scope") == "project"} + for lid_s, v in old["lessons"].items(): + if not isinstance(v, dict) or v.get("status") not in retro.ACTIVE: + continue + if v.get("pattern_id"): + continue + if v.get("scope") == "project": + continue + try: + lid = int(lid_s) + except ValueError: + continue + if lid in exempt or lid in patterned: + continue + errs.append("lesson %d: missing set-pattern - the brief listed this lesson as lacking " + "a pattern; add {\"lesson\": %d, \"action\": \"set-pattern\", \"pattern_id\": N} " + "(reuse a listed pattern) or \"pattern\": \"\"" % (lid, lid)) + for p in _pats_now.values(): + if retro.pattern_ready_for_rule(p) and p["id"] not in _pat_folded: + errs.append("pattern %d (%r) explains %d lessons and %d incidents, past the rulebook " + "threshold (%d lessons, %d incidents): write or update its statement in " + "the rulebook as a strategic behaviour in this round (a patterns " + "fold-into-rule entry, with the rule in this file)" + % (p["id"], p["statement"][:60], p["n_lessons"], p["incidents"], + retro.PATTERN_RULE_MIN_LESSONS, retro.PATTERN_RULE_MIN_OCCURRENCES)) # Whole-document entries: every document the brief listed needs a rewrite or a reviewed # entry, and a rewrite must trace every lesson folded into it (see sisi.documents). required_docs = None @@ -1245,9 +1455,13 @@ def _apply_writes(doc, con): if sets: con.execute("UPDATE lessons SET %s WHERE id=?" % ", ".join(sets), vals + [lid]) retro.rewrite_notes_for_lesson(con, lid) + elif act == "set-pattern": + retro.assign_pattern(con, lid, pattern=e.get("pattern"), pattern_id=e.get("pattern_id")) elif act == "set-scope": + from . import scope as _sc2 con.execute("UPDATE lessons SET scope=?, project=? WHERE id=?", - (e.get("scope"), (e.get("project") or None) if e.get("scope") == "project" else None, lid)) + (_sc2.normalize_scope(e.get("scope")), + (e.get("project") or None) if e.get("scope") == "project" else None, lid)) elif act == "keep-as-draft": con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,)) elif act == "set-when": @@ -1258,6 +1472,23 @@ def _apply_writes(doc, con): con.execute("UPDATE lessons SET status='withdrawn', needs_cycle=0 WHERE id=?", (lid,)) else: # keep con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,)) + for e in doc.get("patterns") or []: + if not isinstance(e, dict) or not isinstance(e.get("pattern"), int): + continue + pid, act = e["pattern"], e.get("action") + if act == "merge": + con.execute("UPDATE lessons SET pattern_id=? WHERE pattern_id=?", (e["into"], pid)) + for (lid2,) in con.execute("SELECT id FROM lessons WHERE pattern_id=?", (e["into"],)): + touched.add(lid2) + con.execute("DELETE FROM patterns WHERE id=?", (pid,)) + elif act == "set-statement": + con.execute("UPDATE patterns SET statement=? WHERE id=?", + (" ".join(str(e["statement"]).split()), pid)) + elif act == "fold-into-rule": + con.execute("UPDATE patterns SET folded_into=? WHERE id=?", + (",".join("rule:" + x for x in _into_list(e)), pid)) + for (lid2,) in con.execute("SELECT id FROM lessons WHERE pattern_id=?", (pid,)): + touched.add(lid2) # project-scoped lessons leave the global store for their project's handover pile from . import handover as _ho for e in doc.get("notes") or []: @@ -1269,26 +1500,26 @@ def _apply_writes(doc, con): def _apply_learn(doc): - """Apply the learn set-scope entries: everywhere stamps the statement; project moves it + """Apply the learn set-scope entries: core/user stamp the statement's tier; project moves it out of the global store into that project's handover pile.""" entries = [e for e in doc.get("learn") or [] if isinstance(e, dict)] if not entries: return - from . import handover as _ho - recs = store.read("quarantine") + from . import handover as _ho, scope as _sc + recs = store.read("learn") by_text = {e.get("text"): e for e in entries} kept = [] for rec in recs: e = by_text.get(rec.get("text")) - if e is None or rec.get("scope") in ("everywhere", "project"): + if e is None or rec.get("scope") in ("core", "user", "project"): kept.append(rec) elif e.get("scope") == "project": _ho.move_learn(rec, e.get("project")) else: - rec = dict(rec, scope="everywhere") + rec = dict(rec, scope=_sc.normalize_scope(e.get("scope"))) rec.pop("project", None) kept.append(rec) - p = store.file_path("quarantine") + p = store.file_path("learn") os.makedirs(os.path.dirname(p), exist_ok=True) tmp = p + ".tmp%d" % os.getpid() with open(tmp, "w", encoding="utf-8") as f: @@ -1314,6 +1545,10 @@ def apply_file(path): raise CycleError("refused, nothing was applied:\n" + "\n".join(" - " + e for e in errs)) before_files = _scan_files() before_rows = {r["id"]: dict(r) for r in con.execute("SELECT * FROM lessons")} + try: + before_patterns = [dict(r) for r in con.execute("SELECT * FROM patterns ORDER BY id")] + except Exception: + before_patterns = [] before_m = measures(con) before_lines = before_m["rulebook_lines"] before_chars = before_m.get("rulebook_chars") @@ -1364,6 +1599,7 @@ def apply_file(path): "document_lessons": docs_changed, "before": before_m, "after": measures(con), "lessons_before": [before_rows[i] for i in touched if i in before_rows], + "patterns_before": before_patterns, "changed_files": changed, "prev_last_cycle_ts": prev_last, "reverted": None} os.makedirs(cycles_dir(), exist_ok=True) pdata.write_text(os.path.join("cycles", cid + ".json"), json.dumps(rec, indent=1, sort_keys=True) + "\n") @@ -1374,7 +1610,7 @@ def apply_file(path): except OSError: pass # the round is closed now; its snapshot no longer defers retirement retro.export_jsonl() - specs = ["overlay", "lessons.jsonl", "cycles", "handover.json", "learn-quarantine.jsonl"] + specs = ["overlay", "lessons.jsonl", "cycles", "handover.json", "learn.jsonl", "learn-quarantine.jsonl", "oracle.md"] if paths.notes_dir().startswith(paths.data() + os.sep): specs.append(os.path.relpath(paths.notes_dir(), paths.data())) if pdata._commit("cycle %s: %s" % (cid, rec["summary"] or "consolidation"), specs) is None \ @@ -1387,6 +1623,7 @@ def apply_file(path): {rel: base64.b64encode(b).decode() for rel, b in before_files.items()}) for row in before_rows.values(): _restore_lesson_row(con, row) + _restore_patterns(con, before_patterns) if prev_last is None: con.execute("DELETE FROM meta WHERE key='last_cycle_ts'") else: @@ -1402,6 +1639,17 @@ def apply_file(path): con.close() +def _restore_patterns(con, rows): + """Put the patterns table back exactly (a cycle may create, merge or fold patterns).""" + try: + con.execute("DELETE FROM patterns") + for r in rows or []: + con.execute("INSERT INTO patterns(id, statement, created, folded_into) VALUES(?,?,?,?)", + (r.get("id"), r.get("statement"), r.get("created"), r.get("folded_into"))) + except Exception: + pass + + def _restore_lesson_row(con, row): """Put a lesson row back exactly, recreating it when the cycle moved it to the handover pile.""" cols = [c for c in retro.LESSON_COLS if c in row] @@ -1433,6 +1681,8 @@ def revert_cycle(cid=None): _restore_changed(rec.get("changed_files") or {}) for row in rec.get("lessons_before") or []: _restore_lesson_row(con, row) + if "patterns_before" in rec: + _restore_patterns(con, rec.get("patterns_before")) prev = rec.get("prev_last_cycle_ts") if prev is None: con.execute("DELETE FROM meta WHERE key='last_cycle_ts'") @@ -1444,7 +1694,7 @@ def revert_cycle(cid=None): rec = dict(rec, reverted=store.now()) pdata.write_text(os.path.join("cycles", rec["id"] + ".json"), json.dumps(rec, indent=1, sort_keys=True) + "\n") - specs = ["overlay", "lessons.jsonl", "cycles", "handover.json", "learn-quarantine.jsonl"] + specs = ["overlay", "lessons.jsonl", "cycles", "handover.json", "learn.jsonl", "learn-quarantine.jsonl", "oracle.md"] if paths.notes_dir().startswith(paths.data() + os.sep): specs.append(os.path.relpath(paths.notes_dir(), paths.data())) pdata._commit("cycle revert %s" % rec["id"], specs) @@ -1554,9 +1804,25 @@ def improve_text(): return round(sum(r.get("send_backs", 0) for r in rows) / len(rows), 2) if rows else None rows_now = time.time() cur_rows, prev_rows = delivery.windows(store.read("deliveries"), rows_now) - lines = ["Is it getting better?", "", - "lessons: %d recorded, %d taking effect now, %d strengthened (rule or enforced), " - "%d retired, %d withdrawn" % (total, active, strong, by.get("retired", 0), by.get("withdrawn", 0)), + try: + _pcon = retro.connect() + try: + _pats = retro.patterns(_pcon) + _ptrends = {p["id"]: retro.pattern_recurrence_trend(_pcon, p) for p in _pats} + finally: + _pcon.close() + except Exception: + _pats, _ptrends = [], {} + lines = ["Is it getting better?", ""] + if _pats: + lines.append("patterns (the general failures of thinking behind the incidents):") + for p in sorted(_pats, key=lambda x: (-(x.get("incidents") or 0), x.get("id") or 0)): + lines.append(" - %s (pattern %d; %d incident(s), %d lesson(s); recurrence %s; %s)" + % (p["statement"], p["id"], p.get("incidents") or 0, p.get("n_lessons") or 0, + _ptrends.get(p["id"], "too little data"), + "in the rulebook" if p.get("folded_into") else "not in the rulebook yet")) + lines += ["lessons: %d recorded, %d taking effect now, %d strengthened (rule or enforced), " + "%d retired, %d withdrawn" % (total, active, strong, by.get("retired", 0), by.get("withdrawn", 0)), "of those taking effect: %d folded into a recipe, entry or rule, %d still loose notes " "(found only by matching words and when-terms, or by an agent reading the headings)" % (folded, active - folded), @@ -1639,7 +1905,15 @@ def check_file(path): extra += " topic=%r" % e["topic"][:60] if e.get("scope"): extra += " scope=%s%s" % (e["scope"], (" project=%s" % e["project"]) if e.get("project") else "") + if e.get("pattern"): + extra += " pattern=%r" % str(e["pattern"])[:60] + if e.get("pattern_id") is not None: + extra += " pattern_id=%s" % e["pattern_id"] out.append(" lesson %s: %s%s" % (e.get("lesson"), e.get("action"), extra)) + for e in doc.get("patterns") or []: + out.append(" pattern %s: %s%s" % (e.get("pattern"), e.get("action"), + (" into %s" % e.get("into")) if e.get("into") else + (" statement=%r" % str(e.get("statement"))[:60]) if e.get("statement") else "")) for e in doc.get("learn") or []: out.append(" learn %r: set-scope %s%s" % (str(e.get("text"))[:60], e.get("scope"), (" project=%s" % e["project"]) if e.get("project") else "")) diff --git a/sisi/design.py b/sisi/design.py new file mode 100644 index 0000000..56aec6a --- /dev/null +++ b/sisi/design.py @@ -0,0 +1,257 @@ +"""Choosing the approach as a checked step: the contract's `design` section and `sisi design`. + +The design section records, before building: what the goal and the owner's standing principles +(`sisi oracle`) imply that the request did not spell out; what the environment, host tool or +existing system already provides that should be used instead of built; at least two +alternatives with cost and risk; the chosen one and why it is what the owner would pick; for +every standing principle, the objection the owner would raise and how the design answers it +(or why it does not apply); and an independent challenge, by a different model or a subagent +playing the owner, with what changed in response. + +Validation is structural only, but it is aimed at filler: entries must be non-trivial, +`provided` must name at least one thing that verifiably exists (a `command:NAME` on PATH or a +`file:PATH` in the repository, given as evidence), alternatives must differ from each other +and from the chosen approach, and the challenge must contain an objection plus a change (or a +stated reason for no change) from someone who is not the author. + +One thing is honestly not checkable: that the challenge was recorded before the first code +edit. The edit-attribution data in sisi/watch.py records which paths a session changed, but no +first-edit timestamp survives (the only timestamp is on a pending before-snapshot, consumed +when the command finishes), so validation requires a parseable `recorded_at` that is not in +the future and no more. +""" +import json, os, re, shutil +from datetime import datetime, timezone + +QUESTIONS = """Before building, answer these in the contract's design section: + implies what the goal and the owner's standing principles imply that the request did + not spell out (consequences of what the owner already said) + provided what the environment, the host tool or the existing system already provides + that should be used instead of built; give evidence for each item as + "command:NAME" (on PATH) or "file:PATH" (in the repository) + alternatives at least two approaches, one line each on cost and on risk + chosen which approach, and why it is the one the owner would pick + objections one entry per standing principle: when it applies, the objection the owner + would raise and how the design answers it; when it does not, why not + challenge an independent attack on the design by a different model or a subagent, + playing the owner (what will he say is missing or wrong), who did it, when it + was recorded, and what was changed in response (or why nothing changed)""" + +_FILLER = {"tbd", "todo", "n/a", "na", "none", "nothing", "as requested", "best", "low", + "high", "medium", "x", "y", "-", "stuff", "things", "various", "etc", "placeholder", + "as above", "see above", "obvious", "standard", "normal", "usual"} + + +def _norm(s): + return " ".join(str(s or "").split()).lower().strip(" .!?:;\"'") + + +def _trivial(s, min_chars, min_words): + t = " ".join(str(s or "").split()) + n = _norm(t) + if not t or n in _FILLER or "todo" in n or "placeholder" in n: + return True + return len(t) < min_chars or len(t.split()) < min_words + + +def skeleton(principle_recs=None): + if principle_recs is None: + try: + from . import principles + principle_recs = principles.statements() + except Exception: + principle_recs = [] + from . import principles as P + return { + "implies": ["TODO: what the goal and the owner's principles imply that the request did not spell out"], + "provided": [{"what": "TODO: what already exists that this should use instead of building", + "evidence": "command:TODO or file:TODO"}], + "alternatives": [ + {"name": "TODO first approach", "cost": "TODO cost in one line", "risk": "TODO risk in one line"}, + {"name": "TODO second approach", "cost": "TODO cost in one line", "risk": "TODO risk in one line"}], + "chosen": {"name": "TODO chosen approach", + "why": "TODO why this is the one the owner would pick"}, + "objections": [{"principle": P.plain_of(r), "applicable": True, + "objection": "TODO the objection the owner would raise", + "answer": "TODO how the design answers it"} for r in principle_recs], + "challenge": {"by": "TODO who attacked it (a different model or a subagent)", + "recorded_at": "TODO ISO timestamp, recorded before building", + "objections": ["TODO what the owner would say is missing or wrong"], + "changes": ["TODO what was changed in response"]}, + } + + +def _as_list(v): + if v is None: + return [] + return v if isinstance(v, list) else [v] + + +def _text_of(v, keys=()): + if isinstance(v, str): + return v + if isinstance(v, dict): + for k in keys: + if isinstance(v.get(k), str) and v[k].strip(): + return v[k] + return "" + + +def _evidence_ok(item, cwd): + """True when a `provided` item verifiably names something that exists.""" + evidences = [] + if isinstance(item, dict): + for k in ("evidence", "exists", "check"): + if isinstance(item.get(k), str): + evidences.append(item[k]) + text = _text_of(item, ("what", "name", "use", "text")) + else: + text = str(item or "") + for ev in evidences + [text]: + for m in re.finditer(r"command:([A-Za-z0-9_./-]+)", ev or ""): + if shutil.which(m.group(1)): + return True + for m in re.finditer(r"(?:file|path):([^\s\"']+)", ev or ""): + p = m.group(1).rstrip(".,;)") + if os.path.exists(p if os.path.isabs(p) else os.path.join(cwd, p)): + return True + for tok in re.findall(r"[A-Za-z0-9_./~-]+", text): + if "/" in tok and os.path.exists(os.path.join(cwd, tok.rstrip(".,;)"))): + return True + return False + + +def _match_principle(field, principle_recs): + from . import principles as P + if isinstance(field, int) and 1 <= field <= len(principle_recs): + return field - 1 + f = _norm(field) + m = re.fullmatch(r"p(\d+)", f) + if m and 1 <= int(m.group(1)) <= len(principle_recs): + return int(m.group(1)) - 1 + for i, rec in enumerate(principle_recs): + for cand in (rec["text"], P.plain_of(rec)): + c = _norm(cand) + if f == c or (f and c and (f in c or c in f)): + return i + return None + + +def validate_design(contract, cwd=None, principle_recs=None): + """Structural refusal reasons for a contract's design section; empty means acceptable.""" + cwd = cwd or os.getcwd() + if principle_recs is None: + try: + from . import principles + principle_recs = principles.statements() + except Exception: + principle_recs = [] + if not isinstance(contract, dict) or not isinstance(contract.get("design"), dict): + return ["design section is missing: sizeable work needs a `design` section in the " + "contract (`sisi design` prints the owner's principles and the questions)"] + d = contract["design"] + errs = [] + goal = _norm(contract.get("goal")) + implies = _as_list(d.get("implies")) + if not implies or all(_trivial(_text_of(x, ("text", "implies")), 40, 7) for x in implies): + errs.append("design.implies: name at least one consequence of the goal and the owner's " + "principles that the request did not spell out (a real sentence, not filler)") + elif any(_norm(_text_of(x, ("text", "implies"))) == goal for x in implies): + errs.append("design.implies: restating the goal is not an implication") + provided = _as_list(d.get("provided")) + if not provided: + errs.append("design.provided: name what the environment, host tool or existing system " + "already provides that should be used instead of built") + else: + if all(_trivial(_text_of(x, ("what", "name", "use", "text")), 25, 5) for x in provided): + errs.append("design.provided: each item must say concretely what already exists") + elif not any(_evidence_ok(x, cwd) for x in provided): + errs.append("design.provided: at least one item must name something that verifiably " + "exists, with evidence as \"command:NAME\" (on PATH) or \"file:PATH\" " + "(in the repository)") + chosen_name = _text_of(d.get("chosen"), ("name", "approach", "chosen")) + alts = _as_list(d.get("alternatives")) + alt_names = [_norm(_text_of(a, ("name", "approach"))) for a in alts] + if len(alts) < 2: + errs.append("design.alternatives: at least two approaches are required") + else: + if any(not n or _trivial(n, 4, 1) for n in alt_names) or len(set(alt_names)) != len(alt_names): + errs.append("design.alternatives: the approaches must be distinct and named") + if _norm(chosen_name) and _norm(chosen_name) in alt_names: + errs.append("design.alternatives: alternatives must differ from the chosen approach " + "(they are the approaches not taken, with their cost and risk)") + for a in alts: + if not isinstance(a, dict) or _trivial(a.get("cost"), 12, 3) or _trivial(a.get("risk"), 12, 3): + errs.append("design.alternatives: each approach needs one real line on cost and one on risk") + break + why = _text_of(d.get("chosen"), ("why", "reason")) if isinstance(d.get("chosen"), dict) else "" + if _trivial(chosen_name, 4, 1): + errs.append("design.chosen: name the chosen approach") + if _trivial(why, 40, 7): + errs.append("design.chosen.why: say why this is the approach the owner would pick " + "(a real sentence, not filler)") + objections = _as_list(d.get("objections")) + covered = {} + for o in objections: + if isinstance(o, dict): + i = _match_principle(o.get("principle"), principle_recs) + if i is not None: + covered[i] = o + for i, rec in enumerate(principle_recs): + from . import principles as P + o = covered.get(i) + if o is None: + errs.append("design.objections: no entry for the standing principle %r - state the " + "owner's objection and its answer, or why it does not apply" + % P.plain_of(rec)[:80]) + continue + if o.get("applicable") is False: + if _trivial(o.get("reason"), 20, 4): + errs.append("design.objections: principle %r is marked not applicable without a reason" + % P.plain_of(rec)[:80]) + elif _trivial(o.get("objection"), 20, 4) or _trivial(o.get("answer"), 20, 4): + errs.append("design.objections: principle %r needs the objection the owner would " + "raise and how the design answers it" % P.plain_of(rec)[:80]) + ch = d.get("challenge") if isinstance(d.get("challenge"), dict) else {} + by = _text_of(ch, ("by", "who", "challenger")) + if _trivial(by, 3, 1) or _norm(by) in ("self", "me", "myself", "the agent", "author"): + errs.append("design.challenge.by: name who attacked the design (a different model or a " + "subagent playing the owner, not the author)") + cobjs = _as_list(ch.get("objections")) + if not cobjs or all(_trivial(_text_of(x, ("text", "objection")), 25, 5) for x in cobjs): + errs.append("design.challenge: at least one real objection from the challenger is required") + changes = _as_list(ch.get("changes")) + if (not changes or all(_trivial(_text_of(x, ("text", "change")), 25, 5) for x in changes)) \ + and _trivial(ch.get("no_change_reason"), 25, 5): + errs.append("design.challenge: say what was changed in response, or why nothing changed") + ts = ch.get("recorded_at") + if not isinstance(ts, str) or not ts.strip() or "todo" in _norm(ts): + errs.append("design.challenge.recorded_at: when the challenge was recorded (an ISO timestamp, before building)") + else: + try: + when = datetime.fromisoformat(ts.strip().replace("Z", "+00:00")) + now = datetime.now(timezone.utc) if when.tzinfo else datetime.now() + if (when - now).total_seconds() > 3600: + errs.append("design.challenge.recorded_at: %r is in the future" % ts) + except ValueError: + errs.append("design.challenge.recorded_at: %r is not an ISO timestamp" % ts) + return errs + + +def main(args=()): + """`sisi design`: the owner's principles and the design questions, before a contract exists.""" + from . import principles + print("Choosing the approach: work out what the goal and the owner's principles imply, " + "use what already exists, and have the design attacked as the owner would - before building.\n") + recs = principles.statements() + if recs: + print("The owner's standing principles (`sisi oracle` prints them in full, with his words):") + for i, rec in enumerate(recs, 1): + print("%d. %s" % (i, principles.plain_of(rec))) + print() + else: + print("No standing principles are recorded yet (`sisi learn --scope user \"\"` records one).\n") + print(QUESTIONS) + print("\nSkeleton for .sisi/contract.json (the gate checks it on a large change):") + print(json.dumps({"design": skeleton(recs)}, indent=2)) + return 0 diff --git a/sisi/documents.py b/sisi/documents.py index c3814f1..7de5a9e 100644 --- a/sisi/documents.py +++ b/sisi/documents.py @@ -55,12 +55,18 @@ def max_bullet_chars(): def doc_key(kind, id): - return "rulebook" if kind == "rulebook" else "%s:%s" % (kind, id) + if kind == "rulebook": + return "rulebook" + if kind == "oracle": + return "oracle" + return "%s:%s" % (kind, id) def parse_doc_key(key): if key == "rulebook": return "rulebook", "rulebook" + if key in ("oracle", "oracle:oracle"): + return "oracle", "oracle" if isinstance(key, str) and ":" in key: kind, _, id = key.partition(":") if kind in ("recipe", "verifier") and id: @@ -140,6 +146,9 @@ def next_round_number(): def effective_text(kind, id): if kind == "rulebook": return overlay.render() + if kind == "oracle": + from . import principles + return principles.oracle_text() from . import verifiers as V entries = V.load_recipes() if kind == "recipe" else V.load_verifiers() for e in entries: @@ -226,12 +235,32 @@ def required_documents(con): reviews = load_reviews() rounds = len(cycle.cycle_records()) every = review_every_rounds() - cands = [("rulebook", "rulebook")] + cands = [("rulebook", "rulebook"), ("oracle", "oracle")] cands += [("recipe", e["id"]) for e in V.load_recipes() if e["header"]] cands += [("verifier", e["id"]) for e in V.load_verifiers() if e["header"]] out = [] for kind, id in cands: key = doc_key(kind, id) + if kind == "oracle": + from . import principles as _pr + recs = _pr.statements() + if not recs: + continue + file_text = _pr._oracle_file_text() or "" + entries = trace_entries(kind, id) + traced_texts = {e.get("statement") for e in entries.values() if isinstance(e, dict)} + missing = [r for r in recs if r["text"] not in traced_texts or r["text"] not in file_text] + reasons = [] + if missing: + reasons.append("standing principles not yet integrated and traced into the " + "oracle document (they are in force; this round owns the document)") + last = int((reviews.get(key) or {}).get("round") or 0) + if rounds >= every and rounds - last >= every: + reasons.append("no whole-document review for %d rounds" % (rounds - last)) + if reasons: + out.append({"doc": key, "kind": kind, "id": id, "reasons": reasons, + "lessons": [], "statements": [r["text"] for r in missing]}) + continue folded = folded_lesson_ids(con, kind, id) traced = {int(k) for k in trace_entries(kind, id) if str(k).isdigit()} covered = set((reviews.get(key) or {}).get("covered") or []) @@ -448,6 +477,8 @@ def structure_problems(kind, text, doc_id=None): out.append("a bullet of %d characters holds %d sentences; one instruction per " "bullet (limit %d characters): %r" % (len(b), _sentence_count(b), limit, b[:60])) out.extend(_long_line_problems(text)) + if kind == "oracle" and not (text or "").lstrip().startswith("# "): + out.append("the oracle document must start with a `# title` heading") if kind == "rulebook": out.extend(rulebook_problems(text)) elif kind in ("recipe", "verifier"): @@ -487,11 +518,11 @@ def validate_documents(doc, con, required=None): by_doc = {} for e in entries: if not isinstance(e, dict) or not e.get("doc"): - errs.append("each documents entry needs a doc (\"rulebook\", \"recipe:\" or \"verifier:\"): %r" % (e,)) + errs.append("each documents entry needs a doc (\"rulebook\", \"oracle\", \"recipe:\" or \"verifier:\"): %r" % (e,)) continue kind, id = parse_doc_key(e["doc"]) if kind is None: - errs.append("documents entry %r: doc must be \"rulebook\", \"recipe:\" or \"verifier:\"" % e["doc"]) + errs.append("documents entry %r: doc must be \"rulebook\", \"oracle\", \"recipe:\" or \"verifier:\"" % e["doc"]) continue if kind != "rulebook" and not effective_text(kind, id): errs.append("document %s: no such %s" % (e["doc"], kind)) @@ -499,6 +530,14 @@ def validate_documents(doc, con, required=None): by_doc[e["doc"]] = e if required is None: required = required_documents(con) + # an oracle whose only unintegrated statements this same file scopes to their project + # needs no rewrite: they leave the global store in this round + _to_project = {e.get("text") for e in doc.get("learn") or [] + if isinstance(e, dict) and e.get("scope") == "project"} + if _to_project: + required = [r for r in required + if not (r.get("doc") == "oracle" and r.get("statements") + and all(t in _to_project for t in r["statements"]))] for req in required: if req["doc"] not in by_doc: errs.append("document %s: missing whole-document entry - the brief listed it (%s); add a " @@ -584,6 +623,19 @@ def validate_documents(doc, con, required=None): errs.append("lesson #%d: cannot retire it in a rewrite: %s" % (lid, why_not)) else: errs.append("lesson #%d: disposition must be carried, moved, merged or retired" % lid) + if kind == "oracle": + from . import principles as _pr + stmt_seen = {t["statement"]: t for t in trace + if isinstance(t, dict) and isinstance(t.get("statement"), str)} + for rec in _pr.statements(): + t = stmt_seen.get(rec["text"]) + if t is None: + errs.append("principle %r: no trace entry in the rewrite of oracle - give the " + "exact fragment of the new text that carries it (every statement " + "must be traced)" % rec["text"][:60]) + elif not _fragment_in(t.get("fragment"), text): + errs.append("principle %r: its fragment %r does not occur in the new oracle text" + % (rec["text"][:60], str(t.get("fragment"))[:60])) if kind == "rulebook": _pre, new_rules = overlay.parse_rules(text) new_ids = [r["id"] for r in new_rules] @@ -697,6 +749,25 @@ def apply_documents(doc, con, touched): if isinstance(t, dict) and isinstance(t.get("lesson"), int)} if kind == "rulebook": _apply_rulebook(e, text, con, touched) + elif kind == "oracle": + from . import principles as _pr + p = _pr.oracle_path() + os.makedirs(os.path.dirname(p), exist_ok=True) + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp, p) + for t in e.get("trace") or []: + if isinstance(t, dict) and isinstance(t.get("statement"), str): + entries = trace_entries(kind, id) + entries[t["statement"]] = {"statement": t["statement"], + "fragment": t.get("fragment"), + "disposition": t.get("disposition") or "carried"} + rec = {"doc": key, "kind": kind, "id": id, "base_hash": None, "entries": entries} + overlay._write(_trace_rel(kind, id), json.dumps(rec, indent=1, sort_keys=True) + "\n") + _record_review(reviews, key, con, kind, id, "rewrite") + changed[key] = [] + continue else: _id, rel, mine = overlay._put_entry(kind, text, id, True) for p in mine: diff --git a/sisi/gate.py b/sisi/gate.py index 2052d0e..c88cb44 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -551,7 +551,49 @@ def _question_sendback(payload): return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the " "tool's question dialog (%s), with options to pick from and the one you recommend marked — or " "decide it yourself, record the assumption, and finish without the question. " - "(Rule 5 in full: `sisi rule 5`.)" % dialogs[0]) + "(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0]) + + +def _measure_work(cwd, base=None): + """Growth of the work itself: sisi's own contract file is not product work and never counts.""" + m = gitutil.measure(cwd, base) + rel = C.REL.replace(os.sep, "/") + if rel in m["files"]: + lines = m["lines"] + try: + with open(os.path.join(gitutil.root(cwd) or cwd, C.REL), "rb") as f: + lines = max(0, lines - (f.read().count(b"\n") or 1)) + except OSError: + pass + return {"lines": lines, "files": [f for f in m["files"] if f != rel]} + return m + + +def _design_required(sess, cwd, top, g, payload, attr): + """The design section is required exactly where a contract is already required: a large + change (the gate's growth thresholds). Small edits, subagents, and sessions that edited + nothing here are exempt. Returns True when required, else None.""" + if payload.get("agent_id") or payload.get("agent_transcript_path"): + return None # a subagent works to its parent's brief; the parent owns the design + if attr is not None and not attr.get("writing") and not attr.get("unknown"): + return None # this session edited nothing: no design is owed for others' work + if not top: + return None + try: + if sess.get("baseline") is not None: + now = _measure_work(cwd, sess.get("head")) + base = sess["baseline"] + dl = max(0, now["lines"] - base["lines"]) + df = len(set(now["files"]) - set(base["files"])) + else: + m = _measure_work(cwd, gitutil.head(cwd)) + dl, df = m["lines"], len(m["files"]) + except Exception as e: + store.log_error("gate-design-measure", e) + return None + if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))): + return None + return True def _decide(payload): @@ -742,6 +784,23 @@ def _decide(payload): kind=sess.get("last_kind", "fast")) if path: + if c is not None and not errs: + try: + if _design_required(sess, cwd, top, g, payload, attr): + from . import design as _design + derrs = _design.validate_design(c, cwd=project) + if derrs: + missing = "missing" if "design" not in c else "invalid" + return ctx.block( + "sisi: this is a large change and the contract's design section is %s " + "(send-back {n}). Choosing the approach is a checked step: fill the " + "design section before building (`sisi design` prints the owner's " + "standing principles and the questions; `sisi oracle` prints the " + "principles in his words). Do not report this work as done.\n\n%s" + % (missing, "\n".join("- " + e for e in derrs)), + c["id"] if c else None, project, kind="design") + except Exception as e: # the design check must never break the gate + store.log_error("gate-design", e) deadline = time.time() + float(g.get("budget_s", 120)) if c is not None: errs = C.validate(c) @@ -807,7 +866,7 @@ def _decide(payload): if not top: return "allow", None if sess.get("baseline") is None: - sess.update(baseline=gitutil.measure(cwd), head=gitutil.head(cwd), started=sess.get("started") or store.now()) + sess.update(baseline=_measure_work(cwd), head=gitutil.head(cwd), started=sess.get("started") or store.now()) sess["baseline_fp"] = fp if attr is not None: sess["attr_baseline_gen"] = int(sess.get("attr_gen", 0) or 0) @@ -821,7 +880,7 @@ def _decide(payload): sess["head"] = w.get("head") sess["waiver_ns"] = w.get("ns", 0) sess["blocks"] = 0 - now = gitutil.measure(cwd, sess.get("head")) + now = _measure_work(cwd, sess.get("head")) base = sess["baseline"] dl = max(0, now["lines"] - base["lines"]) df = len(set(now["files"]) - set(base["files"])) @@ -832,7 +891,9 @@ def _decide(payload): return ctx.allow() return ctx.block("sisi: this session has changed %d lines and %d files since its start and there is no " "contract (send-back {n}). Write `.sisi/contract.json` (`sisi contract init` makes the " - "skeleton; give it at least one check with a real command), then run `sisi verify`. If " + "skeleton; give it at least one check with a real command, and for a change this size " + "fill its design section - `sisi design` prints the owner's principles and the " + "questions), then run `sisi verify`. If " "the change needs no checks, run `sisi contract waive \"\"` instead." % (dl, df)) diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index 7a62acf..553cac6 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -149,7 +149,7 @@ def _move_retro_db(src, dst, notes): pass -STATE_JSONL = ("learn-quarantine.jsonl", "notes.jsonl", "proposals.jsonl") +STATE_JSONL = ("learn.jsonl", "learn-quarantine.jsonl", "notes.jsonl", "proposals.jsonl") def pending(): diff --git a/sisi/pdata.py b/sisi/pdata.py index 505f33f..b6d78ad 100644 --- a/sisi/pdata.py +++ b/sisi/pdata.py @@ -5,7 +5,7 @@ Layout (see docs/personal-data.md): oracle.md what the person wants overlay/ learned changes to the base rulebook, verifiers and recipes notes/ field notes per verifier or recipe id - config.json, trusted.json, lessons.jsonl, retest.jsonl, *.jsonl (notes, proposals, quarantine) + config.json, trusted.json, lessons.jsonl, retest.jsonl, *.jsonl (notes, proposals, learn statements) retro.db the lessons database (sqlite; kept out of git, lessons.jsonl is its committed dump) generated/ the effective rulebook (rebuildable; kept out of git) install/ manifest and backups of the files `sisi install` edited (machine specific; out of git) diff --git a/sisi/principles.py b/sisi/principles.py new file mode 100644 index 0000000..2ded6f8 --- /dev/null +++ b/sisi/principles.py @@ -0,0 +1,113 @@ +"""The owner's standing principles: `sisi learn` statements in the user tier (plus core +statements until the product carries them, and not-yet-tiered ones meanwhile), live at once. + +A statement takes effect the moment it is recorded: `sisi oracle` prints it, request-time +delivery hands it over, and a contract's design section must answer its objections. There is +no quarantine and no holding file. The oracle is a proper document (oracle.md in the personal +folder) whose structure a learning round owns through the whole-document edit in +sisi/documents.py, tracing every statement into the text like any other document; until a +round integrates a statement, `sisi oracle` prints it under its own heading so it is never +parked unread. +""" +import os + +from . import paths, store + +EMPTY = """# sisi oracle + +What the human wants, so a thing is asked once ever. Empty so far: it is filled from +preferences the human stated (`sisi learn`), which take effect at once. +""" + + +def statements(): + """The standing principles, in the order recorded: user-tier statements (how this owner + wants work done), plus core statements until the product carries them, plus not-yet-tiered + statements, which are still delivered while they wait for a tier.""" + from . import scope as _scope + out = [] + for rec in store.read("learn"): + text = " ".join(str(rec.get("text") or "").split()) + if text and _scope.tier_of(rec.get("scope")) != "project": + out.append(dict(rec, text=text)) + return out + + +def core_statements(): + return [r for r in statements() if r.get("scope") == "core"] + + +def unscoped_statements(): + """Statements with no tier yet (old two-way `everywhere` included; a round tiers them).""" + from . import scope as _scope + return [rec for rec in store.read("learn") + if (rec.get("text") or "").strip() and _scope.tier_of(rec.get("scope")) == "unscoped-tier"] + + +def plain_of(rec): + """The principle in plain words on one line: the stored plain form when a round wrote one, + else the statement itself, tidied into a sentence.""" + plain = " ".join(str(rec.get("plain") or "").split()) + if plain: + return plain + t = " ".join(str(rec.get("text") or "").split()).strip("\"") + if t and t[-1] not in ".!?": + t += "." + return t + + +def date_of(rec): + return (rec.get("ts") or "")[:10] + + +def short_lines(limit_chars=None): + """One short plain line per principle, for request-time and contract-init delivery.""" + out, total = [], 0 + for rec in statements(): + line = "- " + plain_of(rec) + if limit_chars is not None and total + len(line) + 1 > limit_chars and out: + out.append("- ... and more (`sisi oracle` prints them all)") + break + out.append(line) + total += len(line) + 1 + return out + + +def _principle_block(rec): + date = date_of(rec) + return '- %s\n > "%s"%s' % (plain_of(rec), rec["text"], " (%s)" % date if date else "") + + +def _oracle_file_text(): + try: + with open(paths.data_file("oracle.md"), encoding="utf-8") as f: + return f.read() + except OSError: + return None + + +def oracle_text(): + """The oracle document as agents should read it now: the round-written document when one + exists, with any not-yet-integrated statements printed after it, never hidden.""" + recs = statements() + file_text = _oracle_file_text() + if file_text: + missing = [r for r in recs if r["text"] not in file_text] + if not missing: + return file_text + return (file_text.rstrip("\n") + "\n\n## Not yet integrated\n\n" + "Recorded since the last learning round rewrote this document; in force now.\n\n" + + "\n".join(_principle_block(r) for r in missing) + "\n") + if not recs: + return EMPTY + lines = ["# sisi oracle", "", + "What the human wants, so a thing is asked once ever. Statements recorded with " + "`sisi learn` take effect at once; a learning round rewrites this document as a " + "whole and traces every statement into it.", "", + "## Standing principles", ""] + lines += [_principle_block(r) for r in recs] + return "\n".join(lines) + "\n" + + +def oracle_path(): + return paths.data_file("oracle.md") diff --git a/sisi/prompt.py b/sisi/prompt.py index 9e2c4e2..f344d44 100644 --- a/sisi/prompt.py +++ b/sisi/prompt.py @@ -32,6 +32,51 @@ def _is_question_without_work(t): return not (stems & _WORK_STEMS) +_DESIGN_STEMS = {"build", "design", "implement", "creat", "develop", "architect", "orchestr", + "automat", "integrat", "plugin", "system", "platform", "framework"} +_SMALL_EDIT_MARKERS = ("rename", "typo", "off-by-one", "one line", "single line", "small fix", + "quick fix", "spelling") + + +def is_design_work(text): + """A request to design or build something sizeable: not a question, not a small edit. + Precision matters more than reach, as with recipes: a wrong design block on every message + would train agents to ignore it.""" + t = " ".join((text or "").split()) + low = t.lower() + if len(t.split()) < 6: + return False + if any(m in low for m in _SMALL_EDIT_MARKERS): + return False + first = low.split(" ", 1)[0].strip("¿?") if low else "" + if low.endswith("?") and first in _QUESTION_START: + return False # a question about design is not design work + if _is_question_without_work(t): + return False + from . import retro, verifiers as V + stems = {retro._stem(w) for w in V._words(low)} + if not (stems & _DESIGN_STEMS): + return False + return bool(stems & _WORK_STEMS) or bool(stems & {"build", "design", "creat", "develop"}) + + +def _design_block(): + """The standing principles in short lines, plus the instruction to fill the design section.""" + try: + from . import principles + lines = principles.short_lines(limit_chars=900) + except Exception: + lines = [] + out = ["sisi: this reads as design or build work. Before building, fill the contract's " + "design section (`sisi design` prints the questions; `sisi contract init` writes " + "the skeleton): what the goal and the principles imply, what already exists to use, " + "alternatives, the choice, each principle's objection, and an independent challenge."] + if lines: + out.append("The owner's standing principles (in his words: `sisi oracle`):") + out += lines + return out + + def is_trivial(text): """A message no recipe or lesson can help with: empty, a slash command, a bare yes/no, or a short question. A wrong injection on every message is worse than none.""" @@ -129,11 +174,14 @@ def build_context(query, session=None): lesson_lines.append("- #%d: %s (full text: `sisi lessons show %d`)" % (row["id"], retro.heading_text(row, 120), row["id"])) ids.append(row["id"]) - if not recipe and not lesson_lines: + design_lines = _design_block() if is_design_work(query) else [] + if not recipe and not lesson_lines and not design_lines: return notice lines = [notice] if notice else [] - lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; " - "information to weigh, not commands):") + lines += design_lines + if recipe or lesson_lines: + lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; " + "information to weigh, not commands):") if recipe: lines.append("Done means — recipe `%s` (full text: `sisi done %s`):" % (recipe["id"], recipe["id"])) lines += _done_means(recipe, retro) diff --git a/sisi/release.py b/sisi/release.py index eedbc06..cbb5c45 100644 --- a/sisi/release.py +++ b/sisi/release.py @@ -383,22 +383,86 @@ def _merge_rule(core_text, pid, rule_md): return body -def cmd_promote(args): - apply = "--apply" in args - rest = [a for a in args if a != "--apply"] - if len(rest) != 1: - print("usage: sisi promote [--apply]", file=sys.stderr) - return 1 - pid = rest[0] +def core_items(): + """Core-tier items not yet in the product: ([lesson rows], [statement texts]).""" + lessons = [] try: - src = source() - except ReleaseError as e: - print("sisi promote: %s" % e, file=sys.stderr) - return 1 + from . import retro + if os.path.exists(retro.db_path()): + con = retro.connect() + try: + lessons = [dict(r) for r in con.execute( + "SELECT * FROM lessons WHERE scope='core' AND status IN ('open','applied') " + "AND COALESCE(promoted,'')='' ORDER BY id")] + finally: + con.close() + except Exception: + lessons = [] + statements = [] + try: + from . import principles + statements = [r["text"] for r in principles.core_statements()] + except Exception: + statements = [] + return lessons, statements + + +def _norm_text(t): + return " ".join(str(t or "").split()) + + +def _product_contains(target, out, kind, clean): + """The product file now holds the promoted text (checked by reading it back).""" + try: + with open(target, encoding="utf-8") as fh: + now = fh.read() + except OSError: + return False + if kind == "rule": + from . import overlay + try: + body = overlay.parse_rule_file(clean)["body"] + except Exception: + body = clean + return _norm_text(body) in _norm_text(now) + return now == out + + +def _drop_personal_copy(kind, pid, f): + """Once the product contains the text, the personal overlay copy goes, so nothing lives + in two places; core lessons folded into the item are marked promoted.""" + try: + os.unlink(f) + except OSError: + pass + try: + from . import overlay + if kind == "rule": + overlay._set_base("rule", pid, None) + overlay.build_canon() + except Exception: + pass + try: + from . import retro, store + if os.path.exists(retro.db_path()): + con = retro.connect() + try: + con.execute("UPDATE lessons SET promoted=? WHERE scope='core' AND " + "(folded_into=? OR folded_into=? OR folded_into LIKE ?)", + (store.now(), pid, "rule:" + pid, "%" + pid + "%")) + con.commit() + finally: + con.close() + retro.sync("lessons: core item %s promoted into the product" % pid) + except Exception: + pass + + +def _promote_overlay(pid, apply, src): + """The long-standing overlay promote, now dropping the personal copy once verified.""" item = _find_item(pid) if not item: - print("sisi promote: no overlay rule, verifier or recipe with id %r in %s" % (pid, paths.overlay_dir()), file=sys.stderr) - return 1 + return None kind, f, dest = item with open(f, encoding="utf-8") as fh: text = fh.read() @@ -425,11 +489,177 @@ def cmd_promote(args): print(clean.rstrip("\n")) print("-" * 20 + "\nrun again with --apply to write it") return 0 - os.makedirs(os.path.dirname(target), exist_ok=True) - tmp = target + ".sisi-tmp" - with open(tmp, "w", encoding="utf-8") as fh: - fh.write(out) - os.replace(tmp, target) - print("written: %s (not committed). After the next release, remove the overlay copy so the two do not diverge:" - " `sisi overlay list`" % target) + already = _product_contains(target, out, kind, clean) + if not already: + os.makedirs(os.path.dirname(target), exist_ok=True) + tmp = target + ".sisi-tmp" + with open(tmp, "w", encoding="utf-8") as fh: + fh.write(out) + os.replace(tmp, target) + if not _product_contains(target, out, kind, clean): + print("sisi promote: the product does not contain the text after writing; the personal " + "copy is kept", file=sys.stderr) + return 1 + _drop_personal_copy(kind, pid, f) + print("%s: %s (not committed; an ordinary uncommitted edit for your normal review). " + "The personal copy was dropped: the product contains the text." + % ("already in the product" if already else "written", target)) return 0 + + +def _promote_lesson(lid, apply): + from . import retro + if not os.path.exists(retro.db_path()): + print("sisi promote: no lessons yet", file=sys.stderr) + return 1 + con = retro.connect() + try: + row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone() + finally: + con.close() + if not row: + print("sisi promote: no lesson with id %d" % lid, file=sys.stderr) + return 1 + r = dict(row) + if retro._get(r, "scope") != "core": + print("sisi promote: lesson #%d is in the %s tier, not core; only core items are queued " + "for the product" % (lid, retro._get(r, "scope") or "unscoped-tier"), file=sys.stderr) + return 1 + if retro._get(r, "promoted"): + print("lesson #%d is already in the product (promoted %s)" % (lid, retro._get(r, "promoted"))) + return 0 + targets = [t.strip() for t in str(r.get("folded_into") or "").split(",") if t.strip()] + pid = None + for t in targets: + cand = t[5:] if t.startswith("rule:") else t + if cand.startswith("draft:") or cand == "enforced": + continue + if _find_item(cand): + pid = cand + break + if pid is None: + print("sisi promote: lesson #%d is core but is not folded into a personal rule, recipe or " + "technique yet, so there is no product file to write. Fold it in a learning round " + "(`sisi cycle`) first, then promote it; or send it upstream with " + "`sisi promote --export`." % lid, file=sys.stderr) + return 1 + src = dev_source() + if not src or not is_source(src): + print("sisi promote: this is not a developer install (no developer source set): nothing " + "was written. `sisi promote --export` writes a contribution file you may send " + "upstream; on a developer install (`sisi dev on PATH`) promote writes into the " + "source tree.", file=sys.stderr) + return 1 + return _promote_overlay(pid, apply, src) + + +def _export_core(path=None): + lessons, statements = core_items() + if not lessons and not statements: + print("no core items are waiting: nothing to export") + return 0 + extra_terms = set() + try: + from . import retro + con = retro.connect() + try: + for r in lessons: + for (repo,) in con.execute("SELECT repo FROM occurrences WHERE lesson_id=?", (r["id"],)): + if repo: + extra_terms.add(os.path.basename(str(repo).rstrip("/"))) + finally: + con.close() + except Exception: + pass + lines = ["# sisi core contributions", "", + "Universal text only: no history, no user or project names. Nothing was sent " + "anywhere; send this file upstream yourself if you choose.", ""] + for t in statements: + lines += ["## Statement (core)", "", t, ""] + for r in lessons: + pat = "" + try: + from . import retro + con = retro.connect() + try: + if r.get("pattern_id"): + prow = con.execute("SELECT statement FROM patterns WHERE id=?", + (r["pattern_id"],)).fetchone() + pat = prow[0] if prow else "" + finally: + con.close() + except Exception: + pat = "" + lines += ["## Lesson %d (core, kind %s%s)" % (r["id"], r.get("change_kind") or "", + ", target " + r["target"] if r.get("target") else ""), ""] + if pat: + lines += ["Pattern: " + pat, ""] + if r.get("short"): + lines += [str(r["short"]), ""] + lines += [str(r.get("change") or ""), ""] + if r.get("when_terms"): + lines += ["When: " + str(r["when_terms"]), ""] + text = "\n".join(lines) + for term in sorted(extra_terms): + if len(term) >= 3: + text = _word(term).sub("", text) + clean, found, left = scrub(text) + if left: + print("sisi promote: refused, personal terms remain on these lines:", file=sys.stderr) + for n, l in left: + print(" %d: %s" % (n, l), file=sys.stderr) + return 1 + path = path or os.path.join(os.getcwd(), "sisi-core-contribution.md") + with open(path, "w", encoding="utf-8") as fh: + fh.write(clean if clean.endswith("\n") else clean + "\n") + print("wrote %s (%d lesson(s), %d statement(s); universal text only). Nothing was sent anywhere." + % (path, len(lessons), len(statements))) + return 0 + + +def cmd_promote(args): + apply = "--apply" in args + args = [a for a in args if a != "--apply"] + if "--export" in args: + rest = [a for a in args if a != "--export"] + if len(rest) > 1: + print("usage: sisi promote --export [PATH]", file=sys.stderr) + return 1 + return _export_core(rest[0] if rest else None) + if not args: + lessons, statements = core_items() + if not lessons and not statements: + print("no core items are waiting to be promoted") + print("promote one overlay rule, recipe or technique by id: sisi promote [--apply]") + return 0 + print("Core items not yet in the product (in force for you through the personal overlay):") + for r in lessons: + from . import retro + print(" lesson:%d [%s] %s (`sisi promote lesson:%d --apply` on a developer install)" + % (r["id"], r.get("change_kind") or "", retro.heading_text(r, 100), r["id"])) + for t in statements: + print(" statement (core): %r (fold it into a rule in a learning round, then promote " + "the rule; or `sisi promote --export`)" % t[:100]) + return 0 + if len(args) != 1: + print("usage: sisi promote [|lesson:N] [--apply] | sisi promote --export [PATH]", + file=sys.stderr) + return 1 + pid = args[0] + if pid.startswith("lesson:"): + if not pid[7:].isdigit(): + print("usage: sisi promote lesson:N [--apply]", file=sys.stderr) + return 1 + return _promote_lesson(int(pid[7:]), apply) + try: + src = source() + except ReleaseError as e: + print("sisi promote: %s" % e, file=sys.stderr) + return 1 + rc = _promote_overlay(pid, apply, src) + if rc is None: + print("sisi promote: no overlay rule, verifier or recipe with id %r in %s" % (pid, paths.overlay_dir()), file=sys.stderr) + return 1 + return rc + + diff --git a/sisi/retro.py b/sisi/retro.py index 49da6cc..d8d52f8 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -22,6 +22,8 @@ RETIRE_SHOWS = 20 # shown this often with no recurrence (and folded somewhere) MIN = {"moment": (30, 5), "cause": (15, 3), "change": (25, 4)} # (characters, words) SHORT_MAX = 140 TOPIC_MAX = 30 +PATTERN_RULE_MIN_LESSONS = 3 # a pattern explaining at least this many lessons ... +PATTERN_RULE_MIN_OCCURRENCES = 6 # ... and at least this many incidents belongs in the rulebook def _get(row, key): @@ -97,7 +99,8 @@ NEW_LESSON_COLS = (("strength", "INTEGER DEFAULT 1"), ("triggers", "TEXT"), ("ef ("applied_at", "TEXT"), ("folded_into", "TEXT"), ("needs_cycle", "INTEGER DEFAULT 0"), ("check_json", "TEXT"), ("change_fp", "TEXT"), ("promoted_shown", "INTEGER DEFAULT 0"), ("when_terms", "TEXT"), ("short", "TEXT"), ("topic", "TEXT"), - ("scope", "TEXT"), ("project", "TEXT")) + ("scope", "TEXT"), ("project", "TEXT"), ("pattern_id", "INTEGER"), + ("promoted", "TEXT")) def connect(): @@ -115,8 +118,12 @@ def connect(): ready = bool(lcols) and all(c in lcols for c, _ in NEW_LESSON_COLS) and \ con.execute("SELECT 1 FROM sqlite_master WHERE name='occ_lesson'").fetchone() and \ con.execute("SELECT 1 FROM sqlite_master WHERE name='impressions'").fetchone() and \ + con.execute("SELECT 1 FROM sqlite_master WHERE name='patterns'").fetchone() and \ con.execute("SELECT 1 FROM sqlite_master WHERE name='sightings'").fetchone() if ready: + if con.execute("SELECT 1 FROM lessons WHERE scope='everywhere' LIMIT 1").fetchone(): + con.execute("UPDATE lessons SET scope='unscoped-tier' WHERE scope='everywhere'") + con.commit() return con # schema is there: executescript commits and syncs, so skip it con.executescript(""" CREATE TABLE IF NOT EXISTS lessons( @@ -129,6 +136,8 @@ def connect(): id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, place TEXT, occ_count INTEGER); CREATE TABLE IF NOT EXISTS sightings( id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, moment TEXT); + CREATE TABLE IF NOT EXISTS patterns( + id INTEGER PRIMARY KEY, statement TEXT, created TEXT, folded_into TEXT); CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT); CREATE INDEX IF NOT EXISTS occ_repo ON occurrences(repo, ts); CREATE INDEX IF NOT EXISTS occ_lesson ON occurrences(lesson_id); @@ -137,6 +146,7 @@ def connect(): for name, decl in NEW_LESSON_COLS: # migrate a database from before the learning loop, losing nothing if name not in lcols: con.execute("ALTER TABLE lessons ADD COLUMN %s %s" % (name, decl)) + con.execute("UPDATE lessons SET scope='unscoped-tier' WHERE scope='everywhere'") con.commit() _backfill(con) return con @@ -155,10 +165,11 @@ def _backfill(con): # ---- the committed dump ------------------------------------------------------ LESSON_COLS = ("id", "created", "aim", "change_kind", "target", "moment", "cause", "change", "status", "count", "last_seen", "strength", "triggers", "effect", "applied_at", "folded_into", "needs_cycle", "check_json", "change_fp", - "promoted_shown", "when_terms", "short", "topic", "scope", "project") + "promoted_shown", "when_terms", "short", "topic", "scope", "project", "pattern_id", "promoted") OCC_COLS = ("id", "lesson_id", "ts", "session", "tool", "cwd", "repo", "moment", "fp", "delivery_s") IMP_COLS = ("id", "lesson_id", "ts", "session", "place", "occ_count") SIGHT_COLS = ("id", "lesson_id", "ts", "session", "moment") +PATTERN_COLS = ("id", "statement", "created", "folded_into") def dump_lines(con): @@ -166,7 +177,8 @@ def dump_lines(con): Columns a table predates are omitted, so an old dump and a new one describe the same lessons.""" out = [] for t, cols, table in (("lesson", LESSON_COLS, "lessons"), ("occurrence", OCC_COLS, "occurrences"), - ("impression", IMP_COLS, "impressions"), ("sighting", SIGHT_COLS, "sightings")): + ("impression", IMP_COLS, "impressions"), ("sighting", SIGHT_COLS, "sightings"), + ("pattern", PATTERN_COLS, "patterns")): try: have = [r[1] for r in con.execute("PRAGMA table_info(%s)" % table)] except sqlite3.Error: @@ -213,7 +225,9 @@ def import_jsonl(path, con): except ValueError: continue t = d.pop("t", None) - if t == "lesson": + if t == "pattern": + cols, table, i = PATTERN_COLS, "patterns", 1 + elif t == "lesson": cols, table, i = LESSON_COLS, "lessons", 0 elif t == "occurrence": cols, table, i = OCC_COLS, "occurrences", 1 @@ -422,6 +436,98 @@ def triggers_for(change, target=None, when=None): return " ".join(sorted(_stems(when or "") | _stems(change) | _stems((target or "").replace("-", " ")))) +def pattern_refusal(pattern, change, cwd, moment=None): + """One refusal reason for a pattern, or None. Structural only: the general failure of + thinking in one line that would apply to unrelated work. It must not name the current + project (the scope module's check) and must not merely restate the incident's change.""" + from . import scope as _scope + p = str(pattern or "") + if "\n" in p or "\r" in p: + return "pattern must be one line (check: pattern one line)" + p = " ".join(p.split()) + if len(p) < 25 or len(p.split()) < 5: + return ("pattern is too short: %s - name the general failure of thinking this incident " + "is an instance of, in one line that would apply to unrelated work " + "(check: pattern length)" % _quote(p)) + if _normalized(p) == _normalized(change) or (moment and _normalized(p) == _normalized(moment)): + return ("pattern merely restates the incident: %s - state the general failure of " + "thinking behind it instead (check: pattern differs from change)" % _quote(p)) + reason = _scope.universal_refusal([p], cwd) + if reason: + return ("pattern %s (check: pattern names no project; a pattern must apply to " + "unrelated work)" % reason) + return None + + +def get_or_create_pattern(con, statement): + """The id of a pattern, reusing an existing one with the same statement instead of + adding a duplicate (exact normalised match; near-duplicates are a learning round's job).""" + p = " ".join(str(statement or "").split()) + for r in con.execute("SELECT id, statement FROM patterns ORDER BY id"): + if _normalized(r[1]) == _normalized(p): + return r[0] + cur = con.execute("INSERT INTO patterns(statement, created) VALUES (?,?)", (p, store.now())) + return cur.lastrowid + + +def assign_pattern(con, lesson_id, pattern=None, pattern_id=None): + if pattern_id is None and pattern: + pattern_id = get_or_create_pattern(con, pattern) + if pattern_id is not None: + con.execute("UPDATE lessons SET pattern_id=? WHERE id=?", (int(pattern_id), lesson_id)) + return pattern_id + + +def patterns(con=None): + """Patterns first-class: [{id, statement, created, folded_into, lessons, n_lessons, incidents}].""" + own = con is None + if own: + if not os.path.exists(db_path()): + return [] + con = connect() + try: + out = [] + try: + rows = [dict(r) for r in con.execute("SELECT * FROM patterns ORDER BY id")] + except Exception: + return [] + for r in rows: + try: + lessons = [dict(x) for x in con.execute( + "SELECT * FROM lessons WHERE pattern_id=? ORDER BY id", (r["id"],))] + except Exception: + lessons = [] + out.append(dict(r, lessons=[x["id"] for x in lessons], lesson_rows=lessons, + n_lessons=len(lessons), + incidents=sum(int(x.get("count") or 1) for x in lessons))) + return out + finally: + if own: + con.close() + + +def pattern_recurrence_trend(con, pattern): + """'falling', 'not falling', or 'too little data': incidents in the last 7 days against the 7 before.""" + ids = pattern.get("lessons") or [] + if not ids: + return "too little data" + w = lambda d: time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - d * 86400)) + q = ",".join("?" * len(ids)) + cur = con.execute("SELECT count(*) FROM occurrences WHERE lesson_id IN (%s) AND ts>=?" % q, + list(ids) + [w(7)]).fetchone()[0] + prev = con.execute("SELECT count(*) FROM occurrences WHERE lesson_id IN (%s) AND ts>=? AND ts= PATTERN_RULE_MIN_LESSONS + and pattern.get("incidents", 0) >= PATTERN_RULE_MIN_OCCURRENCES + and not pattern.get("folded_into")) + + def change_fp(change): """Fingerprint of a lesson's change, so a withdrawn form is not re-learned word for word.""" return hashlib.sha256(" ".join(sorted(_stems(change))).encode("utf-8")).hexdigest()[:16] @@ -622,7 +728,7 @@ def new_lesson(con, f, cwd, fp): cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")] extra_cols = [c for c in ("short", "topic", "scope", "project") if c in cols] _scope_vals = {"short": short, "topic": topic, - "scope": (f.get("scope") or "unscoped"), + "scope": (f.get("scope") or "unscoped-tier"), "project": (f.get("project") or None)} extra_vals = [_scope_vals[c] for c in extra_cols] base_cols = ("created, aim, change_kind, target, moment, cause, change, status, count, last_seen," @@ -633,6 +739,13 @@ def new_lesson(con, f, cwd, fp): (now, f["aim"], f["change_kind"], target, f["moment"].strip(), f["cause"].strip(), change, now, triggers_for(change, target, when), change_fp(change), when) + tuple(extra_vals)) lid = cur.lastrowid + if f.get("pattern") or f.get("pattern_id"): + _pid = f.get("pattern_id") + try: + _pid = int(_pid) if _pid is not None and str(_pid).strip() != "" else None + except (TypeError, ValueError): + _pid = None + assign_pattern(con, lid, pattern=f.get("pattern"), pattern_id=_pid) add_occurrence(con, lid, f["moment"].strip(), cwd, fp) apply_effect(con, lid) # every lesson takes effect on its first occurrence return lid @@ -834,10 +947,12 @@ def satisfied(repo, since, fp): TEMPLATE = ('sisi: before you finish, record how this work could have gone better. The question is how, not whether. Run:\n' - ' sisi retro --aim --moment "" ' + ' sisi retro --scope --aim --moment "" ' '--cause "" --change-kind --change "" ' '--when "" [--target ]\n' + 'for a CSV lesson: csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file>" ' + '--pattern "" ' + '(or --pattern-id N to reuse one; `sisi retro patterns` lists them) [--target ]\n' '"Nothing" and generic advice are refused. If an earlier lesson already covers it, add --same-as ID instead. (send-back {n})') @@ -1184,7 +1299,8 @@ def _parse(argv): f, flags, i = {}, set(), 0 names = {"--aim": "aim", "--moment": "moment", "--cause": "cause", "--change-kind": "change_kind", "--change": "change", "--target": "target", "--same-as": "same_as", "--when": "when", - "--short": "short", "--topic": "topic", "--scope": "scope", "--project": "project"} + "--short": "short", "--topic": "topic", "--scope": "scope", "--project": "project", + "--pattern": "pattern", "--pattern-id": "pattern_id"} while i < len(argv): a = argv[i] if a in names: @@ -1205,7 +1321,28 @@ def _parse(argv): return f, flags +def cmd_retro_patterns(): + pats = patterns() + if not pats: + print("no patterns yet: name the general failure of thinking behind this incident " + "with --pattern (one line that would apply to unrelated work)") + return 0 + print("Patterns so far - reuse one with --pattern-id N instead of inventing a near-duplicate:") + con = connect() + try: + for p in pats: + print(" %d. %s (%d lesson(s), %d incident(s); recurrence %s%s)" + % (p["id"], p["statement"], p["n_lessons"], p["incidents"], + pattern_recurrence_trend(con, p), + "; in the rulebook" if p.get("folded_into") else "")) + finally: + con.close() + return 0 + + def cmd_retro(argv, stdin=None): + if argv and argv[0] == "patterns": + return cmd_retro_patterns() try: f, flags = _parse(argv) except ValueError as e: @@ -1224,7 +1361,7 @@ def cmd_retro(argv, stdin=None): if k == "new": if v: flags.add("new") - elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as", "when", "short", "topic", "scope", "project"): + elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as", "when", "short", "topic", "scope", "project", "pattern", "pattern_id"): f.setdefault(k, str(v)) for k in list(f): f[k] = f[k].strip() @@ -1234,15 +1371,30 @@ def cmd_retro(argv, stdin=None): print("sisi retro: refused, nothing was recorded:") for e in errs: print(" - " + e) - print("Answer how it could have gone better, concretely: see `sisi help` and canon rule 7.") + print("Answer how it could have gone better, concretely: see `sisi help` and the rule " + "retro-every-time (`sisi rule retro-every-time`).") return 2 + if not same: + if not (f.get("pattern") or "").strip() and not str(f.get("pattern_id") or "").strip(): + print("sisi retro: refused, nothing was recorded: --pattern is required: the general " + "failure of thinking this incident is an instance of, in one line that would " + "apply to unrelated work. `sisi retro patterns` lists the patterns so far; " + "reuse one with --pattern-id N instead of inventing a near-duplicate.") + return 2 + if (f.get("pattern") or "").strip(): + reason = pattern_refusal(f["pattern"], f.get("change"), os.getcwd(), f.get("moment")) + if reason: + print("sisi retro: refused, nothing was recorded: %s" % reason) + return 2 if not same: from . import scope as _scope sc = f.get("scope") - if sc not in _scope.SCOPES: + if sc not in _scope.SCOPES and sc != "everywhere": print(_scope.MISSING_SCOPE) return 2 - if sc == "everywhere": + sc = _scope.normalize_scope(sc) + f["scope"] = sc + if sc in ("core", "user", "unscoped-tier"): reason = _scope.universal_refusal( [f.get("change"), f.get("short"), f.get("when")], os.getcwd(), kind=f.get("change_kind")) if reason: @@ -1262,11 +1414,21 @@ def cmd_retro(argv, stdin=None): "withdrawn because the problem kept recurring after it was enforced. Record what is " "different this time, not the same change again." % w[0]) return 2 + if str(f.get("pattern_id") or "").strip(): + pid = f["pattern_id"] + if not str(pid).isdigit() or not con.execute("SELECT 1 FROM patterns WHERE id=?", (int(pid),)).fetchone(): + print("sisi retro: no pattern with id %r (see `sisi retro patterns`)" % pid) + return 2 if same: if not same.isdigit() or not con.execute("SELECT 1 FROM lessons WHERE id=?", (int(same),)).fetchone(): print("sisi retro: no lesson with id %r (see `sisi lessons`)" % same) return 2 lid = int(same) + if f.get("pattern") or f.get("pattern_id"): + cur = con.execute("SELECT pattern_id FROM lessons WHERE id=?", (lid,)).fetchone() + if cur and not cur[0]: + assign_pattern(con, lid, pattern=f.get("pattern"), + pattern_id=int(f["pattern_id"]) if str(f.get("pattern_id") or "").isdigit() else None) add_occurrence(con, lid, f["moment"], cwd, None) con.commit() applied = maybe_auto_apply(con, lid) @@ -1376,14 +1538,22 @@ def digest_lines(include_all=False, con=None): con.close() if not include_all: rows = [r for r in rows if r.get("status") not in ("retired", "withdrawn", "superseded")] - said = [] + from . import scope as _scope0 + said, said_core, said_user = [], [], [] try: - for rec in store.read("quarantine"): + for rec in store.read("learn"): t = " ".join(str(rec.get("text") or "").split()) - if t and rec.get("scope") != "project": + if not t: + continue + tier = _scope0.tier_of(rec.get("scope")) + if tier == "core": + said_core.append(t) + elif tier == "user": + said_user.append(t) + elif tier != "project": said.append(t) except Exception: - said = [] + said, said_core, said_user = [], [], [] # any project-scoped rows still in the store (recorded before handover, not yet moved) # are not global lessons: the digest names only how many wait to be filed, per project from . import scope as _scope, handover as _ho @@ -1410,8 +1580,59 @@ def digest_lines(include_all=False, con=None): for t in said: out.append('- "%s"' % t) out.append("") + active_ids = {r["id"] for r in rows} + try: + _pcon = connect() + try: + pats = [p for p in patterns(_pcon) if active_ids & set(p.get("lessons") or [])] + trends = {p["id"]: pattern_recurrence_trend(_pcon, p) for p in pats} + finally: + _pcon.close() + except Exception: + pats, trends = [], {} + if pats: + out.append("## Patterns") + out.append("The handful of general failures of thinking behind the incidents below; " + "each lesson under one says what to do differently.") + for p in sorted(pats, key=lambda x: (-(x.get("incidents") or 0), x.get("id") or 0)): + state = "in the rulebook" if p.get("folded_into") else "not in the rulebook yet" + out.append("- %s (pattern %d; explains %d incident(s) in %d lesson(s): %s; " + "recurrence %s; %s)" + % (p["statement"], p["id"], p.get("incidents") or 0, p.get("n_lessons") or 0, + ", ".join("lesson %d" % i for i in p.get("lessons") or []) or "-", + trends.get(p["id"], "too little data"), state)) + out.append("") + def _tier_line(r, extra_state=None): + text = " ".join(str(r["short"]).split()) if (r.get("short") or "").strip() else word_cut(r.get("change") or "", 140) + line = "- %s (lesson %d; %s" % (text, r["id"], extra_state or plain_state(r)) + if (r.get("count") or 1) > 1: + line += "; seen %d times" % r["count"] + return line + ")" + + core_rows = [r for r in rows if _scope.row_scope(r) == "core"] + user_rows = [r for r in rows if _scope.row_scope(r) == "user"] + rest_ids = {r["id"] for r in core_rows + user_rows} + if core_rows or said_core: + out.append("## In sisi itself, for every user") + out.append("Changes to sisi itself: in force for you now, and queued for the product " + "until promoted (`sisi promote`).") + for t in said_core: + out.append('- "%s" (what you said; waiting to be promoted)' % t) + for r in sorted(core_rows, key=lambda x: x.get("id")): + out.append(_tier_line(r, "in the product" if _get(r, "promoted") + else "waiting to be promoted")) + out.append("") + if user_rows or said_user: + out.append("## How you want work done") + for t in said_user: + out.append('- "%s" (what you said)' % t) + for r in sorted(user_rows, key=lambda x: x.get("id")): + out.append(_tier_line(r)) + out.append("") groups = {} for r in summarized: + if r["id"] in rest_ids: + continue groups.setdefault(" ".join(str(r["topic"]).split()), []).append(r) for topic in sorted(groups, key=lambda t: (-len(groups[t]), t)): out.append("## %s" % topic) @@ -1421,6 +1642,7 @@ def digest_lines(include_all=False, con=None): line += "; seen %d times" % r["count"] out.append(line + ")") out.append("") + pending = [r for r in pending if r["id"] not in rest_ids] if pending: out.append("## Not yet summarized") for r in sorted(pending, key=lambda x: x.get("id")): @@ -1469,7 +1691,17 @@ def cmd_lessons(argv): from . import scope as _scope _sc = _scope.row_scope(r) print("scope : %s%s" % (_sc, (" (%s)" % _get(r, "project")) if _sc == "project" else - " (not yet scoped; a learning round will ask)" if _sc == "unscoped" else "")) + " (not yet tiered; a learning round will ask)" if _sc == "unscoped-tier" else "")) + _pid = _get(r, "pattern_id") + _pstmt = None + if _pid: + try: + _prow = con.execute("SELECT statement FROM patterns WHERE id=?", (_pid,)).fetchone() + _pstmt = _prow[0] if _prow else None + except Exception: + _pstmt = None + print("pattern: %s" % (("%d. %s" % (_pid, _pstmt)) if _pstmt else + "- (none yet; a learning cycle can assign one)")) print("change: %s" % r["change"]) print("short : %s" % (_get(r, "short") or "- (none yet; a learning cycle can write one)")) print("topic : %s" % (_get(r, "topic") or "-")) diff --git a/sisi/rulecmd.py b/sisi/rulecmd.py index cb2195a..b824f2f 100644 --- a/sisi/rulecmd.py +++ b/sisi/rulecmd.py @@ -33,6 +33,14 @@ def _question_gate(): return False +def _design_gate(): + try: + from . import design, gate + return callable(design.validate_design) and callable(gate._design_required) + except Exception: + return False + + def _delivery_measured(): try: from . import delivery @@ -44,6 +52,10 @@ def _delivery_measured(): _NOT = "not enforced: depends on the agent" ENFORCEMENT = { + "choose-the-approach": lambda: ("end-of-turn check sends a large change back when the contract's " + "design section is missing or fails validation (small edits and " + "subagents exempt)" + if _gate_wired() and _design_gate() else _NOT), "know-done": lambda: ("end-of-turn check sends the agent back (no contract on a large change)" if _gate_wired() else _NOT), "strongest-check": lambda: ("minimum rungs refused when the contract is checked; the choice of check depends on the agent" diff --git a/sisi/scope.py b/sisi/scope.py index d8939a4..f19c410 100644 --- a/sisi/scope.py +++ b/sisi/scope.py @@ -1,4 +1,16 @@ -"""Lesson scope: everywhere or one project. +"""Lesson and statement tiers: core, user, or one project. + +The owner's test, two questions: (a) does it apply to all projects where sisi may be used? +(b) would it be useful to every user who installs sisi? Both yes is `core`: a change to the +product itself (a rule, a recipe or technique, a mechanism, a design principle), in force for +this user at once through the personal overlay and queued for the product (`sisi promote`). +(a) yes, (b) no is `user`: how this owner wants work done, kept in the personal store and +delivered in all of this user's projects. (a) no is `project`: a fact about one project, +handed over to that project's own documentation or work list. Items recorded with the old +two-way scope `everywhere` are `unscoped-tier`: still delivered, tiered by the next learning +round. sisi is normally the shell around other projects; working in the sisi repository +itself is the exception, and an item is never project merely because it was recorded there - +a statement about how sisi itself should behave is core. A project is identified by its git remote URL when there is one (normalised, so an ssh and an https remote for the same repository, a trailing `.git`, credentials and a @@ -9,21 +21,46 @@ the personal data store, keyed by that id; nothing is written into the repositor The universality check is structural only, no model call: it looks at the parts that are delivered to agents (change, short, when-terms; a learn statement) and refuses -when they name the current project. History (moment, cause, occurrences) may name -the project freely and is never checked. +when a core or user item names the current project. The tool's own name, sisi, is always +exempt. History (moment, cause, occurrences) may name the project freely and is never checked. """ import os, re, subprocess from . import gitutil -SCOPES = ("everywhere", "project") +SCOPES = ("core", "user", "project") +UNTIERED = (None, "", "unscoped", "unscoped-tier", "everywhere") +TIER_QUESTIONS = ( + "Ask two questions: (a) does it apply to all projects where sisi may be used? " + "(b) would it be useful to every user who installs sisi? Both yes: --scope core (a change " + "to sisi itself - a rule, a recipe or technique, a mechanism, a design principle; it takes " + "effect for you at once and is queued for the product, `sisi promote`). (a) yes but (b) no, " + "because it is how this owner wants things: --scope user (kept in your personal store, " + "delivered in all your projects). (a) no: --scope project (a fact about this project, " + "handed over to its own documentation or work list).") MISSING_SCOPE = ( - "sisi: --scope is required: use --scope everywhere for a lesson that holds in any project, stated in " - "general terms so a different project can use it, or --scope project for a fact about this project only, " - "which is kept with this project and shown only here. To make a project fact universal, restate it in " - "general terms: name the kind of work and the rule that follows, not this project's name, files or " - "address (for example, not 'the exporter here joins rows by hand' but 'write delimited files with a " - "quoting writer'). The moment and cause may name this project either way: they stay as its history.") + "sisi: --scope is required (core, user or project). " + TIER_QUESTIONS + " " + "Core and user items are stated in general terms so any project can use them: name the kind " + "of work and the rule that follows, not this project's name, files or address (for example, " + "not 'the exporter here joins rows by hand' but 'write delimited files with a quoting " + "writer'). A statement about how sisi itself should behave is core, even recorded inside " + "the sisi repository. The moment and cause may name this project either way: they stay as " + "its history.") + + +def tier_of(value): + """The tier a stored scope value means today: legacy `everywhere` is not yet tiered.""" + if value in SCOPES: + return value + return "unscoped-tier" + + +def normalize_scope(value): + """A scope given on a command line, canonicalised: legacy `everywhere` is accepted and + stored as unscoped-tier (still delivered; the next learning round tiers it).""" + if value == "everywhere": + return "unscoped-tier" + return value # File and directory names so common that merely mentioning them names no project. COMMON_NAMES = { @@ -87,12 +124,8 @@ def project_label(pid): def visible(scope_value, project_value, cwd=None): - """Legacy (unscoped) and everywhere items show everywhere; project items only at home.""" - if scope_value in (None, "", "unscoped"): - return True - if scope_value == "everywhere": - return True - if scope_value == "project": + """Core, user and not-yet-tiered items show in every project; project items only at home.""" + if tier_of(scope_value) == "project": return (project_value or "") == project_id(cwd or os.getcwd()) return True @@ -110,7 +143,7 @@ def row_scope(row): v = row.get("scope") if isinstance(row, dict) else (row["scope"] if "scope" in row.keys() else None) except Exception: v = None - return v or "unscoped" + return tier_of(v) def _existing(cwd): @@ -138,8 +171,8 @@ def universal_refusal(texts, cwd, kind=None): """Reason string when a delivered text names the current project, else None. Checks the repository name, its remote URL (and the repository name inside it), - any path or file name that exists in it, and the root path itself. A tool lesson - (a change to sisi itself) may say 'sisi': that word alone is exempt there. + any path or file name that exists in it, and the root path itself. The tool's own + name, 'sisi', is always exempt: how sisi itself should behave is core, not project. """ texts = [t for t in (texts or []) if t and str(t).strip()] if not texts: @@ -164,7 +197,7 @@ def universal_refusal(texts, cwd, kind=None): # the repository's own name, as a whole token or inside a path/URL token for name in {repo_name, remote_name} - {""}: if tl == name or tl.endswith("/" + name) or ("/" in tl and tl.rsplit("/", 1)[-1] == name): - if kind == "tool" and name == "sisi": + if name == "sisi": continue return "it names this project (%s)" % name if "/" in tl: @@ -183,13 +216,13 @@ def universal_refusal(texts, cwd, kind=None): def refusal_text(reason): - return ("sisi: refused: a lesson scoped everywhere must be universal, and %s. Rewrite it in general " + return ("sisi: refused: a core or user item must be universal, and %s. Rewrite it in general " "terms (the kind of work and the rule that follows, not this project's name, files or address), " - "or record it with --scope project so it stays with this project." % reason) + "or record it with --scope project so it stays with this project. " + TIER_QUESTIONS) % reason def cmd_learn(argv): - """`sisi learn [--scope everywhere|project] TEXT` (also `--scope=X`).""" + """`sisi learn [--scope core|user|project] TEXT` (also `--scope=X`).""" from . import store scope_value, text_parts, i = None, [], 0 argv = list(argv) @@ -203,14 +236,15 @@ def cmd_learn(argv): text_parts.append(a); i += 1 text = " ".join(text_parts).strip() if not text: - print("usage: sisi learn --scope everywhere|project TEXT") + print("usage: sisi learn --scope core|user|project TEXT") return 1 - if scope_value not in SCOPES: + if scope_value not in SCOPES and scope_value != "everywhere": print(MISSING_SCOPE) return 2 + scope_value = normalize_scope(scope_value) cwd = os.getcwd() - if scope_value == "everywhere": - reason = universal_refusal([text], cwd) + if scope_value in ("core", "user", "unscoped-tier"): + reason = universal_refusal([text], cwd, kind="learn") if reason: print(refusal_text(reason)) return 2 @@ -218,15 +252,22 @@ def cmd_learn(argv): if scope_value == "project": from . import handover handover.move_learn(store.stamp(rec), project_id(cwd)) - print("recorded for this project (quarantined until verified); it will be handed over to this " + print("recorded for this project; it will be handed over to this " "project at session start (`sisi handover` lists it)") return 0 - store.append("quarantine", store.stamp(rec)) + store.append("learn", store.stamp(rec)) try: from . import cli - cli._commit_personal(store.file_path("quarantine"), + cli._commit_personal(store.file_path("learn"), "learn: %s" % " ".join(text.split())[:60]) except Exception: pass - print("recorded (quarantined until verified)") + if scope_value == "core": + print("recorded as core; it takes effect at once (`sisi oracle` shows it) and is queued " + "for the product (`sisi promote` lists core items)") + elif scope_value == "unscoped-tier": + print("recorded (the old everywhere scope); it takes effect at once and the next " + "learning round will tier it core, user or project") + else: + print("recorded; it takes effect at once as a standing principle (`sisi oracle` shows it)") return 0 diff --git a/sisi/store.py b/sisi/store.py index 0ba7b90..445bb27 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -4,10 +4,65 @@ import json, os, re, time from . import paths FILES = {"results": "results.jsonl", "notes": "notes.jsonl", "proposals": "proposals.jsonl", - "quarantine": "learn-quarantine.jsonl", "waivers": "waivers.jsonl", + "learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl", "deliveries": "deliveries.jsonl"} +def _migrate_learn(): + """Lossless one-time move of the old quarantine file into the live learn store. + + Statements used to be parked in learn-quarantine.jsonl, which no agent read. They now take + effect at once from learn.jsonl. Every old line (quoted words, date, scope, context) is + copied across unchanged, then the old file is removed so nothing is read twice.""" + try: + new = paths.data_file("learn.jsonl") + olds = [paths.data_file("learn-quarantine.jsonl"), paths.state_file("learn-quarantine.jsonl")] + lines = [] + for old in olds: + if os.path.realpath(old) == os.path.realpath(new) or not os.path.exists(old): + continue + with open(old, encoding="utf-8") as f: + lines += [l.rstrip("\n") for l in f if l.strip()] + if not lines and not any(os.path.exists(o) and os.path.realpath(o) != os.path.realpath(new) for o in olds): + return + have = set() + if os.path.exists(new): + with open(new, encoding="utf-8") as f: + have = {l.rstrip("\n") for l in f if l.strip()} + add = [l for l in lines if l not in have] + if add: + os.makedirs(os.path.dirname(new), exist_ok=True) + with open(new, "a", encoding="utf-8") as f: + for l in add: + f.write(l + "\n") + for old in olds: + if os.path.realpath(old) != os.path.realpath(new) and os.path.exists(old): + os.unlink(old) + # the old two-way scope is now three tiers: an everywhere statement is not yet tiered + if os.path.exists(new): + with open(new, encoding="utf-8") as f: + raw = f.read() + if '"everywhere"' in raw: + out = [] + for line in raw.splitlines(): + try: + rec = json.loads(line) + except ValueError: + out.append(line) + continue + if isinstance(rec, dict) and rec.get("scope") == "everywhere": + rec["scope"] = "unscoped-tier" + out.append(json.dumps(rec, ensure_ascii=False, separators=(",", ":"))) + else: + out.append(line) + tmp = new + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write("".join(l + "\n" for l in out)) + os.replace(tmp, new) + except OSError: + pass + + def now(): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + "Z" @@ -27,7 +82,7 @@ def session_id(): return os.environ.get("SISI_SESSION_ID") or None -PERSONAL = ("notes", "proposals", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch +PERSONAL = ("notes", "proposals", "learn", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch def file_path(name): @@ -64,6 +119,8 @@ def read_stdin(wait=None): def append(name, rec): + if name in ("learn", "quarantine"): + _migrate_learn() path = file_path(name) os.makedirs(os.path.dirname(path), exist_ok=True) line = json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n" @@ -75,6 +132,8 @@ def append(name, rec): def read(name): + if name in ("learn", "quarantine"): + _migrate_learn() path = file_path(name) out = [] try: diff --git a/tests/test_design.py b/tests/test_design.py new file mode 100644 index 0000000..80ea3db --- /dev/null +++ b/tests/test_design.py @@ -0,0 +1,276 @@ +"""Live principles (`sisi learn`/`sisi oracle`), the contract design section, `sisi design`, +the gate's design send-back, and request-time design delivery.""" +import json, os, subprocess, unittest +from support import * + +PRINCIPLES = [ + "drop into any user's environment and use what is already there", + "mechanisms over good intentions: check it, do not just advise it", + "never set up scheduled jobs or timers for me", +] + + +def good_design(principles=PRINCIPLES, **over): + d = { + "implies": ["The tool must work in an environment sisi did not choose, so discovery of what " + "the host already provides comes before building any replacement for it."], + "provided": [{"what": "git is already used for change measurement in this repository", + "evidence": "command:git"}, + {"what": "the README documents the existing command surface to build on", + "evidence": "file:README.md"}], + "alternatives": [ + {"name": "shell out to each tool's command line", + "cost": "one driver per tool, each with its own quoting and login handling", + "risk": "breaks wherever a tool has no usable command line or changes its flags"}, + {"name": "build a new agent host of our own", + "cost": "months of work duplicating sessions, auth and tool wiring from scratch", + "risk": "nobody's existing setup carries over, so adoption starts from zero"}, + ], + "chosen": {"name": "use the host tool's own subagent mechanism", + "why": "It drops into the user's existing environment instead of rebuilding what " + "the host already provides, which is what the owner asked for."}, + "objections": [{"principle": p, "applicable": True, + "objection": "You are rebuilding something the environment already gives me.", + "answer": "The design calls the host mechanism and builds only the missing adapter."} + if i < 2 else + {"principle": p, "applicable": False, + "reason": "Nothing in this design runs on a schedule; every step is triggered by use."} + for i, p in enumerate(principles)], + "challenge": {"by": "a subagent on a different model, briefed as the owner", + "recorded_at": "2026-01-01T00:00:00Z", + "objections": ["You never checked what the host already provides before designing drivers."], + "changes": ["Made the host subagent mechanism the main path; command lines are the fallback."]}, + } + d.update(over) + return d + + +class PrinciplesCase(SisiCase): + def learn_all(self): + for p in PRINCIPLES: + r = self.sisi("learn", "--scope", "user", p) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +class LivePrinciplesTests(PrinciplesCase): + def test_learn_takes_effect_at_once_without_quarantine_wording(self): + r = self.sisi("learn", "--scope", "user", PRINCIPLES[0]) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertNotIn("quarantin", (r.stdout + r.stderr).lower()) + out = self.sisi("oracle").stdout + self.assertIn(PRINCIPLES[0], out) + + def test_oracle_prints_one_principle_per_statement_with_quote_and_date(self): + self.learn_all() + out = self.sisi("oracle").stdout + for p in PRINCIPLES: + self.assertIn(p, out) + self.assertIn('"%s"' % p, out) + self.assertIn("Standing principles", out) + + def test_quarantine_file_is_migrated_losslessly(self): + os.makedirs(self.data, exist_ok=True) + rec = {"ts": "2025-01-02T03:04:05Z", "cwd": self.proj, "tool": None, "session": None, + "text": "always show options with a recommendation", "scope": "user"} + with open(os.path.join(self.data, "learn-quarantine.jsonl"), "w") as f: + f.write(json.dumps(rec) + "\n") + out = self.sisi("oracle").stdout + self.assertIn("always show options with a recommendation", out) + self.assertIn("2025-01-02", out) + self.assertTrue(os.path.exists(os.path.join(self.data, "learn.jsonl"))) + self.assertFalse(os.path.exists(os.path.join(self.data, "learn-quarantine.jsonl"))) + rows = [json.loads(l) for l in open(os.path.join(self.data, "learn.jsonl"))] + self.assertEqual(rows[0]["text"], rec["text"]) + self.assertEqual(rows[0]["ts"], rec["ts"]) + + def test_learn_statement_may_name_sisi_itself(self): + # the project folder is named proj in the fixture; use a folder named sisi + d = os.path.join(self.tmp, "sisi") + os.makedirs(d) + subprocess.run(["git", "init", "-q"], cwd=d, check=True) + r = self.sisi("learn", "--scope", "user", + "sisi should anticipate what I need from what I already said", cwd=d) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +class DesignValidationTests(PrinciplesCase): + def errs(self, design): + from sisi import design as D + return D.validate_design({"goal": "g", "design": design}, cwd=REPO) + + def test_good_design_passes(self): + self.learn_all() + self.assertEqual(self.errs(good_design()), []) + + def test_missing_design_is_an_error(self): + from sisi import design as D + self.assertTrue(D.validate_design({"goal": "g"}, cwd=REPO)) + + def test_labelled_good_and_filler_sets(self): + """At least 12 good and 12 filler design sections: every good one passes, every filler fails.""" + self.learn_all() + base = good_design() + def variant(**kw): + d = json.loads(json.dumps(base)) + d.update(kw) + return d + goods = [base] + for i in range(11): + d = json.loads(json.dumps(base)) + d["implies"] = ["Implication %d: the result must keep working when the host, the model " + "and the project layout all change around it over time." % i] + d["provided"] = [{"what": "python3 runs the whole tool and its checks already", + "evidence": "command:python3"}, + {"what": "the licence file fixes the terms this ships under", + "evidence": "file:LICENSE"}] + d["alternatives"][0]["name"] = "bespoke driver number %d" % i + d["challenge"]["by"] = "independent reviewer %d on a different model" % i + goods.append(d) + fillers = [ + variant(implies=["As requested."]), + variant(implies=[]), + variant(provided=[{"what": "existing tools", "evidence": "command:no-such-command-xyz"}]), + variant(provided=["stuff that exists somewhere in general terms"]), + variant(provided=[]), + variant(alternatives=[base["alternatives"][0]]), + variant(alternatives=[dict(base["alternatives"][0], name="use the host tool's own subagent mechanism"), + base["alternatives"][1]]), + variant(alternatives=[dict(base["alternatives"][0], cost="low", risk="low"), + dict(base["alternatives"][1], cost="low", risk="low")]), + variant(chosen={"name": "use the host tool's own subagent mechanism", "why": "best"}), + variant(objections=[{"principle": PRINCIPLES[0], "applicable": True, + "objection": "x", "answer": "y"}]), + variant(objections=[dict(o, applicable=False, reason="n/a") if o.get("applicable") else o + for o in base["objections"]]), + variant(challenge={"by": "self", "recorded_at": "2026-01-01T00:00:00Z", + "objections": ["none"], "changes": []}), + variant(challenge={"by": "a subagent on a different model", "recorded_at": "2026-01-01T00:00:00Z", + "objections": [], "changes": ["changed things in response to the review"]}), + ] + good_pass = sum(1 for d in goods if not self.errs(d)) + filler_fail = sum(1 for d in fillers if self.errs(d)) + self.assertGreaterEqual(len(goods), 12) + self.assertGreaterEqual(len(fillers), 12) + self.assertEqual((good_pass, filler_fail), (len(goods), len(fillers)), + "good %d/%d pass, filler %d/%d refused" % (good_pass, len(goods), filler_fail, len(fillers))) + + +class DesignCommandTests(PrinciplesCase): + def test_sisi_design_prints_principles_and_questions(self): + self.learn_all() + r = self.sisi("design") + self.assertEqual(r.returncode, 0, r.stderr) + for p in PRINCIPLES: + self.assertIn(p, r.stdout) + for key in ("implies", "provided", "alternatives", "chosen", "objections", "challenge"): + self.assertIn(key, r.stdout) + + def test_contract_init_prints_principles_and_design_skeleton(self): + self.learn_all() + r = self.sisi("contract", "init", "--goal", "build the orchestrator") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn(PRINCIPLES[0], r.stdout) + c = json.load(open(os.path.join(self.proj, ".sisi", "contract.json"))) + self.assertIn("design", c) + for key in ("implies", "provided", "alternatives", "chosen", "objections", "challenge"): + self.assertIn(key, c["design"]) + + +class DesignGateTests(PrinciplesCase): + def gate(self, payload): + return self.sisi("gate", stdin=json.dumps(payload)) + + def large_contract_project(self, design=None): + self.git_init() + c = contract([check("a", "true")]) + if design is not None: + c["design"] = design + self.write_contract(c) + with open(os.path.join(self.proj, "big.txt"), "w") as f: + f.write("line\n" * 80) + return {"session_id": "gate-design-1", "cwd": self.proj, "stop_hook_active": False} + + def test_large_change_without_design_is_sent_back_then_never_traps(self): + self.learn_all() + payload = self.large_contract_project() + msgs = [] + for _ in range(5): + r = self.gate(payload) + out = r.stdout.strip() + if not out: + break + d = json.loads(out) + msgs.append(d) + if d.get("decision") != "block": + break + self.assertTrue(any("design" in (m.get("reason") or "") for m in msgs), msgs) + # never traps: within the send-back budget the turn is let through + self.assertLessEqual(len([m for m in msgs if m.get("decision") == "block"]), 3) + + def test_large_change_with_good_design_is_not_sent_back_for_design(self): + self.learn_all() + payload = self.large_contract_project(design=good_design()) + r = self.gate(payload) + self.assertNotIn("design section is missing", r.stdout) + + def test_small_change_needs_no_design(self): + self.git_init() + self.write_contract(contract([check("a", "true")])) + with open(os.path.join(self.proj, "small.txt"), "w") as f: + f.write("one line\n") + r = self.gate({"session_id": "gate-design-small", "cwd": self.proj}) + self.assertNotIn("design", r.stdout) + + +class PromptDesignTests(PrinciplesCase): + def test_design_work_gets_principles_and_instruction(self): + self.learn_all() + from sisi import prompt as P + ctx = P.build_context("Build an automatic orchestrator that delegates work to other agents " + "across the tools installed here, with routing and judged outcomes") + self.assertIn(PRINCIPLES[0], ctx) + self.assertIn("design", ctx.lower()) + self.assertLessEqual(len(ctx), P.MAX_CHARS) + + def test_questions_and_small_edits_get_no_design_block(self): + self.learn_all() + from sisi import prompt as P + for q in ("Should the orchestrator use subagents or command lines?", + "rename the helper that formats the orchestrator headings in the docs", + "fix the typo in the orchestrator help text on the second line"): + self.assertNotIn(PRINCIPLES[0], P.build_context(q), q) + + def test_labelled_design_requests(self): + self.learn_all() + from sisi import prompt as P + should = [ + "Build an automatic orchestrator that delegates work to other agents across tools", + "Design and implement a new storage layer for session records with migration", + "Create a command that discovers installed agent tools and routes work between them", + "Implement a plugin system so other tools can add their own checks to the gate", + ] + should_not = [ + "Why does the orchestrator choose that worker for this kind of work?", + "rename the local variable in the routing helper to something clearer", + "fix the off-by-one in the pagination control of the list view", + "What does the design section of a contract actually require in full?", + ] + hits = sum(1 for t in should if "design section" in P.build_context(t)) + false = sum(1 for t in should_not if "design section" in P.build_context(t)) + self.assertEqual((hits, false), (len(should), 0), + "design hits %d/%d, false %d/%d" % (hits, len(should), false, len(should_not))) + + +class RuleDesignTests(SisiCase): + def test_first_rule_is_choose_the_approach_with_real_enforcement(self): + r = self.sisi("rule", "1") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("choose-the-approach", r.stdout) + self.assertIn("Why:", r.stdout) + from sisi import rulecmd + self.assertIn("design", rulecmd.enforcement_for("choose-the-approach")) + self.assertNotIn("not enforced", rulecmd.enforcement_for("choose-the-approach")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_digest_short.py b/tests/test_digest_short.py index 95378b9..55c1531 100644 --- a/tests/test_digest_short.py +++ b/tests/test_digest_short.py @@ -56,8 +56,23 @@ class ShortCase(LibCase): have = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"} for e in list(notes): if isinstance(e, dict) and isinstance(e.get("lesson"), int) and e["lesson"] not in have: - notes.append({"lesson": e["lesson"], "action": "set-scope", "scope": "everywhere"}) + notes.append({"lesson": e["lesson"], "action": "set-scope", "scope": "core"}) have.add(e["lesson"]) + # every active lesson lacking a pattern needs a set-pattern too + try: + _con = retro.connect() + try: + _prows = [dict(r) for r in _con.execute( + "SELECT id, pattern_id, scope FROM lessons WHERE status IN ('open','applied')")] + finally: + _con.close() + _have_p = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-pattern"} + _exempt = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") in ("retire", "withdraw", "merge")} + for r in _prows: + if not r.get("pattern_id") and r["id"] not in _have_p and r["id"] not in _exempt and r.get("scope") != "project": + notes.append({"lesson": r["id"], "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}) + except Exception: + pass doc["notes"] = notes doc.update(parts) # A cycle file must also answer for every document the brief lists for whole-document diff --git a/tests/test_documents.py b/tests/test_documents.py index 0308160..72a63f4 100644 --- a/tests/test_documents.py +++ b/tests/test_documents.py @@ -53,7 +53,7 @@ class DocCase(LibCase): f = dict(aim="verified", change_kind="recipe", target="parser-or-codec", moment="the parser accepted a truncated file in the nightly job", cause="no truncated-input case existed", change=change, when=WHEN, - scope="everywhere", short="Seed the corpus from golden files.", topic="parsing") + scope="core", short="Seed the corpus from golden files.", topic="parsing", pattern="Reach for the familiar tool instead of the check that fits the claim") f.update(kw) con = retro.connect() try: diff --git a/tests/test_gate.py b/tests/test_gate.py index 7d65d35..aa5afce 100644 --- a/tests/test_gate.py +++ b/tests/test_gate.py @@ -436,7 +436,26 @@ class GateGrowthTests(GateBase): def test_contract_ends_it(self): self.grow("a.txt", 100) self.assertEqual(self.call()[0], "block") - self.write_contract(contract([check("c", "true")])) + c = contract([check("c", "true")]) + c["design"] = { + "implies": ["A change this size needs its approach recorded so the next agent can " + "see why it went this way and what was ruled out."], + "provided": [{"what": "git already measures the change in this repository", + "evidence": "command:git"}], + "alternatives": [ + {"name": "keep blocking on growth alone", "cost": "no new code to write at all", + "risk": "a contract can be gamed with checks that prove nothing real"}, + {"name": "ask the human to approve large changes", "cost": "one prompt per change", + "risk": "the human becomes the bottleneck for routine sizeable work"}], + "chosen": {"name": "contract with a checked design section", + "why": "It is the option the owner would pick: the approach is recorded " + "and checked mechanically instead of depending on goodwill."}, + "objections": [], + "challenge": {"by": "a subagent on a different model", + "recorded_at": "2026-01-01T00:00:00Z", + "objections": ["The design section could become ceremony filled with filler text."], + "changes": ["Required evidence that named existing things actually exist."]}} + self.write_contract(c) self.assertEqual(self.call()[0], "allow") def test_waiver_covers_tree_at_that_moment_only(self): diff --git a/tests/test_learning.py b/tests/test_learning.py index 98c71e5..fca1014 100644 --- a/tests/test_learning.py +++ b/tests/test_learning.py @@ -61,7 +61,7 @@ class LearningCase(LibCase): con = retro.connect() try: rows = [dict(r) for r in con.execute( - "SELECT id, short, topic FROM lessons WHERE status IN ('open','applied')")] + "SELECT id, short, topic, pattern_id, scope FROM lessons WHERE status IN ('open','applied')")] finally: con.close() notes = list(doc.get("notes") or []) @@ -70,9 +70,12 @@ class LearningCase(LibCase): exempt = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") in ("retire", "withdraw", "merge")} extra = [] + patterned = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-pattern"} for r in rows: if r["id"] not in scoped and r["id"] not in exempt: - extra.append({"lesson": r["id"], "action": "set-scope", "scope": "everywhere"}) + extra.append({"lesson": r["id"], "action": "set-scope", "scope": "core"}) + if not r.get("pattern_id") and r["id"] not in patterned and r["id"] not in exempt and r.get("scope") != "project": + extra.append({"lesson": r["id"], "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}) if r["id"] in covered or r["id"] in exempt: continue if (r.get("short") or "").strip() and (r.get("topic") or "").strip(): @@ -493,9 +496,10 @@ class CycleApplyTests(LearningCase): b = self.mk(change="Session two lesson about widget caching", moment="s2 wait at step 2") base = cycle.base_version() # both sessions read the same brief _ss = lambda lid: {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"} - _sc = lambda lid: {"lesson": lid, "action": "set-scope", "scope": "everywhere"} - doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b)]} - doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b)]} + _sc = lambda lid: {"lesson": lid, "action": "set-scope", "scope": "core"} + _sp = lambda lid: {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"} + doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b), _sp(a), _sp(b)]} + doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b), _sp(a), _sp(b)]} paths_ = [] for i, d in enumerate((doc1, doc2)): p = os.path.join(self.tmp, "two-%d.json" % i) @@ -780,7 +784,7 @@ class MatchingCorpusTests(LearningCase): r = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", "--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011", "--cause", "the importer was only tested with three hand-written rows", - "--change-kind", "rule", "--when", CSV_WHEN, + "--change-kind", "rule", "--when", CSV_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works") self.assertEqual(r.returncode, 0, r.stdout) self.assertIn("lesson #", r.stdout) @@ -849,13 +853,13 @@ class MatchingCorpusTests(LearningCase): first = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", "--moment", "the parser server waited 90 seconds in step 4 of the nightly job", "--cause", "no readiness probe existed before the browser step", - "--change-kind", "rule", "--when", PARSER_WHEN, "--change", PARSER_CHANGE) + "--change-kind", "rule", "--when", PARSER_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", PARSER_CHANGE) self.assertEqual(first.returncode, 0, first.stdout) lid = int(first.stdout.split("lesson #")[1].split(",")[0]) dup = self.sisi("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "again the parser server waited 90 seconds in step 9 of the nightly job", "--cause", "still no readiness probe before the browser step at all", - "--change-kind", "rule", "--when", PARSER_WHEN, + "--change-kind", "rule", "--when", PARSER_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "Prefer a readiness probe over a fixed sleep when waiting for parser servers") self.assertEqual(dup.returncode, 4, dup.stdout) self.assertIn("sighting was kept", dup.stdout) @@ -866,7 +870,7 @@ class MatchingCorpusTests(LearningCase): as_new = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", "--moment", "again the parser server waited 90 seconds in step 9 of the nightly job", "--cause", "still no readiness probe before the browser step at all", - "--change-kind", "rule", "--when", PARSER_WHEN, + "--change-kind", "rule", "--when", PARSER_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "Prefer a readiness probe over a fixed sleep when waiting for parser servers") self.assertEqual(as_new.returncode, 0, as_new.stdout) # kept apart, but the sighting is not lost con = retro.connect() @@ -990,7 +994,7 @@ class ImproveFromUseTests(LearningCase): a = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", "--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011", "--cause", "the importer was only tested with three hand-written rows", - "--change-kind", "rule", "--when", CSV_WHEN, + "--change-kind", "rule", "--when", CSV_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works", env={"SISI_SESSION_ID": "session-A"}) self.assertEqual(a.returncode, 0, a.stdout) @@ -1070,7 +1074,8 @@ class CycleGapTests(LearningCase): doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}]) # cycle_doc recomputes base; rebuild with the original base d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}, - {"lesson": lid, "action": "set-scope", "scope": "everywhere"}, + {"lesson": lid, "action": "set-scope", "scope": "core"}, + {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}, {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]} p = os.path.join(self.tmp, "g2.json") with open(p, "w") as f: @@ -1096,7 +1101,8 @@ class CycleGapTests(LearningCase): base = cycle.base_version() self.mk(change="Brand new parser lesson arriving mid cycle", moment="new wait at step 5") d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}, - {"lesson": lid, "action": "set-scope", "scope": "everywhere"}, + {"lesson": lid, "action": "set-scope", "scope": "core"}, + {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}, {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]} p = os.path.join(self.tmp, "g3.json") with open(p, "w") as f: @@ -1230,7 +1236,8 @@ class CycleGapTests(LearningCase): def test_gap16_rule_numbers_map_to_ids(self): out = cycle.brief_text() - self.assertIn("1. know-done", out) + self.assertIn("1. choose-the-approach", out) + self.assertIn("2. know-done", out) self.assertIn("rule 5", out) def test_gap17_enforced_help_fields_and_examples(self): diff --git a/tests/test_patterns.py b/tests/test_patterns.py new file mode 100644 index 0000000..bd90a7f --- /dev/null +++ b/tests/test_patterns.py @@ -0,0 +1,167 @@ +"""Patterns: `sisi retro --pattern`, `sisi retro patterns`, the cycle's set-pattern action, +and patterns-first digest/improve.""" +import json, os, unittest +from support import * +from sisi import retro + +WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file" +PATTERN = "Build the obvious thing instead of using what the environment already provides" + + +def retro_args(**kw): + f = dict(aim="verified", moment="the export broke on a quoted field at step 2 of the run", + cause="rows were joined by hand instead of with the writer the project already had", + change_kind="rule", change="Write delimited files with a quoting writer so fields survive", + when=WHEN, scope="core", pattern=PATTERN, + short="Use a quoting writer for delimited exports.", topic="data files") + f.update(kw) + out = [] + for k in ("aim", "moment", "cause", "change_kind", "change", "when", "scope", "short", "topic", "pattern"): + if f.get(k) is not None: + out += ["--" + k.replace("_", "-"), str(f[k])] + if f.get("pattern_id") is not None: + out += ["--pattern-id", str(f["pattern_id"])] + return out + + +class RetroPatternTests(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + + def test_pattern_is_required_for_a_new_lesson(self): + r = self.sisi("retro", *retro_args(pattern=None)) + self.assertNotEqual(r.returncode, 0, r.stdout) + self.assertIn("pattern", (r.stdout + r.stderr).lower()) + + def test_pattern_is_stored_and_reused_not_duplicated(self): + r = self.sisi("retro", *retro_args()) + self.assertEqual(r.returncode, 0, r.stdout) + r = self.sisi("retro", "--new", *retro_args( + moment="another export broke on an embedded newline at step 4 of the run", + change="Write delimited files with a quoting writer so newlines survive")) + self.assertEqual(r.returncode, 0, r.stdout) + con = retro.connect() + try: + pats = retro.patterns(con) + self.assertEqual(len(pats), 1, pats) + self.assertEqual(pats[0]["statement"], PATTERN) + ids = [row[0] for row in con.execute("SELECT pattern_id FROM lessons ORDER BY id")] + self.assertEqual(ids, [pats[0]["id"], pats[0]["id"]]) + finally: + con.close() + + def test_retro_patterns_lists_them_and_pattern_id_selects(self): + self.assertEqual(self.sisi("retro", *retro_args()).returncode, 0) + out = self.sisi("retro", "patterns").stdout + self.assertIn(PATTERN, out) + r = self.sisi("retro", "--new", *retro_args( + pattern=None, pattern_id=1, + moment="a third export broke on a delimiter in a name at step 1 of the run", + change="Write delimited files with a quoting writer so delimiters survive")) + self.assertEqual(r.returncode, 0, r.stdout) + con = retro.connect() + try: + self.assertEqual(len(retro.patterns(con)), 1) + finally: + con.close() + + def test_pattern_naming_the_project_or_restating_the_change_is_refused(self): + r = self.sisi("retro", *retro_args(pattern="proj export rows are joined by hand in this repo")) + self.assertNotEqual(r.returncode, 0, r.stdout) + r = self.sisi("retro", *retro_args(pattern="Write delimited files with a quoting writer so fields survive")) + self.assertNotEqual(r.returncode, 0, r.stdout) + + +class CyclePatternTests(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + + def lesson_without_pattern(self): + con = retro.connect() + try: + lid = retro.new_lesson(con, dict( + aim="verified", change_kind="rule", target=None, + moment="the export broke on a quoted field at step 2 of the run", + cause="rows were joined by hand instead of with a quoting writer", + change="Write delimited files with a quoting writer so fields survive", + when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files", + scope="core"), self.proj, None) + con.commit() + return lid + finally: + con.close() + + def test_cycle_brief_lists_patterns_and_check_requires_set_pattern(self): + lid = self.lesson_without_pattern() + brief = self.sisi("cycle", "--now").stdout + self.assertIn("pattern", brief.lower()) + from sisi import cycle + doc = {"version": 1, "base": cycle.base_version(), "summary": "x", + "notes": [{"lesson": lid, "action": "keep"}]} + p = os.path.join(self.tmp, "cyc.json") + with open(p, "w") as f: + json.dump(doc, f) + r = self.sisi("cycle", "check", p) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("set-pattern", r.stdout) + doc["notes"].append({"lesson": lid, "action": "set-pattern", "pattern": PATTERN}) + with open(p, "w") as f: + json.dump(doc, f) + r = self.sisi("cycle", "check", p) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + r = self.sisi("cycle", "apply", p) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + con = retro.connect() + try: + self.assertEqual(retro.patterns(con)[0]["statement"], PATTERN) + finally: + con.close() + + def test_pattern_merge_keeps_one(self): + con = retro.connect() + try: + a = retro.get_or_create_pattern(con, PATTERN) + b = retro.get_or_create_pattern(con, "Rebuild what already exists instead of calling it") + con.commit() + finally: + con.close() + lid = self.lesson_without_pattern() + from sisi import cycle + doc = {"version": 1, "base": cycle.base_version(), "summary": "merge patterns", + "notes": [{"lesson": lid, "action": "set-pattern", "pattern_id": b}], + "patterns": [{"pattern": b, "action": "merge", "into": a}]} + p = os.path.join(self.tmp, "cyc.json") + with open(p, "w") as f: + json.dump(doc, f) + r = self.sisi("cycle", "apply", p) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + con = retro.connect() + try: + pats = retro.patterns(con) + self.assertEqual([x["id"] for x in pats], [a]) + self.assertEqual(con.execute("SELECT pattern_id FROM lessons WHERE id=?", (lid,)).fetchone()[0], a) + finally: + con.close() + + +class PatternsFirstTests(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + self.assertEqual(self.sisi("retro", *retro_args()).returncode, 0) + + def test_digest_shows_patterns_first(self): + out = self.sisi("lessons", "digest").stdout + self.assertIn("## Patterns", out) + self.assertLess(out.index("## Patterns"), out.index("## In sisi itself")) + self.assertIn(PATTERN, out) + + def test_improve_shows_patterns(self): + out = self.sisi("improve").stdout + self.assertIn(PATTERN, out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_personal.py b/tests/test_personal.py index 51d5825..0cf95d6 100644 --- a/tests/test_personal.py +++ b/tests/test_personal.py @@ -554,7 +554,7 @@ class ExportImportTests(PersonalCase): self.ok("learn", "--scope", "everywhere", "never", "ask", "twice") self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", "--cause", "the test was written after the code", "--change-kind", "rule", - "--when", "tests, pytest, failing first, regression, test quality, red green", + "--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "write the failing test first and show it fail with `pytest -k new`") os.makedirs(os.path.join(self.state, "sessions")) open(os.path.join(self.state, "sessions", "s1.json"), "w").write('{"a": 1}') @@ -590,7 +590,7 @@ class ExportImportTests(PersonalCase): def test_import_sets_existing_data_aside_and_rebuilds_db_from_the_dump(self): self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", "--cause", "the test was written after the code", "--change-kind", "rule", - "--when", "tests, pytest, failing first, regression, test quality, red green", + "--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "write the failing test first and show it fail with `pytest -k new`") arc = os.path.join(self.tmp, "out.tar.gz") self.ok("export", arc) @@ -634,7 +634,7 @@ def LessonRows(): class LessonDumpTests(PersonalCase): RETRO = ["--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", "--cause", "the test was written after the code", "--change-kind", "rule", - "--when", "tests, pytest, failing first, regression, test quality, red green", + "--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", "write the failing test first and show it fail with `pytest -k new`"] def test_dump_is_committed_sorted_and_the_database_is_not(self): @@ -661,8 +661,8 @@ class LessonDumpTests(PersonalCase): def test_learn_and_note_are_personal_and_committed(self): self.ok("learn", "--scope", "everywhere", "Always", "use", "options") self.assertIn("learn: Always use options", self.git_log()[0]) - self.assertIn("learn-quarantine.jsonl", pdata.git("ls-files").stdout) - self.assertFalse(os.path.exists(os.path.join(self.state, "learn-quarantine.jsonl"))) + self.assertIn("learn.jsonl", pdata.git("ls-files").stdout) + self.assertFalse(os.path.exists(os.path.join(self.state, "learn.jsonl"))) self.assertIn("oracle", self.ok("oracle").stdout.lower()) diff --git a/tests/test_retro.py b/tests/test_retro.py index 583c2ee..612020d 100644 --- a/tests/test_retro.py +++ b/tests/test_retro.py @@ -10,7 +10,7 @@ GOOD = dict(aim="verified", change_kind="recipe", change="Add the fuzz verifier to the Checks of the parser-or-codec recipe so parser work picks it by default", when="parser, fuzzing, codec, hostile input, generated input, parsing", - scope="everywhere", target="parser-or-codec") + scope="everywhere", target="parser-or-codec", pattern="Reach for the familiar tool instead of the check that fits the claim") def argv(f): @@ -266,6 +266,7 @@ class SimilarityAndSameAsTests(RetroCase): def test_dissimilar_lesson_accepted_directly(self): self.retro() other = dict(aim="speed", change_kind="tool", target="", scope="everywhere", + pattern="Reach for the familiar tool instead of the check that fits the claim", moment="the screenshot comparison in `web-ui` waited 90 seconds on a dev server that never started", cause="no readiness probe before the browser step", when="browser, screenshot, dev server, port waiting, ui checks, startup", @@ -539,7 +540,7 @@ class GateRetroTests(RetroCase): self.work() a, msg = self.gate() self.assertEqual(a, "block") - self.assertIn("sisi retro --aim", msg) + self.assertIn("sisi retro --scope", msg) self.assertIn("--change-kind", msg) self.assertIn("how, not whether", msg) self.do_retro() diff --git a/tests/test_rule.py b/tests/test_rule.py index 2677125..3797297 100644 --- a/tests/test_rule.py +++ b/tests/test_rule.py @@ -31,7 +31,7 @@ class RuleTableTests(SisiCase): class RuleDetailTests(SisiCase): def test_rule_by_number_and_by_id(self): - by_num = self.sisi("rule", "5") + by_num = self.sisi("rule", "6") by_id = self.sisi("rule", "decide-dont-ask") self.assertEqual(by_num.returncode, 0, by_num.stderr) self.assertEqual(by_id.returncode, 0, by_id.stderr) diff --git a/tests/test_scope.py b/tests/test_scope.py index a32f94f..8bd3bc9 100644 --- a/tests/test_scope.py +++ b/tests/test_scope.py @@ -9,7 +9,8 @@ def retro_args(**kw): cause="rows were joined by hand in acme-widgets instead of with a quoting writer", change_kind="rule", change="Write delimited files with a quoting writer so embedded newlines survive", - when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files") + when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files", + pattern="Build the obvious thing instead of using what the environment already provides") f.update(kw) out = [] for k, v in f.items(): @@ -93,7 +94,7 @@ class RetroScopeTests(ScopeCase): def test_missing_scope_refused_with_explanation(self): r = self.sisi("retro", *retro_args()) self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("everywhere", r.stdout); self.assertIn("project", r.stdout) + self.assertIn("core", r.stdout); self.assertIn("user", r.stdout); self.assertIn("project", r.stdout) self.assertIn("general terms", r.stdout) def test_everywhere_naming_project_refused(self): @@ -182,7 +183,8 @@ class StaleReadingTests(ScopeCase): self.assertEqual(st["status"], "applied") # retirement deferred while the round is open doc = {"version": 1, "base": base, "summary": "keep", "notes": [{"lesson": lid, "action": "set-short", "short": "Seed fuzz corpus from golden files.", "topic": "testing"}, - {"lesson": lid, "action": "set-scope", "scope": "everywhere"}]} + {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}, + {"lesson": lid, "action": "set-scope", "scope": "core"}]} p = os.path.join(self.tmp, "cyc.json") with open(p, "w") as f: json.dump(doc, f) r = self.sisi("cycle", "check", p) diff --git a/tests/test_tick_store.py b/tests/test_tick_store.py index 8c724bb..da6ae6c 100644 --- a/tests/test_tick_store.py +++ b/tests/test_tick_store.py @@ -82,7 +82,7 @@ class StoreTests(SisiCase): return [json.loads(l) for l in f] def test_note_propose_learn_append_with_context(self): - for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn-quarantine.jsonl")): + for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn.jsonl")): extra = ["--scope", "everywhere"] if cmd == "learn" else [] self.assertEqual(self.sisi(cmd, *(extra + ["first", "entry"]), env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0) self.sisi(cmd, *(extra + ["second"])) diff --git a/tests/test_tiers_amendment.py b/tests/test_tiers_amendment.py new file mode 100644 index 0000000..b86510b --- /dev/null +++ b/tests/test_tiers_amendment.py @@ -0,0 +1,207 @@ +"""Three tiers (core, user, project): round-trips, migration of `everywhere`, the sisi-name +exemption, promote on a developer install, export, and exact cycle revert with tiers.""" +import json, os, shutil, subprocess, unittest +from support import * +from sisi import retro, scope, store + +WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file" +PATTERN = "Build the obvious thing instead of using what the environment already provides" + + +def retro_cli(case, tier, **kw): + f = dict(aim="verified", moment="the export broke on a quoted field at step 2 of the run", + cause="rows were joined by hand instead of with a quoting writer", + change_kind="rule", change="Write delimited files with a quoting writer so fields survive", + when=WHEN, pattern=PATTERN, short="Use a quoting writer for delimited exports.", + topic="data files") + f.update(kw) + args = ["retro", "--scope", tier] + for k in ("aim", "moment", "cause", "change_kind", "change", "when", "pattern", "short", "topic"): + args += ["--" + k.replace("_", "-"), f[k]] + return case.sisi(*args) + + +class TierTests(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + + def test_tier_decisions_round_trip(self): + for tier in ("core", "user"): + r = retro_cli(self, tier, moment="export %s broke on a quoted field at step 3" % tier, + change="Write delimited files with a quoting writer so %s fields survive" % tier) + if tier == "user": + self.assertIn(r.returncode, (0, 4), r.stdout) # 4 = similar lesson kept as sighting + if r.returncode == 4: + r = self.sisi("retro", "--new", "--scope", "user", "--aim", "verified", + "--moment", "export user broke on a quoted field at step 3", + "--cause", "rows were joined by hand instead of with a quoting writer", + "--change-kind", "rule", + "--change", "Write delimited files with a quoting writer so user fields survive", + "--when", WHEN, "--pattern", PATTERN, + "--short", "Use a quoting writer for delimited exports.", + "--topic", "data files") + self.assertEqual(r.returncode, 0, r.stdout) + con = retro.connect() + try: + tiers = [scope.tier_of(r[0]) for r in con.execute("SELECT scope FROM lessons ORDER BY id")] + finally: + con.close() + self.assertEqual(tiers, ["core", "user"]) + for tier, text in (("core", "sisi should anticipate what is needed from what was already said"), + ("user", "always ask questions as options with a recommendation")): + r = self.sisi("learn", "--scope", tier, text) + self.assertEqual(r.returncode, 0, r.stdout) + recs = store.read("learn") + self.assertEqual([r["scope"] for r in recs], ["core", "user"]) + out = self.sisi("oracle").stdout + self.assertIn("always ask questions as options", out) + self.assertIn("sisi should anticipate", out) # core, until the product carries it + + def test_missing_scope_text_asks_the_two_questions(self): + r = self.sisi("learn", "always show options") + self.assertEqual(r.returncode, 2) + self.assertIn("all projects where sisi may be used", r.stdout) + self.assertIn("every user who installs sisi", r.stdout) + + def test_statement_naming_sisi_is_accepted_as_core_inside_sisi_repo(self): + d = os.path.join(self.tmp, "sisi") + os.makedirs(d) + subprocess.run(["git", "init", "-q"], cwd=d, check=True) + r = self.sisi("learn", "--scope", "core", + "sisi should anticipate what I need from what I already said", cwd=d) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(store.read("learn")[0]["scope"], "core") + + def test_everywhere_migrates_to_unscoped_tier_and_still_delivers(self): + con = retro.connect() + lid = retro.new_lesson(con, dict( + aim="verified", change_kind="rule", target=None, + moment="the export broke on a quoted field at step 2 of the run", + cause="rows were joined by hand instead of with a quoting writer", + change="Write delimited files with a quoting writer so fields survive", + when=WHEN, short="Use a quoting writer.", topic="data files", + scope="user", pattern=PATTERN), self.proj, None) + con.execute("UPDATE lessons SET scope='everywhere' WHERE id=?", (lid,)) + con.commit(); con.close() + con = retro.connect() # migration on open + try: + v = con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0] + finally: + con.close() + self.assertEqual(v, "unscoped-tier") + self.assertIn("Use a quoting writer", retro.tick_block(self.proj)) + brief = self.sisi("cycle", "--now").stdout + self.assertIn("tier", brief.lower()) + + def test_digest_groups_core_user_and_project_counts(self): + r = retro_cli(self, "core") + self.assertEqual(r.returncode, 0, r.stdout) + self.sisi("learn", "--scope", "user", "always ask questions as options with a recommendation") + out = self.sisi("lessons", "digest").stdout + self.assertIn("## In sisi itself, for every user", out) + self.assertIn("## How you want work done", out) + self.assertIn("waiting to be promoted", out) + + +class PromoteTierTests(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + self.src = os.path.join(self.tmp, "src") + for d in ("bin", "sisi", "canon"): + os.makedirs(os.path.join(self.src, d)) + open(os.path.join(self.src, "bin", "sisi"), "w").write("#!/bin/sh\n") + open(os.path.join(self.src, "sisi", "cli.py"), "w").write("# cli\n") + shutil.copy(os.path.join(REPO, "canon", "core.md"), os.path.join(self.src, "canon", "core.md")) + os.makedirs(os.path.join(self.data), exist_ok=True) + json.dump({"developer": {"source": self.src}}, open(os.path.join(self.data, "config.json"), "w")) + + def core_lesson_folded_to_rule(self): + r = retro_cli(self, "core") + self.assertEqual(r.returncode, 0, r.stdout) + d = os.path.join(self.data, "overlay", "rules") + os.makedirs(d, exist_ok=True) + with open(os.path.join(d, "quoting-writer.md"), "w") as f: + f.write("## Write delimited files with a quoting writer\n\n" + "Write delimited files with a quoting writer so embedded delimiters and " + "newlines survive.\n\nWhy: hand-joined rows break on real data.\n") + con = retro.connect() + try: + con.execute("UPDATE lessons SET folded_into='rule:quoting-writer' WHERE id=1") + con.commit() + finally: + con.close() + + def test_promote_lists_core_items(self): + self.assertEqual(retro_cli(self, "core").returncode, 0) + out = self.sisi("promote").stdout + self.assertIn("lesson:1", out) + + def test_promote_on_dev_install_edits_product_and_drops_personal_copy(self): + self.core_lesson_folded_to_rule() + overlay_file = os.path.join(self.data, "overlay", "rules", "quoting-writer.md") + self.assertTrue(os.path.exists(overlay_file)) + r = self.sisi("promote", "lesson:1") # dry run: product untouched + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertNotIn("quoting-writer", open(os.path.join(self.src, "canon", "core.md")).read()) + r = self.sisi("promote", "lesson:1", "--apply") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + core = open(os.path.join(self.src, "canon", "core.md")).read() + self.assertIn("quoting writer so embedded delimiters", core) + self.assertFalse(os.path.exists(overlay_file)) # dropped only after the product has it + con = retro.connect() + try: + self.assertTrue(con.execute("SELECT promoted FROM lessons WHERE id=1").fetchone()[0]) + finally: + con.close() + self.assertNotIn("lesson:1", self.sisi("promote").stdout) + + def test_export_contains_no_history_or_names(self): + self.assertEqual(retro_cli(self, "core").returncode, 0) + self.sisi("learn", "--scope", "core", "sisi should use what the host already provides") + p = os.path.join(self.tmp, "contrib.md") + r = self.sisi("promote", "--export", p) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + text = open(p).read() + self.assertIn("Write delimited files with a quoting writer", text) + self.assertIn("sisi should use what the host already provides", text) + self.assertNotIn("the export broke on a quoted field", text) # the moment (history) + self.assertNotIn("rows were joined by hand", text) # the cause (history) + self.assertNotIn(self.tmp, text) + + def test_cycle_set_scope_to_core_and_exact_revert(self): + con = retro.connect() + lid = retro.new_lesson(con, dict( + aim="verified", change_kind="rule", target=None, + moment="the export broke on a quoted field at step 2 of the run", + cause="rows were joined by hand instead of with a quoting writer", + change="Write delimited files with a quoting writer so fields survive", + when=WHEN, short="Use a quoting writer.", topic="data files", + pattern=PATTERN), self.proj, None) + con.commit(); con.close() + from sisi import cycle + doc = {"version": 1, "base": cycle.base_version(), "summary": "tier it", + "notes": [{"lesson": lid, "action": "set-scope", "scope": "core"}]} + p = os.path.join(self.tmp, "cyc.json") + with open(p, "w") as f: + json.dump(doc, f) + r = self.sisi("cycle", "apply", p) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + con = retro.connect() + try: + self.assertEqual(con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0], "core") + finally: + con.close() + r = self.sisi("cycle", "revert") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + con = retro.connect() + try: + self.assertEqual(con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0], + "unscoped-tier") + finally: + con.close() + + +if __name__ == "__main__": + unittest.main()