sisi 0.2.0: the self-improvement loop, and every major harness

Lessons take effect when recorded, are offered to later agents starting the
same kind of work, are counted as listed and read, and are strengthened when
the mistake recurs: note, rule, enforced check. `sisi cycle` consolidates
them from normal use with no scheduler; `sisi improve` reports the effect.

Wiring for Codex, Gemini CLI, Copilot CLI, Qwen Code, Pi, Cursor, OpenCode
and rulebook loading for nine more tools, with a dry run, preflight checks
and a tested uninstall guarantee. Time to delivery is measured per turn.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 00:06:34 -07:00
1 parent d2ed821480
commit 9e9a684ff7
29 files changed
+7001 -235

No files matched your search

+45
View File
@@ -4,6 +4,51 @@ All notable changes to this project are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[Semantic Versioning](https://semver.org/).
## [0.2.0] - 2026-11-23
### Added
- Lessons take effect on their first occurrence: verifier and recipe lessons attach as field notes at once,
recipe lessons naming a missing recipe become draft recipe notes shown by `sisi done for`, rule, oracle and
brief lessons become learned notes with trigger words, and tool lessons form a backlog (`sisi backlog`).
- Lessons are delivered at the moment they match — in `sisi done for`, `sisi verifiers for`,
`sisi verifiers show`, `sisi contract init` and the gate's send-back message, at most three in 600
characters — and every showing is recorded. Session start shows the strongest lessons first.
- A strength ladder (1 note, 2 candidate rule, 3 enforced): a recurrence after at least two showings moves a
lesson up; folded lessons shown 20 times without a recurrence retire; lessons that keep recurring at
strength 3 are withdrawn and not re-learned in the same form.
- `sisi cycle` (`due`, brief, `apply`, `revert`, `status`): agent-run consolidation under a base version and
the personal-data lock, one commit per cycle, exact revert, and flagging of cycles whose deliveries got
worse. Due-ness is a counter checked at session start, at the end of each turn, and in `sisi retro`,
`sisi verify` and `sisi done for`; there is no scheduler, and a session is told at most once until 20
further checks pass or the counter grows.
- Enforced lessons (`overlay/enforced.json`), checked like floors; command checks run only in trusted projects.
- `sisi improve` and a learning line in `sisi status`; [docs/learning.md](docs/learning.md).
- Matching measured on labelled corpora in the test suite (distinctive-word weighting), matched lessons on
`sisi done ID`, unconfirmed duplicate sightings recorded on the retro refusal path, promotions that
require two showings since the previous promotion, and required `--when` terms on `sisi retro` (the bridge
vocabulary a later agent with different words needs).
- A two-part delivery block in `sisi done for`, `sisi done ID`, `sisi verifiers for` and
`sisi contract init`: strict "likely to apply" lessons in full (two of the request's own content words
inside the when-terms, or one plus the printed entry as target), then every loose lesson as a heading
within a 1,500-character budget for the asking agent to judge. Listings and readings are counted
separately, and more than 30 loose lessons (or headings over budget) makes a cycle due.
- Retro refusals are structural only (presence, length, enums, when-term count, moment differs from
change, five exact empty answers), each naming its check and quoting the text. The earlier
phrase-matching rules are gone: one of them refused a true lesson whose moment spelled its number out.
- Wiring for every major harness, one adapter per tool (`sisi/adapters.py`) with per-tool hook translation
in `sisi/hookio.py` (`sisi tick --tool NAME`, `sisi gate --tool NAME`): blocking session-start and
end-of-turn hooks for Codex CLI (with its one-time `/hooks` trust step called out in install and doctor),
Gemini CLI, GitHub Copilot CLI, Qwen Code and Pi; a follow-up gate for Cursor; an OpenCode plugin whose
enforcement is unproven on v2.3.2; rulebook-only links for Windsurf (pointer file), Cline, Kiro, Zed,
Goose, Amp, Grok CLI, Crush and Aider; truthful `sisi doctor` rows for Muse Code (rulebook via foreign
context, no native gate), Antigravity, and the T3 Code / Orca hosts. See [docs/harnesses.md](docs/harnesses.md).
### Changed
- Verifier and recipe field notes are written on a lesson's first occurrence (previously the second, from a
second session). Existing personal data migrates on open without loss.
## [0.1.0] - 2026-11-22
First public release.
+57 -18
View File
@@ -15,9 +15,14 @@ and a small command-line tool, plain Python with no dependencies. What it learns
clone, so updating never loses it.
**How far along this is.** The name states the goal, not the present. Today every turn is checked, measured and
ends with a recorded lesson, and lessons are shown to every later session. The part that turns lessons into
stronger rules and enforced checks on its own is under construction. See [Status](#status) for exactly what
works.
ends with a recorded lesson; each lesson takes effect at once (a field note, a draft recipe, a learned note or
a backlog item), is offered to later agents when they start that kind of work (strong matches in full, the rest as one-line
headings the agent chooses from), and is strengthened when the same problem recurs
after being shown — up to an enforced check the gate runs. Consolidation (`sisi cycle`) folds lessons into the
rulebook without growing it, and `sisi improve` reports whether any of this is working. There is nothing to
schedule: it all runs from normal use. See [Status](#status) for exactly what works, and
[docs/learning.md](docs/learning.md) for the loop in plain words. What is not yet shown: that this makes agents
measurably better over weeks of real use. `sisi improve` exists to answer that, and it needs use to have data.
## Why it exists
@@ -41,7 +46,8 @@ works.
- **An end-of-turn gate.** A hook calls `sisi verify` when the agent tries to finish. If a check fails or did not
run, the agent is sent back with the failures. If a large change has no contract, it is sent back to write one.
Small edits pass. After three send-backs in a row the agent is let through and the result is marked unverified,
so a broken check cannot trap a session. Today this blocks in Claude Code only (see the table below).
so a broken check cannot trap a session. Today this blocks in Claude Code, Codex, Gemini CLI, Copilot CLI,
Qwen Code and Pi, and sends the agent back with a follow-up message in Cursor (see the table below).
- **A retrospective after each piece of work.** `sisi retro` records how the work could have gone better, against
five aims: the human could have worked at a higher level, a stronger check was possible, the human was
interrupted more than needed, the result was not what they meant, it took longer than it had to. Retros become
@@ -64,7 +70,8 @@ CI are meant to cover; Windows is not supported (the code imports `fcntl`).
`sisi install` links `bin/sisi` as `~/.local/bin/sisi`; make sure that folder is on your `PATH`, or call
`bin/sisi` from the clone. It edits your tools' global instruction files only by adding an import line, and
`sisi uninstall` restores the originals exactly. It skips any tool whose configuration folder does not exist.
`sisi uninstall` restores every file you have not edited since exactly as it was, and removes only its own
entries from a file you have edited. `sisi install --dry-run` shows every change first and makes none. It skips any tool whose configuration folder does not exist.
Now a first contract. Change to one of your own projects (not the sisi clone), where `sisi contract init --goal "slugify() turns titles into URL slugs"` creates a
skeleton whose placeholder check fails until you replace it. Replace it with a real check. Here, for a small
@@ -103,16 +110,39 @@ contract, and the gate runs it at the end of each turn.
## Which tools are supported
| Tool | What `sisi install` does | Instructions loaded | Blocking end-of-turn gate | Session-start hook |
| Tool | Rulebook loaded | Lessons at session start | End-of-turn enforcement | How verified |
|---|---|---|---|---|
| Claude Code | adds an import line to `~/.claude/CLAUDE.md` and registers hooks in `~/.claude/settings.json` | yes | yes (`Stop` and `SubagentStop` hooks) | yes (`SessionStart`) |
| Codex | links `~/.codex/AGENTS.md` to the generated rulebook | yes | no: Codex hooks are documented but not built here | no |
| OpenCode | links `~/.config/opencode/AGENTS.md` to the generated rulebook | yes | no: no blocking hook has been verified | no |
| Muse | nothing: its global instruction path is unconfirmed | no | unknown | no |
| Claude Code | yes | yes | blocks | ran end to end |
| Codex CLI | yes | yes | blocks | built from documentation; session-start hook fired live |
| Gemini CLI | yes | yes | blocks | built from documentation |
| GitHub Copilot CLI | yes | yes | blocks | ran end to end |
| Qwen Code | yes | yes | blocks | built from documentation; session-start hook fired live |
| Pi | yes | yes | blocks | built from documentation; extension loaded and tick ran live |
| Cursor | no (no confirmed global file) | yes | sends a follow-up | built from documentation |
| OpenCode | yes | no | unknown | built from documentation; plugin load verified live |
| Muse Code | yes (via the Claude/Codex files) | no | unknown | not built |
| Antigravity | via the shared Gemini file | no | unknown | not built |
| Windsurf | pointer file | no | none | built from documentation |
| Cline | yes | no | none | built from documentation |
| Kiro | yes | no | none | built from documentation |
| Zed | yes | no | none | built from documentation |
| Goose | yes | no | none | built from documentation |
| Amp | yes | no | none | built from documentation |
| Grok CLI | yes | no | none | ran end to end (`grok inspect` lists the file as global) |
| Crush | yes | no | none | built from documentation |
| Aider | yes (via `read:` in an existing `~/.aider.conf.yml`) | no | none | built from documentation |
| T3 Code | via provider | via provider | via provider | host app; nothing to wire |
| Orca | via provider | via provider | via provider | host app; nothing to wire |
This table comes from `sisi doctor` and the wiring code (`sisi/wiring.py`). Where there is no gate, the rulebook
still tells the agent to write and run a contract, but nothing enforces it. `sisi install` is skipped for a tool
whose configuration folder is missing. Agent skills linked into `~/.agents/skills` are supported by the wiring but
This table comes from `sisi doctor` and the wiring code (`sisi/wiring.py`, `sisi/adapters.py`); per-tool limits
and any step you must take yourself are in [docs/harnesses.md](docs/harnesses.md). Where there is no gate, the
rulebook still tells the agent to write and run a contract, but nothing enforces it. `sisi install` is skipped
for a tool whose configuration folder is missing, and `sisi install --dry-run` prints exactly what would be
created, edited (with diffs) or skipped while changing nothing. The uninstall guarantee: a file you have not
edited since install is restored byte for byte (or removed, if sisi created it); a file you have edited since
install keeps your edits, with only sisi's own entries removed and every other byte left as it was; a file
sisi cannot edit with certainty is skipped and reported, never rewritten, and a generated plugin or extension
you edited is left alone entirely. Agent skills linked into `~/.agents/skills` are supported by the wiring but
the product ships none yet.
## The verifier library
@@ -159,7 +189,8 @@ re-test. `sisi export` and `sisi import` move personal data to another machine a
sisi uninstall
removes the import line, hooks and links, restoring each edited file from its backup. Your personal data and
removes the import line, hooks and links. A file not edited since install is restored byte for byte; a file you
edited keeps your edits and loses only sisi's entries. Your personal data and
scratch folders are left alone; delete them yourself if you want them gone. Then delete the clone.
## Status
@@ -169,10 +200,17 @@ Version 0.1.0, an early release.
Works today, with tests:
- Contracts, `sisi verify` (fast and deep tiers), the trust mechanism, the end-of-turn gate and session-start hook.
- Wiring for Claude Code (with the blocking gate), Codex and OpenCode (rulebook only), and `sisi doctor`, `audit`.
- Wiring for every tool in the table above: blocking gates in Claude Code, Codex, Gemini CLI, Copilot CLI,
Qwen Code and Pi; a follow-up gate in Cursor; rulebook-only links elsewhere; an OpenCode plugin whose
enforcement is unproven (see [docs/harnesses.md](docs/harnesses.md)); and `sisi doctor`, `audit`.
- The verifier library and recipes, with `sisi verifiers lint`.
- Retros, lessons, quarantined preferences, time to delivery, personal data, overlay, update, export and import,
releases and rollback.
- The learning loop that acts on lessons: immediate effects (field notes, draft recipes, learned notes,
`sisi backlog`), delivery at the matching moment, the strength ladder (note, candidate rule, enforced check),
consolidation (`sisi cycle`, with exact revert) and `sisi improve`. No scheduler: due-ness is a counter
checked at session start, at the end of each turn and in `sisi retro`, `sisi verify` and `sisi done for`.
Plain-words tour: [docs/learning.md](docs/learning.md).
- A data layer that reads past Claude Code transcripts into a local database and builds a task set, escape
candidates, per-check statistics and a weekly scoreboard (`sisi harvest`, `tasks`, `escapes`, `checks`,
`scoreboard`; these are not listed in `sisi help`).
@@ -181,9 +219,10 @@ Designed but not built (see [docs/design.md](docs/design.md)):
- The build conductor: `sisi build "<what I want>"` turning a statement into verified work, and the question queue
(`sisi inbox`). Neither command exists.
- The model-driven learning loop: background runs, experiments on a task set, automatic shipping and removal of
rule changes, the taste judge, playbooks. The data layer above is groundwork for it; nothing acts on it yet.
- Blocking gates outside Claude Code, and harvest of transcripts from tools other than Claude Code.
- Replay experiments on a task set before a learned change ships, and the taste judge and playbooks. Learned
changes currently ship first (personal overlay only) and are judged by measured deliveries afterwards, with
exact revert and withdrawal as the safety net; the data layer above is groundwork for the replay version.
- Proven end-to-end enforcement in OpenCode, and harvest of transcripts from tools other than Claude Code.
Not verified: whether Codex and OpenCode obey the rulebook as well as Claude Code does.
+1 -1
View File
@@ -1 +1 @@
0.1.0
0.2.0
+1 -1
View File
@@ -99,7 +99,7 @@ higher level, the outcome is verified by the strongest method, the human is inte
result is what they meant, and it arrives sooner. Name the one thing that would have helped most:
the moment it went slower, weaker or wider than it should have, why, and the change to sisi (a rule,
a recipe, a technique, a fact about the human, a tool) that would make the next agent do it right
without being told. "Nothing" and general advice are refused. Subagents do this too.
without being told, named (`--when`, at least five terms) in the words a different agent would use for that work, synonyms included, because word overlap alone cannot bridge "CSV" and "spreadsheet". "Nothing" and general advice are refused. Subagents do this too. When session start or a command says a learning cycle is due, run `sisi cycle` in the background of your work and never involve the human.
Also, when the human states a lasting preference, record it at once with `sisi learn "<their
words>"`. Quote them. Never record your own guess.
+1
View File
@@ -4,6 +4,7 @@
|---|---|
| [../README.md](../README.md) | learn what sisi is, install it and try it |
| [design.md](design.md) | understand why sisi works the way it does, and what is built versus only designed |
| [learning.md](learning.md) | how a recorded lesson takes effect, is measured, strengthened, consolidated or withdrawn |
| [personal-data.md](personal-data.md) | know where sisi keeps what it learns, how the overlay works, and what an update touches |
| [verifier-format.md](verifier-format.md) | write or review an entry in the verifier library (`verifiers/`) or a recipe (`done/`) |
| [developing.md](developing.md) | work on sisi while also using it: the source folder, stable releases and rollback |
+28 -13
View File
@@ -35,8 +35,9 @@ and 90th percentile for the last 7 days against the 7 days before, the share spe
slowest checks; `sisi status` shows the 7-day median.
A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check
passing but makes median delivery slower is flagged for reversal. (The measurement exists; the automatic
flagging belongs to the learning loop, which is not built.)
passing but makes median delivery slower is flagged for reversal. (Built: `sisi cycle status` flags a cycle
whose deliveries got worse, and the next cycle brief puts reverting or repairing it first. There is still no
replay testing before a learned change ships; it lands in the personal overlay and is judged after.)
## Why the first design was thrown out
@@ -160,7 +161,11 @@ ledger file, to match delegations with sessions when it builds the task set.
## Part 3: learning that compounds
The data layer of this part is built; the model-driven loop that would act on it is not.
The agent-run loop over retro lessons is built: lessons take effect at once, are delivered at matching
moments, are measured per lesson, climb a strength ladder, and are consolidated by `sisi cycle`
([learning.md](learning.md)). The heavier machinery designed below — background runs, replay experiments on a
task set before shipping, the taste judge — is not built; the built loop ships to the personal overlay first
and judges by measured deliveries, with exact revert and withdrawal as the safety net.
**Signals, strongest first.** The loop learns from outcomes that do not depend on a model's opinion:
@@ -170,10 +175,13 @@ The data layer of this part is built; the model-driven loop that would act on it
4. The human's corrections and the agent's questions, read from transcripts by a classifier. Useful for finding
causes, weakest as proof.
**Trigger.** Each tool's session-start hook runs `sisi tick`, which returns quickly. The design has it start a
detached background run when there is work and budget, with one lock in the store preventing overlap, so a tick
from any tool processes sessions from all tools. Today `sisi tick` records the session baseline and checks the
wiring; it starts no background run.
**Trigger.** There is no scheduler and no background run. Whether consolidation is due is a counter check made
during normal use: the session-start hook (`sisi tick`), the end-of-turn gate on an otherwise-clean stop, and
the output of `sisi retro`, `sisi verify` and `sisi done for` — so tools without hooks are covered by commands
agents run anyway. A session is told at most once until 20 further checks pass or the counter grows. Two
sessions consolidating at once are kept apart by the personal-data lock and a base version in the cycle file:
the second apply is refused and re-reads a fresh brief. (The earlier design of tick starting detached
background runs on a budget was dropped for this simpler trigger.)
**What the loop would produce.**
@@ -189,9 +197,11 @@ wiring; it starts no background run.
product are saved for the next one.
- **Brief templates**, from what the ledger shows fixed rejected work.
**Testing a change.** Splitting live sessions between old and new rules proves about one change every three or
four days, which is too slow. The main test is a task set built from the user's own work, re-run in the
background:
**Testing a change.** (Not built; the built loop takes the opposite order by decision — a change lands in the
personal overlay at once and is judged by measured deliveries, because waiting for replay evidence left every
lesson inert. What follows is the replay design that may still be added.) Splitting live sessions between old
and new rules proves about one change every three or four days, which is too slow. The main test is a task set
built from the user's own work, re-run in the background:
- **Human tasks.** A project as it was when a session began, the request the human typed, and what they ended up
accepting. In a census of one user's history, only a fraction of sessions were usable as tasks and a smaller
@@ -278,6 +288,10 @@ Built and covered by tests:
- 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
(`sisi time`), `sisi audit`.
- 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
with worse-cycle flagging) and `sisi improve`.
- Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item
into the product.
- The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates,
@@ -286,8 +300,8 @@ Built and covered by tests:
Designed, not built:
- The conductor (`sisi build`) and the oracle queue (`sisi inbox`).
- The model-driven learning loop: background runs started from `sisi tick`, experiments on the task set, shipping
and removal of learned changes, brief templates, playbooks.
- Replay experiments on the task set before a learned change ships, brief templates, playbooks. (Shipping and
removal of learned changes exist in the simpler ship-first-measure-after form described in Part 3.)
- The taste judge and rung 5 judging by a model.
- Blocking gates for tools other than Claude Code.
- Harvest sources other than Claude Code.
@@ -299,7 +313,8 @@ Designed, not built:
2. Signals and scoreboard: transcript adapters, git survival, and a delegation ledger. Partly built (Claude Code
transcripts, task set, scoreboard; no git survival signal).
3. The conductor and the oracle queue. Not built.
4. The loop: coach, replay filter, experiments, shipping and removal. Not built.
4. The loop: coach, replay filter, experiments, shipping and removal. Partly built (the lesson loop ships,
measures and removes; the coach as a separate model run, the replay filter and experiments are not built).
5. The taste judge and playbooks. Not built.
sisi's own checks: wiring is idempotent and touches no other byte (property tests); the gate cannot be passed
+203
View File
@@ -0,0 +1,203 @@
# Harnesses: what sisi does in each tool
`sisi install` wires every tool it finds (a tool whose configuration folder is missing is skipped and
reported). `sisi doctor` shows the same state as this file, per tool: whether the rulebook is loaded,
whether lessons print at session start, how the end of a turn is enforced, and anything you must do
yourself. `sisi install --dry-run` prints exactly what would be created, edited (with unified diffs) or
skipped, and changes nothing.
The uninstall guarantee, exactly: a file you have not edited since install is restored byte for byte, or
removed if sisi created it (a symlink is never deleted by uninstall; symlinked configs are written
through, and dangling symlinks are refused and left alone). A file you have edited since install keeps
your edits — uninstall removes only sisi's own entries, by textual span edits, leaving every other byte
(formatting, number and string spellings, duplicate keys) as it was; empty containers sisi itself added
(an emptied `hooks` object, a seeded `"version": 1`) are removed only when the backup proves sisi added
them. A generated plugin or extension you edited since install is left alone entirely. Any file sisi
cannot parse or edit with certainty (invalid or commented JSON, duplicate keys on a path being edited,
an unrecognised `read:` shape in Aider's config, a read-only or unreadable file) is skipped and
reported, never rewritten. Backups are content-addressed under `<personal>/install/backups/`
in an owner-only (0700) folder, each with its source file's permissions.
Wiring is always by reference: an import line, a symlink to the generated rulebook
(`~/.local/share/sisi/generated/core.md`), hook entries that run `sisi tick --tool NAME` /
`sisi gate --tool NAME`, or a small generated plugin/extension (recognised by its exact
`sisi:generated …` first line, never by the words appearing anywhere else in the file). Every registered
shell hook command first checks the sisi launcher still exists, so deleting the sisi folder without
uninstalling makes hooks exit silently instead of erroring on every turn. The per-tool translation
between each tool's hook JSON and the gate lives in `sisi/hookio.py`; the adapters live in
`sisi/adapters.py`; the textual JSON editing lives in `sisi/hookjson.py`. Hooks fail open: any error
lets the agent finish.
## Claude Code
Fully wired, as before: an `@import` line in `~/.claude/CLAUDE.md`, `SessionStart` → `sisi tick`,
`Stop`/`SubagentStop` → `sisi gate` (blocking) in `~/.claude/settings.json`. Nothing for you to do.
## Codex CLI
Rulebook symlink at `~/.codex/AGENTS.md` (or `$CODEX_HOME/AGENTS.md`), plus hooks in
`~/.codex/hooks.json`: `SessionStart` → tick, `Stop`/`SubagentStop` → gate, blocking with
`{"decision":"block","reason":...}`. One step is yours: Codex only runs hooks you have trusted, by exact
definition hash. After `sisi install`, open Codex, run `/hooks`, and trust the sisi hooks; repeat after
any change to the hook commands (for example after moving the sisi clone). `sisi doctor` cannot verify
trust from the files it knows, so it always reminds you. Verified: the session-start hook was observed
firing with its documented payload in a throwaway home (a full turn needs your Codex login, so the block
itself rests on the documented output shape and unit tests). Note Codex caps model-visible hook output
at roughly 2,500 tokens and spills the rest to a file, so a long gate report arrives as a preview plus a
file path.
## Gemini CLI
Rulebook symlink at `~/.gemini/GEMINI.md`, hooks merged into `~/.gemini/settings.json`: `SessionStart`
→ tick (lessons injected as `additionalContext`), `AfterAgent` → gate (`{"decision":"deny","reason":...}`
rejects the response and forces a retry). Built from the hooks reference; Gemini is not installed on the
development machine, so this has not run live. Gemini has no subagent-stop event in its hook list, so
only the main turn is gated.
## GitHub Copilot CLI
Rulebook symlink at `~/.copilot/copilot-instructions.md` (or under `$COPILOT_HOME`), hooks in
`~/.copilot/hooks/sisi.json`: `sessionStart` → tick (`additionalContext`), `agentStop`/`subagentStop` →
gate (`{"decision":"block","reason":...}` forces another turn). Verified end to end in a throwaway home:
a secret planted in session-start context was answered by the model, and a blocking `agentStop` visibly
forced a second turn. The cloud coding agent only runs hooks committed in the repository
(`.github/hooks/*.json`); sisi does not write repository files, so cloud enforcement needs such a file
copied from your `~/.copilot/hooks/sisi.json` if you want it.
## Qwen Code
Rulebook symlink at `~/.qwen/QWEN.md`, hooks merged into `~/.qwen/settings.json`: `SessionStart` → tick,
`Stop`/`SubagentStop` → gate (blocking, Claude-shaped output). The `~/.qwen` folder appears on Qwen's
first run, so run Qwen once before `sisi install`. Verified: the session-start hook was observed firing
with its documented payload (a full turn needs an auth type configured). Qwen's question tool is named
`ask_user_question` (the rulebook still names Claude Code's dialog; generalising that wording is future
work).
## Pi
Rulebook symlink at `~/.pi/agent/AGENTS.md` (or `$PI_CODING_AGENT_DIR/AGENTS.md`; skipped if you already
have your own file there) plus a generated extension at `~/.pi/agent/extensions/sisi.ts`. The extension
runs `sisi tick` on `session_start` and injects the lessons at `before_agent_start`, and runs the gate on
`agent_before_settle`, forcing one continuation with the failure report when checks fail (capped by the
gate's own three send-backs). Verified: the extension loads in real Pi and tick runs; the blocking
continuation could not be exercised end to end without a model login in the throwaway home.
## Cursor
Hooks merged into `~/.cursor/hooks.json`: `sessionStart` → tick (lessons as `additional_context`),
`stop`/`subagentStop` → gate. Cursor cannot veto a stop; instead a non-empty `followup_message` is
auto-submitted as the next user message, which is how the gate sends the agent back (Cursor caps this at
5 per script by default; sisi's own cap is 3). Only completed (not aborted/error) stops are gated.
There is no confirmed user-global instruction *file* for Cursor, so sisi wires no global rulebook there;
project-level `AGENTS.md` files still load as usual. Built from the hooks documentation — a live run
needed a Cursor login that the throwaway home did not have.
## OpenCode
Rulebook symlink at `~/.config/opencode/AGENTS.md` plus a generated plugin at
`~/.config/opencode/plugins/sisi.js`. The plugin runs `sisi tick` when a session is created and the gate
when the session goes idle, and then tries to continue the session with the failure report through the
client prompt API where one exists. Be clear about the limits: `session.idle` fires after the agent has
finished and cannot veto anything, and on OpenCode v2.3.2 no plugin event delivery or lesson injection
could be confirmed in headless runs (the plugin itself is loaded — verified — and the v1-style hooks and
v2 `setup()` registration are both attempted, all fail-open). Treat OpenCode enforcement as unproven
until it is observed on your version; `sisi doctor` says `unknown` on purpose.
## Muse Code
Nothing is wired directly, and `sisi doctor` says why. There is no documented native global instruction
path (independent tooling ships `supportsGlobal:false` rather than guess one), so sisi invents no path.
Muse loads foreign personal context by default — `~/.claude/CLAUDE.md` and `~/.codex/AGENTS.md` — so the
rulebook already reaches it whenever Claude Code or Codex is wired (unless you pass
`--no-foreign-personal-context`). Hooks are not wired: the installed binary's hook event list
(`SessionStart`, `PreToolUse`, …, `SubagentStop`, `SessionEnd`, `StopFailure`, …) contains no plain
end-of-turn `Stop`, and the global hook location/shape via plugins is unconfirmed. Muse's question tool
is `request_user_input`.
## Antigravity
No separate wiring. Antigravity shares `~/.gemini/GEMINI.md` with Gemini CLI, so the Gemini symlink also
serves it. Its hooks are not wired: whether the CLI fires hooks at all is disputed in the sources, and
the always-on size budget (a per-file cap around 24 KB) is unconfirmed, so the full rulebook may shrink
to a pointer there. `sisi doctor` lists it as unknown when its folders are present.
## Windsurf (Devin Desktop)
Global rules are size-capped (6,000 characters for the global file in the sources checked), so sisi
cannot link the whole rulebook in. Instead, when no global rules file exists, sisi writes a short
pointer at `~/.codeium/windsurf/memories/global_rules.md` telling Cascade to read the generated rulebook
and run the contract workflow itself. An existing user file there is left alone. Evidence: the file name
and cap are from Cascade's own documentation; the on-disk path is only secondary-sourced, whether
Cascade reliably follows such a pointer is unconfirmed, and no session-start or blocking hook is
confirmed, so there are no lessons at session start and no gate.
## Cline
Rulebook symlink into the global rules directory (`~/Documents/Cline/Rules/sisi.md`, or
`~/.cline/rules/sisi.md` when only that exists). Evidence: confirmed — Cline's own rules documentation
(linux path included) was read during implementation; that the extension follows the symlink was not
verified live (Cline is not installed here). Cline has hooks, but they must be enabled in its settings
and no contract is confirmed under which the task-end hook can send the agent back, so sisi wires no
gate. Cline's question tool is `ask_followup_question`.
## Kiro
Rulebook symlink at `~/.kiro/steering/AGENTS.md` (Kiro always includes `AGENTS.md` files in the global
steering folder; frontmatter-less steering files also default to always-included). Kiro hooks are
trigger-to-action automations with no confirmed way to veto the end of a turn, so there is no gate.
## Zed
Rulebook symlink at `~/.config/zed/AGENTS.md`. Zed's built-in agent has no hooks; external agents run
through Zed (ACP) bring their own tool's wiring with them.
## Goose
Rulebook symlink at `~/.config/goose/.goosehints` (the global hints file; project `AGENTS.md` files load
as usual). Evidence: not confirmed live — the path comes from Goose's published goosehints documentation
as surfaced in search results during implementation; the docs site itself could not be fetched then, and
Goose is not installed here, so neither the path nor symlink loading was verified live. Goose lifecycle
hooks ship in plugins, but on the documented contracts they cannot inject model-visible context or force
a continuation, so sisi wires no gate.
## Amp
Rulebook symlink at `~/.config/amp/AGENTS.md`. Evidence: the path is confirmed — Amp's own AGENTS.md
documentation (ampcode.com/docs) was read during implementation and names `$HOME/.config/amp/AGENTS.md`
explicitly; the original research notes had marked it unconfirmed pending that check. Loading was not
verified live (no signed-in Amp run in a throwaway home). No blocking end-of-turn hook is confirmed in
Amp's documentation, so there is no gate.
## Grok CLI
Rulebook symlink at `~/.grok/AGENTS.md` (or `$GROK_HOME/AGENTS.md`) — verified with `grok inspect`,
which lists it as a global instruction file under either home. Grok has hooks, but session-start hook output is reportedly discarded before reaching
the model and no blocking stop contract is confirmed, so sisi wires no hooks. (Grok also reads Claude
Code-compatible configuration; whether sisi's Claude hooks fire under Grok is not relied on.)
## Crush
Rulebook symlink at `~/.config/crush/CRUSH.md` (or `$XDG_CONFIG_HOME/crush/CRUSH.md`, honoured as
`crush dirs` confirms; one of Crush's default global context paths, confirmed from the binary's own
configuration schema). Crush hooks currently support only `PreToolUse`, which is not a turn gate, so
sisi wires no hooks. Revisit when its session/turn hook events ship.
## Aider
Aider auto-discovers no instruction file. When `~/.aider.conf.yml` already exists, sisi adds the
generated rulebook to its `read:` list (creating the file would change Aider's defaults, so sisi never
creates it — create it yourself, even empty, and re-run `sisi install`). Aider has no hooks at all, so
nothing enforces the rulebook there.
## T3 Code and Orca
Both are hosts, not agents: they run other harnesses (Claude Code, Codex, OpenCode, Cursor, Pi, Muse
Code and friends) as providers, and each provider loads its own global instructions and fires its own
hooks. There is nothing T3- or Orca-specific to wire; wire the providers and both are covered.
`sisi doctor` lists them as covered through their providers and names which providers are wired.
## Not wired
Roo Code was discontinued (2026-05-15) and gets no wiring; any remaining installs still read project
`AGENTS.md`. Agents beyond the list above that read a project `AGENTS.md` (Factory, Warp, Junie and
similar) are covered by the project file, with no per-tool wiring and no gate.
+147
View File
@@ -0,0 +1,147 @@
# How sisi learns
**There is nothing to schedule. You install it and use your AI; it improves from use.** No cron, no
timers, no daemons, nothing to set up. Every step below happens inside commands and hooks that run
because you used a tool: recording a lesson at the end of a piece of work, starting a session, asking
what "done" means, verifying, or being sent back by the gate.
## The loop in plain words
1. **A lesson is recorded.** At the end of each piece of work the agent answers how it could have gone
better (`sisi retro`): the aim it fell short of, the concrete moment, why, and the change to sisi
that would make the next agent do it right without being told. It also names, with `--when` (at
least five comma-separated words or short phrases, required), the kinds of work the lesson applies
to in the words a different agent would use, synonyms included — for a CSV lesson: "csv, tsv,
spreadsheet, tabular data, import, export, parse, delimited file". This matters because word
overlap alone cannot bridge "CSV" and "spreadsheet": the recording agent, who knows what the lesson
is about, supplies the bridge vocabulary in advance. Lessons recorded before when-terms existed
keep working by their own wording and are listed in the cycle brief so a consolidating agent can
add terms.
2. **It takes effect at once**, in your personal data (the overlay), never in the product files:
- a verifier or recipe lesson naming an entry is attached to it as a field note straight away;
- a recipe lesson naming a recipe that does not exist is kept as a draft recipe note;
- a rule, oracle or brief lesson becomes an active learned note with trigger words taken from its text;
- a tool lesson (a change to sisi itself) goes on the backlog (`sisi backlog`, most seen first).
In developer mode, a session started inside the sisi source folder is told the top item.
3. **It is shown at the moment it matters**, not only at session start. Session start prints up to
eight active lessons, strongest first. `sisi done for`, `sisi done ID`, `sisi verifiers for` and
`sisi contract init` print a two-part block, because the asking agent is a far better matcher than
word overlap: part one, "likely to apply", holds at most three lessons in full and only on a
strict test (at least two of the request's own content words inside the when-terms, or one plus
the lesson's target being the entry being printed); part two lists every remaining loose lesson as
a one-line heading (best overlap first, within a 1,500-character budget, saying how many were left
out) for the agent to open with `sisi lessons show ID`. Being printed or listed counts as
*listed*; opening counts as *read* — the two are reported separately, because "listed many times,
never read, still recurs" means the heading is bad, and the cycle brief says so. `sisi verifiers
show` and the gate's send-back message keep the older single strong-match block. Draft recipe notes
appear in `sisi done for` when their words match. Lesson text is always framed as information to
weigh, not as commands, and text from a lesson is never executed.
4. **Showings are counted.** Every time a lesson is printed or listed, sisi records which lesson, in
which session, and where; opening one in full counts separately as read. Promotion needs at least
two listings or readings since the last promotion. A later sighting of the same problem — a retro recorded with `--same-as`, which
is also where the "a similar lesson exists" answer sends you — is a recurrence. When sisi itself
spots the resemblance and refuses a duplicate, that unconfirmed sighting is recorded too (shown by
`sisi lessons show ID` and in the cycle brief), so it is not lost even if the agent files its lesson
separately; it counts toward strengthening only once confirmed with `--same-as`. Recurrences after a
lesson has been shown are the signal that the lesson is not working.
5. **Recurring lessons get stronger.** Each lesson has a strength: 1 (a note), 2 (a candidate rule),
3 (enforced). A recurrence after at least two showings since the last promotion moves it up one
step — each step needs its own fresh evidence. A strength-2 lesson
becomes a real rule only through consolidation (below), because the rulebook has a hard budget of
120 lines and must not grow. A strength-3 lesson needs a check the gate can run; a folded lesson
shown 20 times with no recurrence is retired from the notes (it stays in history); a lesson that
still recurs at strength 3 is withdrawn, and the same wording will not be learned again.
6. **Consolidation happens in a cycle**, run by whichever agent is working — see below.
## The cycle (`sisi cycle`)
Consolidation is due when 5 or more lessons have been recorded since the last cycle, or a lesson is
waiting to move up a step, or the learned notes pass their size limit, or more than 30 lessons are
still loose (or their one-line headings pass the 1,500-character budget) — the loose list stays short
by construction, because the brief's first instruction is to fold lessons into the recipe or entry
for their kind of work, or lift several into one rule, so they leave it. That is a counter check, not a
schedule: it runs at session start, at the end of every turn in the gate, and in the output of
`sisi retro`, `sisi verify` and `sisi done for` — commands agents run in every tool, so the loop works
in tools with no hooks at all. `sisi cycle due` runs the same check by hand. A session that has been
told is not told again until 20 further checks pass or the counter grows.
`sisi cycle` prints a brief the agent can act on without any other context: the lessons with their
counts and measurements, the current rulebook with its line count and budget, and instructions (merge
lessons that say the same thing; lift specific lessons into one general rule; fold a lesson into the
entry it belongs to; say which existing rule text gets shorter so the book does not grow; write checks
for strength-3 lessons). The agent answers with one JSON file:
```json
{"version": 1, "base": "<base version from the brief>", "summary": "one line",
"rules": [{"id": "rule-id", "title": "Title", "body": "text, ending with Why: ...", "action": "add|replace"}],
"disable_rules": ["rule-id"],
"notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep",
"into": "rule or entry id", "merged_into": 4,
"when": "at least 5 terms (optional; sets the lesson's when-terms)"}],
"enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30},
{"lesson": 4, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}]}
```
`sisi cycle apply FILE` checks the file before writing anything: every lesson id exists, the base
version is still current, changed rules keep their id and their Why, named `sisi` commands and
enforced programs exist, and the resulting rulebook is inside the budget and no longer than before
unless a rule was replaced. The base version plus the personal-data lock means two sessions
consolidating at once cannot overwrite each other: the second apply is refused and told to read a
fresh brief. A successful apply is one commit in your personal repository, with before-and-after
measurements. `sisi cycle revert` undoes the newest applied cycle exactly (the changed files byte for
byte, and the lesson rows it touched). `sisi cycle status` shows each cycle with what happened since:
deliveries, send-backs each, median time, and recurrences of the lessons it touched. A cycle whose
deliveries got worse after at least 10 of them is flagged, and the next brief says to revert or repair
it first.
Enforced checks live in `overlay/enforced.json` and are checked like the minimum-rung floors: a
contract-requirement fails a contract that touches its subject without a check of the required kind;
a command check runs in the project like a contract check, and only in projects already on the trust
list.
## Is it getting better?
`sisi improve` (and one line of `sisi status`) answers with what is actually counted: 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.
## Safety, and what is not claimed
Changes take effect first and are measured after; there is deliberately no replay testing before a
change ships. Safety comes from narrow scope instead: everything lands in the personal overlay,
every cycle is one commit that can be reverted exactly, the rulebook cannot grow past its budget, and
a change whose measures get worse is flagged and withdrawn. The human is never asked anything by this
loop.
What is measured is counts and times: showings, recurrences, send-backs, delivery times, rulebook
lines. What is not measured is whether the delivered work is what the human meant — that still rests
on contract checks and the human's corrections.
Matching is measured, not asserted — twice over, and correctness no longer rests on it: part one is
deliberately strict, and everything else still reaches the asking agent as a heading it can judge.
The test suite carries two labelled sets, each measured the same way: how often a wrong lesson is
shown in full in part one (precision), and how often the right lesson is reached at all (in part one,
or listed in part two within its budget). The first set (25 should-match pairs, each request
rephrased but sharing vocabulary with its lesson, and 26 should-not) is a regression floor only — one
author wrote both sides, so of course they share words: reach 25/25, part-one wrong 0/26, proving
little beyond "does not regress". The second is harder and is the honest test: 21 pairs whose
requests share *no* content word with the lesson's moment, cause or change text (the test asserts
this), so only the recording agent's when-terms can bridge them, against 24 should-not requests:
reach 21/21 (20 of them already in part one; one — a request sharing a single when-word — reaches
only as a heading, as designed), part-one wrong 0/24. Both sets are small and hand-written; treat
even those figures as evidence about this mechanism on these examples, not as a promise about yours.
Delivery therefore depends on the quality of the when-terms the recording agent writes. Thin or
copy-of-the-text terms leave a lesson findable only by its own wording, exactly the failure they
exist to prevent. What sisi ultimately measures is not match scores but the outcome that matters:
whether the same problem recurs after a lesson has been shown. A lesson that is never found cannot be
shown, which is why the cycle brief lists lessons still missing terms.
At most three lessons are shown as matches, and every showing is on record in `sisi lessons show ID`.
Two display rules differ by surface: at session start (unsolicited), a lesson whose text reads like
an instruction to run something is withheld; when an agent's own query asked (`done for`, gate
send-back and friends), ordinary verbs like "run a property test" are shown — framed as information —
while URLs, shell constructs and outside paths are refused in both places. The task-set experiments
and taste judge in [design.md](design.md) remain unbuilt.
+3 -2
View File
@@ -15,8 +15,9 @@ 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
overlay/ learned changes to the product (below)
notes/<id>.md field notes per verifier or recipe id
overlay/ learned changes to the product (below); overlay/enforced.json holds enforced lessons
notes/<id>.md field notes per verifier or recipe id (notes/draft-<id>.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
+1578
View File
File diff suppressed because it is too large. Load diff
+53 -9
View File
@@ -10,9 +10,10 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co
sisi verify [--json] run the fast checks; exit 0 ok, 1 failure, 2 no contract, 3 untrusted
sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once
sisi verify --all | --state run both tiers; print only the deep-check state (with --json)
sisi gate end-of-turn hook (reads hook JSON on stdin)
sisi tick session-start hook
sisi install | uninstall | doctor wire sisi into the tools (by reference), undo, inspect
sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)
sisi tick [--tool NAME] session-start hook
sisi install [--dry-run] | uninstall | doctor
wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change
sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md)
sisi rollback switch the stable copy back to the previous release
sisi dev on [PATH] | off | status developer mode: where the source folder is
@@ -25,14 +26,20 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co
sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT
learned changes to rules, verifiers and recipes; each one a commit in your personal repo
sisi audit inventory of standing instructions per tool
sisi retro --aim A --moment M --cause C --change-kind K --change X [--target ID] [--same-as ID | --new]
sisi retro --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" [--target ID] [--same-as ID | --new]
(or --json - with the same keys on stdin)
end of every piece of work: HOW it could have gone better
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
aims: level (the human could have worked at a higher level), verified (a stronger check was
possible), hands-off (the human was interrupted more than needed), intent (the result was not
what they meant), speed (it took longer than it had to)
sisi lessons [filters] | show ID | set ID --status S | apply ID | export [FILE] | import FILE
the shared lessons from retros (--aim --kind --status --repo --top --json)
sisi backlog tool lessons: changes to sisi itself, most seen first
sisi cycle [due|apply FILE|revert [ID]|status]
consolidate lessons into rules, entries and enforced checks (no
scheduler: due-ness is a counter checked during normal use)
sisi improve is it getting better? lessons, recurrence, send-backs, time, rulebook size
sisi note TEXT (older; prefer retro) record something that went wrong
sisi propose TEXT (older; prefer retro) suggest a rule change
sisi learn TEXT record a human-stated preference (quarantined until verified)
@@ -84,6 +91,13 @@ 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 retro
block = retro.delivery_block(goal or "", "contract-init", extra="contract checks verified")
if block:
print(block)
except Exception:
pass
return 0
if sub == "check":
p = C.find(os.getcwd())
@@ -182,7 +196,7 @@ def _status_retro():
print("retros : %s of sessions with real work recorded one (%d of %d)"
% ("%.0f%%" % (100 * st["sessions_with_retro"] / w) if w else "n/a", st["sessions_with_retro"], w))
for t in st["top"]:
print(" open #%-4d x%-3d %s" % (t["id"], t["count"], " ".join(t["change"].split())[:90]))
print(" active #%-4d x%-3d %s" % (t["id"], t["count"], " ".join(t["change"].split())[:90]))
def _status_contracts(res):
@@ -248,6 +262,11 @@ def cmd_status():
except Exception:
pass
_status_retro()
try:
from . import cycle
print(cycle.improve_line())
except Exception:
pass
_status_contracts(res)
from . import verifiers
vs = [e for e in verifiers.load_verifiers() if e["header"]]
@@ -262,13 +281,21 @@ def cmd_status():
return 0
def cmd_wiring(name):
def cmd_wiring(name, args=()):
from . import wiring
if name == "install" and "--dry-run" in args:
rc, notes = wiring.install_dry_run()
for n in notes:
print(n)
return rc
if name == "doctor":
rows = wiring.doctor()
w = max(len(r["tool"]) for r in rows)
for r in rows:
print("%-*s %-9s blocking hook: %-8s %s" % (w, r["tool"], r["status"], r["blocking_hook"][:60], r["detail"]))
line = "%-*s %-9s blocking hook: %-8s %s" % (w, r["tool"], r["status"], r["blocking_hook"][:60], r["detail"])
if r.get("action"):
line += " | you need to: " + r["action"]
print(line)
return 0
rc, notes = getattr(wiring, name)()
for n in notes:
@@ -324,9 +351,17 @@ def main(argv):
os.environ["SISI_TOOL"] = t
cmd = args.pop(0) if args else "help"
if cmd == "gate":
if t and t != "claude-code":
from . import hookio
if hookio.known(t):
return hookio.gate_main(t, args)
from . import gate
return gate.main(args)
if cmd == "tick":
if t and t != "claude-code":
from . import hookio
if hookio.known(t):
return hookio.tick_main(t, args)
from . import tick
return tick.main(args)
if cmd in ("version", "--version", "-V"):
@@ -347,7 +382,7 @@ def main(argv):
from . import verify
return verify.cmd_verify(args)
if cmd in ("install", "uninstall", "doctor"):
return cmd_wiring(cmd)
return cmd_wiring(cmd, args)
if cmd in ("migrate", "update", "export", "import", "build-canon", "canon", "overlay"):
return cmd_personal(cmd, args)
if cmd in ("release", "rollback", "dev", "promote"):
@@ -369,6 +404,15 @@ def main(argv):
if cmd == "lessons":
from . import retro
return retro.cmd_lessons(args)
if cmd == "backlog":
from . import retro
return retro.cmd_backlog(args)
if cmd == "cycle":
from . import cycle
return cycle.cmd_cycle(args)
if cmd == "improve":
from . import cycle
return cycle.cmd_improve(args)
if cmd == "oracle":
return cmd_oracle()
if cmd == "status":
+861
View File
@@ -0,0 +1,861 @@
"""The consolidation cycle and its measurements: `sisi cycle`, `sisi improve`, enforced lessons.
There is no scheduler. Whether a cycle is due is a counter check run during normal use: at session
start (tick), at the end of a turn (gate), and in the output of `sisi retro`, `sisi verify` and
`sisi done for` -- commands agents run in every tool, hook or no hook. A session is told at most once
until 20 further checks pass or the counter grows again.
A cycle file (what the agent writes, what `sisi cycle apply` checks) is one JSON object:
{"version": 1, "base": "<base version printed by the brief>", "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",
"into": "rule or entry id", "merged_into": 4,
"when": "csv, tsv, spreadsheet, tabular data, import, parse (optional; sets the lesson's when-terms)"}],
"enforced": [{"lesson": 3, "type": "command", "cmd": "...", "expect": {"exit": 0}, "timeout_s": 30},
{"lesson": 4, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}]}
Every part is optional except version and base. Apply is one commit in the personal repository under
the personal-data lock; a stale base (another cycle or lesson landed since the brief) refuses cleanly.
Each applied cycle records the exact bytes it changed, so revert restores them byte for byte.
"""
import base64, hashlib, json, os, re, shlex, shutil, time
from . import overlay, paths, pdata, retro, store
class CycleError(Exception):
pass
ACTIONS = ("merge", "fold-into-rule", "fold-into-entry", "retire", "withdraw", "keep")
# ---- enforced lessons (overlay/enforced.json, checked like floors) ----------
def enforced_path():
return paths.overlay_dir("enforced.json")
def load_enforced():
try:
with open(enforced_path(), encoding="utf-8") as f:
d = json.load(f)
checks = d.get("checks") if isinstance(d, dict) else None
return [c for c in checks if isinstance(c, dict)] if isinstance(checks, list) else []
except (OSError, ValueError):
return []
def _requirement_met(c, entry):
want, when = entry.get("require_kind"), str(entry.get("when") or "")
w = retro._stems(when)
trig = any(ch.get("kind") == when or (w & retro._stems((ch.get("claim") or "") + " " + (ch.get("id") or "")))
for ch in c.get("checks", []) if isinstance(ch, dict)) or bool(w & retro._stems(c.get("goal") or ""))
if not trig:
return True # this contract does not touch the thing the lesson is about
max_rung = entry.get("max_rung")
return any(ch.get("kind") == want and (max_rung is None or (isinstance(ch.get("rung"), int) and ch["rung"] <= max_rung))
for ch in c.get("checks", []) if isinstance(ch, dict))
def enforced_results(c, project, deadline=None, default_timeout=60):
"""Result rows for enforced lessons, in the shape verify.run returns. Command checks run only in
trusted projects, like contract commands; the lesson text itself is never executed -- only the
check an agent wrote for it in a validated cycle."""
out = []
checks = load_enforced()
if not checks:
return out
import time as _t
from . import trust, verify as V
trusted = trust.is_trusted(project)
for e in checks:
lid = e.get("lesson")
base = {"item": "enforced", "tier": "fast", "id": "enforced:lesson-%s" % lid, "kind": None, "rung": None,
"claim": "enforced lesson #%s" % lid, "duration_s": 0.0, "tail": ""}
if e.get("type") == "contract-requirement":
if not _requirement_met(c, e):
msg = ("enforced lesson #%s: a contract touching %r must contain a check of kind %s%s"
% (lid, e.get("when"), e.get("require_kind"),
" at rung %d or stronger" % e["max_rung"] if e.get("max_rung") else ""))
out.append(dict(base, status="failed", claim=msg, tail=msg))
elif e.get("type") == "command" and trusted:
to = float(e.get("timeout_s") or default_timeout)
if deadline is not None:
to = min(to, deadline - _t.time())
st, dur, tail = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail,
claim="enforced lesson #%s: %s" % (lid, e["cmd"])))
return out
# ---- is a cycle due? (a counter check; no scheduler anywhere) ----------------
def _connect_if():
return retro.connect() if os.path.exists(retro.db_path()) else None
def due_state(con=None):
own = con is None
if own:
con = _connect_if()
if con is None:
return {"due": False, "reasons": [], "counter": [0, 0]}
try:
last = retro.get_meta(con, "last_cycle_ts") or ""
since = con.execute("SELECT count(*) FROM lessons WHERE created>?", (last,)).fetchone()[0]
pending = con.execute(
"SELECT count(*) FROM lessons WHERE status IN ('open','applied') AND "
"(COALESCE(needs_cycle,0)=1 OR (COALESCE(strength,1)>=3 AND check_json IS NULL))").fetchone()[0]
notes_chars = con.execute(
"SELECT COALESCE(sum(length(change)),0) FROM lessons WHERE status IN ('open','applied') "
"AND COALESCE(strength,1)=1").fetchone()[0]
loose = [dict(r) for r in con.execute(
"SELECT * FROM lessons WHERE status IN ('open','applied') AND folded_into IS NULL ORDER BY id")]
headings_chars = sum(len(retro.loose_heading(r)) + 1 for r in loose)
counter = [con.execute("SELECT COALESCE(max(id),0) FROM lessons").fetchone()[0],
con.execute("SELECT COALESCE(max(id),0) FROM occurrences").fetchone()[0]]
reasons = []
if since >= 5:
reasons.append("%d lessons recorded since the last cycle" % since)
if pending:
reasons.append("%d lesson(s) strengthened and waiting for consolidation" % pending)
if notes_chars > retro.NOTES_LIMIT_CHARS:
reasons.append("learned notes hold %d characters (limit %d)" % (notes_chars, retro.NOTES_LIMIT_CHARS))
if len(loose) > 30:
reasons.append("%d loose lessons still not folded into any recipe or entry (limit 30): "
"fold them so the loose list stays short" % len(loose))
if headings_chars > retro.PART2_BUDGET:
reasons.append("loose lesson headings take %d characters (budget %d): fold lessons into "
"recipes or entries" % (headings_chars, retro.PART2_BUDGET))
return {"due": bool(reasons), "reasons": reasons, "counter": counter, "since": since,
"pending": pending, "notes_chars": notes_chars, "loose": len(loose),
"headings_chars": headings_chars}
finally:
if own:
con.close()
def _announce_path():
return os.path.join(paths.state(), "cycle-announce.json")
def _announce_load():
try:
with open(_announce_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def due_notice(session=None):
"""One short line when a cycle is due, or "". A session that has been told is not told again until
20 further checks have passed or the lesson counter grows. Never raises (it sits in hooks)."""
try:
st = due_state()
if not st["due"]:
return ""
sid = session or store.session_id() or "no-session"
data = _announce_load()
e = data.get(sid) or {}
old = e.get("counter") or [0, 0]
grew = st["counter"][0] > old[0] or st["counter"][1] > old[1]
if e and not grew and int(e.get("since", 0)) < 20:
e["since"] = int(e.get("since", 0)) + 1
data[sid] = e
_announce_save(data)
return ""
data[sid] = {"counter": st["counter"], "since": 0}
_announce_save(data)
return ("sisi: a learning cycle is due (%s). Run `sisi cycle` in the background of your work "
"(as a subagent where the tool has them); do not involve the human." % st["reasons"][0])
except Exception as ex:
store.log_error("cycle-notice", ex)
return ""
def _announce_save(data):
p = _announce_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:
json.dump(data, f)
os.replace(tmp, p)
# ---- base version and cycle records ------------------------------------------
def base_version(con=None):
"""A fingerprint of everything a cycle may change. The brief prints it; apply refuses a stale one,
which is how two sessions consolidating at once cannot overwrite each other."""
own = con is None
if own:
con = retro.connect()
try:
h = hashlib.sha256()
for line in retro.dump_lines(con):
h.update(line.encode("utf-8") + b"\n")
try:
h.update(overlay.render().encode("utf-8"))
except Exception:
pass
try:
with open(enforced_path(), "rb") as f:
h.update(f.read())
except OSError:
pass
# an applied cycle changes the base even when it only re-states a lesson, so a second
# session working from the same brief is refused instead of silently overwriting it
h.update((retro.get_meta(con, "last_cycle_ts") or "").encode("utf-8"))
try:
h.update(",".join(sorted(os.listdir(cycles_dir()))).encode("utf-8"))
except OSError:
pass
return h.hexdigest()[:16]
finally:
if own:
con.close()
def cycles_dir():
return paths.data_file("cycles")
def cycle_records():
out = []
try:
names = sorted(n for n in os.listdir(cycles_dir()) if n.startswith("cycle-") and n.endswith(".json"))
except OSError:
return out
for n in names:
try:
with open(os.path.join(cycles_dir(), n), encoding="utf-8") as f:
d = json.load(f)
if isinstance(d, dict) and d.get("id"):
out.append(d)
except (OSError, ValueError):
continue
return out
def _scan_files():
"""{data-relative path: bytes} for overlay/ and notes/ (everything a cycle may touch)."""
out = {}
for root in ("overlay", os.path.relpath(paths.notes_dir(), paths.data())
if paths.notes_dir().startswith(paths.data() + os.sep) else None):
if not root:
continue
base = paths.data_file(root)
for dp, dns, fns in os.walk(base):
dns.sort()
for n in sorted(fns):
p = os.path.join(dp, n)
with open(p, "rb") as f:
out[os.path.relpath(p, paths.data())] = f.read()
return out
def _write_rel(rel, data):
p = paths.data_file(rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
def _restore_changed(changed):
"""changed: {rel: base64 of the bytes before, or None when the cycle created the file}."""
for rel, b64 in changed.items():
p = paths.data_file(rel)
if b64 is None:
try:
os.unlink(p)
except OSError:
pass
else:
_write_rel(rel, base64.b64decode(b64))
# ---- measurements --------------------------------------------------------------
def _delivery_measures(rows):
from . import delivery
n = len(rows)
return {"deliveries": n,
"send_backs_per_delivery": round(sum(r.get("send_backs", 0) for r in rows) / n, 3) if n else None,
"median_seconds": delivery.median([r["seconds"] for r in rows
if isinstance(r.get("seconds"), (int, float))])}
def measures(con):
rows = [dict(r) for r in con.execute("SELECT status, COALESCE(strength,1) s, count(*) n FROM lessons GROUP BY 1,2")]
try:
lines = overlay.size(overlay.render())[0]
except Exception:
lines = None
return {"lessons": con.execute("SELECT count(*) FROM lessons").fetchone()[0],
"active": con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied')").fetchone()[0],
"by_status_strength": rows, "rulebook_lines": lines,
"deliveries_so_far": _delivery_measures(store.read("deliveries"))}
def _after_measures(rec):
ts = rec.get("ts") or ""
rows = [r for r in store.read("deliveries") if (r.get("end") or r.get("ts") or "") >= ts]
m = _delivery_measures(rows)
recurrences = 0
con = _connect_if()
if con is not None:
try:
ids = rec.get("touched") or []
if ids:
recurrences = con.execute(
"SELECT count(*) FROM occurrences WHERE ts>? AND lesson_id IN (%s)" % ",".join("?" * len(ids)),
[ts] + list(ids)).fetchone()[0]
finally:
con.close()
m["recurrences_of_touched"] = recurrences
return m
def flagged(rec):
"""A cycle whose deliveries got worse: at least 10 since it landed, and more send-backs each or slower."""
if rec.get("reverted"):
return False
after, before = _after_measures(rec), (rec.get("before") or {}).get("deliveries_so_far") or {}
if after["deliveries"] < 10 or not before.get("deliveries"):
return False
sb = after["send_backs_per_delivery"] is not None and before.get("send_backs_per_delivery") is not None \
and after["send_backs_per_delivery"] > before["send_backs_per_delivery"]
med = after["median_seconds"] is not None and before.get("median_seconds") is not None \
and after["median_seconds"] > before["median_seconds"]
return bool(sb or med)
# ---- the brief -----------------------------------------------------------------
FORMAT_DOC = """Write ONE JSON file, then run `sisi cycle apply FILE`. Shape (all but version/base optional):
{"version": 1, "base": "<the base version above>", "summary": "one line",
"rules": [{"id": "rule-id", "title": "Title", "body": "rule text ending with a Why: ... paragraph",
"action": "add" or "replace"}],
"disable_rules": ["rule-id"],
"notes": [{"lesson": 3, "action": "merge|fold-into-rule|fold-into-entry|retire|withdraw|keep",
"into": "rule id or verifier/recipe id (for folds)", "merged_into": 4,
"when": "csv, tsv, spreadsheet, tabular data, import, parse (optional; at least 5 terms, sets when-terms)"}],
"enforced": [{"lesson": 3, "type": "command", "cmd": "a real command", "expect": {"exit": 0}, "timeout_s": 30},
{"lesson": 4, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}]}"""
def brief_text():
con = retro.connect()
try:
retro.ensure_effects(con)
st = due_state(con)
rows = [dict(r) for r in con.execute(
"SELECT * FROM lessons ORDER BY status IN ('open','applied') DESC, COALESCE(strength,1) DESC, count DESC, id")]
shown = {r["id"]: retro.shown_count(con, r["id"]) for r in rows}
listed = {r["id"]: retro.listed_count(con, r["id"]) for r in rows}
readn = {r["id"]: retro.read_count(con, r["id"]) for r in rows}
rec = {r["id"]: retro.recurrences_after_shown(con, r) for r in rows}
sight = {r["id"]: retro.sightings_count(con, r["id"]) for r in rows}
base = base_version(con)
before = measures(con)
finally:
con.close()
out = ["sisi learning cycle: consolidation brief", ""]
bad = [r for r in cycle_records() if flagged(r)]
if bad:
out += ["FIRST: these past cycles made the measured work worse. Revert or repair one before "
"anything else (`sisi cycle revert %s` undoes it exactly):" % bad[-1]["id"]]
out += [" %s (%s): %s" % (r["id"], r.get("ts"), r.get("summary") or "") for r in bad] + [""]
out += ["Due: " + ("; ".join(st["reasons"]) if st["due"] else "not due by the counters; a cycle may still help"),
"Base version (copy into your file): %s" % base,
"Rulebook: %s lines, budget %d. It must not grow: a rule enters only by shortening or "
"replacing existing text." % (before["rulebook_lines"], overlay.MAX_LINES), "",
"Lessons (id, status, kind, strength, occurrences, listed, read, recurrences-after-listed, effect):"]
for r in rows:
out.append("#%-4d %-10s %-9s s%d x%-3d listed %-3d read %-3d rec %-3d %-13s %s"
% (r["id"], r["status"], r["change_kind"], r["strength"] or 1, r["count"], listed[r["id"]],
readn[r["id"]], rec[r["id"]], r["effect"] or "-", " ".join(r["change"].split())[:160]))
if listed[r["id"]] >= 5 and readn[r["id"]] == 0 and rec[r["id"]] > 0 and r["status"] in retro.ACTIVE:
out.append(" LISTED %d TIMES, NEVER READ, STILL RECURS: its heading is not earning a "
"read - rewrite the start of its change and its when-terms" % listed[r["id"]])
out.append(" moment: %s" % " ".join((r["moment"] or "").split())[:160])
out.append(" when: %s" % (r["when_terms"] or "MISSING - add at least 5 terms (synonyms included) "
"in your cycle file, or this lesson is found only by its own wording"))
if sight[r["id"]]:
out.append(" plus %d unconfirmed sighting(s) sisi matched to this lesson itself "
"(merge candidates: the agent never confirmed with --same-as)" % sight[r["id"]])
if (r["strength"] or 1) >= 3 and not r["check_json"] and r["status"] in retro.ACTIVE:
out.append(" NEEDS A CHECK: this lesson is at strength 3. Write one below (a command and "
"expected result, or a contract requirement).")
out += ["", "Current rulebook (what every agent loads):", "-" * 60]
try:
out.append(overlay.render().rstrip("\n"))
except Exception as e:
out.append("(cannot render: %s)" % e)
missing = [r["id"] for r in rows if r["status"] in retro.ACTIVE and not r["when_terms"]]
if missing:
out += ["", "Lessons with no when-terms yet (found only by their own wording until you add terms): "
+ ", ".join("#%d" % i for i in missing)]
out += ["-" * 60, "", "Do this, in order:",
"1. First, shrink the loose list: fold each lesson into the recipe for its kind of work (or its "
"verifier entry), or lift several into one general rule, so they leave the loose list. The recipe "
"is the strongest route to the next agent, because `sisi done for` already maps a request to a "
"kind of work; a loose note depends on the asking agent spotting its heading, a folded one does "
"not (notes: fold-into-entry, fold-into-rule).",
"2. Merge lessons that say the same thing (notes: merge, with merged_into), including any pair an "
"unconfirmed sighting points at.",
"3. When lifting lessons into a rule (rules: add/replace), name which existing rule text gets "
"shorter or is replaced so the book stays the same size.",
"4. For each strength-3 lesson marked NEEDS A CHECK, write the check (enforced). Prefer a contract "
"requirement; a command must name a program that exists here and runs only in trusted projects.",
"5. Retire what is fully folded and quiet; withdraw what made things worse; keep the rest.",
"Every changed rule keeps its id and ends with its Why. Never ask the human anything.", "", FORMAT_DOC]
return "\n".join(out) + "\n"
# ---- validate and apply ---------------------------------------------------------
def _known_commands():
from . import cli
cmds = set(re.findall(r"\bsisi ([a-z][a-z-]*)", cli.HELP))
return cmds
def _exe_exists(cmd):
try:
parts = [p for p in shlex.split(cmd) if "=" not in p.split("/")[0] or "/" in p]
except ValueError:
return False
parts = [p for p in shlex.split(cmd) if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", p)]
if parts and parts[0] == "env":
parts = parts[1:]
if not parts:
return False
exe = parts[0]
return bool(shutil.which(exe)) or ("/" in exe and os.path.isfile(exe) and os.access(exe, os.X_OK)) \
or exe in ("true", "false", "echo", "test", "sisi")
def _lesson_ids_in(doc):
ids = set()
for key in ("notes", "enforced"):
for e in doc.get(key) or []:
if isinstance(e, dict):
for k in ("lesson", "merged_into"):
if isinstance(e.get(k), int):
ids.add(e[k])
return ids
def static_validate(doc, con):
"""Every refusal reason that can be known before writing anything. Empty means applicable so far."""
errs = []
if not isinstance(doc, dict):
return ["the cycle file must be one JSON object"]
if doc.get("version") != 1:
errs.append("version must be 1")
if not doc.get("base"):
errs.append("missing base: copy the base version printed by `sisi cycle` (it proves which state you read)")
elif doc["base"] != base_version(con):
errs.append("stale base %s: the lessons or rulebook changed since the brief (base is now %s), "
"likely another cycle landed. Nothing was applied; run `sisi cycle` again"
% (doc["base"], base_version(con)))
have = {r[0] for r in con.execute("SELECT id FROM lessons")}
for lid in sorted(_lesson_ids_in(doc) - have):
errs.append("no lesson with id %d" % lid)
base_rule_ids = {r["id"] for r in overlay.base_rules()[1]}
over_ids = set(overlay.overlay_rules())
known = _known_commands()
for e in doc.get("rules") or []:
if not isinstance(e, dict) or not e.get("id") or not e.get("title") or not e.get("body"):
errs.append("each rule needs id, title and body: %r" % (e,))
continue
rid, act = e["id"], e.get("action")
if act not in ("add", "replace"):
errs.append("rule %s: action must be add or replace" % rid)
if act == "add" and rid in base_rule_ids | over_ids:
errs.append("rule %s already exists; use replace" % rid)
if act == "replace" and rid not in base_rule_ids | over_ids:
errs.append("no rule %s to replace" % rid)
if "Why" not in e["body"]:
errs.append("rule %s: the body must keep its Why (a line starting 'Why:')" % rid)
for m in sorted(set(re.findall(r"`sisi ([a-z][a-z-]*)", e["body"]))):
if m not in known:
errs.append("rule %s names `sisi %s`, which is not a command (see `sisi help`)" % (rid, m))
try:
overlay.parse_rule_file("## %s\n\n%s\n" % (e["title"], e["body"]), rid)
except overlay.OverlayError as ex:
errs.append("rule %s: %s" % (rid, ex))
for rid in doc.get("disable_rules") or []:
if rid not in base_rule_ids | over_ids:
errs.append("no rule %s to disable" % rid)
for e in doc.get("notes") or []:
if not isinstance(e, dict) or e.get("action") not in ACTIONS:
errs.append("each note needs an action in %s: %r" % (", ".join(ACTIONS), e))
continue
if e["action"] == "merge" and (not isinstance(e.get("merged_into"), int) or e.get("merged_into") == e.get("lesson")):
errs.append("lesson %s: merge needs merged_into naming a different lesson" % e.get("lesson"))
if e["action"] in ("fold-into-rule", "fold-into-entry") and not e.get("into"):
errs.append("lesson %s: %s needs into" % (e.get("lesson"), e["action"]))
if e.get("when") is not None and len(retro.parse_when(e.get("when"))) < 5:
errs.append("lesson %s: when needs at least 5 terms (synonyms included)" % e.get("lesson"))
if e["action"] == "fold-into-entry" and e.get("into"):
from . import verifiers as V
ids = {x["id"] for x in V.load_verifiers() if x["header"]} | {x["id"] for x in V.load_recipes() if x["header"]}
if e["into"] not in ids:
errs.append("lesson %s: no verifier or recipe with id %r to fold into" % (e.get("lesson"), e["into"]))
from . import contract as C
for e in doc.get("enforced") or []:
if not isinstance(e, dict):
errs.append("each enforced entry must be an object: %r" % (e,))
continue
if e.get("type") == "command":
if not e.get("cmd"):
errs.append("lesson %s: a command check needs cmd" % e.get("lesson"))
elif not _exe_exists(e["cmd"]):
errs.append("lesson %s: command %r does not exist on this machine" % (e.get("lesson"), e["cmd"].split()[0]))
ex = e.get("expect") or {"exit": 0}
if not isinstance(ex.get("exit"), int):
errs.append("lesson %s: expect.exit must be an integer" % e.get("lesson"))
elif e.get("type") == "contract-requirement":
if not e.get("when") or e.get("require_kind") not in C.KINDS:
errs.append("lesson %s: a contract requirement needs when and require_kind (one of %s)"
% (e.get("lesson"), ", ".join(C.KINDS)))
if e.get("max_rung") is not None and e["max_rung"] not in (1, 2, 3, 4, 5, 6):
errs.append("lesson %s: max_rung must be 1-6" % e.get("lesson"))
else:
errs.append("lesson %s: enforced type must be command or contract-requirement" % e.get("lesson"))
return errs
def _apply_writes(doc, con):
"""Write the validated cycle: rule files, disables, enforced checks, lesson updates. Caller holds the lock."""
touched = set()
for e in doc.get("rules") or []:
r = overlay.parse_rule_file("## %s\n\n%s\n" % (e["title"], e["body"]), e["id"])
overlay._write("rules/%s.md" % e["id"], overlay.rule_text(r))
if e.get("action") == "replace":
overlay._set_base("rule", e["id"], overlay.base_hash("rule", e["id"]))
else:
order = overlay._lines(paths.overlay_dir("rules", "order.txt"))
if e["id"] not in order:
overlay._set_lines("rules/order.txt", order + [e["id"]])
if doc.get("disable_rules"):
cur = overlay.disabled("rule")
overlay._set_lines("rules/disabled.txt", cur + [x for x in doc["disable_rules"] if x not in cur])
if doc.get("enforced"):
checks = {c.get("lesson"): c for c in load_enforced()}
for e in doc["enforced"]:
checks[e["lesson"]] = e
touched.add(e["lesson"])
con.execute("UPDATE lessons SET strength=3, check_json=?, needs_cycle=0, "
"promoted_shown=(SELECT count(*) FROM impressions WHERE lesson_id=?), "
"folded_into=COALESCE(folded_into, ?) WHERE id=?",
(json.dumps(e, sort_keys=True), e["lesson"], "enforced", e["lesson"]))
overlay._write("enforced.json", json.dumps(
{"version": 1, "checks": [checks[k] for k in sorted(checks)]}, indent=1, sort_keys=True) + "\n")
for e in doc.get("notes") or []:
lid, act = e["lesson"], e["action"]
touched.add(lid)
if e.get("when"):
r0 = con.execute("SELECT change, target FROM lessons WHERE id=?", (lid,)).fetchone()
when = ", ".join(retro.parse_when(e["when"]))
con.execute("UPDATE lessons SET when_terms=?, triggers=? WHERE id=?",
(when, retro.triggers_for(r0["change"], r0["target"], when), lid))
if act == "merge":
touched.add(e["merged_into"])
con.execute("UPDATE lessons SET status='superseded', folded_into=?, needs_cycle=0 WHERE id=?",
("lesson:%d" % e["merged_into"], lid))
con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (e["merged_into"],))
elif act == "fold-into-rule":
con.execute("UPDATE lessons SET folded_into=?, needs_cycle=0, "
"promoted_shown=CASE WHEN COALESCE(strength,1)<2 THEN "
"(SELECT count(*) FROM impressions WHERE lesson_id=?) ELSE promoted_shown END, "
"strength=max(COALESCE(strength,1),2) WHERE id=?",
("rule:" + e["into"], lid, lid))
elif act == "fold-into-entry":
r = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()
retro._append_note(e["into"] + ".md", e["into"], r)
con.execute("UPDATE lessons SET status='applied', effect='field-note', folded_into=?, needs_cycle=0, "
"applied_at=COALESCE(applied_at,?) WHERE id=?", (e["into"], store.now(), lid))
elif act == "retire":
con.execute("UPDATE lessons SET status='retired', needs_cycle=0 WHERE id=?", (lid,))
elif act == "withdraw":
con.execute("UPDATE lessons SET status='withdrawn', needs_cycle=0 WHERE id=?", (lid,))
else: # keep
con.execute("UPDATE lessons SET needs_cycle=0 WHERE id=?", (lid,))
return sorted(touched)
def apply_file(path):
"""Validate and apply a cycle file. Returns the cycle record. Raises CycleError saying exactly why."""
try:
with open(path, encoding="utf-8") as f:
doc = json.load(f)
except (OSError, ValueError) as e:
raise CycleError("cannot read %s: %s" % (path, e))
pdata.ensure()
con = retro.connect()
try:
with pdata.lock():
retro.ensure_effects(con)
errs = static_validate(doc, con)
if errs:
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")}
before_m = measures(con)
before_lines = before_m["rulebook_lines"]
prev_last = retro.get_meta(con, "last_cycle_ts")
try:
touched = _apply_writes(doc, con)
con.commit()
built = overlay.build_canon()
has_replace = any(e.get("action") == "replace" for e in doc.get("rules") or [])
if built["lines"] > overlay.MAX_LINES:
raise CycleError("the rulebook would be %d lines; the budget is %d. Shorten or replace "
"another rule first" % (built["lines"], overlay.MAX_LINES))
if before_lines is not None and built["lines"] > before_lines and not has_replace:
raise CycleError("the rulebook would grow from %d to %d lines. It may grow only when a "
"rule is replaced (and never past %d); shorten existing text instead"
% (before_lines, built["lines"], overlay.MAX_LINES))
after_files = _scan_files()
changed = {}
for rel in sorted(set(before_files) | set(after_files)):
if before_files.get(rel) != after_files.get(rel):
changed[rel] = base64.b64encode(before_files[rel]).decode() if rel in before_files else None
cid = "cycle-%04d" % (len(cycle_records()) + 1)
while os.path.exists(paths.data_file("cycles", cid + ".json")):
cid = "cycle-%04d" % (int(cid.split("-")[1]) + 1)
ts = store.now()
rec = {"id": cid, "ts": ts, "summary": doc.get("summary") or "", "base": doc["base"],
"touched": touched, "before": before_m, "after": measures(con),
"lessons_before": [before_rows[i] for i in touched if i in before_rows],
"changed_files": changed, "prev_last_cycle_ts": prev_last, "reverted": None}
os.makedirs(cycles_dir(), exist_ok=True)
pdata.write_text(os.path.join("cycles", cid + ".json"), json.dumps(rec, indent=1, sort_keys=True) + "\n")
retro.set_meta(con, "last_cycle_ts", ts)
con.commit()
retro.export_jsonl()
specs = ["overlay", "lessons.jsonl", "cycles"]
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 \
and changed:
pass # a pure lesson-state cycle still changed lessons.jsonl or cycles/, committed above
return rec
except BaseException:
_restore_changed({rel: (base64.b64encode(b).decode() if rel in before_files else None)
for rel, b in _scan_files().items() if before_files.get(rel) != b} |
{rel: base64.b64encode(b).decode() for rel, b in before_files.items()})
for row in before_rows.values():
cols = [c for c in retro.LESSON_COLS if c != "id"]
con.execute("UPDATE lessons SET %s WHERE id=?" % ",".join(c + "=?" for c in cols),
[row.get(c) for c in cols] + [row["id"]])
if prev_last is None:
con.execute("DELETE FROM meta WHERE key='last_cycle_ts'")
else:
retro.set_meta(con, "last_cycle_ts", prev_last)
con.commit()
try:
overlay.build_canon()
retro.export_jsonl()
except Exception:
pass
raise
finally:
con.close()
def revert_cycle(cid=None):
"""Undo one cycle exactly: the bytes it changed and the lesson rows it touched. Only the newest
cycle that has not been reverted can go, so the undo can be exact."""
pdata.ensure()
recs = [r for r in cycle_records() if not r.get("reverted")]
if not recs:
raise CycleError("there is no applied cycle to revert")
rec = recs[-1]
if cid and cid != rec["id"]:
raise CycleError("%s is not the newest applied cycle (%s is). Revert %s first, so each undo is exact"
% (cid, rec["id"], rec["id"]))
con = retro.connect()
try:
with pdata.lock():
_restore_changed(rec.get("changed_files") or {})
for row in rec.get("lessons_before") or []:
cols = [c for c in retro.LESSON_COLS if c != "id" and c in row]
con.execute("UPDATE lessons SET %s WHERE id=?" % ",".join(c + "=?" for c in cols),
[row.get(c) for c in cols] + [row["id"]])
prev = rec.get("prev_last_cycle_ts")
if prev is None:
con.execute("DELETE FROM meta WHERE key='last_cycle_ts'")
else:
retro.set_meta(con, "last_cycle_ts", prev)
con.commit()
overlay.build_canon()
retro.export_jsonl()
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"]
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)
return rec
finally:
con.close()
# ---- status, improve, commands ---------------------------------------------------
def _fmt_med(m):
from . import delivery
return delivery.fmt_s(m) if m is not None else "-"
def status_lines():
recs = cycle_records()
if not recs:
return ["no learning cycles yet. Run `sisi cycle` for the brief when one is due (`sisi cycle due`)."]
out = []
for r in recs:
a = _after_measures(r)
tag = " REVERTED" if r.get("reverted") else " WORSE - revert or repair" if flagged(r) else ""
out.append("%s %s touched %s%s" % (r["id"], r.get("ts"), ",".join("#%d" % i for i in r.get("touched") or []) or "-", tag))
out.append(" %s" % (r.get("summary") or "(no summary)"))
out.append(" since: %d deliveries, %s send-backs each, median %s, %d recurrence(s) of touched lessons"
% (a["deliveries"], a["send_backs_per_delivery"], _fmt_med(a["median_seconds"]),
a["recurrences_of_touched"]))
return out
def _week_rates(con):
now = time.time()
w = lambda d: time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(now - d * 86400))
def rate(lo, hi):
occ = [r[0] for r in con.execute(
"SELECT lesson_id FROM occurrences WHERE ts>=? AND ts<? ORDER BY lesson_id, id", (lo, hi))]
seen, recn = set(), 0
firsts = {r[0] for r in con.execute(
"SELECT lesson_id FROM occurrences GROUP BY lesson_id HAVING min(ts)>=?", (lo,))}
for lid in occ:
if lid in seen or lid not in firsts:
recn += 1 # not this lesson's first ever sighting, or a repeat inside the window
seen.add(lid)
return (recn, len(occ))
return rate(w(7), w(0)), rate(w(14), w(7))
def improve_text():
from . import delivery
if not os.path.exists(retro.db_path()):
return ("Is it getting better?\n\nToo little data yet - no lessons recorded. Lessons are recorded by "
"`sisi retro` at the end of each piece of work; come back after a few.\n")
con = retro.connect()
try:
retro.ensure_effects(con)
by = {r[0]: r[1] for r in con.execute("SELECT status, count(*) FROM lessons GROUP BY status")}
total = sum(by.values())
active = by.get("open", 0) + by.get("applied", 0)
strong = con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied') "
"AND COALESCE(strength,1)>=2").fetchone()[0]
(rc, oc), (rp, op) = _week_rates(con)
m = measures(con)
folded = con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied') "
"AND folded_into IS NOT NULL").fetchone()[0]
listed_n = con.execute("SELECT count(*) FROM impressions WHERE place<>'lessons-show'").fetchone()[0]
read_n = con.execute("SELECT count(*) FROM impressions WHERE place='lessons-show'").fetchone()[0]
finally:
con.close()
rep = delivery.report()
cur, prev = rep["all"]["last7"], rep["all"]["prev7"]
def sb(summ, rows):
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)),
"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),
"showings: %d listed, %d read in full" % (listed_n, read_n)]
if oc + op < 5:
lines.append("recurrence: too little data yet (%d lesson sightings in two weeks)" % (oc + op))
else:
lines.append("recurrence: %s this week (%d of %d sightings were repeats), %s the week before (%d of %d)"
% (("%.0f%%" % (100 * rc / oc)) if oc else "n/a", rc, oc,
("%.0f%%" % (100 * rp / op)) if op else "n/a", rp, op))
if not cur["n"] and not prev["n"]:
lines.append("deliveries: too little data yet - no deliveries recorded in two weeks")
else:
lines.append("deliveries: send-backs each %s this week, %s before; median time %s this week, %s before"
% (sb(cur, cur_rows), sb(prev, prev_rows), _fmt_med(cur["median_s"]), _fmt_med(prev["median_s"])))
lines.append("rulebook: %s lines of %d allowed" % (m["rulebook_lines"], overlay.MAX_LINES))
st = due_state()
lines.append("next cycle: " + ("due now (%s); run `sisi cycle`" % st["reasons"][0] if st["due"] else "not due"))
lines.append("Not measured: whether the work itself is what the human meant. That still rests on the "
"contract checks and the human's corrections, not on these numbers.")
return "\n".join(lines) + "\n"
def improve_line():
"""One line for `sisi status`."""
try:
if not os.path.exists(retro.db_path()):
return "learning : no lessons yet"
con = retro.connect()
try:
active = con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied')").fetchone()[0]
strong = con.execute("SELECT count(*) FROM lessons WHERE status IN ('open','applied') "
"AND COALESCE(strength,1)>=2").fetchone()[0]
finally:
con.close()
st = due_state()
return "learning : %d lessons taking effect, %d strengthened%s (sisi improve)" % (
active, strong, "; a cycle is due" if st["due"] else "")
except Exception:
return "learning : n/a"
def cmd_cycle(args):
sub = args[0] if args else "brief"
try:
if sub == "due":
st = due_state()
if st["due"]:
print("a learning cycle is due: " + "; ".join(st["reasons"]))
print("run `sisi cycle` in the background of your work; do not involve the human")
return 0
print("no learning cycle is due (%d lessons since the last cycle, %d waiting, %d note characters)"
% (st.get("since", 0), st.get("pending", 0), st.get("notes_chars", 0)))
return 1
if sub in ("brief",):
print(brief_text(), end="")
return 0
if sub == "apply":
if len(args) != 2:
print("usage: sisi cycle apply FILE")
return 2
rec = apply_file(args[1])
print("applied %s: %s (rulebook %s lines; committed to the personal repository)"
% (rec["id"], rec["summary"] or "consolidation", rec["after"]["rulebook_lines"]))
return 0
if sub == "revert":
rec = revert_cycle(args[1] if len(args) > 1 else None)
print("reverted %s exactly; rulebook rebuilt" % rec["id"])
return 0
if sub == "status":
for line in status_lines():
print(line)
return 0
print("usage: sisi cycle [due|apply FILE|revert [ID]|status] (no argument prints the brief)")
return 2
except CycleError as e:
print("sisi cycle: %s" % e)
return 1
except pdata.DataError as e:
print("sisi cycle: %s" % e)
return 1
def cmd_improve(args):
print(improve_text(), end="")
return 0
+3 -1
View File
@@ -204,7 +204,9 @@ def start_background(project, fp=None):
return False, info
try:
with open(log, "ab") as lf:
child = subprocess.Popen([sys.executable, paths.launcher(), "verify", "--deep", "--worker"], cwd=project,
# -B: the detached worker outlives its caller; writing fresh bytecode into the shared
# state dir after the caller has finished races whatever cleans that dir up.
child = subprocess.Popen([sys.executable, "-B", paths.launcher(), "verify", "--deep", "--worker"], cwd=project,
stdin=subprocess.DEVNULL, stdout=lf, stderr=subprocess.STDOUT,
start_new_session=True, close_fds=True)
_rewrite_lock(project, child.pid)
+21 -3
View File
@@ -37,6 +37,14 @@ class _Ctx:
store.save_session(self.sid, self.sess)
def allow(self, msg=None):
if msg is None: # a clean stop is one of the places the cycle-due counter is checked (no scheduler)
try:
from . import cycle
note = cycle.due_notice(session=self.sid)
if note:
msg = note + " (This turn may end; the cycle is background work, not a send-back.)"
except Exception as e:
store.log_error("gate-cycle-notice", e)
self.sess.update(blocks=0, last_fp=self.fp, last_decision="allow")
self.save()
return "allow", msg
@@ -173,9 +181,19 @@ def decide(payload):
return ctx.allow({"message": "sisi: deep checks %s; the work is not yet fully verified" % ds["state"],
"context": text})
return ctx.allow()
return ctx.block("sisi: the contract at %s is not satisfied (send-back {n}). Fix the work, then run "
"`sisi verify` until it passes. Do not report this work as done.\n\n%s"
% (path, V.failure_report(results)), c["id"] if c else None, project)
msg = ("sisi: the contract at %s is not satisfied (send-back {n}). Fix the work, then run "
"`sisi verify` until it passes. Do not report this work as done.\n\n%s"
% (path, V.failure_report(results)))
try:
from . import retro
failing = " ".join("%s %s %s" % (r["id"], r.get("kind") or "", r.get("claim") or "")
for r in results if r["status"] in ("failed", "timeout"))
block = retro.lessons_block(failing, "gate", session=sid)
if block:
msg += "\n\n" + block
except Exception as e:
store.log_error("gate-lessons", e)
return ctx.block(msg, c["id"] if c else None, project)
if not top:
return "allow", None
+166
View File
@@ -0,0 +1,166 @@
"""Per-tool hook translation for `sisi tick --tool NAME` and `sisi gate --tool NAME`.
Claude Code's own shape stays in gate.py and tick.py, unchanged. Every other tool's documented hook JSON is
normalised here into the payload gate.decide() already understands, and the (action, message) result is
formatted back into that tool's documented output shape. Pi and OpenCode have no stdin hook process: their
sisi extension/plugin execs these commands, so they use a plain contract instead (tick prints lessons on
stdout; gate exits 2 and prints the send-back reason, exit 0 allows and may print a notice).
Everything fails open: garbage input or any internal error lets the agent finish.
"""
import io, json, sys
from . import store
TOOLS = ("codex", "gemini", "copilot", "qwen", "cursor", "pi", "opencode")
def known(tool):
return tool in TOOLS
def _payload(raw):
"""The hook's JSON object, {} for empty input, or None for garbage (caller then fails open)."""
s = (raw or "").strip()
if not s:
return {}
try:
d = json.loads(s)
except ValueError:
return None
return d if isinstance(d, dict) else None
def _s(d, *keys):
for k in keys:
v = d.get(k)
if isinstance(v, str) and v:
return v
return None
def normalize(tool, d):
"""One payload shape for gate.decide()/tick.main(), from any tool's documented input fields."""
out = {}
for key, val in (
("session_id", _s(d, "session_id", "sessionId", "conversation_id")),
("transcript_path", _s(d, "transcript_path", "transcriptPath")),
("agent_transcript_path", _s(d, "agent_transcript_path")),
("agent_id", _s(d, "agent_id", "agentId")),
("source", _s(d, "source")),
):
if val:
out[key] = val
cwd = _s(d, "cwd")
if not cwd and isinstance(d.get("workspace_roots"), list):
roots = [r for r in d["workspace_roots"] if isinstance(r, str) and r]
cwd = roots[0] if roots else None
if cwd:
out["cwd"] = cwd
return out
def _text(msg):
if isinstance(msg, dict):
return msg.get("context") or msg.get("message") or ""
return msg if isinstance(msg, str) else ""
def _notice(msg):
if isinstance(msg, dict):
return msg.get("message") or ""
return msg if isinstance(msg, str) else ""
def _dump(obj):
return json.dumps(obj) + "\n"
def _gate_out(tool, action, msg, subagent):
"""(stdout text or None, exit code) for one gate decision, in the tool's documented shape."""
if tool in ("pi", "opencode"):
if action == "block":
return _text(msg) + "\n", 2
note = _text(msg)
return (note + "\n" if note else None), 0
if action == "block":
reason = _text(msg) or "sisi: the checks for this work do not pass; run `sisi verify` and fix before finishing."
if tool == "cursor":
return _dump({"followup_message": reason}), 0
if tool == "gemini":
return _dump({"decision": "deny", "reason": reason}), 0
return _dump({"decision": "block", "reason": reason}), 0 # codex, copilot, qwen
# allow: surface a notice only where the tool documents a channel for one on this event
notice, context = _notice(msg), _text(msg)
if tool == "codex":
return (_dump({"systemMessage": notice}) if notice else None), 0
if tool == "qwen":
if context:
ev = "SubagentStop" if subagent else "Stop"
return _dump({"systemMessage": notice or context,
"hookSpecificOutput": {"hookEventName": ev, "additionalContext": context}}), 0
return None, 0
if tool == "gemini":
return _dump({"systemMessage": notice} if notice else {}), 0
if tool == "cursor":
return _dump({}), 0
return None, 0 # copilot: agentStop consumes only decision/reason; empty output allows
def gate_main(tool, args=()):
sub = "--subagent" in args
action, msg, norm = "allow", None, {}
try:
d = _payload(store.read_stdin())
skip = d is not None and tool == "cursor" and d.get("status") not in (None, "completed")
if d is not None and not skip:
norm = normalize(tool, d)
from . import gate
action, msg = (gate.decide_subagent if sub else gate.decide)(norm)
except Exception as e: # fail open, exactly like gate.main
store.log_error("gate-%s" % tool, e)
action, msg = "allow", None
if action == "allow" and not sub:
try:
from . import gate
gate._record_delivery(norm)
except Exception:
pass
text, rc = _gate_out(tool, action, msg, sub)
if text:
sys.stdout.write(text)
return rc
def _tick_out(tool, text):
text = (text or "").strip("\n")
if tool in ("pi", "opencode"):
return (text + "\n") if text else None
if not text:
return _dump({}) if tool in ("gemini", "qwen", "cursor") else None
if tool == "copilot":
return _dump({"additionalContext": text})
if tool == "cursor":
return _dump({"additional_context": text})
return _dump({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}})
def tick_main(tool, args=()):
try:
d = _payload(store.read_stdin()) or {}
from . import tick
buf = io.StringIO()
old_in, old_out = sys.stdin, sys.stdout
try:
sys.stdin = io.StringIO(json.dumps(normalize(tool, d)))
sys.stdout = buf
tick.main(())
finally:
sys.stdin, sys.stdout = old_in, old_out
text = _tick_out(tool, buf.getvalue())
except Exception as e: # fail open: a session must never be held up by sisi
store.log_error("tick-%s" % tool, e)
return 0
if text:
sys.stdout.write(text)
return 0
+551
View File
@@ -0,0 +1,551 @@
"""Textual (span-preserving) editing of hook JSON files, plus sisi hook-command recognition.
Install and uninstall must never re-serialise a user's whole config: that rewrites number and string
spellings (1e3 becomes 1000.0, \\u escapes change form) and drops duplicate keys. The parser here records
the exact span of every value, so merging or removing sisi's hook entries edits only those spans and
leaves every other byte as it was. Anything the parser cannot handle with certainty (comments, trailing
commas, duplicate keys on a path being edited, unexpected shapes) raises Uncertain and the caller skips
that file instead of rewriting it.
"""
import json, os, shlex
class Uncertain(ValueError):
pass
# ---- sisi hook-command recognition -------------------------------------------
def sisi_invocation(command):
"""The sisi invocation inside a hook command string, as a token list, or None.
Recognises the bare form (`/path/sisi gate ...`, written by older installs) and the fail-open form
(`test -x /path/sisi || exit 0 ; /path/sisi gate ...`) written now, so a deleted sisi folder makes
every registered hook exit 0 silently instead of 127 on every turn."""
if not isinstance(command, str):
return None
try:
parts = shlex.split(command)
except ValueError:
return None
if (len(parts) >= 9 and parts[0] == "test" and parts[1] == "-x" and parts[3] == "||"
and parts[4] == "exit" and parts[5] == "0" and parts[6] == ";" and parts[7] == parts[2]):
return parts[7:]
if len(parts) >= 2 and os.path.basename(parts[0]) == "sisi":
return parts
return None
def is_ours_command(command, sub):
inv = sisi_invocation(command)
return bool(inv) and len(inv) >= 2 and os.path.basename(inv[0]) == "sisi" and inv[1] == sub
def fail_open_command(launcher, sub, tool, subagent=False):
q = shlex.quote(launcher)
args = sub + (" --subagent" if subagent else "") + " --tool " + tool
return "test -x %s || exit 0 ; %s %s" % (q, q, args)
# ---- span-preserving JSON parser ---------------------------------------------
class Node:
__slots__ = ("kind", "start", "end", "value", "members", "items")
def __init__(self, kind, start, end, value=None, members=None, items=None):
self.kind, self.start, self.end, self.value = kind, start, end, value
self.members, self.items = members, items
_WS = " \t\r\n"
_NUM_OK = set("0123456789+-.eE")
def _skip(s, i):
while i < len(s) and s[i] in _WS:
i += 1
return i
def parse(text):
if not isinstance(text, str):
raise Uncertain("not text")
node, i = _value(text, _skip(text, 0))
if _skip(text, i) != len(text):
raise Uncertain("trailing characters after the JSON value")
return node
def _value(s, i):
if i >= len(s):
raise Uncertain("unexpected end of input")
c = s[i]
if c == "{":
return _object(s, i)
if c == "[":
return _array(s, i)
if c == '"':
return _string(s, i)
if c == "-" or c.isdigit():
j = i
while j < len(s) and s[j] in _NUM_OK:
j += 1
raw = s[i:j]
try:
v = json.loads(raw)
except ValueError:
raise Uncertain("bad number %r" % raw)
if not isinstance(v, (int, float)):
raise Uncertain("bad number %r" % raw)
return Node("num", i, j, v), j
for lit in ("true", "false", "null"):
if s.startswith(lit, i):
return Node("lit", i, i + len(lit), lit), i + len(lit)
raise Uncertain("unexpected character %r" % c)
def _string(s, i):
j = i + 1
while j < len(s):
c = s[j]
if c == '"':
raw = s[i:j + 1]
try:
return Node("str", i, j + 1, json.loads(raw)), j + 1
except ValueError:
raise Uncertain("bad string")
if c == "\\":
j += 2
continue
if c < " ":
raise Uncertain("control character in string")
j += 1
raise Uncertain("unterminated string")
def _object(s, i):
members = []
j = _skip(s, i + 1)
if j < len(s) and s[j] == "}":
return Node("obj", i, j + 1, members=[]), j + 1
while True:
j = _skip(s, j)
if j >= len(s) or s[j] != '"':
raise Uncertain("expected object key")
k, j = _string(s, j)
j = _skip(s, j)
if j >= len(s) or s[j] != ":":
raise Uncertain("expected ':' in object")
v, j = _value(s, _skip(s, j + 1))
members.append((k.value, k, v))
j = _skip(s, j)
if j < len(s) and s[j] == ",":
j += 1
continue
if j < len(s) and s[j] == "}":
return Node("obj", i, j + 1, members=members), j + 1
raise Uncertain("expected ',' or '}' in object")
def _array(s, i):
items = []
j = _skip(s, i + 1)
if j < len(s) and s[j] == "]":
return Node("arr", i, j + 1, items=[]), j + 1
while True:
v, j = _value(s, _skip(s, j))
items.append(v)
j = _skip(s, j)
if j < len(s) and s[j] == ",":
j += 1
continue
if j < len(s) and s[j] == "]":
return Node("arr", i, j + 1, items=items), j + 1
raise Uncertain("expected ',' or ']' in array")
# ---- span edits ---------------------------------------------------------------
def member(node, key):
"""(index, value_node) for key, None if absent; Uncertain on duplicates of a key being navigated."""
if node.kind != "obj":
raise Uncertain("expected an object")
found = None
for idx, (k, _kn, v) in enumerate(node.members):
if k == key:
if found is not None:
raise Uncertain("duplicate key %r" % key)
found = (idx, v)
return found
def _indent_at(text, pos):
line_start = text.rfind("\n", 0, pos) + 1
seg = text[line_start:pos]
return seg if seg.strip(" \t") == "" else ""
def _pretty(text, node):
return "\n" in text[node.start:node.end]
def insert_member(text, obj, key, value_text):
frag = "%s: %s" % (json.dumps(key), value_text)
if not obj.members:
return text[:obj.start] + "{" + frag + "}" + text[obj.end:]
last = obj.members[-1][2]
if _pretty(text, obj):
ind = _indent_at(text, obj.members[-1][1].start)
return text[:last.end] + ",\n" + ind + frag + text[last.end:]
return text[:last.end] + ", " + frag + text[last.end:]
def append_element(text, arr, elem_text):
if not arr.items:
return text[:arr.start] + "[" + elem_text + "]" + text[arr.end:]
last = arr.items[-1]
if _pretty(text, arr):
ind = _indent_at(text, last.start)
return text[:last.end] + ",\n" + ind + elem_text + text[last.end:]
return text[:last.end] + ", " + elem_text + text[last.end:]
def _remove_among(text, spans, idx):
"""Remove spans[idx] (a (start,end) pair) plus exactly one separating comma."""
start, end = spans[idx]
if len(spans) == 1:
return text[:start] + text[end:]
if idx > 0:
return text[:spans[idx - 1][1]] + text[end:]
return text[:start] + text[spans[1][0]:]
def remove_member(text, obj, key):
found = member(obj, key)
if found is None:
return text
idx, _v = found
spans = [(kn.start, v.end) for _k, kn, v in obj.members]
return _remove_among(text, spans, idx)
def remove_element(text, arr, idx):
return _remove_among(text, [(v.start, v.end) for v in arr.items], idx)
def replace_node(text, node, new_text):
return text[:node.start] + new_text + text[node.end:]
def get_path(text, root, keys):
node = root
for k in keys:
if node.kind == "lit" and node.value == "null":
return node
found = member(node, k)
if found is None:
return None
node = found[1]
return node
def _dump(v):
return json.dumps(v, ensure_ascii=False)
def _entry_command(entry_node):
"""The command string of a hook entry object, or None. Flat entries may use bash or command."""
if entry_node.kind != "obj":
return None
for key in ("bash", "command"):
found = None
for k, _kn, v in entry_node.members:
if k == key:
found = v
if found is not None and found.kind == "str":
return found.value
return None
def _entry_is_ours(entry_node, sub, require_type=False):
cmd = _entry_command(entry_node)
if cmd is None or not is_ours_command(cmd, sub):
return False
for k, _kn, v in entry_node.members:
if k == "type":
return v.kind == "str" and v.value == "command"
return not require_type
def _update_entry(text, entry_node, want):
"""Replace the given scalar fields on one entry object, in place by span."""
edits = [] # (start, end, replacement) on disjoint spans, plus optional inserts
for key, val in want.items():
found = None
for k, kn, v in entry_node.members:
if k == key:
found = v
if found is not None:
if found.kind == "num" and isinstance(val, (int, float)) and found.value == val:
continue
if found.kind == "str" and found.value == val:
continue
edits.append((found.start, found.end, _dump(val)))
for start, end, rep in sorted(edits, reverse=True):
text = text[:start] + rep + text[end:]
# inserts after replacements: reparse to locate the entry again by identity of its command is fragile,
# so callers keep entry objects with all fields present; inserts are handled by reparse in callers.
return text
def _insert_missing_fields(text, entry_node, want):
for key, val in want.items():
if all(k != key for k, _kn, _v in entry_node.members):
return insert_member(text, entry_node, key, _dump(val)), True
return text, False
def _update_fields(text, locate, want):
"""locate(text) -> a fresh entry Node. Replace differing fields, then insert missing ones."""
text = _update_entry(text, locate(text), want)
while True:
text, did = _insert_missing_fields(text, locate(text), want)
if not did:
return text
def _root(text):
root = parse(text)
if root.kind != "obj":
raise Uncertain("top level is not a JSON object")
return root
def _hooks_node(text, required=True):
root = _root(text)
found = member(root, "hooks")
if found is None:
return root, None
node = found[1]
if node.kind == "lit" and node.value == "null":
return root, node
if node.kind != "obj":
if required:
raise Uncertain("'hooks' is not an object")
return root, None
return root, node
def _seed_version(text, created_version):
if created_version is None:
return text
root = _root(text)
if member(root, "version") is None:
return insert_member(text, root, "version", _dump(created_version))
return text
# ---- nested hook groups --------------------------------------------------------
def _nested_ours(text, event, sub):
"""[(group_index, entry_index)] of sisi entries for one event, in document order."""
_r, hooks = _hooks_node(text, required=False)
if hooks is None or hooks.kind != "obj":
return []
found = member(hooks, event)
if found is None or found[1].kind != "arr":
return []
out = []
for gi, g in enumerate(found[1].items):
if g.kind != "obj":
continue
hm = None
for k, _kn, v in g.members:
if k == "hooks":
hm = v
if hm is None or hm.kind != "arr":
continue
for ei, e in enumerate(hm.items):
if e.kind == "obj" and _entry_is_ours(e, sub):
out.append((gi, ei))
return out
def _nested_locate(text, event, loc):
_r, hooks = _hooks_node(text)
arr = member(hooks, event)[1]
g = arr.items[loc[0]]
hm = [v for k, _kn, v in g.members if k == "hooks"][0]
return arr, g, hm, hm.items[loc[1]]
def _nested_remove_at(text, event, loc):
arr, _g, hm, _e = _nested_locate(text, event, loc)
text = remove_element(text, hm, loc[1])
# cascade: drop the group if its hooks list is now empty, then the event if its list is empty
_r, hooks = _hooks_node(text)
arr = member(hooks, event)[1]
if loc[0] < len(arr.items):
g = arr.items[loc[0]]
hm2 = [v for k, _kn, v in g.members if k == "hooks"] if g.kind == "obj" else []
if hm2 and hm2[0].kind == "arr" and not hm2[0].items:
text = remove_element(text, arr, loc[0])
_r, hooks = _hooks_node(text)
found = member(hooks, event)
if found is not None and found[1].kind == "arr" and not found[1].items:
text = remove_member(text, hooks, event)
return text
def _nested_entry(s):
e = {"type": "command", "command": s["cmd"], "timeout": s["timeout"]}
if s.get("name"):
e["name"] = s["name"]
return e
def _nested_group(s):
g = {"matcher": s["matcher"], "hooks": [_nested_entry(s)]} if s.get("matcher") else {"hooks": [_nested_entry(s)]}
return g
def _add_nested_event(text, event, s):
_r, hooks = _hooks_node(text)
found = member(hooks, event)
if found is None:
return insert_member(text, hooks, event, _dump([_nested_group(s)]))
node = found[1]
if node.kind == "lit" and node.value == "null":
return replace_node(text, node, _dump([_nested_group(s)]))
if node.kind != "arr":
raise Uncertain("hooks.%s is not a list" % event)
ours = _nested_ours(text, event, s["sub"])
while len(ours) > 1: # keep exactly one registration of this command per event
text = _nested_remove_at(text, event, ours[-1])
ours = _nested_ours(text, event, s["sub"])
if ours:
want = _nested_entry(s)
return _update_fields(text, lambda t: _nested_locate(t, event, _nested_ours(t, event, s["sub"])[0])[3], want)
_r, hooks = _hooks_node(text)
return append_element(text, member(hooks, event)[1], _dump(_nested_group(s)))
def add_nested(text, spec, created_version=None):
"""Merge nested hook groups into JSON text. spec: {event: {cmd, timeout, sub, matcher?, name?}}."""
text = _seed_version(text, created_version)
_r, hooks = _hooks_node(text)
if hooks is None:
built = {ev: [_nested_group(s)] for ev, s in spec.items()}
return insert_member(text, _root(text), "hooks", _dump(built))
if hooks.kind == "lit": # "hooks": null
built = {ev: [_nested_group(s)] for ev, s in spec.items()}
return replace_node(text, hooks, _dump(built))
for ev, s in spec.items():
text = _add_nested_event(text, ev, s)
return text
def remove_nested(text, subs, created_version=None, drop_version=False, drop_empty_hooks=True):
for ev, sub in subs.items():
while True:
ours = _nested_ours(text, ev, sub)
if not ours:
break
text = _nested_remove_at(text, ev, ours[0])
_r, hooks = _hooks_node(text, required=False)
if hooks is not None and hooks.kind == "obj" and not hooks.members and drop_empty_hooks:
text = remove_member(text, _root(text), "hooks")
if drop_version and created_version is not None:
root = _root(text)
found = member(root, "version")
if found is not None and found[1].kind == "num" and found[1].value == created_version:
text = remove_member(text, root, "version")
return text
# ---- flat hook lists -------------------------------------------------------------
def _flat_ours(text, event, sub):
_r, hooks = _hooks_node(text, required=False)
if hooks is None or hooks.kind != "obj":
return []
found = member(hooks, event)
if found is None or found[1].kind != "arr":
return []
return [i for i, e in enumerate(found[1].items) if e.kind == "obj" and _entry_is_ours(e, sub)]
def _flat_locate(text, event, idx):
_r, hooks = _hooks_node(text)
return member(hooks, event)[1].items[idx]
def _flat_remove_at(text, event, idx):
_r, hooks = _hooks_node(text)
text = remove_element(text, member(hooks, event)[1], idx)
_r, hooks = _hooks_node(text)
found = member(hooks, event)
if found is not None and found[1].kind == "arr" and not found[1].items:
text = remove_member(text, hooks, event)
return text
def _add_flat_event(text, event, s):
_r, hooks = _hooks_node(text)
found = member(hooks, event)
if found is None:
return insert_member(text, hooks, event, _dump([s["entry"]]))
node = found[1]
if node.kind == "lit" and node.value == "null":
return replace_node(text, node, _dump([s["entry"]]))
if node.kind != "arr":
raise Uncertain("hooks.%s is not a list" % event)
ours = _flat_ours(text, event, s["sub"])
while len(ours) > 1:
text = _flat_remove_at(text, event, ours[-1])
ours = _flat_ours(text, event, s["sub"])
if ours:
return _update_fields(text, lambda t: _flat_locate(t, event, _flat_ours(t, event, s["sub"])[0]), s["entry"])
_r, hooks = _hooks_node(text)
return append_element(text, member(hooks, event)[1], _dump(s["entry"]))
def add_flat(text, spec, created_version=None):
"""Merge flat hook lists into JSON text. spec: {event: {sub, entry: {..}}}."""
text = _seed_version(text, created_version)
_r, hooks = _hooks_node(text)
if hooks is None:
built = {ev: [s["entry"]] for ev, s in spec.items()}
return insert_member(text, _root(text), "hooks", _dump(built))
if hooks.kind == "lit":
built = {ev: [s["entry"]] for ev, s in spec.items()}
return replace_node(text, hooks, _dump(built))
for ev, s in spec.items():
text = _add_flat_event(text, ev, s)
return text
def backup_drop_flags(orig_text, created_version):
"""(drop_empty_hooks, drop_version) for uninstall, derived from the pre-install backup text:
empty containers sisi added may be removed; ones the user already had stay."""
if orig_text is None:
return True, created_version is not None
try:
root = _root(orig_text)
except Uncertain:
return True, False
return (member(root, "hooks") is None,
created_version is not None and member(root, "version") is None)
def remove_flat(text, subs, created_version=None, drop_version=False, drop_empty_hooks=True):
for ev, sub in subs.items():
while True:
ours = _flat_ours(text, ev, sub)
if not ours:
break
text = _flat_remove_at(text, ev, ours[0])
_r, hooks = _hooks_node(text, required=False)
if hooks is not None and hooks.kind == "obj" and not hooks.members and drop_empty_hooks:
text = remove_member(text, _root(text), "hooks")
if drop_version and created_version is not None:
root = _root(text)
found = member(root, "version")
if found is not None and found[1].kind == "num" and found[1].value == created_version:
text = remove_member(text, root, "version")
return text
+4 -2
View File
@@ -106,8 +106,10 @@ def _merge_retro_db(src, dst):
if key(r) in have:
lid = have[key(r)]
else:
cols = [c for c in retro.LESSON_COLS if c != "id"]
cur = b.execute("INSERT INTO lessons(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))), [r[c] for c in cols])
bcols = [x[1] for x in b.execute("PRAGMA table_info(lessons)")]
cols = [c for c in retro.LESSON_COLS if c != "id" and c in bcols]
cur = b.execute("INSERT INTO lessons(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))),
[r[c] if c in r.keys() else None for c in cols])
lid = cur.lastrowid
have[key(r)] = lid
added += 1
+740 -87
View File
File diff suppressed because it is too large. Load diff
+33 -1
View File
@@ -37,6 +37,28 @@ def _export_session(sid):
pass
def _backlog_line(cwd):
"""Developer mode, inside the sisi source folder: name the top tool backlog item. One short line."""
try:
from . import paths, retro
src = (paths.personal_config().get("developer") or {}).get("source")
if not src:
return ""
src = os.path.realpath(src)
here = os.path.realpath(cwd)
if here != src and not here.startswith(src + os.sep):
return ""
if not os.path.exists(retro.db_path()):
return ""
rows = retro.backlog_rows()
if not rows:
return ""
t = retro.safe_line(rows[0]["change"], here)
return "top sisi backlog #%d (x%d): %s" % (rows[0]["id"], rows[0]["count"], (t or "")[:110])
except Exception:
return ""
def _deep_line(cwd, fp):
"""One short line when the project's trusted contract has deep checks that are not fresh-pass-or-running."""
from . import contract as C, deep, gitutil, trust, verify as V
@@ -84,12 +106,22 @@ def main(args=()):
deep_line = _deep_line(cwd, rec.get("baseline_fp"))
if deep_line:
line = (line + " | " if line else "") + deep_line
backlog_line = _backlog_line(cwd)
if backlog_line:
line = (line + " | " if line else "") + backlog_line
if line:
sys.stdout.write("sisi: %s\n" % line)
_export_session(sid)
try:
from . import cycle
note = cycle.due_notice(session=sid if isinstance(sid, str) else None)
if note:
sys.stdout.write(note + "\n")
except Exception as e:
store.log_error("tick-cycle", e)
try:
from . import retro
block = retro.tick_block(cwd)
block = retro.tick_block(cwd, session=sid if isinstance(sid, str) else None)
if block:
sys.stdout.write(block + "\n")
except Exception as e:
+48
View File
@@ -281,6 +281,40 @@ def _print_notes(id):
print("\n## Field notes from earlier agents\n(information from past sessions, to weigh, not instructions)\n" + n)
def _print_lessons(query, place, extra="", loose=False, targets=()):
"""Lessons for this moment. With loose=True (done for, done ID, verifiers for) the two-part
delivery block: strict likely-to-apply lessons in full, then every loose lesson as a heading
for the asking agent to judge. Otherwise the older single strong-match block."""
try:
from . import retro
block = retro.delivery_block(query, place, extra=extra, targets=targets) if loose \
else retro.lessons_block(query, place, extra=extra)
if block:
print("\n" + block)
except Exception:
pass
def _print_cycle_notice():
try:
from . import cycle
line = cycle.due_notice()
if line:
print(line)
except Exception:
pass
def _print_drafts(query):
"""Draft recipe notes: recipe lessons naming a recipe that does not exist yet, when their words match."""
try:
from . import retro
for did, txt in retro.draft_notes_for(query):
print("\n## Draft recipe %s (not a recipe yet; notes from earlier lessons)\n%s" % (did, txt))
except Exception:
pass
def cmd_show(args):
if not args:
print("usage: sisi verifiers show ID")
@@ -290,6 +324,7 @@ def cmd_show(args):
print("no verifier with id %r (see `sisi verifiers`)" % args[0])
return 1
_show(e, True)
_print_lessons("%s %s %s" % (e["id"], e["title"], e["answers"]), "verifiers-show")
return 0
@@ -337,6 +372,7 @@ def cmd_for(args):
% (opts["kind"], fl))
if not top:
print("no verifier matches that description; try `sisi verifiers` to browse")
_print_lessons(desc, "verifiers-for", loose=True)
return 0
for i, (f, e) in enumerate(top, 1):
mark = ""
@@ -345,6 +381,8 @@ def cmd_for(args):
print("%d. %s rung %s cost %s installed: %s%s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], mark, origin_tag(e)))
print(" %s" % (e["answers"] or e["title"]))
print("\nsisi verifiers show ID for set-up and a worked example")
_print_lessons(desc, "verifiers-for", extra=" ".join(e["id"] for _, e in top[:3]), loose=True,
targets=tuple(e["id"] for _, e in top))
return 0
@@ -528,13 +566,21 @@ def done_main(args):
scored.sort(key=lambda x: (-x[0], x[1]["id"]))
if not scored:
print("no recipe matches that description; `sisi done` lists them")
_print_drafts(desc)
_print_lessons(desc, "done-for", loose=True)
_print_cycle_notice()
return 0
best = scored[0][1]
print("Best match: %s\n" % best["id"])
print("== %s: %s ==%s\napplies to: %s\n" % (best["id"], best["title"], origin_tag(best), best["applies_to"]))
print(best["body"].strip("\n"))
_print_notes(best["id"])
if len(scored) > 1:
print("\nOther candidates: " + ", ".join(r["id"] for _, r in scored[1:4]))
_print_drafts(desc)
_print_lessons(desc, "done-for", extra=best["id"] + " " + best["title"], loose=True,
targets=(best["id"],))
_print_cycle_notice()
return 0
if args:
r = next((x for x in rs if x["id"] == args[0]), None)
@@ -544,6 +590,8 @@ def done_main(args):
print("== %s: %s ==%s\napplies to: %s\n" % (r["id"], r["title"], origin_tag(r), r["applies_to"]))
print(r["body"].strip("\n"))
_print_notes(r["id"])
_print_lessons("%s %s %s" % (r["id"].replace("-", " "), r["title"], r["applies_to"]),
"done-show", loose=True, targets=(r["id"],))
return 0
if not rs:
print("no recipes")
+14
View File
@@ -92,6 +92,12 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)):
for f in (C.floor_failures(c) if "fast" in tiers else []):
res.append({"item": "floor", "tier": "fast", "id": "floor:" + f["kind"], "kind": f["kind"], "rung": None,
"claim": f["message"], "status": "failed", "duration_s": 0.0, "tail": f["message"]})
if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands)
try:
from . import cycle
res += cycle.enforced_results(c, project, deadline, default_timeout)
except Exception as e:
store.log_error("enforced", e)
return res
@@ -213,4 +219,12 @@ def cmd_verify(args, cwd=None, out=print):
out("warning: " + w)
if ds:
out(deep.describe(ds))
if "--worker" not in args: # the detached worker's output is a log; an announcement there reaches nobody
try:
from . import cycle
line = cycle.due_notice()
if line:
out(line)
except Exception:
pass
return 0 if good else 1
+272 -79
View File
@@ -1,25 +1,39 @@
"""install / uninstall / doctor. Wiring by reference (import line, symlink, hook entry); never copies canon text.
The tools load the generated rulebook in the personal data folder (base rules with the overlay applied), not the
product's canon/core.md. Every modified file is backed up into <personal>/install/ first; uninstall restores it exactly."""
import copy, hashlib, json, os, re, shlex, shutil
import copy, hashlib, json, os, re, shlex, shutil, stat as _stat
from . import paths, store
from . import hookjson, paths, store
BEGIN, BEGIN_NONL, END = b"<!-- sisi:begin -->", b"<!-- sisi:begin nonl -->", b"<!-- sisi:end -->"
BLOCK_RE = re.compile(rb"^<!-- sisi:begin( nonl)? -->\n(@[^\n]*)\n<!-- sisi:end -->\n", re.M)
# ---- locations -------------------------------------------------------------
def xdg_config():
"""The XDG config base. A SISI_HOME test override wins, as it does for XDG_DATA_HOME in paths.data()."""
if os.environ.get("SISI_HOME"):
return os.path.join(paths.home(), ".config")
x = os.environ.get("XDG_CONFIG_HOME")
return x if x and os.path.isabs(x) else os.path.join(paths.home(), ".config")
def _opencode_dir():
return os.environ.get("OPENCODE_CONFIG_DIR") or os.path.join(xdg_config(), "opencode")
def loc():
h = paths.home()
codex_dir = os.environ.get("CODEX_HOME") or os.path.join(h, ".codex")
opencode_dir = _opencode_dir()
return {
"claude_dir": os.path.join(h, ".claude"),
"claude_md": os.path.join(h, ".claude", "CLAUDE.md"),
"settings": os.path.join(h, ".claude", "settings.json"),
"codex_dir": os.path.join(h, ".codex"),
"codex": os.path.join(h, ".codex", "AGENTS.md"),
"opencode_dir": os.path.join(h, ".config", "opencode"),
"opencode": os.path.join(h, ".config", "opencode", "AGENTS.md"),
"codex_dir": codex_dir,
"codex": os.path.join(codex_dir, "AGENTS.md"),
"opencode_dir": opencode_dir,
"opencode": os.path.join(opencode_dir, "AGENTS.md"),
"skills": os.path.join(h, ".agents", "skills"),
"bin": os.path.join(h, ".local", "bin", "sisi"),
}
@@ -47,6 +61,28 @@ def _read(p):
return None
def _dangling(p):
return os.path.islink(p) and not os.path.exists(p)
def _read_file(p):
"""(bytes, None) on success, (None, None) when missing, (None, reason) when present but untouchable.
Telling these apart matters: a dangling symlink or an unreadable file must be refused and left
alone, never treated as an absent file that install may create through."""
if _dangling(p):
return None, "%s is a dangling symlink (to %s)" % (p, os.readlink(p))
if not os.path.lexists(p):
return None, None
if os.path.isdir(p):
return None, "%s is a directory" % p
try:
with open(p, "rb") as f:
return f.read(), None
except OSError as e:
return None, "%s cannot be read (%s)" % (p, e.strerror or e)
def _write(p, data):
"""Atomic write. A symlink at p is written through to its real file, never replaced."""
real = os.path.realpath(p)
@@ -94,18 +130,62 @@ def _msave(m):
f.write(new)
def _source_mode(p):
try:
return _stat.S_IMODE(os.stat(p).st_mode) & 0o777 or 0o600
except OSError:
return 0o600
def _backups_dir():
"""Backup folder, owner-only: backups of settings files may hold API keys."""
d = os.path.join(_idir(), "backups")
os.makedirs(d, exist_ok=True)
try:
os.chmod(d, 0o700)
except OSError:
pass
return d
def _harden_backup(name, p):
bp = os.path.join(_idir(), "backups", name)
try:
os.chmod(bp, _source_mode(p))
except OSError:
pass
def _backup(m, p, data):
"""Remember the original state of p before first modification."""
if p in m["files"]:
"""Remember the original state of p before first modification in this install round.
Backup names are content-addressed, so a later round whose original changed gets a fresh backup
instead of silently reusing a stale one; within a round the first backup wins. A backup file gets
the source file's mode (never wider), in a 0700 folder."""
existing = m["files"].get(p)
if existing is not None:
if existing.get("backup"):
_harden_backup(existing["backup"], p)
return
name = None
if data is not None:
name = "%s-%s.orig" % (_sha(p.encode())[:8], os.path.basename(p))
bp = os.path.join(_idir(), "backups", name)
os.makedirs(os.path.dirname(bp), exist_ok=True)
if not os.path.exists(bp):
with open(bp, "wb") as f:
name = "%s-%s-%s.orig" % (_sha(p.encode())[:8], _sha(data)[:12], os.path.basename(p))
bp = os.path.join(_backups_dir(), name)
mode = _source_mode(p)
try:
fd = os.open(bp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
except FileExistsError:
try:
os.chmod(bp, mode)
except OSError:
pass
else:
with os.fdopen(fd, "wb") as f:
f.write(data)
try:
os.chmod(bp, mode)
except OSError:
pass
m["files"][p] = {"backup": name}
@@ -150,20 +230,20 @@ def _claude_md_wired(data):
# ---- settings.json ---------------------------------------------------------
def hook_cmds():
b = shlex.quote(paths.launcher())
gate_to = int(store.config()["gate"].get("budget_s", 120)) + 30
return {"SessionStart": (b + " tick --tool claude-code", 10), "Stop": (b + " gate --tool claude-code", gate_to),
"SubagentStop": (b + " gate --subagent --tool claude-code", 30)}
return {"SessionStart": (hookjson.fail_open_command(paths.launcher(), "tick", "claude-code"), 10),
"Stop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code"), gate_to),
"SubagentStop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code", True), 30)}
def _claude_spec():
return {ev: {"cmd": cmd, "timeout": to,
"sub": hookjson.sisi_invocation(cmd)[1]} for ev, (cmd, to) in hook_cmds().items()}
def _is_ours(h, sub):
if not (isinstance(h, dict) and h.get("type") == "command" and isinstance(h.get("command"), str)):
return False
try:
parts = shlex.split(h["command"])
except ValueError:
return False
return len(parts) >= 2 and os.path.basename(parts[0]) == "sisi" and parts[1] == sub
return (isinstance(h, dict) and h.get("type") == "command"
and hookjson.is_ours_command(h.get("command"), sub))
def _parse_settings(text):
@@ -192,23 +272,40 @@ def add_hooks(obj):
if not isinstance(hooks, dict):
raise ValueError("settings.json 'hooks' is not an object")
for ev, (cmd, to) in hook_cmds().items():
sub = shlex.split(cmd)[1]
sub = hookjson.sisi_invocation(cmd)[1]
groups = hooks.get(ev)
if groups is None:
groups = hooks[ev] = []
changed = True
if not isinstance(groups, list):
raise ValueError("settings.json hooks.%s is not a list" % ev)
found = False
found, kept = False, []
for g in groups:
for h in (g.get("hooks", []) if isinstance(g, dict) and isinstance(g.get("hooks"), list) else []):
hs = g.get("hooks") if isinstance(g, dict) else None
if not isinstance(hs, list):
kept.append(g)
continue
rest = []
for h in hs:
if _is_ours(h, sub):
if found:
changed = True # a second registration would run the hook twice; keep exactly one
continue
found = True
if h.get("command") != cmd:
h["command"] = cmd
changed = True
if h.get("timeout") != to:
h["timeout"] = to
changed = True
rest.append(h)
if rest or not hs:
kept.append(dict(g, hooks=rest) if rest != hs else g)
else:
changed = True
hooks[ev] = kept
if not found:
groups.append({"hooks": [{"type": "command", "command": cmd, "timeout": to}]})
kept.append({"hooks": [{"type": "command", "command": cmd, "timeout": to}]})
changed = True
return changed
@@ -251,7 +348,8 @@ def _hooks_wired(obj):
out[key] = False
for g in groups if isinstance(groups, list) else []:
for h in g.get("hooks", []) if isinstance(g, dict) and isinstance(g.get("hooks"), list) else []:
if _is_ours(h, sub) and shlex.split(h["command"])[0] == paths.launcher():
inv = hookjson.sisi_invocation(h.get("command")) if isinstance(h, dict) else None
if _is_ours(h, sub) and inv and inv[0] == paths.launcher():
out[key] = True
return out
@@ -295,11 +393,18 @@ def _link(m, p, target, notes, label):
# ---- install / uninstall ---------------------------------------------------
def _writable(p):
"""Can we create or replace the file p (following symlinks)? Returns an error string or None."""
if os.path.islink(p) and not os.path.exists(p):
return "%s is a dangling symlink" % p
"""Can we read and create-or-replace the file p (following symlinks)? Returns an error string or None.
An existing file must itself be writable, not just its folder: an atomic replace would otherwise
silently overwrite a file the user made read-only."""
if _dangling(p):
return "%s is a dangling symlink (to %s)" % (p, os.readlink(p))
if os.path.isdir(p):
return "%s is a directory" % p
real = os.path.realpath(p)
if os.path.exists(real):
if not os.access(real, os.R_OK):
return "%s cannot be read" % p
ok = os.access(real, os.W_OK) and os.access(os.path.dirname(real), os.W_OK)
else:
d = os.path.dirname(real)
@@ -309,6 +414,31 @@ def _writable(p):
return None if ok else "%s is not writable" % p
def _link_writable(p, target):
"""Would creating or replacing the symlink p be possible? None when no write is needed or possible."""
if os.path.islink(p) and os.readlink(p) == target:
return None
if os.path.lexists(p) and not (os.path.islink(p) and _ours(p)):
return None # a user file or foreign symlink: _link leaves it alone
d = os.path.dirname(p)
while d and not os.path.isdir(d):
d = os.path.dirname(d)
return None if os.access(d, os.W_OK) else "%s is not writable" % d
def _link_plan_lines(p, target, label):
if os.path.islink(p):
cur = os.readlink(p)
if cur == target:
return []
if not _ours(p):
return ["%s: skip %s (symlink to %s; not touched)" % (label, p, cur)]
return ["%s: replace link %s -> %s" % (label, p, target)]
if os.path.lexists(p):
return ["%s: skip %s (exists and is not a symlink; not touched)" % (label, p)]
return ["%s: create link %s -> %s" % (label, p, target)]
def _plan_claude(L):
"""Compute every change to Claude Code's files without touching anything. Returns (steps, errors)."""
steps, errs = [], []
@@ -328,11 +458,16 @@ def _plan_claude(L):
else:
data = _read(p)
try:
obj, ind, nl = _parse_settings(data if data is not None else b"")
if add_hooks(obj):
steps.append((p, data, _dump(obj, ind, nl if data is not None else True),
"claude-code: hooks registered in %s" % p))
except (ValueError, UnicodeDecodeError) as ex:
if data is None or not data.strip():
obj, ind, nl = _parse_settings(data if data is not None else b"")
if add_hooks(obj):
steps.append((p, data, _dump(obj, ind, nl if data is not None else True),
"claude-code: hooks registered in %s" % p))
else:
new = hookjson.add_nested(data.decode("utf-8"), _claude_spec()).encode("utf-8")
if new != data:
steps.append((p, data, new, "claude-code: hooks registered in %s" % p))
except ValueError as ex:
errs.append("settings.json is not valid (%s); %s left untouched" % (ex, p))
return steps, errs
@@ -357,6 +492,8 @@ def install():
except Exception as e:
return 1, ["install refused, the personal data could not be prepared (%r); nothing was wired" % e]
m = _mload()
from . import adapters
prefailed = adapters.preflight_all() # every adapter target checked before the first one is touched
try:
for p, old, new, note in steps:
_backup(m, p, old)
@@ -367,11 +504,10 @@ def install():
_write(p, new)
notes.append(note)
for key in ("codex", "opencode"):
if os.path.isdir(L[key + "_dir"]):
if os.path.isdir(L[key + "_dir"]) and key not in prefailed:
_link(m, L[key], core(), notes, key)
else:
notes.append("%s: %s not found; skipped" % (key, L[key + "_dir"]))
notes.append("muse: not wired (global instruction path unconfirmed)")
# absence (and any preflight refusal) is reported once, by the tool's adapter below
adapters.wire_all(m, notes, prefailed)
sk = os.path.join(paths.product_root(), "canon", "skills")
for name in sorted(os.listdir(sk)) if os.path.isdir(sk) else []:
if os.path.isdir(os.path.join(sk, name)):
@@ -385,46 +521,87 @@ def install():
return 0, notes
def install_dry_run():
"""Exactly what install would create, edit (with diffs) or skip — changing nothing at all.
Nothing is prepared either: no personal folder, no generated rulebook, no manifest."""
from . import adapters
L = loc()
notes = ["dry-run: nothing will be changed"]
rc = 0
if os.path.isdir(L["claude_dir"]):
steps, errs = _plan_claude(L)
if errs:
rc = 1
notes += ["claude-code: install would be refused: " + e for e in errs]
else:
ops = [{"kind": "create" if old is None else "edit", "path": p, "old": old, "new": new}
for p, old, new, _note in steps]
notes += adapters.format_ops("claude-code", ops)
else:
notes.append("claude-code: %s not found; skipped" % L["claude_dir"])
prefailed = adapters.preflight_all()
for key in ("codex", "opencode"):
if os.path.isdir(L[key + "_dir"]) and key not in prefailed:
notes += _link_plan_lines(L[key], core(), key)
notes += adapters.dry_run_lines()
sk = os.path.join(paths.product_root(), "canon", "skills")
for name in sorted(os.listdir(sk)) if os.path.isdir(sk) else []:
if os.path.isdir(os.path.join(sk, name)):
notes += _link_plan_lines(os.path.join(L["skills"], name), os.path.join(sk, name), "skills")
notes += _link_plan_lines(L["bin"], paths.launcher(), "cli")
notes.append("dry-run: no files were changed")
return rc, notes
def uninstall():
L, notes = loc(), []
m = _mload()
# CLAUDE.md
p = L["claude_md"]
data = _read(p)
if _dangling(p):
notes.append("claude-code: %s is a dangling symlink; not touched" % p)
data = None
if data is not None and BLOCK_RE.search(data):
new = remove_import(data)
if not new and m["files"].get(p, {}).get("backup") is None and p in m["files"]:
if not new and m["files"].get(p, {}).get("backup") is None and p in m["files"] and not os.path.islink(p):
os.unlink(p)
else:
_write(p, new)
notes.append("claude-code: import line removed")
# settings.json
p = L["settings"]
data = _read(p)
data, read_err = _read_file(p)
ent = m["files"].get(p)
if data is not None:
if read_err:
notes.append("claude-code: settings.json not touched (%s)" % read_err)
elif data is not None:
try:
obj, ind, nl = _parse_settings(data)
before = copy.deepcopy(obj)
if remove_hooks(obj):
if ent is not None and ent["backup"] is None and not obj:
text = data.decode("utf-8")
subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate"}
orig = _read(os.path.join(_idir(), "backups", ent["backup"])) if ent and ent["backup"] else None
drop_hooks, _dv = hookjson.backup_drop_flags(
orig.decode("utf-8") if orig is not None else None, None) if orig is not None else (True, False)
removed = hookjson.remove_nested(text, subs, drop_empty_hooks=drop_hooks)
if removed != text:
root = hookjson.parse(removed) if removed.strip() else None
empty_root = root is not None and root.kind == "obj" and not root.members
if ent is not None and ent["backup"] is None and empty_root and not os.path.islink(p):
os.unlink(p)
else:
orig = _read(os.path.join(_idir(), "backups", ent["backup"])) if ent and ent["backup"] else None
try:
back = _parse_settings(orig)[0] if orig is not None else None
except ValueError:
back = None
if back is not None:
t = copy.deepcopy(back)
add_hooks(t)
if back is not None and t == before:
_write(p, orig) # current file is original + our entries: restore exact bytes
else:
_write(p, _dump(obj, ind, nl))
restored = False
if orig is not None:
try:
restored = hookjson.add_nested(orig.decode("utf-8"), _claude_spec()) == text
except ValueError:
restored = False
# unedited since install: restore exact bytes; edited: only our spans were removed above
_write(p, orig if restored else removed.encode("utf-8"))
notes.append("claude-code: hooks removed")
except (ValueError, UnicodeDecodeError) as e:
except ValueError as e:
notes.append("claude-code: settings.json not touched (%s)" % e)
from . import adapters
adapters.unwire_all(m, notes)
# symlinks
cand = [L["codex"], L["opencode"], L["bin"]]
if os.path.isdir(L["skills"]):
@@ -458,22 +635,36 @@ def doctor():
("gate hook", hw["gate"]), ("subagent hook", hw["subagent"])) if not ok]
rows.append({"tool": "claude-code", "status": "not wired" if missing else "wired",
"detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + gate registered",
"blocking_hook": "yes (Stop)" if hw["gate"] else "no"})
for key, name, hook in (("codex", "codex", "no (documented, not built)"),
("opencode", "opencode", "no (none verified)")):
p = L[key]
if os.path.islink(p) and os.readlink(p) == core():
st_, det = "wired", "%s -> the generated rulebook" % p
elif os.path.islink(p) and os.readlink(p) in _old_cores():
st_, det = "not wired", "%s -> the product's canon/core.md (old wiring; run `sisi install`)" % p
elif os.path.lexists(p):
st_, det = "not wired", "%s exists and is not ours (left alone)" % p
else:
st_, det = "not wired", "no %s" % p
rows.append({"tool": name, "status": st_, "detail": det, "blocking_hook": hook})
rows.append({"tool": "muse", "status": "not wired",
"detail": "global instruction path unconfirmed (binary mentions ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md as foreign context; unverified)",
"blocking_hook": "unknown"})
"blocking_hook": "yes (Stop)" if hw["gate"] else "no",
"rulebook": not missing and _claude_md_wired(cm), "tick": hw["tick"],
"enforcement": "blocks", "action": None})
from . import adapters
tool_rows = []
for a in adapters.ADAPTERS:
st = a.status()
if a.name not in ("codex", "opencode", "muse") and not st["detected"]:
continue # a tool this user does not have gets no row; codex/opencode keep their historic rows
enf = st["enforcement"]
blocking = ("blocks (%s)" % st["via"] if enf == "blocks" else
"sends a follow-up (%s)" % st["via"] if enf == "sends a follow-up" else enf)
tool_rows.append({"tool": st["tool"], "status": "wired" if st["wired"] else "not wired",
"detail": st["detail"], "blocking_hook": blocking, "rulebook": st["rulebook"],
"tick": st["tick"], "enforcement": enf, "action": st["action"]})
rows += tool_rows
anti = adapters.antigravity_status()
if anti["detected"]:
rows.append({"tool": "antigravity", "status": "not wired", "detail": anti["detail"],
"blocking_hook": "unknown", "rulebook": anti["rulebook"], "tick": False,
"enforcement": "unknown", "action": None})
_providers = {"claude-code", "codex", "opencode", "cursor", "pi", "muse", "gemini", "copilot", "qwen", "grok"}
wired_names = [n for n in ([r["tool"] for r in tool_rows if r["status"] == "wired"]
+ (["claude-code"] if rows[0]["status"] == "wired" else [])) if n in _providers]
providers = ", ".join(sorted(set(wired_names))) or "none wired yet"
for host in ("t3-code", "orca"):
rows.append({"tool": host, "status": "ok",
"detail": "host app with no instructions or hooks of its own; covered through the providers it runs (wired: %s)" % providers,
"blocking_hook": "via provider", "rulebook": bool(wired_names), "tick": False,
"enforcement": "via provider", "action": None})
sk = paths.canon("skills")
names = [n for n in sorted(os.listdir(sk)) if os.path.isdir(os.path.join(sk, n))] if os.path.isdir(sk) else []
bad = [n for n in names if not (_ours(os.path.join(L["skills"], n)))]
@@ -502,7 +693,9 @@ def doctor():
def quick_problem():
"""Cheap check for tick. Returns a short string or None."""
L = loc()
refs = any(os.path.islink(L[k]) and os.readlink(L[k]) == core() for k in ("codex", "opencode"))
from . import adapters
links = [(k, L[k]) for k in ("codex", "opencode")] + adapters.rulebook_links()
refs = any(os.path.islink(p) and os.readlink(p) == core() for _, p in links)
refs = refs or _claude_md_wired(_read(L["claude_md"])) # only complain about a rulebook something points at
if refs and not os.path.isfile(core()):
return "the generated rulebook is missing at %s (run `sisi build-canon`)" % core()
@@ -510,8 +703,8 @@ def quick_problem():
from . import overlay
if overlay.is_stale():
return "the generated rulebook is out of date (run `sisi build-canon`)"
for k in ("codex", "opencode"):
if os.path.islink(L[k]) and os.readlink(L[k]).startswith((paths.REPO, paths.data())) and not os.path.exists(L[k]):
for k, p in links:
if os.path.islink(p) and os.readlink(p).startswith((paths.REPO, paths.data())) and not os.path.exists(p):
return "%s link is dangling" % k
if os.path.isdir(L["claude_dir"]):
r = doctor_claude()
+5 -2
View File
@@ -44,10 +44,13 @@ class SisiCase(unittest.TestCase):
self.proj = os.path.join(self.tmp, "proj")
for d in (self.home, self.proj):
os.makedirs(d)
saved = {k: os.environ.get(k) for k in ("SISI_HOME", "SISI_STATE", "SISI_DATA", "SISI_TOOL", "SISI_SESSION_ID", "SISI_RETRO_REQUIRED", "SISI_NOTES")}
tool_env = ("CODEX_HOME", "COPILOT_HOME", "PI_CODING_AGENT_DIR", "OPENCODE_CONFIG_DIR",
"GROK_HOME", "XDG_CONFIG_HOME")
saved = {k: os.environ.get(k) for k in ("SISI_HOME", "SISI_STATE", "SISI_DATA", "SISI_TOOL", "SISI_SESSION_ID", "SISI_RETRO_REQUIRED", "SISI_NOTES") + tool_env}
os.environ.update(SISI_HOME=self.home, SISI_STATE=self.state, SISI_DATA=self.data,
SISI_RETRO_REQUIRED="0") # retro tests turn it on
os.environ.pop("SISI_NOTES", None)
for k in ("SISI_NOTES",) + tool_env: # tool config-dir overrides must not leak the real ones in
os.environ.pop(k, None)
_CURRENT.append(self.tmp)
self.addCleanup(_CURRENT.pop)
for k in ("SISI_TOOL", "SISI_SESSION_ID"):
+348
View File
@@ -0,0 +1,348 @@
import json, os, random, shutil, unittest
from support import *
from test_wiring import WiringBase, snapshot, rand_json, rand_hook_group
from sisi import adapters, paths, wiring
class AdapterBase(WiringBase):
def fresh_home(self):
shutil.rmtree(self.home, ignore_errors=True)
shutil.rmtree(self.state, ignore_errors=True)
shutil.rmtree(self.data, ignore_errors=True)
os.makedirs(os.path.join(self.home, ".claude"))
def cycle(self):
"""install, install again (idempotent), uninstall (exact). Returns first install's notes."""
before = snapshot(self.home)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
after = snapshot(self.home)
rc2, _ = wiring.install()
self.assertEqual(rc2, 0)
self.assertEqual(snapshot(self.home), after, "second install changed something")
wiring.uninstall()
self.assertEqual(snapshot(self.home), before, "uninstall did not restore the original home")
return notes
def rows(self):
return {r["tool"]: r for r in wiring.doctor()}
class HookToolTests(AdapterBase):
def test_codex_hooks_trust_note_and_exact_uninstall(self):
os.makedirs(self.path(".codex"))
pre = {"description": "mine", "hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "echo keep"}]}],
"Stop": [{"hooks": [{"type": "command", "command": "echo also-keep"}]}]}}
self.put(".codex/hooks.json", json.dumps(pre, indent=2).encode())
notes = self.cycle()
self.assertTrue(any("/hooks" in n and "trust" in n for n in notes))
def test_codex_hooks_wired_then_doctor(self):
os.makedirs(self.path(".codex"))
self.put(".codex/hooks.json", b'{"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "echo keep"}]}]}}\n')
wiring.install()
d = json.load(open(self.path(".codex/hooks.json")))
self.assertEqual(d["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "echo keep")
for ev, frag in (("SessionStart", "tick --tool codex"), ("Stop", "gate --tool codex"), ("SubagentStop", "gate --subagent --tool codex")):
cmds = [h["command"] for g in d["hooks"][ev] for h in g["hooks"]]
self.assertTrue(any(frag in c for c in cmds), (ev, cmds))
self.assertEqual(d["hooks"]["SessionStart"][0]["matcher"], "startup|resume")
r = self.rows()["codex"]
self.assertEqual((r["status"], r["enforcement"]), ("wired", "blocks"))
self.assertIn("/hooks", r["action"])
wiring.uninstall()
def test_gemini_hooks_and_link(self):
os.makedirs(self.path(".gemini"))
self.put(".gemini/settings.json", b'{"theme": "dark", "hooks": {"BeforeTool": [{"matcher": ".*", "hooks": [{"type": "command", "command": "echo k"}]}]}}\n')
self.cycle()
wiring.install()
d = json.load(open(self.path(".gemini/settings.json")))
self.assertEqual(d["theme"], "dark")
cmds = {ev: [h["command"] for g in d["hooks"][ev] for h in g["hooks"]] for ev in ("SessionStart", "AfterAgent")}
self.assertTrue(any("tick --tool gemini" in c for c in cmds["SessionStart"]))
self.assertTrue(any("gate --tool gemini" in c for c in cmds["AfterAgent"]))
gate_hook = [h for g in d["hooks"]["AfterAgent"] for h in g["hooks"] if "gate" in h["command"]][0]
self.assertGreaterEqual(gate_hook["timeout"], 60000) # Gemini timeouts are milliseconds
self.assertTrue(os.path.islink(self.path(".gemini/GEMINI.md")))
self.assertEqual(self.rows()["gemini"]["status"], "wired")
wiring.uninstall()
def test_gemini_user_file_not_touched(self):
os.makedirs(self.path(".gemini"))
self.put(".gemini/GEMINI.md", b"mine\n")
notes = self.cycle()
self.assertEqual(open(self.path(".gemini/GEMINI.md"), "rb").read(), b"mine\n")
def test_copilot_hooks_file_and_link(self):
os.makedirs(self.path(".copilot", "hooks"))
self.put(".copilot/hooks/other.json", b'{"version": 1, "hooks": {}}\n')
self.put(".copilot/hooks/sisi.json", b'{"version": 1, "mine": true, "hooks": {"preToolUse": [{"type": "command", "bash": "echo keep", "timeoutSec": 5}]}}\n')
self.cycle()
wiring.install()
d = json.load(open(self.path(".copilot/hooks/sisi.json")))
self.assertTrue(d["mine"])
self.assertEqual(d["hooks"]["preToolUse"][0]["bash"], "echo keep")
for ev, frag in (("sessionStart", "tick --tool copilot"), ("agentStop", "gate --tool copilot")):
self.assertTrue(any(frag in e.get("bash", "") for e in d["hooks"][ev]), ev)
self.assertTrue(os.path.islink(self.path(".copilot/copilot-instructions.md")))
self.assertEqual(self.rows()["copilot"]["enforcement"], "blocks")
wiring.uninstall()
self.assertEqual(open(self.path(".copilot/hooks/other.json"), "rb").read(), b'{"version": 1, "hooks": {}}\n')
def test_qwen_hooks_and_link(self):
os.makedirs(self.path(".qwen"))
self.put(".qwen/settings.json", b'{"ui": {"theme": "x"}}\n')
self.cycle()
wiring.install()
d = json.load(open(self.path(".qwen/settings.json")))
self.assertEqual(d["ui"], {"theme": "x"})
self.assertTrue(os.path.islink(self.path(".qwen/QWEN.md")))
self.assertEqual(self.rows()["qwen"]["status"], "wired")
wiring.uninstall()
def test_cursor_hooks_preserve_existing(self):
os.makedirs(self.path(".cursor"))
pre = {"version": 1, "hooks": {"sessionStart": [{"command": "bash '/x/herdr.sh' session"}], "afterFileEdit": [{"command": "./fmt.sh"}]}}
self.put(".cursor/hooks.json", json.dumps(pre, indent=2).encode())
self.cycle()
wiring.install()
d = json.load(open(self.path(".cursor/hooks.json")))
self.assertEqual(d["hooks"]["afterFileEdit"][0]["command"], "./fmt.sh")
self.assertIn("herdr", d["hooks"]["sessionStart"][0]["command"])
self.assertTrue(any("gate --tool cursor" in e["command"] for e in d["hooks"]["stop"]))
r = self.rows()["cursor"]
self.assertEqual((r["status"], r["enforcement"], r["rulebook"]), ("wired", "sends a follow-up", False))
wiring.uninstall()
def test_pi_extension_and_link(self):
os.makedirs(self.path(".pi", "agent"))
self.cycle()
wiring.install()
ext = self.path(".pi/agent/extensions/sisi.ts")
text = open(ext).read()
for frag in ("session_start", "before_agent_start", "agent_before_settle", "sisi:generated", paths.launcher()):
self.assertIn(frag, text)
self.assertTrue(os.path.islink(self.path(".pi/agent/AGENTS.md")))
self.assertEqual(self.rows()["pi"]["status"], "wired")
wiring.uninstall()
self.assertFalse(os.path.lexists(ext))
def test_pi_user_agents_md_kept(self):
os.makedirs(self.path(".pi", "agent"))
self.put(".pi/agent/AGENTS.md", b"my own rules\n")
self.cycle()
self.assertEqual(open(self.path(".pi/agent/AGENTS.md"), "rb").read(), b"my own rules\n")
def test_opencode_plugin_written_and_foreign_plugin_kept(self):
os.makedirs(self.path(".config", "opencode", "plugins"))
self.put(".config/opencode/plugins/herdr-agent-state.js", b"// theirs\n")
self.cycle()
self.assertEqual(open(self.path(".config/opencode/plugins/herdr-agent-state.js"), "rb").read(), b"// theirs\n")
wiring.install()
text = open(self.path(".config/opencode/plugins/sisi.js")).read()
for frag in ("session.created", "session.idle", "sisi:generated", paths.launcher()):
self.assertIn(frag, text)
r = self.rows()["opencode"]
self.assertEqual((r["status"], r["enforcement"], r["tick"]), ("wired", "unknown", False))
wiring.uninstall()
def test_generated_file_conflict_skipped(self):
os.makedirs(self.path(".config", "opencode", "plugins"))
self.put(".config/opencode/plugins/sisi.js", b"// my own plugin, not sisi's\n")
notes = self.cycle()
self.assertEqual(open(self.path(".config/opencode/plugins/sisi.js"), "rb").read(), b"// my own plugin, not sisi's\n")
self.assertTrue(any("not touched" in n for n in notes))
def test_invalid_tool_config_skips_only_that_tool(self):
os.makedirs(self.path(".gemini"))
os.makedirs(self.path(".codex"))
self.put(".gemini/settings.json", b"{ not json")
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".gemini/settings.json"), "rb").read(), b"{ not json")
self.assertTrue(any(n.startswith("gemini: skipped") for n in notes))
self.assertTrue(os.path.exists(self.path(".codex/hooks.json"))) # other tools still wired
wiring.uninstall()
self.assertEqual(open(self.path(".gemini/settings.json"), "rb").read(), b"{ not json")
class RulebookOnlyTests(AdapterBase):
DIRS = {"kiro": (".kiro", ".kiro/steering/AGENTS.md"), "zed": (".config/zed", ".config/zed/AGENTS.md"),
"goose": (".config/goose", ".config/goose/.goosehints"), "amp": (".config/amp", ".config/amp/AGENTS.md"),
"grok": (".grok", ".grok/AGENTS.md"), "crush": (".config/crush", ".config/crush/CRUSH.md")}
def test_each_links_and_uninstalls_exactly(self):
for name, (d, link) in self.DIRS.items():
with self.subTest(tool=name):
self.fresh_home()
os.makedirs(self.path(d))
self.cycle()
wiring.install()
self.assertTrue(os.path.islink(self.path(link)), link)
self.assertEqual(os.readlink(self.path(link)), wiring.core())
r = self.rows()[name]
self.assertEqual((r["status"], r["enforcement"]), ("wired", "none"))
wiring.uninstall()
def test_cline_documents_and_dotcline_variants(self):
for base, link in (("Documents/Cline", "Documents/Cline/Rules/sisi.md"), (".cline", ".cline/rules/sisi.md")):
with self.subTest(base=base):
self.fresh_home()
os.makedirs(self.path(base))
self.cycle()
wiring.install()
self.assertTrue(os.path.islink(self.path(link)))
wiring.uninstall()
def test_windsurf_pointer_and_user_file_guard(self):
os.makedirs(self.path(".codeium", "windsurf"))
self.cycle()
wiring.install()
text = open(self.path(".codeium/windsurf/memories/global_rules.md")).read()
self.assertIn(wiring.core(), text)
self.assertLess(len(text), 6000)
wiring.uninstall()
self.assertFalse(os.path.exists(self.path(".codeium/windsurf/memories/global_rules.md")))
self.fresh_home()
os.makedirs(self.path(".codeium", "windsurf", "memories"))
self.put(".codeium/windsurf/memories/global_rules.md", b"my rules\n")
self.cycle()
self.assertEqual(open(self.path(".codeium/windsurf/memories/global_rules.md"), "rb").read(), b"my rules\n")
def test_aider_shapes_round_trip(self):
cases = [
b"model: test\n",
b"",
b"read:\n - docs/a.md\nmodel: test\n",
b"read: [docs/a.md, docs/b.md]\n",
b"read: []\n",
b"read: docs/a.md\n",
b"# comment\nread:\n - 'quoted name.md'\n",
]
for orig in cases:
with self.subTest(orig=orig[:24]):
self.fresh_home()
self.put(".aider.conf.yml", orig)
self.cycle()
wiring.install()
now = open(self.path(".aider.conf.yml")).read()
self.assertIn(wiring.core(), now)
self.assertEqual(self.rows()["aider"]["status"], "wired")
wiring.uninstall()
self.assertEqual(open(self.path(".aider.conf.yml"), "rb").read(), orig)
def test_aider_unrecognised_shape_left_alone(self):
self.put(".aider.conf.yml", b"read: &anchor docs/a.md\n")
rc, notes = wiring.install()
self.assertEqual(rc, 0)
self.assertEqual(open(self.path(".aider.conf.yml"), "rb").read(), b"read: &anchor docs/a.md\n")
self.assertTrue(any(n.startswith("aider: skipped") for n in notes))
wiring.uninstall()
class DetectionAndDoctorTests(AdapterBase):
ALL_DIRS = [".codex", ".gemini", ".copilot", ".qwen", ".pi/agent", ".cursor", ".config/opencode",
".codeium/windsurf", "Documents/Cline", ".kiro", ".config/zed", ".config/goose",
".config/amp", ".grok", ".config/crush", ".config/muse", ".gemini/antigravity", ".t3"]
def test_absent_tools_skipped_and_no_rows(self):
rc, notes = wiring.install()
self.assertEqual(rc, 0)
for name in ("codex", "gemini", "copilot", "qwen", "pi", "cursor", "opencode", "windsurf", "cline",
"kiro", "zed", "goose", "amp", "grok", "crush", "aider", "muse"):
self.assertTrue(any(n.startswith(name + ":") and "skipped" in n for n in notes), name)
rows = self.rows()
for name in ("gemini", "copilot", "qwen", "pi", "cursor", "windsurf", "antigravity"):
self.assertNotIn(name, rows)
self.assertEqual(rows["muse"]["status"], "not wired")
self.assertIn("foreign", rows["muse"]["detail"])
self.assertIn("t3-code", rows)
self.assertIn("orca", rows)
wiring.uninstall()
def test_every_row_when_every_folder_exists(self):
for d in self.ALL_DIRS:
os.makedirs(self.path(d), exist_ok=True)
self.put(".aider.conf.yml", b"model: test\n")
wiring.install()
rows = self.rows()
for name in ("claude-code", "codex", "gemini", "copilot", "qwen", "pi", "cursor", "opencode", "windsurf",
"cline", "kiro", "zed", "goose", "amp", "grok", "crush", "aider", "muse", "antigravity",
"t3-code", "orca", "skills", "cli", "product", "personal", "rulebook"):
self.assertIn(name, rows)
for name in ("codex", "gemini", "copilot", "qwen", "pi"):
self.assertEqual((rows[name]["status"], rows[name]["enforcement"]), ("wired", "blocks"), name)
self.assertEqual(rows["cursor"]["enforcement"], "sends a follow-up")
self.assertEqual(rows["opencode"]["enforcement"], "unknown")
self.assertEqual(rows["muse"]["rulebook"], True)
self.assertIn("claude-code", rows["t3-code"]["detail"])
wiring.uninstall()
def test_plan_changes_nothing(self):
for d in self.ALL_DIRS:
os.makedirs(self.path(d), exist_ok=True)
self.put(".aider.conf.yml", b"model: test\n")
before = snapshot(self.home)
plans = {a.name: a.plan() for a in adapters.ADAPTERS if a.detect()}
self.assertEqual(snapshot(self.home), before)
self.assertTrue(plans["codex"])
self.assertTrue(plans["pi"])
def rand_hooks_obj(rng, flat):
obj = {rng.choice("pqrs") + str(i): rand_json(rng) for i in range(rng.randint(0, 3))}
if rng.random() < 0.75:
h = {}
events = ("sessionStart", "stop", "agentStop") if flat else ("SessionStart", "Stop", "PreToolUse", "AfterAgent")
for ev in events:
if rng.random() < 0.5:
if flat:
h[ev] = [{"command": "echo %d" % rng.randint(0, 9)} if rng.random() < 0.5
else {"type": "command", "bash": "echo %d" % rng.randint(0, 9), "timeoutSec": 5}
for _ in range(rng.randint(0, 2))]
else:
h[ev] = [rand_hook_group(rng) for _ in range(rng.randint(0, 2))]
obj["hooks"] = h
if flat and rng.random() < 0.5:
obj["version"] = 1
ind = rng.choice([None, 2, 4])
text = json.dumps(obj, indent=ind, ensure_ascii=rng.random() < 0.5)
if rng.random() < 0.5:
text += "\n"
return text.encode("utf-8")
class MergePropertyTests(AdapterBase):
TARGETS = {"codex": (".codex", ".codex/hooks.json", False), "gemini": (".gemini", ".gemini/settings.json", False),
"qwen": (".qwen", ".qwen/settings.json", False), "cursor": (".cursor", ".cursor/hooks.json", True),
"copilot": (".copilot", ".copilot/hooks/sisi.json", True)}
def test_random_preexisting_configs(self):
for name, (d, f, flat) in self.TARGETS.items():
for seed in (11, 12, 13):
rng = random.Random(seed * 1000 + len(name))
for n in range(6 * ITERS):
with self.subTest(tool=name, seed=seed, n=n):
self.fresh_home()
os.makedirs(self.path(d), exist_ok=True)
if rng.random() < 0.8:
self.put(f, rand_hooks_obj(rng, flat))
self.cycle()
class GeneratedScriptTests(AdapterBase):
def test_opencode_plugin_parses_as_javascript(self):
node = shutil.which("node")
if not node:
self.skipTest("node not installed")
import subprocess
p = os.path.join(self.tmp, "sisi-check.mjs")
with open(p, "wb") as fh:
fh.write(adapters._opencode_plugin())
r = subprocess.run([node, "--check", p], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stderr)
if __name__ == "__main__":
unittest.main()
+154
View File
@@ -0,0 +1,154 @@
import json, os, unittest
from support import *
from sisi import hookio, paths
def payload(tool, proj, sid):
if tool == "codex":
return {"session_id": sid, "transcript_path": "/tmp/t.jsonl", "cwd": proj,
"hook_event_name": "Stop", "turn_id": "t1", "stop_hook_active": False, "last_assistant_message": "done"}
if tool == "qwen":
return {"session_id": sid, "transcript_path": "/tmp/t.jsonl", "cwd": proj,
"hook_event_name": "Stop", "stop_hook_active": False, "last_assistant_message": "done"}
if tool == "gemini":
return {"session_id": sid, "transcript_path": "/tmp/t.jsonl", "cwd": proj,
"hook_event_name": "AfterAgent", "timestamp": "2026-01-01T00:00:00Z",
"prompt": "do it", "prompt_response": "done", "stop_hook_active": False}
if tool == "copilot":
return {"sessionId": sid, "timestamp": 123, "cwd": proj, "transcriptPath": "/tmp/t.jsonl",
"stopReason": "end_turn", "stop_hook_active": False}
if tool == "cursor":
return {"conversation_id": sid, "generation_id": "g1", "model": "m", "hook_event_name": "stop",
"workspace_roots": [proj], "transcript_path": None, "status": "completed", "loop_count": 0}
return {"session_id": sid, "cwd": proj} # pi, opencode: the extension's own payload
ALLOW_OUT = {"codex": "", "qwen": "", "copilot": "", "gemini": "{}\n", "cursor": "{}\n", "pi": "", "opencode": ""}
class NormalizeTests(unittest.TestCase):
def test_camel_and_cursor_shapes(self):
n = hookio.normalize("copilot", {"sessionId": "s", "transcriptPath": "/t", "cwd": "/w", "agentId": "a"})
self.assertEqual(n, {"session_id": "s", "transcript_path": "/t", "cwd": "/w", "agent_id": "a"})
n = hookio.normalize("cursor", {"conversation_id": "c", "workspace_roots": ["/w"], "transcript_path": None})
self.assertEqual(n, {"session_id": "c", "cwd": "/w"})
def test_gate_out_shapes(self):
self.assertEqual(json.loads(hookio._gate_out("codex", "block", "why", False)[0]), {"decision": "block", "reason": "why"})
self.assertEqual(json.loads(hookio._gate_out("gemini", "block", "why", False)[0]), {"decision": "deny", "reason": "why"})
self.assertEqual(json.loads(hookio._gate_out("cursor", "block", "why", False)[0]), {"followup_message": "why"})
self.assertEqual(hookio._gate_out("pi", "block", "why", False), ("why\n", 2))
self.assertEqual(hookio._gate_out("opencode", "allow", None, False), (None, 0))
def test_tick_out_shapes(self):
self.assertEqual(json.loads(hookio._tick_out("codex", "lessons")),
{"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "lessons"}})
self.assertEqual(json.loads(hookio._tick_out("copilot", "lessons")), {"additionalContext": "lessons"})
self.assertEqual(json.loads(hookio._tick_out("cursor", "lessons")), {"additional_context": "lessons"})
self.assertEqual(hookio._tick_out("pi", "lessons"), "lessons\n")
self.assertIsNone(hookio._tick_out("codex", ""))
class GateTranslationTests(SisiCase):
def run_gate(self, tool, sid, raw=None):
return self.sisi("gate", "--tool", tool, stdin=raw if raw is not None else json.dumps(payload(tool, self.proj, sid)))
def test_allow_and_block_per_tool(self):
self.write_contract(contract([check("ok", "true")]))
for tool in hookio.TOOLS:
with self.subTest(tool=tool, case="allow"):
r = self.run_gate(tool, "allow-" + tool)
self.assertEqual((r.returncode, r.stdout), (0, ALLOW_OUT[tool]))
self.write_contract(contract([check("bad", "echo boom-output >&2; exit 1")]))
for tool in hookio.TOOLS:
with self.subTest(tool=tool, case="block"):
r = self.run_gate(tool, "block-" + tool)
if tool in ("pi", "opencode"):
self.assertEqual(r.returncode, 2)
self.assertIn("boom-output", r.stdout)
continue
self.assertEqual(r.returncode, 0)
d = json.loads(r.stdout)
if tool == "gemini":
self.assertEqual(d["decision"], "deny")
self.assertIn("boom-output", d["reason"])
elif tool == "cursor":
self.assertIn("boom-output", d["followup_message"])
else:
self.assertEqual(d["decision"], "block")
self.assertIn("boom-output", d["reason"])
def test_copilot_snake_case_variant(self):
self.write_contract(contract([check("bad", "false")]))
p = {"hook_event_name": "Stop", "session_id": "snake-1", "timestamp": "2026-01-01T00:00:00Z",
"cwd": self.proj, "transcript_path": "/tmp/t", "stop_reason": "end_turn", "stop_hook_active": False}
r = self.sisi("gate", "--tool", "copilot", stdin=json.dumps(p))
self.assertEqual(json.loads(r.stdout)["decision"], "block")
def test_cursor_aborted_turn_is_not_gated(self):
self.write_contract(contract([check("bad", "false")]))
p = payload("cursor", self.proj, "cur-abort")
p["status"] = "aborted"
r = self.sisi("gate", "--tool", "cursor", stdin=json.dumps(p))
self.assertEqual((r.returncode, r.stdout), (0, "{}\n"))
def test_garbage_fails_open_per_tool(self):
self.write_contract(contract([check("bad", "false")]))
for tool in hookio.TOOLS:
for raw in ("not json{{{", "[1, 2]", "42"):
with self.subTest(tool=tool, raw=raw):
r = self.run_gate(tool, "garbage-" + tool, raw=raw)
self.assertEqual((r.returncode, r.stdout), (0, ALLOW_OUT[tool]))
def test_unknown_tool_keeps_claude_shape(self):
self.write_contract(contract([check("bad", "false")]))
p = {"session_id": "u1", "cwd": self.proj, "hook_event_name": "Stop"}
r = self.sisi("gate", "--tool", "no-such-tool", stdin=json.dumps(p))
self.assertEqual(json.loads(r.stdout)["decision"], "block")
class TickTranslationTests(SisiCase):
def make_tick_speak(self):
"""A dangling rulebook reference makes tick print one problem line, deterministically."""
d = os.path.join(self.home, ".codex")
os.makedirs(d, exist_ok=True)
link = os.path.join(d, "AGENTS.md")
if os.path.lexists(link):
os.unlink(link)
os.symlink(paths.generated(), link) # generated rulebook does not exist in this fresh home
def test_tick_shapes_with_text(self):
self.make_tick_speak()
starts = {
"codex": {"session_id": "t1", "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup"},
"gemini": {"session_id": "t2", "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup"},
"copilot": {"sessionId": "t3", "cwd": self.proj, "source": "startup"},
"cursor": {"session_id": "t4", "is_background_agent": False, "composer_mode": "agent"},
"pi": {"session_id": "t5", "cwd": self.proj},
}
for tool, p in starts.items():
with self.subTest(tool=tool):
r = self.sisi("tick", "--tool", tool, stdin=json.dumps(p))
self.assertEqual(r.returncode, 0)
if tool == "pi":
self.assertIn("generated rulebook is missing", r.stdout)
continue
d = json.loads(r.stdout)
if tool == "copilot":
text = d["additionalContext"]
elif tool == "cursor":
text = d["additional_context"]
else:
self.assertEqual(d["hookSpecificOutput"]["hookEventName"], "SessionStart")
text = d["hookSpecificOutput"]["additionalContext"]
self.assertIn("generated rulebook is missing", text)
def test_tick_garbage_fails_open(self):
for tool in hookio.TOOLS:
with self.subTest(tool=tool):
r = self.sisi("tick", "--tool", tool, stdin="not json{{{")
self.assertEqual(r.returncode, 0)
if __name__ == "__main__":
unittest.main()
+517
View File
@@ -0,0 +1,517 @@
import json, os, random, shutil, stat, subprocess, sys, unittest
from unittest import mock
from support import *
from test_wiring import WiringBase, snapshot
from sisi import adapters, paths, wiring
class SafetyBase(WiringBase):
def fresh_home(self):
shutil.rmtree(self.home, ignore_errors=True)
shutil.rmtree(self.state, ignore_errors=True)
shutil.rmtree(self.data, ignore_errors=True)
os.makedirs(os.path.join(self.home, ".claude"))
def rows(self):
return {r["tool"]: r for r in wiring.doctor()}
def skip_if_perms_ignored(self, p):
if os.access(p, os.W_OK):
self.skipTest("running as a user that ignores permissions")
class DanglingAndUnreadableTests(SafetyBase):
def test_dangling_symlink_config_refused_and_preserved(self):
os.makedirs(self.path(".gemini"))
os.makedirs(os.path.join(self.tmp, "elsewhere"))
target = os.path.join(self.tmp, "elsewhere", "settings.json")
os.symlink(target, self.path(".gemini/settings.json"))
before = snapshot(self.home)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertTrue(os.path.islink(self.path(".gemini/settings.json")))
self.assertEqual(os.readlink(self.path(".gemini/settings.json")), target)
self.assertFalse(os.path.exists(target), "install wrote through a dangling symlink")
self.assertTrue(any("dangling" in n for n in notes), notes)
wiring.uninstall()
self.assertTrue(os.path.islink(self.path(".gemini/settings.json")), "uninstall deleted the symlink")
self.assertEqual(snapshot(self.home), before)
def test_dangling_symlink_generated_refused_and_preserved(self):
os.makedirs(self.path(".config", "opencode", "plugins"))
os.makedirs(os.path.join(self.tmp, "elsewhere"))
target = os.path.join(self.tmp, "elsewhere", "sisi.js")
os.symlink(target, self.path(".config/opencode/plugins/sisi.js"))
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertTrue(os.path.islink(self.path(".config/opencode/plugins/sisi.js")))
self.assertFalse(os.path.exists(target), "install wrote through a dangling symlink")
wiring.uninstall()
self.assertTrue(os.path.islink(self.path(".config/opencode/plugins/sisi.js")), "uninstall deleted the symlink")
def test_directory_at_config_path_is_not_missing(self):
os.makedirs(self.path(".gemini", "settings.json"))
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertTrue(os.path.isdir(self.path(".gemini/settings.json")))
self.assertTrue(any("gemini" in n and ("director" in n or "cannot be read" in n or "not writable" in n) for n in notes), notes)
wiring.uninstall()
def test_live_symlinked_config_written_through_and_restored(self):
real = os.path.join(self.tmp, "dotfiles")
os.makedirs(real)
with open(os.path.join(real, "gemini-settings.json"), "wb") as f:
f.write(b'{"theme": "dark"}\n')
os.makedirs(self.path(".gemini"))
os.symlink(os.path.join(real, "gemini-settings.json"), self.path(".gemini/settings.json"))
wiring.install()
self.assertTrue(os.path.islink(self.path(".gemini/settings.json")))
self.assertIn(b"sisi", open(os.path.join(real, "gemini-settings.json"), "rb").read())
wiring.uninstall()
self.assertTrue(os.path.islink(self.path(".gemini/settings.json")))
self.assertEqual(open(os.path.join(real, "gemini-settings.json"), "rb").read(), b'{"theme": "dark"}\n')
class BackupPermissionTests(SafetyBase):
def test_backup_permissions_match_secret_source(self):
self.put(".claude/settings.json", b'{"apiKey": "secret"}\n')
os.chmod(self.path(".claude/settings.json"), 0o600)
os.makedirs(self.path(".gemini"))
self.put(".gemini/settings.json", b'{"apiKey": "secret2"}\n')
os.chmod(self.path(".gemini/settings.json"), 0o600)
wiring.install()
bdir = os.path.join(self.data, "install", "backups")
self.assertEqual(stat.S_IMODE(os.stat(bdir).st_mode), 0o700)
self.assertTrue(os.listdir(bdir))
for n in os.listdir(bdir):
mode = stat.S_IMODE(os.stat(os.path.join(bdir, n)).st_mode)
self.assertEqual(mode & 0o077, 0, (n, oct(mode)))
self.assertEqual(mode, 0o600, (n, oct(mode)))
wiring.uninstall()
class ReadOnlyPreflightTests(SafetyBase):
def test_readonly_adapter_config_skips_whole_tool_untouched(self):
os.makedirs(self.path(".gemini"))
self.put(".gemini/settings.json", b'{"theme": "dark"}\n')
os.chmod(self.path(".gemini/settings.json"), 0o444)
self.addCleanup(os.chmod, self.path(".gemini/settings.json"), 0o644)
self.skip_if_perms_ignored(self.path(".gemini/settings.json"))
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".gemini/settings.json"), "rb").read(), b'{"theme": "dark"}\n')
self.assertFalse(os.path.lexists(self.path(".gemini/GEMINI.md")), "half-wired: link created though hooks were refused")
self.assertTrue(any("gemini" in n and "skipped" in n for n in notes), notes)
os.chmod(self.path(".gemini/settings.json"), 0o644)
wiring.uninstall()
def test_readonly_codex_hooks_no_link_either(self):
os.makedirs(self.path(".codex"))
self.put(".codex/hooks.json", b'{"hooks": {}}\n')
os.chmod(self.path(".codex/hooks.json"), 0o444)
self.addCleanup(os.chmod, self.path(".codex/hooks.json"), 0o644)
self.skip_if_perms_ignored(self.path(".codex/hooks.json"))
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".codex/hooks.json"), "rb").read(), b'{"hooks": {}}\n')
self.assertFalse(os.path.lexists(self.path(".codex/AGENTS.md")), "half-wired: rulebook linked though hooks were refused")
os.chmod(self.path(".codex/hooks.json"), 0o644)
wiring.uninstall()
class DuplicateHookTests(SafetyBase):
def _count_nested(self, path, *events):
d = json.load(open(path))
out = {}
for ev in events:
out[ev] = sum(1 for g in d.get("hooks", {}).get(ev, []) for h in g.get("hooks", []) if "sisi" in h.get("command", ""))
return out
def test_duplicate_hooks_deduped_in_all_add_functions(self):
# structural add functions directly (Claude nested, adapter nested, adapter flat)
cmds = wiring.hook_cmds()
dup = {"hooks": {"Stop": [{"hooks": [{"type": "command", "command": cmds["Stop"][0], "timeout": 5}]},
{"hooks": [{"type": "command", "command": cmds["Stop"][0], "timeout": 5},
{"type": "command", "command": "echo user"}]}]}}
wiring.add_hooks(dup)
n = sum(1 for g in dup["hooks"]["Stop"] for h in g["hooks"] if h.get("command") == cmds["Stop"][0])
self.assertEqual(n, 1, dup)
self.assertTrue(any(h.get("command") == "echo user" for g in dup["hooks"]["Stop"] for h in g["hooks"]))
a = adapters.BY_NAME["codex"]
spec = a.spec()
dup2 = {"hooks": {"Stop": [{"hooks": [{"type": "command", "command": spec["Stop"]["cmd"], "timeout": 1}]},
{"hooks": [{"type": "command", "command": spec["Stop"]["cmd"], "timeout": 1}]}]}}
adapters.add_nested(dup2, spec)
n2 = sum(1 for g in dup2["hooks"]["Stop"] for h in g["hooks"] if h.get("command") == spec["Stop"]["cmd"])
self.assertEqual(n2, 1, dup2)
c = adapters.BY_NAME["cursor"]
cspec = c.spec()
dup3 = {"version": 1, "hooks": {"stop": [{"command": cspec["stop"]["cmd"]}, {"command": cspec["stop"]["cmd"]}, {"command": "./mine.sh"}]}}
adapters.add_flat(dup3, cspec, c._entry)
self.assertEqual(sum(1 for e in dup3["hooks"]["stop"] if e.get("command") == cspec["stop"]["cmd"]), 1, dup3)
self.assertTrue(any(e.get("command") == "./mine.sh" for e in dup3["hooks"]["stop"]))
def test_duplicate_hooks_deduped_on_install(self):
os.makedirs(self.path(".codex"))
wiring.install()
d = json.load(open(self.path(".codex/hooks.json")))
d["hooks"]["Stop"] = d["hooks"]["Stop"] + d["hooks"]["Stop"] # register the gate twice
json.dump(d, open(self.path(".codex/hooks.json"), "w"), indent=2)
wiring.install()
self.assertEqual(self._count_nested(self.path(".codex/hooks.json"), "Stop")["Stop"], 1)
wiring.uninstall()
class GeneratedHeaderTests(SafetyBase):
def test_marker_string_in_user_file_not_overwritten(self):
os.makedirs(self.path(".config", "opencode", "plugins"))
mine = b"// my own plugin\n// mentions sisi:generated in passing\nexport default {};\n"
self.put(".config/opencode/plugins/sisi.js", mine)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".config/opencode/plugins/sisi.js"), "rb").read(), mine)
r = self.rows()["opencode"]
self.assertEqual(r["status"], "not wired")
wiring.uninstall()
self.assertEqual(open(self.path(".config/opencode/plugins/sisi.js"), "rb").read(), mine)
def test_marker_string_in_windsurf_file_not_overwritten(self):
os.makedirs(self.path(".codeium", "windsurf", "memories"))
mine = b"# my rules\n<!-- sisi:generated is a string I read about -->\n- be nice\n"
self.put(".codeium/windsurf/memories/global_rules.md", mine)
wiring.install()
self.assertEqual(open(self.path(".codeium/windsurf/memories/global_rules.md"), "rb").read(), mine)
wiring.uninstall()
self.assertEqual(open(self.path(".codeium/windsurf/memories/global_rules.md"), "rb").read(), mine)
class AiderQuoteTests(SafetyBase):
def test_aider_flow_quoted_comma_survives_edit_and_uninstall(self):
self.put(".aider.conf.yml", b'read: ["a,b.md", docs/c.md]\nmodel: test\n')
wiring.install()
p = self.path(".aider.conf.yml")
now = open(p).read()
self.assertIn('"a,b.md"', now)
self.assertIn(wiring.core(), now)
edited = now.replace("docs/c.md]", "docs/c.md, docs/d.md]").replace("docs/c.md,", "docs/c.md,")
if "docs/d.md" not in edited:
edited = now.replace("]", ", docs/d.md]")
open(p, "w").write(edited)
wiring.uninstall()
out = open(p).read()
self.assertIn('"a,b.md"', out, out)
self.assertIn("docs/c.md", out)
self.assertIn("docs/d.md", out)
self.assertNotIn(wiring.core(), out)
span = adapters._aider_read_span(out.split("\n"))
self.assertEqual(span[2], ["a,b.md", "docs/c.md", "docs/d.md"])
def test_aider_uncertain_flow_skipped(self):
orig = b"read: [[nested], docs/c.md]\n"
self.put(".aider.conf.yml", orig)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertEqual(open(self.path(".aider.conf.yml"), "rb").read(), orig)
self.assertTrue(any(n.startswith("aider: skipped") for n in notes), notes)
wiring.uninstall()
class ByteExactTests(SafetyBase):
ORIG = b'{"theme": "caf\\u00e9", "limit": 1e3, "x": 1, "x": 2, "hooks": {"BeforeTool": [{"hooks": [{"type": "command", "command": "echo k"}]}]}}\n'
def test_uninstall_after_user_edit_preserves_spellings(self):
os.makedirs(self.path(".gemini"))
self.put(".gemini/settings.json", self.ORIG)
wiring.install()
p = self.path(".gemini/settings.json")
now = open(p, "rb").read()
self.assertIn(b"1e3", now)
self.assertIn(b"caf\\u00e9", now)
edited = now.replace(b'"limit": 1e3', b'"limit": 2e3, "mine": true')
open(p, "wb").write(edited)
wiring.uninstall()
out = open(p, "rb").read()
self.assertIn(b"2e3", out, out)
self.assertIn(b"caf\\u00e9", out, out)
self.assertIn(b'"mine": true', out, out)
self.assertEqual(out.count(b'"x":'), 2, out)
self.assertNotIn(b"sisi", out, out)
def test_second_round_changed_original_restored(self):
os.makedirs(self.path(".gemini"))
self.put(".gemini/settings.json", b'{"theme": "one", "limit": 1e3}\n')
wiring.install(); wiring.uninstall()
self.assertEqual(open(self.path(".gemini/settings.json"), "rb").read(), b'{"theme": "one", "limit": 1e3}\n')
self.put(".gemini/settings.json", b'{"theme": "two", "limit": 2.50, "extra": [1, 2]}\n')
wiring.install(); wiring.uninstall()
self.assertEqual(open(self.path(".gemini/settings.json"), "rb").read(), b'{"theme": "two", "limit": 2.50, "extra": [1, 2]}\n')
def test_uninstall_edited_generated_left_alone(self):
os.makedirs(self.path(".pi", "agent"))
wiring.install()
p = self.path(".pi/agent/extensions/sisi.ts")
with open(p, "a") as f:
f.write("// my own tweak\n")
edited = open(p, "rb").read()
wiring.uninstall()
self.assertTrue(os.path.exists(p))
self.assertEqual(open(p, "rb").read(), edited)
class FailOpenCommandTests(SafetyBase):
def test_hook_command_fails_open_without_launcher(self):
repo = os.path.join(self.tmp, "repo-copy")
shutil.copytree(REPO, repo, ignore=shutil.ignore_patterns(".git", "__pycache__", "tests", ".agent-work"))
old_repo = paths.REPO
paths.REPO = repo
self.addCleanup(setattr, paths, "REPO", old_repo)
os.makedirs(self.path(".codex"), exist_ok=True)
wiring.install()
d = json.load(open(self.path(".claude/settings.json")))
cmd = d["hooks"]["Stop"][0]["hooks"][0]["command"]
payload = json.dumps({"session_id": "s", "cwd": self.proj})
r = subprocess.run(cmd, shell=True, input=payload, capture_output=True, text=True, env=dict(os.environ))
self.assertEqual(r.returncode, 0, (r.stdout, r.stderr))
os.rename(os.path.join(repo, "bin", "sisi"), os.path.join(repo, "bin", "sisi-gone"))
r2 = subprocess.run(cmd, shell=True, input=payload, capture_output=True, text=True, env=dict(os.environ))
self.assertEqual((r2.returncode, r2.stdout), (0, ""), (r2.stdout, r2.stderr))
class DoctorAccuracyTests(SafetyBase):
def test_doctor_stale_generated_not_wired(self):
os.makedirs(self.path(".pi", "agent"))
wiring.install()
p = self.path(".pi/agent/extensions/sisi.ts")
self.assertEqual(self.rows()["pi"]["status"], "wired")
with open(p, "a") as f:
f.write("// drift\n")
r = self.rows()["pi"]
self.assertEqual(r["status"], "not wired", r)
wiring.uninstall()
def test_doctor_agents_override_shadows_codex_and_pi(self):
os.makedirs(self.path(".codex"))
os.makedirs(self.path(".pi", "agent"))
wiring.install()
self.assertEqual(self.rows()["codex"]["status"], "wired")
self.put(".codex/AGENTS.override.md", b"override wins\n")
self.put(".pi/agent/AGENTS.override.md", b"override wins\n")
rows = self.rows()
for tool in ("codex", "pi"):
self.assertEqual(rows[tool]["status"], "not wired", rows[tool])
self.assertFalse(rows[tool]["rulebook"])
self.assertIn("override", rows[tool]["detail"].lower())
wiring.uninstall()
def test_env_overrides_honoured(self):
# Fresh process semantics, in-process: clear the cache effects by checking adapter resolution
# and a real install into the override dirs (all inside the fake home).
for d in ("oc-custom", "codex-home", "copilot-home", "grok-home", "pi-agent"):
os.makedirs(os.path.join(self.home, d))
env = {"OPENCODE_CONFIG_DIR": os.path.join(self.home, "oc-custom"),
"CODEX_HOME": os.path.join(self.home, "codex-home"),
"COPILOT_HOME": os.path.join(self.home, "copilot-home"),
"GROK_HOME": os.path.join(self.home, "grok-home"),
"PI_CODING_AGENT_DIR": os.path.join(self.home, "pi-agent")}
with mock.patch.dict(os.environ, env):
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
self.assertTrue(os.path.islink(os.path.join(self.home, "codex-home", "AGENTS.md")))
self.assertTrue(os.path.exists(os.path.join(self.home, "codex-home", "hooks.json")))
self.assertTrue(os.path.islink(os.path.join(self.home, "oc-custom", "AGENTS.md")))
self.assertTrue(os.path.exists(os.path.join(self.home, "copilot-home", "hooks", "sisi.json")))
self.assertTrue(os.path.islink(os.path.join(self.home, "grok-home", "AGENTS.md")))
self.assertTrue(os.path.exists(os.path.join(self.home, "pi-agent", "extensions", "sisi.ts")))
wiring.uninstall()
def test_xdg_config_home_honoured_for_opencode_and_crush(self):
xdg = os.path.join(self.home, "xdg")
os.makedirs(os.path.join(xdg, "opencode"))
os.makedirs(os.path.join(xdg, "crush"))
env = {"HOME": self.home, "XDG_CONFIG_HOME": xdg}
with mock.patch.dict(os.environ, env):
os.environ.pop("SISI_HOME", None)
self.assertEqual(wiring.loc()["opencode_dir"], os.path.join(xdg, "opencode"))
self.assertEqual(adapters.BY_NAME["crush"]._detect_dir, os.path.join(xdg, "crush"))
class DocsAndDryRunTests(SafetyBase):
def test_docs_evidence_markers_and_no_claude_only_claim(self):
readme = open(os.path.join(REPO, "README.md"), encoding="utf-8").read()
self.assertNotIn("blocks in Claude Code only", readme)
harnesses = open(os.path.join(REPO, "docs", "harnesses.md"), encoding="utf-8").read()
for sec in ("## Amp", "## Goose", "## Cline"):
body = harnesses.split(sec, 1)[1].split("\n## ", 1)[0]
self.assertTrue("onfirmed" in body or "not verified" in body or "nconfirmed" in body, (sec, body))
def test_install_dry_run_changes_nothing(self):
for d in (".codex", ".gemini", ".cursor", ".config/opencode", ".pi/agent"):
os.makedirs(self.path(d), exist_ok=True)
self.put(".gemini/settings.json", b'{"theme": "dark"}\n')
before = (snapshot(self.home), snapshot(self.data) if os.path.isdir(self.data) else {},
snapshot(self.state) if os.path.isdir(self.state) else {})
r = self.sisi("install", "--dry-run")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("dry-run", r.stdout.lower())
self.assertIn("@@", r.stdout)
self.assertIn("settings.json", r.stdout)
after = (snapshot(self.home), snapshot(self.data) if os.path.isdir(self.data) else {},
snapshot(self.state) if os.path.isdir(self.state) else {})
self.assertEqual(after, before)
r2 = self.sisi("install")
self.assertEqual(r2.returncode, 0, r2.stderr)
wiring.uninstall()
class WidenedPropertyTests(SafetyBase):
"""Every config-merging tool against hostile pre-existing configs. The documented guarantee:
unedited files restore byte for byte; edited files keep the user's edits and every other byte;
files sisi cannot edit with certainty are never rewritten."""
TOOLS = {
"codex": (".codex", ".codex/hooks.json", ".codex/AGENTS.md"),
"gemini": (".gemini", ".gemini/settings.json", ".gemini/GEMINI.md"),
"qwen": (".qwen", ".qwen/settings.json", ".qwen/QWEN.md"),
"cursor": (".cursor", ".cursor/hooks.json", None),
"copilot": (".copilot", ".copilot/hooks/sisi.json", ".copilot/copilot-instructions.md"),
}
SPELLINGS = b'{"theme": "caf\\u00e9", "limit": 1e3, "ratio": 2.50, "x": 1, "x": 2}\n'
JSONC = b'{\n // a comment\n "theme": "dark",\n}\n'
def run_case(self, tool, kind):
d, f, link = self.TOOLS[tool]
self.fresh_home()
os.makedirs(self.path(d), exist_ok=True)
p = self.path(f)
elsewhere = os.path.join(self.tmp, "elsewhere-" + tool)
os.makedirs(elsewhere, exist_ok=True)
if kind == "spellings":
self.put(f, self.SPELLINGS)
elif kind == "jsonc":
self.put(f, self.JSONC)
elif kind == "live-symlink":
real = os.path.join(elsewhere, "real.json")
open(real, "wb").write(self.SPELLINGS)
os.makedirs(os.path.dirname(p), exist_ok=True)
os.symlink(real, p)
elif kind == "dangling":
os.makedirs(os.path.dirname(p), exist_ok=True)
os.symlink(os.path.join(elsewhere, "missing.json"), p)
elif kind == "readonly":
self.put(f, self.SPELLINGS)
os.chmod(p, 0o444)
self.skip_if_perms_ignored(p)
before = snapshot(self.home)
try:
rc, notes = wiring.install()
self.assertEqual(rc, 0, (tool, kind, notes))
after1 = snapshot(self.home)
wiring.install()
self.assertEqual(snapshot(self.home), after1, (tool, kind, "install twice != install once"))
if kind in ("jsonc", "readonly"):
self.assertEqual(open(p, "rb").read(), self.JSONC if kind == "jsonc" else self.SPELLINGS)
if kind == "dangling":
self.assertTrue(wiring._dangling(p))
self.assertFalse(os.path.exists(os.path.join(elsewhere, "missing.json")))
if kind in ("jsonc", "dangling", "readonly") and link:
self.assertFalse(os.path.lexists(self.path(link)), (tool, kind, "half-wired link"))
wiring.uninstall()
if kind == "readonly":
os.chmod(p, 0o644)
self.assertEqual(snapshot(self.home), before, (tool, kind, "uninstall not exact"))
finally:
if kind == "readonly" and os.path.exists(p) and not os.path.islink(p):
try:
os.chmod(p, 0o644)
except OSError:
pass
def test_nasty_configs_per_tool(self):
for tool in self.TOOLS:
for kind in ("absent", "spellings", "jsonc", "live-symlink", "dangling", "readonly"):
with self.subTest(tool=tool, kind=kind):
self.run_case(tool, kind)
def test_edit_between_install_and_uninstall_per_tool(self):
for tool, (d, f, _link) in self.TOOLS.items():
with self.subTest(tool=tool):
self.fresh_home()
os.makedirs(self.path(d), exist_ok=True)
self.put(f, self.SPELLINGS)
p = self.path(f)
wiring.install()
now = open(p, "rb").read()
self.assertIn(b"1e3", now)
edited = now.replace(b"1e3", b"2e3").replace(b"{", b'{"mine": true, ', 1)
open(p, "wb").write(edited)
wiring.uninstall()
out = open(p, "rb").read()
self.assertIn(b"2e3", out, (tool, out))
self.assertIn(b'"mine": true', out, (tool, out))
self.assertIn(b"caf\\u00e9", out, (tool, out))
self.assertNotIn(b"--tool", out, (tool, out))
def test_duplicates_then_reinstall_per_tool(self):
for tool, (d, f, _link) in self.TOOLS.items():
with self.subTest(tool=tool):
self.fresh_home()
os.makedirs(self.path(d), exist_ok=True)
wiring.install()
p = self.path(f)
obj = json.load(open(p))
for ev in list(obj.get("hooks", {})):
obj["hooks"][ev] = obj["hooks"][ev] + obj["hooks"][ev]
json.dump(obj, open(p, "w"), indent=2)
wiring.install()
raw = open(p, "rb").read()
self.assertLessEqual(raw.count(b"--tool " + tool.encode()), 4, (tool, raw))
d2 = json.load(open(p))
for ev, entries in d2.get("hooks", {}).items():
flat = [e.get("bash") or e.get("command") for e in entries if isinstance(e, dict)]
nested = [h.get("command") for g in entries if isinstance(g, dict) for h in g.get("hooks", [])]
cmds = [c for c in flat + nested if c and "sisi" in c]
self.assertEqual(len(cmds), len(set(cmds)), (tool, ev, cmds))
wiring.uninstall()
def test_marker_string_files_for_generated_tools(self):
cases = [
(".config/opencode/plugins", ".config/opencode/plugins/sisi.js",
b"// mine\nconst x = 'sisi:generated';\n"),
(".pi/agent/extensions", ".pi/agent/extensions/sisi.ts",
b"// mine\nexport const MARKER = 'sisi:generated';\n"),
]
for d, f, mine in cases:
with self.subTest(file=f):
self.fresh_home()
os.makedirs(self.path(".config", "opencode"), exist_ok=True)
os.makedirs(self.path(d), exist_ok=True)
self.put(f, mine)
before = snapshot(self.home)
wiring.install(); wiring.install()
self.assertEqual(open(self.path(f), "rb").read(), mine)
wiring.uninstall()
self.assertEqual(open(self.path(f), "rb").read(), mine)
self.assertEqual(snapshot(self.home), before)
def test_seeded_random_valid_configs(self):
from test_adapters import rand_hooks_obj
flat_tools = {"cursor", "copilot"}
for tool, (d, f, _link) in self.TOOLS.items():
rng = random.Random(4242 + len(tool))
for n in range(3 * ITERS):
with self.subTest(tool=tool, n=n):
self.fresh_home()
os.makedirs(self.path(d), exist_ok=True)
if rng.random() < 0.85:
self.put(f, rand_hooks_obj(rng, tool in flat_tools))
before = snapshot(self.home)
rc, notes = wiring.install()
self.assertEqual(rc, 0, notes)
after1 = snapshot(self.home)
wiring.install()
self.assertEqual(snapshot(self.home), after1, (tool, n))
wiring.uninstall()
self.assertEqual(snapshot(self.home), before, (tool, n))
if __name__ == "__main__":
unittest.main()
+984
View File
@@ -0,0 +1,984 @@
"""The learning loop: lessons take effect at once, are delivered at the moment they match, are measured,
climb the strength ladder, and are consolidated by `sisi cycle`. Nothing here uses a scheduler: due-ness
is a counter checked in tick, the gate, retro, verify and done-for, announced at most once per session
until 20 further checks pass or the counter grows."""
import json, os, random, sqlite3, time, unittest
from support import *
from sisi import cycle, gate, overlay, paths, pdata, retro, store
from test_verifiers import LibCase, vfile, dfile
PARSER_CHANGE = "Prefer a readiness probe over a fixed sleep when waiting for parser servers to answer"
CSV_WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
PARSER_WHEN = "parser, server readiness, startup wait, readiness probe, dev server, waiting"
def fields(**kw):
f = dict(aim="verified", change_kind="rule", target=None,
moment="the parser server waited 90 seconds in step 4 of the nightly job",
cause="no readiness probe existed before the browser step",
change=PARSER_CHANGE)
f.update(kw)
return f
class LearningCase(LibCase):
def setUp(self):
super().setUp()
self.put("prove/fuzz.md", vfile("fuzz"))
self.put("parser-or-codec.md", dfile("parser-or-codec"), self.ddir)
self.notes = os.path.join(self.data, "notes")
def mk(self, **kw):
con = retro.connect()
try:
lid = retro.new_lesson(con, fields(**kw), self.proj, None)
con.commit()
return lid
finally:
con.close()
def lesson(self, lid):
con = retro.connect()
try:
return dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone())
finally:
con.close()
def again(self, lid):
con = retro.connect()
try:
retro.add_occurrence(con, lid, "again the parser server waited in step 7", self.proj, None)
con.commit()
finally:
con.close()
def cycle_doc(self, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"}
doc.update(parts)
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as f:
json.dump(doc, f)
return p
def overlay_bytes(self):
out = {}
base = paths.overlay_dir()
for dp, dns, fns in os.walk(base):
for n in fns:
p = os.path.join(dp, n)
with open(p, "rb") as f:
out[os.path.relpath(p, base)] = f.read()
return out
class ImmediateEffectTests(LearningCase):
def test_field_note_on_first_occurrence_verifier_and_recipe(self):
a = self.mk(change_kind="verifier", target="fuzz",
change="Say in the fuzz notes: seed the corpus from the golden files before fuzzing parsers")
b = self.mk(change_kind="recipe", target="parser-or-codec",
change="Add the readiness probe to the parser-or-codec recipe Checks for server work")
for lid, target in ((a, "fuzz"), (b, "parser-or-codec")):
l = self.lesson(lid)
self.assertEqual((l["status"], l["effect"], l["folded_into"]), ("applied", "field-note", target))
self.assertIn("lesson %d" % lid, open(os.path.join(self.notes, target + ".md")).read())
self.again(a) # a later occurrence never duplicates the bullet
self.assertEqual(open(os.path.join(self.notes, "fuzz.md")).read().count("seed the corpus"), 1)
def test_draft_recipe_note_for_a_recipe_that_does_not_exist(self):
lid = self.mk(change_kind="recipe", target="curated-record-change",
change="Add a recipe 'curated-record-change' for editing a sourced record in a curated dataset")
l = self.lesson(lid)
self.assertEqual((l["effect"], l["folded_into"]), ("draft-recipe", "draft:curated-record-change"))
self.assertTrue(os.path.exists(os.path.join(self.notes, "draft-curated-record-change.md")))
out = self.sisi("done", "for", "editing a sourced record in a curated dataset").stdout
self.assertIn("Draft recipe curated-record-change", out)
miss = self.sisi("done", "for", "quantum chromodynamics lattice gauge").stdout
self.assertNotIn("Draft recipe", miss)
def test_rule_oracle_brief_become_learned_notes_with_triggers(self):
for kind in ("rule", "oracle", "brief"):
lid = self.mk(change_kind=kind, change=PARSER_CHANGE + " (%s)" % kind,
moment="moment for %s at step 2 of the upload" % kind)
l = self.lesson(lid)
self.assertEqual(l["effect"], "learned-note")
self.assertIn("pars", l["triggers"]) # stems: parser/parsing/parse all meet at 'pars'
self.assertTrue(l["applied_at"])
def test_tool_lessons_backlog_order_and_dev_mode_tick_line(self):
a = self.mk(change_kind="tool", change="Make the gate count session edits separately per session")
b = self.mk(change_kind="tool", change="Make sisi verify name the slowest check first")
c = self.mk(change_kind="tool", change="Cache transcript scans between gate decisions")
self.again(b); self.again(b); self.again(c); self.again(c)
out = self.sisi("backlog").stdout.splitlines()
ids = [int(l.split()[0][1:]) for l in out if l.startswith("#")]
self.assertEqual(ids, [b, c, a]) # most seen first; the tie goes to the older lesson
self.assertEqual(self.lesson(b)["effect"], "backlog")
paths.set_personal_config(("developer", "source"), self.proj, "test")
tick = self.sisi("tick", stdin=json.dumps({"session_id": "dev1", "cwd": self.proj, "source": "startup"})).stdout
self.assertIn("top sisi backlog #%d" % b, tick)
other = os.path.join(self.tmp, "elsewhere"); os.makedirs(other)
tick2 = self.sisi("tick", stdin=json.dumps({"session_id": "dev2", "cwd": other, "source": "startup"})).stdout
self.assertNotIn("backlog", tick2)
class DeliveryTests(LearningCase):
def setUp(self):
super().setUp()
self.lid = self.mk()
def test_each_moment_appends_matching_lessons_and_records_it(self):
checks = [
("done-for", lambda: self.sisi("done", "for", "parser-or-codec server readiness").stdout),
("verifiers-for", lambda: self.sisi("verifiers", "for", "parser server readiness probe").stdout),
("verifiers-show", lambda: self.sisi("verifiers", "show", "fuzz").stdout
if False else self._show()),
]
block = retro.lessons_block("parser server readiness probe", "done-for", session="s-x")
self.assertIn("#%d" % self.lid, block)
self.assertLessEqual(len(block), 600)
out = checks[0][1]()
self.assertIn("lessons from earlier agents", out)
con = retro.connect()
places = [r[0] for r in con.execute("SELECT place FROM impressions WHERE lesson_id=?", (self.lid,))]
con.close()
self.assertIn("done-for", places)
out2 = checks[1][1]()
self.assertIn("lessons from earlier agents", out2)
def _show(self):
lid = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing")
return self.sisi("verifiers", "show", "fuzz").stdout
def test_verifiers_show_and_contract_init(self):
out = self._show()
self.assertIn("lessons from earlier agents", out)
proj2 = os.path.join(self.tmp, "proj2"); os.makedirs(proj2)
r = self.sisi("contract", "init", "--goal", "parser server readiness for uploads", cwd=proj2)
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("lessons from earlier agents", r.stdout)
def test_irrelevant_query_surfaces_nothing(self):
self.assertEqual(retro.lessons_block("quantum chromodynamics lattice gauge theory", "done-for"), "")
self.assertEqual(retro.match_lessons("zebra xylophone quasar"), [])
def test_block_is_capped_at_three_and_600_characters(self):
for i in range(8):
self.mk(change="Parser server readiness variant %d prefers probes over fixed sleeps always" % i,
moment="parser wait number %d at step 3" % i)
block = retro.lessons_block("parser server readiness probe fixed sleep", "done-for")
self.assertLessEqual(len(block), 600)
self.assertLessEqual(len([l for l in block.splitlines() if l.startswith("- #")]), 3)
def test_tick_shows_highest_strength_first_and_records(self):
strong = self.mk(change="Zebra marker lesson about caching widgets quietly", moment="widget cache step 1")
con = retro.connect()
con.execute("UPDATE lessons SET strength=3 WHERE id=?", (strong,))
con.commit(); con.close()
block = retro.tick_block(self.proj, session="tick-s")
lines = [l for l in block.splitlines() if l.startswith("- ")]
self.assertTrue(lines[0].startswith("- Zebra marker"), lines)
con = retro.connect()
self.assertTrue(con.execute("SELECT 1 FROM impressions WHERE lesson_id=? AND place='tick' AND session='tick-s'",
(strong,)).fetchone())
con.close()
def test_gate_send_back_carries_matching_lessons(self):
self.git_init()
c = check("parser-readiness", "false")
c["claim"] = "the parser server answers the readiness probe"
self.write_contract(contract([c]))
self.sisi("tick", stdin=json.dumps({"session_id": "g1", "cwd": self.proj, "source": "startup"}))
with open(os.path.join(self.proj, "work.txt"), "w") as f:
f.write("x\n")
a, msg = gate.decide({"session_id": "g1", "cwd": self.proj})
self.assertEqual(a, "block")
self.assertIn("lessons from earlier agents", msg)
self.assertIn("#%d" % self.lid, msg)
class LadderTests(LearningCase):
def test_promotion_needs_two_showings_then_recurrence(self):
lid = self.mk()
self.again(lid)
self.assertEqual(self.lesson(lid)["strength"], 1) # never shown: no promotion
retro.record_shown([lid], "tick", "s")
self.again(lid)
self.assertEqual(self.lesson(lid)["strength"], 1) # shown once: still no
retro.record_shown([lid], "tick", "s")
self.again(lid)
l = self.lesson(lid)
self.assertEqual((l["strength"], l["needs_cycle"]), (2, 1))
self.again(lid) # no fresh showings since the promotion: no second step on stale evidence
self.assertEqual(self.lesson(lid)["strength"], 2)
retro.record_shown([lid], "tick", "s")
self.again(lid) # only one fresh showing: still no
self.assertEqual(self.lesson(lid)["strength"], 2)
retro.record_shown([lid], "tick", "s")
self.again(lid) # two fresh showings, another recurrence: strength 3
self.assertEqual(self.lesson(lid)["strength"], 3)
self.again(lid)
self.assertEqual(self.lesson(lid)["status"], "open") # withdrawal also needs fresh showings
retro.record_shown([lid], "tick", "s"); retro.record_shown([lid], "tick", "s")
self.again(lid) # enforced, shown afresh, still recurring: withdrawn
self.assertEqual(self.lesson(lid)["status"], "withdrawn")
self.assertEqual(retro.match_lessons("parser server readiness probe"), [])
def test_property_ladder_matches_a_simple_reference(self):
def reference(events):
s, shown, promoted_at, status = 1, 0, 0, "open"
for ev in events:
if status != "open":
continue
if ev == "show":
shown += 1
elif shown - promoted_at >= 2:
if s < 3:
s += 1
promoted_at = shown
else:
status = "withdrawn"
return s, status
for seed in [0, 1, 7] + [random.randrange(2 ** 32) for _ in range(ITERS)]:
rng = random.Random(seed)
events = [rng.choice(("show", "recur")) for _ in range(30)]
lid = self.mk(change="Reference lesson %d about parser readiness probes" % seed,
moment="reference wait %d at step 2" % seed)
for ev in events:
if ev == "show":
retro.record_shown([lid], "tick", "ref")
else:
self.again(lid)
l = self.lesson(lid)
got = (l["strength"], "withdrawn" if l["status"] == "withdrawn" else "open")
self.assertEqual(got, reference(events), "seed %d" % seed)
def test_folded_lesson_shown_twenty_times_without_recurrence_retires(self):
lid = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing")
for _ in range(19):
retro.record_shown([lid], "tick", "s")
self.assertEqual(self.lesson(lid)["status"], "applied")
retro.record_shown([lid], "tick", "s")
self.assertEqual(self.lesson(lid)["status"], "retired")
lid2 = self.mk(change_kind="verifier", target="fuzz",
change="Keep fuzz seeds beside the parser golden files always",
moment="fuzz seeds missing at step 5")
retro.record_shown([lid2], "tick", "s")
self.again(lid2) # a recurrence after being shown: retirement must not fire
for _ in range(20):
retro.record_shown([lid2], "tick", "s")
self.assertNotEqual(self.lesson(lid2)["status"], "retired")
def test_withdrawn_lesson_is_not_relearned_in_the_same_form(self):
lid = self.mk()
con = retro.connect()
con.execute("UPDATE lessons SET status='withdrawn' WHERE id=?", (lid,))
con.commit(); con.close()
from test_retro import argv as retro_argv, GOOD
r = self.sisi("retro", *retro_argv(dict(GOOD, change=PARSER_CHANGE, new=True)))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("withdrawn", r.stdout)
def test_measurement_counts_shows_and_recurrences(self):
lid = self.mk()
retro.record_shown([lid], "done-for", "sess-9")
retro.record_shown([lid], "gate", "sess-9")
self.again(lid)
con = retro.connect()
row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()
self.assertEqual(retro.shown_count(con, lid), 2)
self.assertEqual(retro.recurrences_after_shown(con, row), 1)
sess = con.execute("SELECT DISTINCT session FROM impressions WHERE lesson_id=?", (lid,)).fetchone()[0]
self.assertEqual(sess, "sess-9")
con.close()
out = self.sisi("lessons", "show", str(lid)).stdout
self.assertIn("listed 2 time(s), read 0, 1 recurrence(s)", out)
class CycleDueTests(LearningCase):
def make_due(self, n=5):
return [self.mk(change="Due lesson %d about parser readiness probes" % i,
moment="due wait %d at step 2" % i) for i in range(n)]
def test_due_by_count_pending_and_notes_size(self):
self.assertEqual(self.sisi("cycle", "due").returncode, 1)
self.make_due(2)
con = retro.connect()
con.execute("UPDATE lessons SET needs_cycle=1 WHERE id=(SELECT min(id) FROM lessons)")
con.commit(); con.close()
r = self.sisi("cycle", "due")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("waiting for consolidation", r.stdout)
def test_due_by_five_lessons_and_by_notes_size(self):
self.make_due(5)
r = self.sisi("cycle", "due")
self.assertEqual(r.returncode, 0)
self.assertIn("5 lessons recorded since the last cycle", r.stdout)
con = retro.connect()
con.execute("UPDATE lessons SET created='2000-01-01T00:00:00Z'")
retro.set_meta(con, "last_cycle_ts", "2999-01-01T00:00:00Z")
con.execute("UPDATE lessons SET change=change || ? ", (" padding" * 300,))
con.commit(); con.close()
st = cycle.due_state()
self.assertTrue(any("note" in x for x in st["reasons"]), st)
def test_no_nag_for_twenty_checks_then_again_and_counter_growth(self):
self.make_due()
first = cycle.due_notice(session="nag")
self.assertIn("learning cycle is due", first)
for _ in range(20):
self.assertEqual(cycle.due_notice(session="nag"), "")
self.assertIn("learning cycle is due", cycle.due_notice(session="nag"))
self.assertEqual(cycle.due_notice(session="nag"), "")
self.mk(change="One more parser readiness lesson arrives", moment="one more wait at step 9")
self.assertIn("learning cycle is due", cycle.due_notice(session="nag")) # the counter grew
def test_due_line_in_retro_verify_done_for_gate_and_tick(self):
self.make_due(4)
from test_retro import argv as retro_argv, GOOD
r = self.sisi("retro", *retro_argv(dict(GOOD, change="Add the readiness probe to every server recipe Checks list",
moment="`sisi done` run 12 showed no readiness probe for servers", new=True)),
env={"SISI_SESSION_ID": "due-retro"})
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("learning cycle is due", r.stdout)
tick = self.sisi("tick", stdin=json.dumps({"session_id": "due-tick", "cwd": self.proj, "source": "startup"})).stdout
self.assertIn("learning cycle is due", tick)
self.assertIn("learning cycle is due",
self.sisi("done", "for", "parser-or-codec", env={"SISI_SESSION_ID": "due-done"}).stdout)
self.git_init()
self.write_contract(contract([check("ok", "true")]))
v = self.sisi("verify", env={"SISI_SESSION_ID": "due-verify"})
self.assertEqual(v.returncode, 0, v.stdout)
self.assertIn("learning cycle is due", v.stdout)
v2 = self.sisi("verify", env={"SISI_SESSION_ID": "due-verify"})
self.assertNotIn("learning cycle is due", v2.stdout) # same session: no nagging
with open(os.path.join(self.proj, "work.txt"), "w") as f:
f.write("x\n")
a, msg = gate.decide({"session_id": "due-gate", "cwd": self.proj})
self.assertEqual(a, "allow")
self.assertIn("learning cycle is due", msg or "")
RULE_BODY = ("Before non-trivial work, write a contract at `.sisi/contract.json` in the project "
"(`sisi contract init` creates the skeleton) listing the checks that decide success.\n\n"
"Why: a request says what is wanted, rarely how success is measured.")
class CycleApplyTests(LearningCase):
def test_brief_has_base_lessons_rulebook_and_format(self):
lid = self.mk()
con = retro.connect()
con.execute("UPDATE lessons SET strength=3 WHERE id=?", (lid,))
con.commit(); con.close()
out = self.sisi("cycle").stdout
self.assertIn("Base version (copy into your file): " + cycle.base_version(), out)
self.assertIn("#%-4d" % lid, out)
self.assertIn("NEEDS A CHECK", out)
self.assertIn("budget %d" % overlay.MAX_LINES, out)
self.assertIn("Current rulebook", out)
self.assertIn("sisi cycle apply FILE", out)
self.assertIn("contract-requirement", out)
def test_apply_merges_folds_replaces_and_enforces(self):
a = self.mk(change="Parser readiness probes beat fixed sleeps for servers", moment="wait a at step 1")
b = self.mk(change="Fixed sleeps waste minutes when parser servers start slowly", moment="wait b at step 2")
c = self.mk(change_kind="recipe", target="parser-or-codec",
change="Parser recipes need a fuzz check for hostile inputs", moment="hostile input at step 3")
pre, base = overlay.base_rules()
title = next(r["title"] for r in base if r["id"] == "know-done")
doc = self.cycle_doc(
rules=[{"id": "know-done", "title": title, "body": RULE_BODY, "action": "replace"}],
notes=[{"lesson": a, "action": "fold-into-rule", "into": "know-done"},
{"lesson": b, "action": "merge", "merged_into": a}],
enforced=[{"lesson": c, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}])
r = self.sisi("cycle", "apply", doc)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertTrue(os.path.exists(paths.overlay_dir("rules", "know-done.md")))
self.assertIn("success is measured", open(paths.generated()).read())
la, lb, lc = self.lesson(a), self.lesson(b), self.lesson(c)
self.assertEqual((la["folded_into"], la["strength"]), ("rule:know-done", 2))
self.assertEqual(lb["status"], "superseded")
self.assertEqual((lc["strength"], bool(lc["check_json"])), (3, True))
self.assertEqual(len(cycle.load_enforced()), 1)
self.assertIn("cycle-0001", self.sisi("cycle", "status").stdout)
log = pdata.git("log", "--format=%s", "-1").stdout
self.assertIn("cycle cycle-0001", log)
def test_apply_refuses_saying_exactly_why(self):
lid = self.mk()
cases = [
({"notes": [{"lesson": 9999, "action": "keep"}]}, "no lesson with id 9999"),
({"rules": [{"id": "know-done", "title": "X", "body": "no reason here", "action": "replace"}]}, "must keep its Why"),
({"enforced": [{"lesson": lid, "type": "command", "cmd": "definitely-not-here-xyz --fast",
"expect": {"exit": 0}}]}, "does not exist on this machine"),
({"rules": [{"id": "know-done", "title": "X", "body": "Use `sisi frobnicate` first.\n\nWhy: testing",
"action": "replace"}]}, "not a command"),
]
for parts, why in cases:
with self.subTest(why):
before = self.overlay_bytes()
r = self.sisi("cycle", "apply", self.cycle_doc(**parts))
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn(why, r.stdout)
self.assertEqual(self.overlay_bytes(), before)
doc = {"version": 1, "base": "stale", "summary": "x", "notes": [{"lesson": lid, "action": "keep"}]}
p = os.path.join(self.tmp, "stale.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 1)
self.assertIn("stale base", r.stdout)
def test_rulebook_may_grow_only_by_replacement(self):
r = self.sisi("cycle", "apply", self.cycle_doc(disable_rules=["know-done"]))
self.assertEqual(r.returncode, 0, r.stdout)
doc = self.cycle_doc(rules=[{"id": "brand-new-rule", "title": "Brand new",
"body": "Do the brand new thing carefully.\n\nWhy: it helps.", "action": "add"}])
r = self.sisi("cycle", "apply", doc)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("would grow", r.stdout)
def test_two_sessions_second_apply_refuses_cleanly(self):
a = self.mk(change="Session one lesson about parser readiness", moment="s1 wait at step 1")
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
doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}]}
doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}]}
paths_ = []
for i, d in enumerate((doc1, doc2)):
p = os.path.join(self.tmp, "two-%d.json" % i)
with open(p, "w") as f:
json.dump(d, f)
paths_.append(p)
self.assertEqual(self.sisi("cycle", "apply", str(paths_[0])).returncode, 0)
r = self.sisi("cycle", "apply", str(paths_[1]))
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("stale base", r.stdout)
self.assertEqual(len(cycle.cycle_records()), 1)
def test_revert_undoes_exactly_and_only_the_newest(self):
a = self.mk()
before = self.overlay_bytes()
doc = self.cycle_doc(notes=[{"lesson": a, "action": "retire"}],
enforced=[{"lesson": a, "type": "command", "cmd": "true", "expect": {"exit": 0}}])
self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0)
self.assertNotEqual(self.overlay_bytes(), before)
self.assertEqual(self.lesson(a)["strength"], 3)
r = self.sisi("cycle", "revert", "cycle-9999")
self.assertEqual(r.returncode, 1)
self.assertIn("not the newest", r.stdout)
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(self.overlay_bytes(), before)
l = self.lesson(a)
self.assertEqual((l["status"], l["strength"], l["check_json"]), ("open", 1, None))
self.assertEqual(cycle.load_enforced(), [])
def test_property_apply_then_revert_leaves_overlay_byte_identical(self):
pre, base = overlay.base_rules()
title = next(r["title"] for r in base if r["id"] == "know-done")
ids = [self.mk(change="Property lesson %d about parser readiness" % i,
moment="property wait %d at step 2" % i) for i in range(4)]
for seed in [0, 3] + [random.randrange(2 ** 32) for _ in range(ITERS)]:
rng = random.Random(seed)
before = self.overlay_bytes()
notes = [{"lesson": i, "action": rng.choice(("keep", "retire"))} for i in rng.sample(ids, rng.randint(1, 3))]
body = RULE_BODY + " (variant %d)" % seed
doc = self.cycle_doc(
rules=[{"id": "know-done", "title": title, "body": body, "action": "replace"}],
notes=notes,
enforced=[{"lesson": rng.choice(ids), "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2}])
r = self.sisi("cycle", "apply", doc)
self.assertEqual(r.returncode, 0, "seed %d: %s" % (seed, r.stdout + r.stderr))
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, "seed %d: %s" % (seed, r.stdout))
self.assertEqual(self.overlay_bytes(), before, "seed %d" % seed)
def test_status_flags_a_cycle_that_made_deliveries_worse(self):
lid = self.mk()
rows = [{"end": "2020-01-01T00:00:00Z", "seconds": 60, "send_backs": 0} for _ in range(3)]
for r in rows:
store.append("deliveries", r)
doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}])
self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0)
rec = cycle.cycle_records()[-1]
self.assertFalse(cycle.flagged(rec)) # nothing measured since yet
for _ in range(10):
store.append("deliveries", {"end": "2999-01-01T00:00:00Z", "seconds": 900, "send_backs": 4})
self.assertTrue(cycle.flagged(rec))
self.assertIn("WORSE", self.sisi("cycle", "status").stdout)
self.assertIn("FIRST:", cycle.brief_text())
def test_cycle_can_set_when_terms_on_an_old_lesson(self):
lid = self.mk()
self.assertIsNone(self.lesson(lid)["when_terms"])
brief = cycle.brief_text()
self.assertIn("Lessons with no when-terms yet", brief)
self.assertIn("#%d" % lid, brief)
bad = self.sisi("cycle", "apply", self.cycle_doc(
notes=[{"lesson": lid, "action": "keep", "when": "parser, servers"}]))
self.assertEqual(bad.returncode, 1, bad.stdout)
self.assertIn("when needs at least 5 terms", bad.stdout)
good = self.sisi("cycle", "apply", self.cycle_doc(
notes=[{"lesson": lid, "action": "keep", "when": PARSER_WHEN}]))
self.assertEqual(good.returncode, 0, good.stdout)
self.assertIn("readiness probe", self.lesson(lid)["when_terms"])
self.assertNotIn("MISSING", cycle.brief_text().split("#%-4d" % lid)[1].splitlines()[2])
class EnforcedTests(LearningCase):
def apply_enforced(self, entry):
lid = entry["lesson"]
doc = self.cycle_doc(enforced=[entry])
r = self.sisi("cycle", "apply", doc)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return lid
def test_contract_requirement_is_checked_like_a_floor(self):
lid = self.mk()
self.apply_enforced({"lesson": lid, "type": "contract-requirement", "when": "parser",
"require_kind": "parsing", "max_rung": 2})
weak = contract([check("p1", "true", rung=3, kind="general")])
weak["checks"][0]["claim"] = "the parser accepts the sample files"
self.write_contract(weak)
r = self.sisi("verify")
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("enforced lesson #%d" % lid, r.stdout)
strong = contract([check("p1", "true", rung=2, kind="parsing")])
strong["checks"][0]["claim"] = "the parser accepts the sample files"
self.write_contract(strong)
self.assertEqual(self.sisi("verify").returncode, 0)
def test_command_check_runs_only_for_trusted_projects(self):
lid = self.mk()
self.apply_enforced({"lesson": lid, "type": "command", "cmd": "false", "expect": {"exit": 0}})
c = contract([check("ok", "true")])
self.write_contract(c, trusted=True)
res = cycle.enforced_results(c, self.proj)
self.assertEqual([x["status"] for x in res], ["failed"])
from sisi import trust
trust.remove(self.proj)
self.assertEqual(cycle.enforced_results(c, self.proj), []) # never run untrusted
trust.add(self.proj)
self.assertEqual(self.sisi("verify").returncode, 1)
class ImproveAndMigrationTests(LearningCase):
def test_improve_says_too_little_data_then_answers(self):
out = self.sisi("improve").stdout
self.assertIn("Is it getting better?", out)
self.assertIn("Too little data", out)
lid = self.mk()
self.again(lid)
for _ in range(6):
store.append("deliveries", {"end": store.now(), "seconds": 120, "send_backs": 1})
out = self.sisi("improve").stdout
self.assertIn("1 taking effect", out)
self.assertIn("0 folded into a recipe, entry or rule, 1 still loose notes", out)
self.assertIn("showings:", out)
self.assertIn("rulebook:", out)
self.assertIn("Not measured:", out)
self.assertIn("learning :", self.sisi("status").stdout)
def test_old_database_migrates_without_loss(self):
# a second, old-shaped database on the side, opened through retro.connect by swapping files
old = os.path.join(self.tmp, "old.db")
con = sqlite3.connect(old)
con.executescript("""
CREATE TABLE lessons(id INTEGER PRIMARY KEY, created TEXT, aim TEXT, change_kind TEXT, target TEXT,
moment TEXT, cause TEXT, change TEXT, status TEXT DEFAULT 'open', count INTEGER DEFAULT 1, last_seen TEXT);
CREATE TABLE occurrences(id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, tool TEXT,
cwd TEXT, repo TEXT, moment TEXT, fp TEXT);
""")
con.execute("INSERT INTO lessons VALUES (1,'2020-01-01T00:00:00Z','speed','verifier','fuzz','m','c',"
"'Seed the fuzz corpus from golden parser files','open',2,'2020-01-02T00:00:00Z')")
con.execute("INSERT INTO occurrences VALUES (1,1,'2020-01-01T00:00:00Z','s','t','/tmp','/tmp','m','f')")
con.commit(); con.close()
import shutil
os.makedirs(os.path.dirname(retro.db_path()), exist_ok=True)
shutil.copy(old, retro.db_path())
con = retro.connect() # migration happens on open
row = dict(con.execute("SELECT * FROM lessons WHERE id=1").fetchone())
occ = con.execute("SELECT count(*) FROM occurrences").fetchone()[0]
retro.ensure_effects(con)
con.close()
self.assertEqual((row["change"], occ), ("Seed the fuzz corpus from golden parser files", 1))
self.assertEqual(row["strength"], 1)
self.assertIn("fuzz", row["triggers"])
self.assertTrue(os.path.exists(os.path.join(self.notes, "fuzz.md"))) # effect folds in too
self.assertEqual(self.lesson(1)["status"], "applied")
def test_old_lessons_jsonl_imports(self):
p = os.path.join(self.tmp, "old.jsonl")
with open(p, "w") as f:
f.write(json.dumps({"t": "lesson", "id": 7, "created": "2020-01-01T00:00:00Z", "aim": "speed",
"change_kind": "rule", "target": None, "moment": "m", "cause": "c",
"change": PARSER_CHANGE, "status": "open", "count": 1,
"last_seen": "2020-01-01T00:00:00Z"}) + "\n")
r = self.sisi("lessons", "import", p)
self.assertEqual(r.returncode, 0, r.stdout)
l = self.lesson(7)
self.assertEqual(l["change"], PARSER_CHANGE)
con = retro.connect()
retro._backfill(con)
con.close()
self.assertIn("pars", self.lesson(7)["triggers"])
# ---- measured matching: a labelled corpus -----------------------------------
# (lesson change, a later request as a different agent would phrase the same work)
SHOULD_MATCH = [
("For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works",
"write a CSV importer for customer records"),
("On btrfs, os.replace of a symlink is not atomic for readers: a lookup can see ENOENT mid-switch, so retry a missing current link briefly",
"atomically switch a symlink to the new release folder"),
("Any test that runs a command which reads stdin must pass stdin explicitly (input or DEVNULL), because an inherited open pipe makes it hang",
"my test hangs when the subprocess reads from a pipe"),
("Verify webhook HMAC signatures over the raw request body before parsing JSON, because reserialized JSON never matches",
"add a webhook endpoint that checks the signature"),
("A daily 02:30 local job must decide what happens in the DST spring-forward gap, when that wall-clock time never occurs",
"schedule a daily job at 2:30 local time"),
("Cursor pagination needs a stable tie-breaker on id after the timestamp, or rows sharing a timestamp are skipped between pages",
"paginate a feed without skipping items that share a timestamp"),
("JWT tokens need a small clock-skew leeway on expiry, because client and server clocks differ by seconds",
"auth tokens rejected as expired due to clock differences"),
("Money must be integer cents end to end; float prices round differently per platform and totals drift by a cent",
"price totals are off by a cent sometimes"),
("Websocket reconnects need exponential backoff with jitter, or a dropped server gets a thundering herd of retries",
"live socket connection drops and reconnects in a loop"),
("Phone photos carry EXIF orientation; decode must apply it or portrait uploads render sideways",
"uploaded photos appear sideways"),
("Normalize filenames to NFC on read and write; macOS returns NFD, so accented names miss lookups byte-wise",
"file with an accented name is not found on disk"),
("Reject tar entries whose names escape the destination with .. or absolute paths before extracting anything",
"extract a tar archive from an upload"),
("Respect DNS TTL values and never cache address records in the process beyond them",
"DNS cache keeps serving old records after a change"),
("Add a required column with expand-contract: nullable first, backfill in batches, then set NOT NULL in a later deploy",
"add a required column to a huge table without downtime"),
("Copy dependency manifests and install before copying source, so the Docker layer cache survives code edits",
"docker build is slow because the dependency layer rebuilds after source edits"),
("OAuth redirect URIs match exactly, including a trailing slash; register the byte-exact callback",
"OAuth callback fails with redirect mismatch"),
("Resample microphone input from 48 kHz to the model's 16 kHz explicitly; playing it raw pitches a voice recording down",
"recorded voice plays back pitched down"),
("Store GPS coordinates at full double precision; rounding to 4 decimal places moves a pin by metres",
"map pins drift by a few metres"),
("Encode non-ASCII mail subjects as MIME encoded-words, or accented subjects arrive garbled",
"email subject lines with accents arrive garbled"),
("Escape ampersands in sitemap URLs; a raw ampersand makes the XML unparsable",
"sitemap XML rejected for invalid characters in URLs"),
("Plural choice must use CLDR plural categories per locale; one/other breaks Russian and Polish",
"Russian translations show the wrong plural form"),
("Embed and subset fonts in generated PDFs, or printing on a machine without the font substitutes another typeface",
"PDF prints in the wrong typeface on another machine"),
("A Redis lock must carry a random token and release by compare-and-delete, or an expired lock lets a second worker run the job",
"a second worker entered while the lock was still held"),
("Parallel branches belong in git worktrees; two agents in one checkout share an index and stomp each other's staging",
"work on two branches at once in separate folders of one repo"),
("A failed charge may be retried safely only with an idempotency key per checkout attempt, stored with the first response",
"retry a failed charge without billing the customer twice"),
]
# Later requests that must surface nothing: common words only, or a single distinctive word with no support.
SHOULD_NOT_MATCH = [
"run the test file and check the output", "add a check for empty input",
"the tests take a long time to run", "read the input file line by line",
"run all the checks before finishing", "test it with a small example first",
"check the output matches the example", "write the results to a file",
"add a test for this change", "run it again and check the output",
"check the first line of the output file", "write a small test for the change",
"run the whole test suite again", "the output file is empty after the run",
"add the missing import and run it", "check the return value is not empty",
"write the output to a new file each time", "test the change with the example input",
"the first run is slower than the second", "add a line to the output for each input",
"write tests first, then the code", "open the CSV in a spreadsheet to look at it",
"restart the websocket service", "the tar file is huge", "renew the OAuth secret",
"rename a variable in the logger",
]
def _reached(block, lid):
import re
return bool(re.search(r"#%d \(" % lid, block))
class MatchingCorpusTests(LearningCase):
def test_measured_part_one_precision_and_overall_reach(self):
# New behaviour: part one ("likely to apply", in full) must never fire on a should-not
# request; overall reach counts the right lesson in part one OR listed in part two within
# its budget, where the asking agent reads the headings and decides.
ids = []
for i, (change, _) in enumerate(SHOULD_MATCH):
ids.append(self.mk(change=change, moment="incident %d at step 3" % i,
cause="overlooked at step 2"))
hits, misses = 0, []
for lid, (_, query) in zip(ids, SHOULD_MATCH):
if _reached(retro.delivery_block(query, "corpus"), lid):
hits += 1
else:
misses.append((lid, query))
wrong = [q for q in SHOULD_NOT_MATCH if retro.delivery(q)[0]]
print("matching corpus: reach (part one or listed) %d/%d, part-one wrong %d/%d"
% (hits, len(SHOULD_MATCH), len(wrong), len(SHOULD_NOT_MATCH)))
self.assertGreaterEqual(hits / len(SHOULD_MATCH), 0.90, "misses: %r" % (misses,))
self.assertEqual(wrong, [], "part one must stay empty for should-not requests")
def test_csv_lesson_reaches_the_next_agent_three_ways(self):
r = self.sisi("retro", "--new", "--aim", "verified",
"--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", "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)
lid = int(r.stdout.split("lesson #")[1].split(",")[0])
for q in ("write a CSV importer for customer records", "CSV importer with quotes and commas",
"import customer rows from a csv file"):
with self.subTest(q):
out = self.sisi("done", "for", q).stdout
self.assertIn("#%d" % lid, out)
self.assertIn("CSV importer", out)
def test_recipe_title_words_alone_never_create_a_match(self):
# Regression: 'rename a variable in the logger' matched a gate lesson only through the words
# 'docs-change Changing' that `done for` added from the chosen recipe (chang escaped COMMON).
lid = self.mk(change="Make the gate attribute tree changes to sessions and stop counting a "
"send-back when another live session is changing the same files",
moment="gate send-backs in step 4 while files changed underneath")
self.assertEqual(retro.match_lessons("rename a variable in the logger"), [])
self.assertEqual(retro.match_lessons("rename a variable in the logger",
extra="docs-change Changing documentation"), [])
self.assertIn(retro._stem("changing"), retro.COMMON)
self.assertTrue(retro.match_lessons("gate send-backs when sessions change files",
extra="docs-change Changing documentation"))
def test_part_two_headings_are_listed_not_read(self):
lid = self.mk(change="Seed the fuzz corpus from golden parser files before fuzzing",
moment="fuzz seeds missing at step 5",
when="fuzzing, parser, hostile input, generated input, corpus seeds, property testing")
out = self.sisi("done", "for", "fuzzing").stdout # one shared when word: a heading, not part one
self.assertIn("other lessons from earlier agents; open any that apply", out)
self.assertNotIn("likely to apply", out)
self.assertIn("#%d" % lid, out)
con = retro.connect()
self.assertEqual((retro.listed_count(con, lid), retro.read_count(con, lid)), (1, 0))
self.assertEqual(con.execute("SELECT place FROM impressions WHERE lesson_id=?", (lid,)).fetchone()[0],
"done-for-listed")
con.close()
self.sisi("lessons", "show", str(lid)) # opening one in full is the reading
con = retro.connect()
self.assertEqual((retro.listed_count(con, lid), retro.read_count(con, lid)), (1, 1))
con.close()
def test_semicolon_prose_is_not_hidden_and_generic_fix_is_no_bridge(self):
# Two real-corpus failures: '; fixed-position...' read as a shell separator and silently hid
# the lesson; and the generic verb 'fix' offered an unrelated lesson as possibly related.
self.assertIsNotNone(retro.display_line("check it before shipping; fixed-position footers hide buttons", self.proj))
self.assertIsNone(retro.display_line("do the thing; rm -rf build", self.proj))
lid = self.mk(change="Check every page at a 375px phone width before shipping; fixed-position footers hide primary buttons",
moment="the button was below the fold in step 2 on a phone",
when="responsive, mobile, phone screen, small screen, layout, signup form")
out = self.sisi("done", "for", "make the signup form responsive on mobile").stdout
self.assertIn("#%d" % lid, out)
part1, _ = retro.delivery("fix the flaky thing")
self.assertEqual(part1, []) # a generic verb in the anecdote never makes a part-one match
def test_done_id_also_shows_matched_lessons(self):
lid = self.mk(change_kind="recipe", target="parser-or-codec",
change="Parser recipes need a fuzz check over hostile generated inputs",
moment="hostile parser input at step 3",
when="parser, fuzzing, codec, hostile input, generated input")
out = self.sisi("done", "parser-or-codec").stdout
self.assertIn("likely to apply", out) # one when hit + target is the entry being printed
self.assertIn("#%d" % lid, out)
def test_unconfirmed_duplicate_sighting_is_recorded(self):
first = self.sisi("retro", "--new", "--aim", "verified",
"--moment", "the parser server waited 90 seconds in step 4 of the nightly job",
"--cause", "no readiness probe existed before the browser step",
"--change-kind", "rule", "--when", PARSER_WHEN, "--change", PARSER_CHANGE)
self.assertEqual(first.returncode, 0, first.stdout)
lid = int(first.stdout.split("lesson #")[1].split(",")[0])
dup = self.sisi("retro", "--aim", "verified",
"--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", "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)
con = retro.connect()
self.assertEqual(retro.sightings_count(con, lid), 1)
con.close()
self.assertIn("1 unconfirmed sighting(s)", self.sisi("lessons", "show", str(lid)).stdout)
as_new = self.sisi("retro", "--new", "--aim", "verified",
"--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", "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()
self.assertEqual(retro.sightings_count(con, lid), 1)
con.close()
# A harder set: each request shares NO content word with its lesson's moment, cause or change text.
# Only the recording agent's when-terms bridge the two wordings, as another agent would write them.
# (change, when, later request)
HARD_MATCH = [
("For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works",
CSV_WHEN, "parse a spreadsheet export of orders into the database"),
("Check every page at a 375px phone width with a screenshot before shipping; fixed-position footers hide primary buttons",
"responsive, mobile, phone screen, small screen, layout, viewport, signup form, login page",
"make the signup form responsive on mobile"),
("Expand-contract only: nullable first, backfill in batches, switch reads, only then drop the old shape",
"migration, schema change, add column, users table, backfill, move data, alter table",
"add a column to the users table and move the data over"),
("Photographs carry orientation metadata; decode must apply it or portraits render rotated",
"sideways photos, image rotation, uploaded pictures, EXIF, photo orientation",
"uploaded pictures appear sideways"),
("Verify HMAC signatures over the raw request body before parsing JSON, because reserialized JSON never matches",
"webhook, payment callback, provider notifications, signed callbacks, callback authentication",
"payment provider callbacks must be authenticated"),
("On btrfs, os.replace of a link is not atomic for readers: a lookup can see ENOENT midway, so retry a missing one briefly",
"symlink, release switch, atomic deploy, current pointer, live version",
"point the live release symlink at the new build"),
("Pass standard input explicitly or use DEVNULL; inherited descriptors can block",
"stdin, pipe, subprocess hang, blocked process, standard input, inherited pipe",
"subprocess hangs reading from a pipe"),
("A 02:30 daily trigger must define behaviour for the spring-forward gap, when that local time never occurs",
"DST, daylight saving, schedule, nightly job, clock change, timezone",
"schedule a nightly job that survives clock changes"),
("Cursor order needs a stable tie-breaker on id after the timestamp, or rows sharing a timestamp are skipped between responses",
"pagination, feed scrolling, cursor pages, endless list, missing items",
"scrolling the feed misses items"),
("Amounts must be integer cents end to end; floats round differently per platform",
"money, prices, totals, penny, rounding, billing amounts, checkout total",
"checkout total differs by a penny"),
("Expiry checks need a small leeway in seconds, because two machines' clocks differ",
"JWT, tokens, logged out, session expiry, auth, token expired",
"users randomly logged out with token expired errors"),
("Reject entries whose names escape the destination with dot-dot or absolute paths before extracting anything",
"archive extraction, zip slip, unpack upload, tar, path traversal, extracting archives",
"safely unpack a zip from a customer"),
("Respect TTL values; a process-level resolver cache must expire entries on time",
"DNS, old server, address change, resolver, hostname lookup, stale address",
"app keeps calling the old server address after the move"),
("Copy dependency manifests and install before copying source, so the layer cache survives code edits",
"docker, container build, image layers, slow builds, caching, dockerfile",
"container image builds take ten minutes after every tweak"),
("Redirect URIs match exactly, including a trailing slash; register the byte-exact callback",
"OAuth, login, Google sign-in, callback mismatch, redirect, sign in",
"login with Google fails after consent"),
("Resample microphone input from 48 kHz to the model's 16 kHz explicitly; playing it raw pitches speech lower",
"audio, voice notes, pitch, sample rate, microphone, resampling",
"voice notes sound like a slowed-down robot"),
("Store coordinates at full double precision; rounding to 4 decimal places moves a pin by metres",
"GPS, map markers, coordinates, location accuracy, pins",
"map markers land on the wrong street"),
("Encode non-ASCII mail subjects as encoded-words, or accented subjects arrive garbled",
"MIME, email subject, umlauts, garbled headers, header encoding, non-ASCII mail",
"German umlauts in email headers break"),
("Plural choice must use CLDR categories per locale; one/other is not enough for many languages",
"i18n, plural forms, Polish, Russian, translations, word forms, localization",
"Polish users see incorrect word forms for counts"),
("A Redis lock must carry a random token and release by compare-and-delete, or expiry lets another holder in",
"distributed lock, cron overlap, duplicate runs, Redis lock, mutex, scheduled job",
"the same scheduled job executed on two machines at once"),
("A missing config file must print one plain line naming the path it wanted and exit 2, never a traceback",
"cli, command line, terminal tool, script, arguments, flags, config file, error message, exit code, usage",
"add a --verbose option to the backup script"),
]
HARD_NOT_MATCH = [
"write a haiku about autumn", "fix flaky websocket reconnect", "rename a variable in the logger",
"translate the README into French", "tidy up CSS variable names",
"show each task's deadline on the weekly planner", "optimise the image thumbnail resizer",
"run the test file and check the output", "add a check for empty input",
"read the input file line by line", "run all the checks before finishing",
"export the quarterly report", "mobile app crashes on startup",
"schedule a team lunch next week", "polish the landing page design",
"check the return value is not empty", "write the output to a new file each time",
"test the change with the example input", "add a line to the output for each input",
"write tests first, then the code", "restart the websocket service",
"check the first line of the output file", "run it again and check the output",
"add the missing import and run it",
]
HARD_MOMENT, HARD_CAUSE = "spotted at step 3", "overlooked at step 2"
class HarderMatchingTests(LearningCase):
def test_measured_recall_when_only_when_terms_bridge_the_words(self):
ids = []
for change, when, query in HARD_MATCH:
content = (retro._stems(change) | retro._stems(HARD_MOMENT) | retro._stems(HARD_CAUSE)) - retro.COMMON
asked = retro._stems(query) - retro.COMMON
self.assertFalse(content & asked, "pair shares content words %r: %r" % (content & asked, query))
self.assertTrue(retro._stems(when) & asked, "pair shares no when word either: %r" % query)
ids.append(self.mk(change=change, moment=HARD_MOMENT, cause=HARD_CAUSE, when=when))
hits, part1_hits, misses = 0, 0, []
for lid, (_, _, query) in zip(ids, HARD_MATCH):
p1, _ = retro.delivery(query)
if lid in [d["row"]["id"] for d in p1]:
part1_hits += 1
if _reached(retro.delivery_block(query, "corpus"), lid):
hits += 1
else:
misses.append((lid, query))
wrong = [q for q in HARD_NOT_MATCH if retro.delivery(q)[0]]
print("harder matching (when-terms only): reach %d/%d (part one %d), part-one wrong %d/%d"
% (hits, len(HARD_MATCH), part1_hits, len(wrong), len(HARD_NOT_MATCH)))
self.assertEqual(hits, len(HARD_MATCH), "misses: %r" % (misses,))
self.assertEqual(wrong, [], "part one must stay empty for should-not requests")
class ImproveFromUseTests(LearningCase):
def test_sisi_improves_from_use_end_to_end(self):
"""The purpose itself: a lesson from session A reaches session B doing the same kind of work,
its showing is recorded, and recurrence after fresh showings strengthens it until a cycle is due."""
a = self.sisi("retro", "--new", "--aim", "verified",
"--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", "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)
lid = int(a.stdout.split("lesson #")[1].split(",")[0])
b_env = {"SISI_SESSION_ID": "session-B"}
for out in (self.sisi("done", "for", "write a CSV importer for customer records", env=b_env).stdout,
self.sisi("verifiers", "for", "csv parsing must survive quotes and commas", env=b_env).stdout):
self.assertIn("#%d" % lid, out)
proj2 = os.path.join(self.tmp, "csvproj"); os.makedirs(proj2)
init = self.sisi("contract", "init", "--goal", "import customer rows from a csv file", cwd=proj2, env=b_env)
self.assertIn("#%d" % lid, init.stdout)
unrelated = self.sisi("done", "for", "style a settings page with a sidebar", env=b_env).stdout
self.assertEqual(retro.delivery("style a settings page with a sidebar")[0], []) # never in part one
self.assertNotIn("likely to apply", unrelated) # at most an unconfirmed heading in part two
con = retro.connect()
places = sorted(r[0] for r in con.execute(
"SELECT DISTINCT place FROM impressions WHERE lesson_id=? AND session='session-B'", (lid,)))
con.close()
# verifiers-for matched in part one (csv + parse in the when-terms); the other two listed it
self.assertEqual(places, ["contract-init-listed", "done-for-listed", "verifiers-for"])
same = self.sisi("retro", "--same-as", str(lid),
"--moment", "again a quoted comma in row 88 broke 'python3 import.py small.csv'",
env=b_env)
self.assertEqual(same.returncode, 0, same.stdout)
self.assertEqual(self.lesson(lid)["strength"], 2) # three showings, then the same mistake
due = self.sisi("cycle", "due")
self.assertEqual(due.returncode, 0, due.stdout)
self.assertIn("waiting for consolidation", due.stdout)
# a second round of showings, then another recurrence: up another step on fresh evidence
self.sisi("done", "for", "CSV importer with quotes and commas", env=b_env)
self.sisi("verifiers", "for", "csv parsing must survive quotes and commas", env=b_env)
same2 = self.sisi("retro", "--same-as", str(lid),
"--moment", "a newline inside a quoted field broke 'python3 import.py rows.csv' at row 12",
env=b_env)
self.assertEqual(same2.returncode, 0, same2.stdout)
self.assertEqual(self.lesson(lid)["strength"], 3)
if __name__ == "__main__":
unittest.main()
+3
View File
@@ -553,6 +553,7 @@ class ExportImportTests(PersonalCase):
self.ok("learn", "never", "ask", "twice")
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--change", "write the failing test first and show it fail with `pytest -k new`")
os.makedirs(os.path.join(self.state, "sessions"))
open(os.path.join(self.state, "sessions", "s1.json"), "w").write('{"a": 1}')
@@ -588,6 +589,7 @@ class ExportImportTests(PersonalCase):
def test_import_sets_existing_data_aside_and_rebuilds_db_from_the_dump(self):
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--change", "write the failing test first and show it fail with `pytest -k new`")
arc = os.path.join(self.tmp, "out.tar.gz")
self.ok("export", arc)
@@ -631,6 +633,7 @@ def LessonRows():
class LessonDumpTests(PersonalCase):
RETRO = ["--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--cause", "the test was written after the code", "--change-kind", "rule",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--change", "write the failing test first and show it fail with `pytest -k new`"]
def test_dump_is_committed_sorted_and_the_database_is_not(self):
+160 -16
View File
@@ -9,6 +9,7 @@ GOOD = dict(aim="verified",
cause="the parser-or-codec recipe does not list the fuzz verifier under Checks",
change_kind="recipe",
change="Add the fuzz verifier to the Checks of the parser-or-codec recipe so parser work picks it by default",
when="parser, fuzzing, codec, hostile input, generated input, parsing",
target="parser-or-codec")
@@ -53,20 +54,20 @@ class RefusalTests(RetroCase):
r = self.retro()
self.assertEqual(r.returncode, 0, r.stdout)
l = self.lessons()
self.assertEqual((len(l), l[0]["count"], l[0]["status"], l[0]["aim"]), (1, 1, "open", "verified"))
# a recipe lesson with a valid target takes effect at once, on its first occurrence
self.assertEqual((len(l), l[0]["count"], l[0]["status"], l[0]["aim"]), (1, 1, "applied", "verified"))
self.assertEqual(self.occurrences(), 1)
def test_each_refusal(self):
# Structural checks only: presence, length, enums, moment-is-not-change, exact empty answers.
bad = {
"missing aim": {"aim": ""}, "missing moment": {"moment": ""}, "missing cause": {"cause": " "},
"missing change": {"change": ""}, "bad aim": {"aim": "vibes"}, "bad kind": {"change_kind": "magic"},
"nothing moment": {"moment": "Nothing, it went well and nothing could be better"},
"nothing change": {"change": "None"}, "na cause": {"cause": "n/a"},
"nothing could be better": {"cause": "honestly nothing could be better here at all"},
"nothing moment exact": {"moment": "nothing"},
"be more careful exact": {"change": "be more careful"},
"short moment": {"moment": "it was slow"}, "short change": {"change": "fix the rule"},
"short cause": {"cause": "bad"},
"generic change": {"change": "be more careful and double-check everything next time around"},
"no concrete moment": {"moment": "it took longer than it needed to because things were slower than I expected"},
"same text": {"moment": GOOD["change"], "change": GOOD["change"]},
}
for name, over in bad.items():
@@ -74,14 +75,152 @@ class RefusalTests(RetroCase):
r = self.retro(over)
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("refused", r.stdout)
self.assertIn("(check:", r.stdout) # every refusal names the check that failed
self.assertEqual(self.lessons(), [])
self.assertEqual(self.occurrences(), 0)
VALID = [
("Dates in the report were one day early for users in Sydney",
"the code formatted UTC timestamps without the user's time zone",
"For anything that shows or compares dates, test with a time zone ahead of and behind UTC and across a daylight saving change"),
("Everything looked fine on my machine and then failed for everyone in the beta",
"my local data was a week old and far too small",
"Anything that reads user data should always be checked against a large recent copy before shipping"),
("Nothing could be imported after the upgrade and nobody noticed for a day",
"the importer swallowed every error and reported success",
"An import should never report success when everything was skipped; zero imported is a failure"),
("The button did nothing at all when pressed quickly twice in a row",
"the handler always waited for the first request to finish",
"Buttons that start work should disable themselves until the work settles, always"),
("It was never clear which of the three copies was the newest one",
"each tool kept its own copy and none said which was live",
"Anything installed in two places should print which copy is running and how old it is"),
("Everything was rebuilt from scratch even for a one-word edit",
"the build never reused anything between runs at all",
"A build should always say what it reused and what it redid, so waste is visible"),
("The search found nothing for a perfectly ordinary plural word",
"matching compared whole words only, with no stemming at all",
"Search over user text should stem words so plurals and verb forms meet"),
("Users in Auckland saw tomorrow's date on everything after midnight",
"dates were formatted in the server zone, never the viewer's",
"For anything dated, format in the viewer's zone and test both sides of UTC"),
("The whole page went blank whenever one record had no title",
"rendering assumed every field is always present on every record",
"Rendering should survive any single record missing any optional field"),
("Nobody could tell whether the job had finished or was still running",
"long work reported nothing between starting and ending",
"Anything that takes more than a few seconds should say what stage it is at"),
("The same invoice was sent twice to the same customer in one morning",
"a retry after a timeout could not tell the first send had landed",
"Anything sent to a customer should carry an id that makes a retry harmless"),
("Accented names vanished from the list after the upgrade finished",
"the new code compared names byte for byte across normalisation forms",
"Names should be normalised the same way on write and on every later read"),
("The report said twenty thousand users when nothing had been measured",
"a file count was presented as a session count without checking",
"Any number a decision depends on should come from measuring the thing it names"),
("Saving appeared to work while nothing was actually written anywhere",
"the write error was logged once and the indicator stayed green",
"A failed save should be visible where the save was asked for, never only in a log"),
("The oldest message in the inbox was never shown to anyone at all",
"paging always sorted newest first and the tail fell off the page",
"Any list that pages should be checked for items that can never be reached"),
("Everything slowed down only when the office came online at nine",
"every client retried at the same second after any failure",
"Retries should always spread out with jitter so clients never stampede together"),
("A file that should never change was quietly rewritten by the installer",
"the install step wrote everywhere instead of only where asked",
"Installers should write nothing outside the places the user was told about"),
("The totals never matched the spreadsheet by exactly one cent",
"money travelled as floats and rounded differently in two places",
"Money should be integer minor units from end to end, always, no exceptions"),
("Nobody could open the attachment because its name had spaces in it",
"the download path was built by joining text with no escaping anywhere",
"Anything that turns a name into a path should be tested with spaces and accents"),
("The night run silently did nothing because the clock had moved",
"a fixed local time never occurred on the spring-forward night",
"Scheduled work should say what happens when its local time never occurs"),
("Search results showed records the signed-in person should never see",
"the filter ran after results were already assembled for display",
"Visibility should be decided before anything user-shaped is assembled for output"),
("The copy on the laptop and the copy at work disagreed about everything",
"sync copied files both ways with nothing recording which won",
"Sync should record, for every conflict, which side won and why it won"),
("It always picked the first answer even when the first was clearly stale",
"ranking never considered how old a result was at selection time",
"Anything cached should carry its age and prefer a fresh answer over a stale one"),
("Nothing was logged when the payment provider answered with an error",
"the error path returned early without touching the log at all",
"Every early return on an error path should leave exactly one log line behind"),
("The whole import stopped on one row that nobody could identify later",
"rows were counted from one in the file and from zero in the message",
"Errors about a row should name it the way the person holding the file counts it"),
("Settings changed on one machine never appeared on the other machine",
"settings were read once at startup and never watched afterwards",
"Anything read at startup that users can edit should say when a restart is needed"),
("The preview and the printed page never agreed about the typeface",
"the preview used a font the printer substituted without telling anyone",
"Anything printable should be checked in the form it is finally printed in"),
("Undo brought back a version nobody recognised from any point in time",
"undo restored whole files while other work had landed in between",
"Undo should reverse one change exactly and refuse when later work touches it"),
("The helper kept asking questions that the request had already answered",
"it never read the answers already recorded earlier in the session",
"Before asking anything, an agent should check what was already settled and say so"),
("Everything passed locally and the first real user hit a crash at once",
"tests only ever used the small tidy examples written by hand",
"Anything parsing outside files should be tested on generated hostile examples"),
]
def test_valid_lessons_in_varied_wording_are_all_accepted(self):
self.assertGreaterEqual(len(self.VALID), 30)
for moment, cause, change in self.VALID:
f = dict(GOOD, moment=moment, cause=cause, change=change)
self.assertEqual(retro.validate(f), [], moment)
# and through the real command, Sydney included (no digit, no path, no ALLCAPS in the moment)
m, c, ch = self.VALID[0]
r = self.retro({"moment": m, "cause": c, "change": ch})
self.assertEqual(r.returncode, 0, r.stdout)
EMPTY = [
{"moment": "nothing"}, {"moment": "None."}, {"cause": "n/a"}, {"cause": "nothing"},
{"change": "be more careful"}, {"change": "test more"}, {"change": "none"},
{"moment": "ok"}, {"cause": "all good"}, {"change": "short"}, {"moment": "it went well"},
{"cause": "fine"}, {"change": "no"},
]
def test_empty_answers_are_refused_with_the_check_named(self):
self.assertGreaterEqual(len(self.EMPTY), 12)
for over in self.EMPTY:
with self.subTest(over):
errs = retro.validate(dict(GOOD, **over))
self.assertTrue(errs)
self.assertTrue(any("(check:" in e for e in errs), errs)
r = self.retro({"change": "be more careful"})
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn('change is an empty answer: "be more careful"', r.stdout)
def test_missing_message_names_the_field(self):
r = self.sisi("retro", "--aim", "speed")
self.assertEqual(r.returncode, 2)
for w in ("moment", "cause", "change-kind", "change"):
for w in ("moment", "cause", "change-kind", "change", "--when"):
self.assertIn(w, r.stdout)
self.assertIn("at least 5 terms", r.stdout)
def test_when_is_required_with_five_terms_for_new_lessons(self):
no_when = dict(GOOD); no_when.pop("when")
r = self.sisi("retro", *argv(no_when))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("--when needs at least 5 terms", r.stdout)
self.assertIn("delimited file", r.stdout) # the worked example in the refusal
few = self.retro({"when": "parser, fuzzing"})
self.assertEqual(few.returncode, 2, few.stdout)
self.assertIn("--when has 2 term(s)", few.stdout)
self.assertEqual(self.lessons(), [])
self.assertEqual(self.retro().returncode, 0) # five-plus terms: accepted and stored
self.assertIn("fuzzing", self.lessons()[0]["when_terms"])
same = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran for 5 minutes with no fuzz verifier chosen")
self.assertEqual(same.returncode, 0, same.stdout) # --same-as needs no --when
def test_json_on_stdin(self):
r = self.sisi("retro", "--json", "-", stdin=json.dumps({k.replace("_", "-"): v for k, v in GOOD.items()}))
@@ -91,8 +230,8 @@ class RefusalTests(RetroCase):
self.assertEqual(self.sisi("retro", "--json", "-", stdin=json.dumps({"aim": "speed"})).returncode, 2)
def test_property_refused_answers_are_never_stored(self):
generic = ["nothing", "n/a", "none", "it went well", "be more careful", "short", "", " ", "test more next time",
"nothing could have been better", "I will try harder"]
# Only structural failures belong here now: exact empty answers, too-short text, bad enums.
generic = ["nothing", "n/a", "none", "it went well", "be more careful", "test more", "short", "", " ", "ok"]
for seed in [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
rng = random.Random(seed)
for _ in range(8 * ITERS):
@@ -129,6 +268,7 @@ class SimilarityAndSameAsTests(RetroCase):
other = dict(aim="speed", change_kind="tool", target="",
moment="the screenshot comparison in `web-ui` waited 90 seconds on a dev server that never started",
cause="no readiness probe before the browser step",
when="browser, screenshot, dev server, port waiting, ui checks, startup",
change="Make sisi verify wait for the declared port instead of sleeping a fixed time")
other.pop("target")
self.assertEqual(self.sisi("retro", *argv(other)).returncode, 0)
@@ -191,15 +331,18 @@ class AutoApplyAndLessonsTests(RetroCase):
return self.sisi("retro", "--same-as", str(lid), "--moment", "again `cargo test` ran 5 min, no fuzz verifier chosen (%s)" % sid, env=env)
def test_second_occurrence_from_second_session_applies_to_notes(self):
self.assertEqual(self.occ("s1").returncode, 0)
self.assertFalse(os.path.exists(os.path.join(self.notes, "parser-or-codec.md")))
r = self.occ("s1", 1) # same session again: not enough
self.assertNotIn("applied", r.stdout)
self.assertEqual(self.lessons()[0]["status"], "open")
r = self.occ("s2", 1)
# The learning loop changed this: the field note is written on the FIRST occurrence,
# and later occurrences never duplicate the bullet.
r = self.occ("s1")
self.assertEqual(r.returncode, 0)
self.assertIn("applied", r.stdout)
self.assertTrue(os.path.exists(os.path.join(self.notes, "parser-or-codec.md")))
self.assertEqual(self.lessons()[0]["status"], "applied")
r = self.occ("s2", 1)
self.assertEqual(r.returncode, 0, r.stdout)
text = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Add the fuzz verifier", text)
self.assertEqual(text.count("Add the fuzz verifier"), 1)
self.assertEqual(self.lessons()[0]["status"], "applied")
# the entry itself is untouched, and show/done print the notes under a heading
self.assertNotIn("Field notes", open(os.path.join(self.ddir, "parser-or-codec.md")).read())
@@ -264,9 +407,10 @@ class AutoApplyAndLessonsTests(RetroCase):
def test_status_shows_lessons(self):
self.retro()
out = self.sisi("status").stdout
self.assertIn("lessons : 1 total, 1 open, 0 applied; 1 occurrences in the last 7 days", out)
self.assertIn("open #1", out)
self.assertIn("lessons : 1 total, 0 open, 1 applied; 1 occurrences in the last 7 days", out)
self.assertIn("active #1", out)
self.assertIn("retros", out)
self.assertIn("learning : 1 lessons taking effect", out)
class TickBlockTests(RetroCase):