Cut: dead commands and developer mode removed, product scanned for owner-specific material, shorter README, measurement script
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
ee42f52188
28 files changed
+570
-571
No files matched your search
@@ -6,8 +6,24 @@ All notable changes to this project are recorded here. The format follows
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Removed
|
||||
|
||||
- `sisi note` and `sisi propose`: use `sisi retro` or `sisi learn`. Existing notes and proposal
|
||||
files in a personal store are no longer read.
|
||||
- `sisi audit` and the audit module.
|
||||
- Developer mode (`sisi dev on|off|status` and the developer-source entry in personal config).
|
||||
`sisi release` and `sisi promote` now act on the product folder of the launcher that is
|
||||
running: run `bin/sisi release` from the clone. Release, rollback and the stable copy remain.
|
||||
- `sisi build-canon` and `sisi canon cost` as public commands; the functions remain for install
|
||||
and other code, and `sisi doctor` now shows the always-loaded size.
|
||||
- `sisi migrate` as a command; `sisi update` performs the migration.
|
||||
|
||||
### Changed
|
||||
|
||||
- The package version is read from the VERSION file, the one source of truth.
|
||||
- The README is rewritten and shortened; contributions are judged against SPEC.md by
|
||||
requirement id.
|
||||
|
||||
- Request-time delivery no longer hands over a recipe on a weak match or for a question that names
|
||||
no work; reading lessons can no longer stale a learning round; the due test counts only lessons a
|
||||
round can act on.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Contributing
|
||||
|
||||
Thanks for looking. sisi is small on purpose; this page says how to change it safely.
|
||||
Contributions are judged against [SPEC.md](SPEC.md) by requirement id: say in the change
|
||||
which requirement it serves, and expect review to check that claim first.
|
||||
|
||||
## Run the tests
|
||||
|
||||
|
||||
@@ -1,63 +1,43 @@
|
||||
# **sisi** is still improving
|
||||
|
||||
**Your AI agents get better at working for you on every turn, in every tool, automatically, just by
|
||||
being used. There is nothing to schedule or maintain.** Each piece of work ends with the agent
|
||||
recording how it could have gone better. That lesson goes into one store that every agent in every
|
||||
tool reads, so a later turn in any tool can start from it. A lesson that recurs after being shown is
|
||||
strengthened until an enforced check stops the mistake.
|
||||
**sisi** is the operating layer that makes an AI coding tool behave as the engineering
|
||||
organization described in [SPEC.md](SPEC.md): it understands intent, defines done before
|
||||
building, verifies with the minimum sufficient evidence, delivers fast, and improves from
|
||||
evidence after every piece of work. The host tool supplies the agent; **sisi** supplies the
|
||||
operating policy, the records, the gates, the learning loop and the orchestration record, so
|
||||
that behaviour is observable and improving rather than hoped for.
|
||||
|
||||
The direction is fixed: state an outcome at a higher level and get it back correct, complete,
|
||||
verified by the strongest method available and fast, with fewer interruptions. An agent writes
|
||||
down how success will be checked, runs those checks before saying it is done, and is sent back
|
||||
when they fail.
|
||||
It is for anyone who uses an AI coding CLI for real work and wants the result back correct,
|
||||
complete and verified, with less human attention spent checking it. One shared rulebook and
|
||||
one learning store serve every tool on the machine, connected by reference, never by copy, so
|
||||
a lesson learned in one tool is available in the next turn of any other.
|
||||
|
||||
sisi is a shared rulebook and a small command-line tool in plain Python with no dependencies. What
|
||||
it learns about you is kept outside the clone, so updating never loses it.
|
||||
**sisi** is a small command-line tool in plain Python with no dependencies. What it learns
|
||||
about you is kept outside the clone, so updating never loses it.
|
||||
|
||||
The name is recursive: its first word is the name itself. It is also a plain statement of where
|
||||
things stand: each turn leaves your tools a little better, and that work is never finished. What is
|
||||
not yet shown is that this makes agents measurably better over weeks of real use. `sisi improve`
|
||||
reports the counted evidence for that question, and it needs real use to have data.
|
||||
## What it does
|
||||
|
||||
## How it works
|
||||
- **An operating policy.** A short rulebook of strategic direction is always loaded. The
|
||||
agent works out the tactics. Each rule states the behaviour, the reason, and what enforces
|
||||
or measures it.
|
||||
- **Records.** Each piece of work can carry a contract of executable checks, a verification
|
||||
record that never reports an unrun check as passed, and delivery timing.
|
||||
- **Gates.** Where a host exposes the moments, hooks check at session start, at each prompt
|
||||
and at the end of a turn. A failing check sends the agent back; after bounded send-backs
|
||||
the work is let through marked unverified, so a broken check cannot trap a session.
|
||||
- **A learning loop.** Work ends with a recorded account of how it could have gone better.
|
||||
Lessons take effect in the personal store at once, are strengthened on recurrence, and are
|
||||
consolidated into rules, library entries and enforced checks.
|
||||
- **An orchestration record.** The workers on the machine are discovered, work is routed to
|
||||
the most affordable usable worker by judged results, and every judgement is recorded.
|
||||
|
||||
`sisi retro` ends each piece of work by recording how it could have gone better: the moment, the
|
||||
cause, and the change that would make a later agent do it right without being told, in the words a
|
||||
different agent would use for that work. The lesson takes effect in your personal store at once and
|
||||
is offered to later agents starting matching work. If the problem recurs after a lesson has been
|
||||
shown, it is strengthened: a note, a candidate rule, then an enforced check the gate runs.
|
||||
`sisi cycle` consolidates lessons into rules and library entries without growing the rulebook.
|
||||
Whether it is due is checked during normal use, so nothing is scheduled; see
|
||||
[docs/learning.md](docs/learning.md). `sisi lessons digest` prints what has been learned in plain
|
||||
words, grouped by topic. Where a tool allows it, the matching recipe and lessons are also delivered
|
||||
the moment a request arrives (`sisi prompt`), and each rule names the command that explains it
|
||||
(`sisi rule`). Delegated work is routed the same way, by measured results rather than a fixed
|
||||
list of models: `sisi workers` and `sisi delegate`; see [docs/workers.md](docs/workers.md).
|
||||
The verifier library ships techniques and recipes that say what done means for a kind of
|
||||
work, so agents query them instead of inventing a check. Format and quality bar:
|
||||
[docs/verifier-format.md](docs/verifier-format.md).
|
||||
|
||||
Improvement needs a way to tell success from failure:
|
||||
## Install
|
||||
|
||||
- **A contract of executable checks.** `.sisi/contract.json` lists the checks that decide success,
|
||||
each with its claim, a command, the result expected and its rung, plus invariants (what must not
|
||||
get worse), assumptions and open questions. The agent drafts it from the request.
|
||||
- **A ladder of six rungs.** Rung 1 proof, model checking or the type system; rung 2
|
||||
property-based testing, fuzzing or comparison with a reference; rung 3 examples; rung 4 golden
|
||||
files and snapshots, including screenshots; rung 5 a rubric scored by an independent judge; rung
|
||||
6 the human. Use the highest feasible rung; some claim kinds have a minimum (concurrency,
|
||||
parsing, money, state machines, data migration).
|
||||
- **An end-of-turn gate.** A hook runs `sisi verify` when the agent tries to finish. A failing or
|
||||
unrun check sends it back, a large change with no contract sends it back to write one, and small
|
||||
edits pass. After repeated send-backs it is let through marked unverified, so a broken check
|
||||
cannot trap a session.
|
||||
- **Time to delivery.** When the gate lets a turn end, sisi records how long the verified result
|
||||
took and how often the agent was sent back. `sisi time` reports it.
|
||||
- **One shared store.** Rulebook, lessons, results and settings are written once and read by every
|
||||
tool, connected by reference (an import line or a symlink), never by copy.
|
||||
|
||||
## Quick start
|
||||
|
||||
Requirements: Python 3.9 or newer, and `git`, on Linux or macOS. Windows is not supported (the code
|
||||
imports `fcntl`). The minimum Python version is proved by CI; the reasoning is in
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
Requirements: Python 3.9 or newer, and `git`, on Linux or macOS.
|
||||
|
||||
git clone https://github.com/swaits/sisi.git
|
||||
cd sisi
|
||||
@@ -65,134 +45,52 @@ imports `fcntl`). The minimum Python version is proved by CI; the reasoning is i
|
||||
bin/sisi install
|
||||
bin/sisi doctor
|
||||
|
||||
The dry run prints every change and makes none. Install backs up every file it edits, adds only an
|
||||
import line, a link, hook entries or a generated plugin, and skips a missing configuration folder.
|
||||
It links the command as `~/.local/bin/sisi`; make sure that folder is on your `PATH`, or call
|
||||
`bin/sisi` from the clone. `sisi doctor` shows what is wired and anything you must still do.
|
||||
The dry run prints every change and makes none. Install backs up every file it edits, adds
|
||||
only an import line, a link, hook entries or a generated plugin, and skips a missing
|
||||
configuration folder. It links the command as `~/.local/bin/sisi`; make sure that folder is
|
||||
on your `PATH`, or call `bin/sisi` from the clone. `sisi doctor` shows what is wired, the
|
||||
size of what is always loaded, and anything you must still do. Per-tool detail, limits and
|
||||
steps you must take 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.
|
||||
|
||||
For a first contract, change to one of your own projects and run
|
||||
`sisi contract init --goal "slugify() turns titles into URL slugs"`. That skeleton's placeholder
|
||||
check fails until you replace it. For a small function with a test next to it:
|
||||
For a first contract, change to one of your own projects and run `sisi contract init`. That
|
||||
skeleton's placeholder check fails until you replace it with a real command. With a hook
|
||||
wired you do not run the checks yourself: the agent writes the contract and the gate runs
|
||||
them. `sisi help` lists every command and what each exit code means.
|
||||
|
||||
{
|
||||
"id": "slugify",
|
||||
"goal": "slugify() turns titles into URL slugs",
|
||||
"checks": [
|
||||
{
|
||||
"id": "examples",
|
||||
"claim": "known titles give the expected slugs, and slugifying twice changes nothing",
|
||||
"kind": "general",
|
||||
"rung": 3,
|
||||
"cmd": "python3 -m unittest -q test_slugify",
|
||||
"expect": {"exit": 0},
|
||||
"timeout_s": 30
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"assumptions": ["Non-ASCII letters are dropped, not transliterated."],
|
||||
"questions": []
|
||||
}
|
||||
## What it does to your tools, and how to undo it
|
||||
|
||||
Trimmed output:
|
||||
|
||||
$ sisi verify
|
||||
...
|
||||
OK
|
||||
|
||||
`sisi verify` succeeds only when every check passes; `sisi help` lists the other exit meanings.
|
||||
With a hook wired you do not run it yourself: the agent writes the contract and the gate runs it.
|
||||
|
||||
## Supported tools
|
||||
|
||||
Enforcement is what happens at the end of a turn; evidence is how the wiring was checked.
|
||||
`sisi doctor` gives the live state on your machine. Per-tool detail, limits and steps you must
|
||||
take are in [docs/harnesses.md](docs/harnesses.md).
|
||||
|
||||
| Tool | Enforcement | Evidence |
|
||||
|---|---|---|
|
||||
| Claude Code | blocks | ran end to end |
|
||||
| Codex CLI | blocks | documentation; session-start hook fired live |
|
||||
| Gemini CLI | blocks | documentation |
|
||||
| GitHub Copilot CLI | blocks | ran end to end |
|
||||
| Pi | blocks | documentation; extension loaded, tick ran live |
|
||||
| Qwen Code | blocks | documentation; session-start hook fired live |
|
||||
| Cursor (no confirmed global rulebook file) | sends a follow-up | documentation |
|
||||
| Aider (existing config file only) | rulebook only | documentation |
|
||||
| Amp | rulebook only | documentation |
|
||||
| Cline | rulebook only | documentation |
|
||||
| Crush | rulebook only | documentation |
|
||||
| Goose | rulebook only | documentation |
|
||||
| Grok CLI | rulebook only | verified with `grok inspect` |
|
||||
| Kiro | rulebook only | documentation |
|
||||
| Windsurf (pointer file) | rulebook only | documentation |
|
||||
| Zed | rulebook only | documentation |
|
||||
| Antigravity (through the shared Gemini file) | unknown | nothing wired separately |
|
||||
| Muse Code (through Claude Code or Codex files) | unknown | nothing wired directly |
|
||||
| OpenCode | unknown | documentation; plugin loading verified live |
|
||||
| Orca | through its provider | host app; nothing to wire |
|
||||
| T3 Code | through its provider | host app; nothing to wire |
|
||||
|
||||
Where there is no gate, the rulebook still tells the agent to write and run a contract, but nothing
|
||||
enforces it.
|
||||
|
||||
## The verifier library
|
||||
|
||||
sisi ships verification techniques and recipes that say what "done" means for a kind of work, such
|
||||
as a bug fix or a data migration. Each technique gives an example, the exact command, what passing
|
||||
looks like, and a check to paste into a contract. `sisi verifiers` and `sisi done` list them, so
|
||||
agents query them instead of inventing a check. Trimmed output:
|
||||
|
||||
$ sisi verifiers for "a parser that must not crash on hostile input"
|
||||
1. hostile-input-from-schema rung 2 cost medium installed: no
|
||||
2. klee rung 1 cost high installed: no
|
||||
|
||||
Matching is by word overlap, weighted toward the question each entry answers, so phrase the claim
|
||||
as a doubt and read the top results rather than trusting the first. `sisi verifiers show ID` prints
|
||||
an entry in full, `sisi verifiers doctor` reports installed tools, and `sisi done for "bug fix"`
|
||||
prints a recipe. Format and quality bar: [docs/verifier-format.md](docs/verifier-format.md).
|
||||
|
||||
## Where data lives, updating and uninstalling
|
||||
|
||||
- **The product** is the clone: code, base rulebook, library and defaults. It is never written at
|
||||
run time.
|
||||
- **The product** is the clone: code, base rulebook, library and defaults. It is never
|
||||
written at run time.
|
||||
- **What sisi learns for you** lives in `~/.local/share/sisi` (or `$SISI_DATA`), a local git
|
||||
repository that is never pushed.
|
||||
- **Scratch** that can be rebuilt lives in `~/.local/state/sisi` (or `$SISI_STATE`).
|
||||
|
||||
`sisi update` replaces only the product, after backing up your personal data, and reapplies what
|
||||
you learned. `sisi status` shows the live state; the layout is in
|
||||
`sisi update` replaces only the product, after backing up your personal data, and reapplies
|
||||
what you learned. `sisi status` shows the live state; the layout is in
|
||||
[docs/personal-data.md](docs/personal-data.md).
|
||||
|
||||
`sisi uninstall` removes the import line, hooks and links. A file you have not edited since install
|
||||
is restored byte for byte. A file you edited keeps your edits and loses only sisi's entries. A file
|
||||
sisi cannot edit with certainty is skipped and reported. Personal data and scratch are left for you
|
||||
to delete. The exact guarantee is in [docs/harnesses.md](docs/harnesses.md).
|
||||
|
||||
## Designed but not built
|
||||
|
||||
[docs/design.md](docs/design.md) separates what is built from what is not. The main missing pieces:
|
||||
|
||||
- The build conductor (`sisi build "<what I want>"`) and its question queue (`sisi inbox`).
|
||||
Neither command exists.
|
||||
- Replay experiments on a task set before a learned change ships, a separate coach run, brief
|
||||
templates and playbooks. Learned changes instead ship to your overlay first and are judged by
|
||||
measured deliveries, with exact revert as the safety net.
|
||||
- The taste judge (a model judging at rung 5), a git-survival signal, transcript harvest beyond
|
||||
Claude Code, and proven end-to-end enforcement in OpenCode, reported by `sisi doctor` as unknown.
|
||||
`sisi uninstall` removes the import line, hooks and links. A file you have not edited since
|
||||
install is restored byte for byte. A file you edited keeps your edits and loses only sisi's
|
||||
entries. A file sisi cannot edit with certainty is skipped and reported. Personal data and
|
||||
scratch are left for you to delete. The exact guarantee is in
|
||||
[docs/harnesses.md](docs/harnesses.md).
|
||||
|
||||
## Security
|
||||
|
||||
sisi runs commands from a project contract, so a contract you did not write is untrusted until you
|
||||
read it and run `sisi contract trust`; until then `sisi verify` refuses and the gate runs nothing.
|
||||
sisi does not sandbox what a trusted contract runs. See [SECURITY.md](SECURITY.md), including how
|
||||
sisi runs commands from a project contract, so a contract you did not write is untrusted
|
||||
until you read it and run `sisi contract trust`; until then the checks refuse to run. sisi
|
||||
does not sandbox what a trusted contract runs. See [SECURITY.md](SECURITY.md), including how
|
||||
to report a problem privately.
|
||||
|
||||
## Contributing
|
||||
## Where to read more
|
||||
|
||||
Running the tests, the standard-library-only rule, the library entry format, and what belongs in
|
||||
the product rather than your own overlay are in [CONTRIBUTING.md](CONTRIBUTING.md). For the release
|
||||
you have, run `sisi --version`; changes between releases are in [CHANGELOG.md](CHANGELOG.md), and
|
||||
all docs are indexed in [docs/README.md](docs/README.md).
|
||||
- [SPEC.md](SPEC.md) — the standard sisi is built and judged against.
|
||||
- [docs/target.md](docs/target.md) — how sisi meets that standard.
|
||||
- `sisi help` — every command, with no per-command reference kept in this file.
|
||||
- [docs/README.md](docs/README.md) — the index of the remaining documentation.
|
||||
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to run the tests and send a change.
|
||||
- [CHANGELOG.md](CHANGELOG.md) — what changed.
|
||||
|
||||
## Licence
|
||||
|
||||
|
||||
+5
-1
@@ -3,14 +3,18 @@
|
||||
| Page | Read it to |
|
||||
|---|---|
|
||||
| [../README.md](../README.md) | learn what sisi is, install it and try it |
|
||||
| [../SPEC.md](../SPEC.md) | read the standard sisi is built and judged against |
|
||||
| [target.md](target.md) | see how sisi meets that standard |
|
||||
| [design.md](design.md) | understand why sisi works the way it does, and what is built versus only designed |
|
||||
| [learning.md](learning.md) | how a recorded lesson takes effect, is measured, strengthened, consolidated or withdrawn |
|
||||
| [workers.md](workers.md) | how the agent tools and models on the machine are found, chosen between by measured results, and run |
|
||||
| [personal-data.md](personal-data.md) | know where sisi keeps what it learns, how the overlay works, and what an update touches |
|
||||
| [verifier-format.md](verifier-format.md) | write or review an entry in the verifier library (`verifiers/`) or a recipe (`done/`) |
|
||||
| [developing.md](developing.md) | work on sisi while also using it: the source folder, stable releases and rollback |
|
||||
| [harnesses.md](harnesses.md) | see, per tool, what is wired, what blocks, and what is unproven |
|
||||
| [../CONTRIBUTING.md](../CONTRIBUTING.md) | run the tests and send a change |
|
||||
| [../SECURITY.md](../SECURITY.md) | understand what sisi runs, and report a problem |
|
||||
| [../CHANGELOG.md](../CHANGELOG.md) | see what changed between versions |
|
||||
| [../CHANGELOG.md](../CHANGELOG.md) | see what changed |
|
||||
|
||||
The rulebook that agents actually read is [../canon/core.md](../canon/core.md).
|
||||
Run `sisi help` for every command; no per-command reference is kept in these pages.
|
||||
+5
-7
@@ -243,7 +243,7 @@ Other things the loop would improve, besides rules: recipes are tightened whenev
|
||||
set of checks; techniques are ranked by how often they catch real failures; checks that never fail are flagged
|
||||
(`sisi checks` does this); new models are scored on the task set before routing changes.
|
||||
|
||||
**Owning the instruction surface.** `sisi audit` lists every source of instructions each tool loads
|
||||
**Owning the instruction surface.** Every source of instructions each tool loads
|
||||
(instruction files, plugins, skills) and reports where they contradict the rulebook. Contradictions the loop
|
||||
cannot remove itself would be put in the oracle queue.
|
||||
|
||||
@@ -281,14 +281,12 @@ product, so the product can be published.
|
||||
|
||||
Any agent in any tool reads through the files or the CLI and writes through the CLI:
|
||||
|
||||
- `sisi note`: record a failure now (older; `sisi retro` is preferred).
|
||||
- `sisi propose`: suggest a rule change (older; `sisi retro` is preferred).
|
||||
- `sisi learn`: record something the human said, in their words. It takes effect at once: user-tier
|
||||
statements are the owner's standing principles (`sisi oracle`), core statements are queued for the
|
||||
product, project statements are handed over to their project. Tiers follow the owner's two questions:
|
||||
does it apply to all projects where sisi may be used, and would it help every user who installs
|
||||
sisi? Both yes is a product change (`core`, in force at once through the overlay, written into the
|
||||
source tree by `sisi promote` on a developer install once folded, the personal copy dropped when
|
||||
source tree by `sisi promote` from the clone once folded, the personal copy dropped when
|
||||
the product contains it; on an ordinary install `sisi promote --export` writes a contribution file
|
||||
and nothing is ever sent automatically). The tool's own name never makes an item project-bound: how
|
||||
sisi itself should behave is core, wherever it was recorded.
|
||||
@@ -315,7 +313,7 @@ Built and covered by tests:
|
||||
where nothing blocks.
|
||||
- The rulebook (`canon/core.md`), the minimum-rung floors, the verifier library and the recipes.
|
||||
- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery
|
||||
(`sisi time`), `sisi audit`.
|
||||
(`sisi time`).
|
||||
- Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's
|
||||
design send-back on large changes, and request-time delivery of the standing principles for design
|
||||
or build requests. The rulebook's first rule states it and `sisi rule` reports its enforcement.
|
||||
@@ -323,7 +321,7 @@ Built and covered by tests:
|
||||
first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a
|
||||
threshold; the digest and `sisi improve` show them first. Three tiers (`core`, `user`, `project`)
|
||||
replace the two-way scope, with older universal items tiered by the next round, and `sisi promote`
|
||||
listing, writing (developer installs) or exporting core items.
|
||||
listing, writing (from the clone) or exporting core items.
|
||||
- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes, `sisi backlog`),
|
||||
moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced
|
||||
checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status
|
||||
@@ -353,7 +351,7 @@ Designed, not built:
|
||||
## Build order
|
||||
|
||||
1. Store, CLI, wiring into each tool, contract format, `sisi verify`, the end-of-turn gate, the first
|
||||
verifier-library entries, rulebook version 0, `sisi audit`. Built.
|
||||
verifier-library entries, rulebook version 0. 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.
|
||||
|
||||
+28
-45
@@ -1,67 +1,50 @@
|
||||
# Developing sisi
|
||||
|
||||
If you only use sisi, you can skip this page. Cloned it and ran `sisi install`? Nothing changes for you:
|
||||
the clone is the installed copy.
|
||||
If you only use sisi, you can skip this page. Cloned it and ran `sisi install`? Nothing
|
||||
changes for you: the clone is the installed copy.
|
||||
|
||||
## Two copies
|
||||
|
||||
When you both use sisi and work on it, keep them apart:
|
||||
|
||||
- the **source folder** (for example `~/src/sisi`): where you edit. It may be broken half the time.
|
||||
- the **stable copy** in `~/.local/lib/sisi/`: what Claude Code, Codex and OpenCode actually run.
|
||||
- the **source folder**: where you edit. It may be broken half the time.
|
||||
- the **stable copy** in `~/.local/lib/sisi/`: what the tools actually run, so a running
|
||||
session is protected while sisi itself is being changed.
|
||||
|
||||
The stable copy is a set of releases, `~/.local/lib/sisi/releases/<UTC timestamp>/`, each holding only the product
|
||||
files (`bin/`, `sisi/`, `canon/`, `verifiers/`, `done/`, `docs/`, `config.default.json`, `VERSION`; no tests, notes or contract).
|
||||
A link called `current` points at the active one. `SISI_LIB` moves the whole folder (tests use it).
|
||||
|
||||
Once a `current` release exists, `sisi install` wires the hooks and `~/.local/bin/sisi` to
|
||||
`~/.local/lib/sisi/current/bin/sisi`. A running tool never sees a half-written copy: a release is built under a
|
||||
hidden name and renamed into place, and `current` is switched by writing a new link and renaming it over the old
|
||||
one. A process that has started keeps running the release it started with.
|
||||
|
||||
One limit, measured on btrfs: a lookup that lands on the exact instant of the switch can fail to find `current`
|
||||
(about 1 lookup in 40,000 during a switch). A hook that hits it fails open, as any hook error does, and the next
|
||||
call finds the new release.
|
||||
The stable copy is a set of releases, `~/.local/lib/sisi/releases/<UTC timestamp>/`, each
|
||||
holding only the product files. A link called `current` points at the active one. Once a
|
||||
`current` release exists, `sisi install` wires the hooks and `~/.local/bin/sisi` to it. A
|
||||
release is built under a hidden name and renamed into place, and `current` is switched
|
||||
atomically, so a running tool never sees a half-written copy: a process that has started
|
||||
keeps running the release it started with. `sisi doctor` shows which copy is live and
|
||||
whether the source folder is ahead of it.
|
||||
|
||||
## Make a release
|
||||
|
||||
From the source folder:
|
||||
Run from the clone:
|
||||
|
||||
sisi release # runs `sisi verify`; refuses if it fails
|
||||
sisi release --deep # also needs the slow checks to pass
|
||||
bin/sisi release # runs the checks; refuses if they fail
|
||||
bin/sisi release --deep # also needs the slow checks to pass
|
||||
|
||||
It copies the product files, switches `current`, rebuilds your rulebook with the new code, keeps the newest three
|
||||
releases, and prints what changed. The first time, run `sisi install` afterwards so the tools point at the stable
|
||||
copy (release tells you if they do not).
|
||||
|
||||
`sisi doctor` shows which copy is live, its release time, and whether the source folder is ahead of it.
|
||||
It copies the product files, switches `current`, rebuilds your rulebook with the new code,
|
||||
keeps the newest releases, and prints what changed. The first time, run `sisi install`
|
||||
afterwards so the tools point at the stable copy (release tells you if they do not).
|
||||
|
||||
## Roll back
|
||||
|
||||
sisi rollback
|
||||
bin/sisi rollback
|
||||
|
||||
Switches `current` to the release before it and rebuilds the rulebook. It can be repeated until the oldest kept
|
||||
release.
|
||||
|
||||
## Developer mode
|
||||
|
||||
sisi dev on [PATH] # remember where the source folder is (setting developer.source in your personal config)
|
||||
sisi dev off
|
||||
sisi dev status
|
||||
|
||||
Needed only when you run `sisi release` or `sisi promote` from somewhere else, such as through the installed
|
||||
copy. Run from the source folder, they use that folder.
|
||||
Switches `current` to the release before it and rebuilds the rulebook.
|
||||
|
||||
## Promote a personal addition
|
||||
|
||||
Rules, verifiers and recipes you added live in your personal overlay. To make one part of the product:
|
||||
Rules, verifiers and recipes you added live in your personal overlay. Run from the clone:
|
||||
|
||||
sisi promote <id> # shows what would be written, and every term it scrubbed
|
||||
sisi promote <id> --apply # writes it into the source folder
|
||||
bin/sisi promote <id> # shows what would be written, and every term it scrubbed
|
||||
bin/sisi promote <id> --apply # writes it into the source folder
|
||||
|
||||
It replaces your home path with `~`, your user name with `<user>`, email addresses with `<email>`, and any terms
|
||||
listed under `developer.personal_terms` in your personal `config.json` with `<personal>`. If a personal term still
|
||||
appears afterwards (for example in different capitals), it stops and names the lines; fix the overlay item and
|
||||
try again. A rule goes into `canon/core.md` (replacing the rule with that id, or added as the next number); a
|
||||
verifier into `verifiers/<section>/`; a recipe into `done/`. It never commits. Review the change, commit it, make a
|
||||
release, then remove your overlay copy so the two do not drift apart.
|
||||
It replaces your home path, user name and email addresses, and any terms listed under
|
||||
`developer.personal_terms` in your personal `config.json`, with placeholders. If a personal
|
||||
term still appears afterwards, it stops and names the lines. A rule goes into the base
|
||||
rulebook; a verifier or recipe into the library. It never commits. Review the change,
|
||||
commit it, make a release, then remove your overlay copy so the two do not drift apart.
|
||||
+4
-4
@@ -64,7 +64,7 @@ what "done" means, verifying, or being sent back by the gate.
|
||||
- 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.
|
||||
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
|
||||
@@ -109,7 +109,7 @@ what "done" means, verifying, or being sent back by the gate.
|
||||
3 (enforced). A recurrence after at least two showings since the last promotion moves it up one
|
||||
step — each step needs its own fresh evidence. A strength-2 lesson
|
||||
becomes a real rule only through consolidation (below), because the rulebook has hard budgets in
|
||||
lines and characters (`sisi canon cost` prints them), and must not grow without shortening. A strength-3 lesson needs a check the gate can run; a folded lesson
|
||||
lines and characters (`sisi doctor` prints them), and must not grow without shortening. A strength-3 lesson needs a check the gate can run; a folded lesson
|
||||
shown 20 times with no recurrence is retired from the notes (it stays in history); a lesson that
|
||||
still recurs at strength 3 is withdrawn, and the same wording will not be learned again.
|
||||
6. **Consolidation happens in a cycle**, run by whichever agent is working — see below.
|
||||
@@ -183,7 +183,7 @@ explaining at least three lessons and at least six incidents (two constants in t
|
||||
or update its statement in the rulebook as one strategic behaviour, traced like any folded
|
||||
lesson. These three pressures are what keep patterns few: reuse is listed before invention is
|
||||
allowed, exact duplicates merge themselves, and anything left over is merged or promoted each
|
||||
round. The brief also lists core items waiting for the product; on a developer install it says
|
||||
round. The brief also lists core items waiting for the product; run from the clone it says
|
||||
to run `sisi promote` after folding, otherwise to export. A file containing only the required
|
||||
set-short/set-scope/set-pattern entries is acceptable when nothing else is ready to fold — a
|
||||
cleanup-only round, startable at once with `sisi cycle --now`. Reading lessons during a round cannot stale it: automatic retirement (a
|
||||
@@ -234,7 +234,7 @@ when present: folded lessons no longer count toward the learned-notes limit, whi
|
||||
`sisi cycle apply FILE` checks the file before writing anything: every lesson id exists, the base
|
||||
version is still current, changed rules keep their id and their Why, named `sisi` commands and
|
||||
enforced programs exist, and the resulting rulebook is inside both budgets (lines and
|
||||
characters, printed by `sisi canon cost`) and no longer in characters than before
|
||||
characters, printed by `sisi doctor`) and no longer in characters than before
|
||||
unless `shortens` names what was removed.
|
||||
Rules are re-wrapped to 100 characters on apply. The base version covers only what a cycle may
|
||||
change (lesson content and status, short lines and topics, rules, notes, enforced checks), not
|
||||
|
||||
@@ -28,7 +28,7 @@ Under `SISI_HOME` (tests) the personal folder is `$SISI_HOME/.local/share/sisi`
|
||||
an older learn-quarantine.jsonl is migrated into learn.jsonl on first read)
|
||||
retest.jsonl replaced items whose base changed in an update (id, old base hash, new base hash)
|
||||
retro.db lessons database (sqlite; not in git; lessons.jsonl is its committed form)
|
||||
generated/core.md the effective rulebook (not in git; rebuilt by `sisi build-canon`)
|
||||
generated/core.md the effective rulebook (not in git; rebuilt by install and update)
|
||||
install/ manifest and original copies of the files `sisi install` edited (not in git)
|
||||
backups/ copies taken before a migration or an update (not in git)
|
||||
|
||||
@@ -50,13 +50,13 @@ Ids: rules are `## 1. Title {#rule-id}` in `canon/core.md`; verifiers and recipe
|
||||
Commands: `sisi overlay list | diff | add-rule | replace-rule | disable-rule | enable-rule` (and the same for
|
||||
`verifier` and `recipe`), `sisi overlay revert COMMIT`. Each change is one commit and rebuilds the rulebook.
|
||||
The generated rulebook may not exceed its line and character budgets: a change that would pass it is refused, so a rule is added
|
||||
by shortening or replacing another. `sisi canon cost` prints the always-loaded size.
|
||||
by shortening or replacing another. `sisi doctor` prints the always-loaded size.
|
||||
|
||||
On `sisi update` the overlay is applied to the new product. A replacement whose base item changed keeps the
|
||||
person's version and is queued in `retest.jsonl` for the learning loop.
|
||||
|
||||
## Moving data
|
||||
|
||||
`sisi migrate` (also run by install and update) moves an older layout in, after a timestamped copy under
|
||||
`sisi update` (also run by install) moves an older layout in, after a timestamped copy under
|
||||
`backups/`. `sisi export [PATH]` / `sisi import PATH` carry personal data, results and session records as one
|
||||
tar.gz.
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"commands_in_help": 39,
|
||||
"commit": "ec91e52",
|
||||
"date": "2026-11-23",
|
||||
"hook_median_seconds": {
|
||||
"gate": 0.0315,
|
||||
"prompt": 0.0602,
|
||||
"tick": 0.0801
|
||||
},
|
||||
"library_files": 160,
|
||||
"modules": 41,
|
||||
"prompt_chars": {
|
||||
"add multi-page map printing with selectable paper size": 0,
|
||||
"fix a typo in the README": 0,
|
||||
"why is the build slow?": 0
|
||||
},
|
||||
"python_lines_in_sisi": 18124,
|
||||
"rulebook_chars_fresh": 8533,
|
||||
"test_count": 566,
|
||||
"test_suite_seconds": 16.82,
|
||||
"tick_chars_fresh": 0
|
||||
}
|
||||
+10
-1
@@ -1,2 +1,11 @@
|
||||
"""sisi: one rulebook and enforced definitions of done for every AI coding CLI."""
|
||||
__version__ = "0.1.0"
|
||||
import os
|
||||
|
||||
def _version():
|
||||
try:
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "VERSION"), encoding="utf-8") as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return "unknown"
|
||||
|
||||
__version__ = _version()
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
"""Inventory of standing instructions each tool loads. Counts lines; does not judge."""
|
||||
import glob, json, os, re
|
||||
|
||||
from . import paths
|
||||
|
||||
|
||||
def _lines(p):
|
||||
try:
|
||||
with open(p, "rb") as f:
|
||||
return f.read().count(b"\n") + 1
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _imports(p, depth=0, seen=None):
|
||||
"""Files pulled in by `@path` lines (Claude Code import syntax)."""
|
||||
seen = seen if seen is not None else set()
|
||||
out = []
|
||||
try:
|
||||
text = open(p, encoding="utf-8", errors="replace").read()
|
||||
except OSError:
|
||||
return out
|
||||
for m in re.finditer(r"^@(\S+)\s*$", text, re.M):
|
||||
q = os.path.expanduser(m.group(1))
|
||||
if not os.path.isabs(q):
|
||||
q = os.path.join(os.path.dirname(p), q)
|
||||
if q not in seen and os.path.isfile(q):
|
||||
seen.add(q)
|
||||
out.append(("import of %s" % os.path.basename(p), q))
|
||||
if depth < 4:
|
||||
out += _imports(q, depth + 1, seen)
|
||||
return out
|
||||
|
||||
|
||||
def _skills(d, label):
|
||||
return [(label, f) for f in sorted(glob.glob(os.path.join(d, "*", "SKILL.md")))]
|
||||
|
||||
|
||||
def _dirmd(d, label):
|
||||
return [(label, f) for f in sorted(glob.glob(os.path.join(d, "**", "*.md"), recursive=True))]
|
||||
|
||||
|
||||
def collect():
|
||||
h = paths.home()
|
||||
j = lambda *a: os.path.join(h, *a)
|
||||
inv = {}
|
||||
cl = []
|
||||
for f in (j(".claude", "CLAUDE.md"),):
|
||||
if os.path.isfile(f):
|
||||
cl.append(("global instructions", f))
|
||||
cl += _imports(f)
|
||||
cl += _dirmd(j(".claude", "rules"), "rules")
|
||||
cl += _skills(j(".claude", "skills"), "skill")
|
||||
cl += _skills(j(".agents", "skills"), "skill (shared)")
|
||||
try:
|
||||
with open(j(".claude", "plugins", "installed_plugins.json"), encoding="utf-8") as f:
|
||||
plugins = json.load(f).get("plugins", {})
|
||||
except (OSError, ValueError, AttributeError):
|
||||
plugins = {}
|
||||
for name, entries in sorted(plugins.items()):
|
||||
for e in entries if isinstance(entries, list) else []:
|
||||
ip = e.get("installPath") if isinstance(e, dict) else None
|
||||
if ip:
|
||||
pl = "plugin " + name
|
||||
cl += _skills(ip, pl + " skill") + _dirmd(os.path.join(ip, "commands"), pl + " command") \
|
||||
+ _dirmd(os.path.join(ip, "agents"), pl + " agent")
|
||||
inv["claude-code"] = cl
|
||||
cx = []
|
||||
for n in ("AGENTS.override.md", "AGENTS.md"):
|
||||
f = j(".codex", n)
|
||||
if os.path.isfile(f):
|
||||
cx.append(("global instructions", f))
|
||||
cx += _skills(j(".codex", "skills"), "skill") + _skills(j(".agents", "skills"), "skill (shared)")
|
||||
inv["codex"] = cx
|
||||
oc = []
|
||||
f = j(".config", "opencode", "AGENTS.md")
|
||||
if os.path.isfile(f):
|
||||
oc.append(("global instructions", f))
|
||||
else:
|
||||
f2 = j(".claude", "CLAUDE.md")
|
||||
if os.path.isfile(f2):
|
||||
oc.append(("global instructions (fallback to Claude's file)", f2))
|
||||
for n in ("opencode.json", "opencode.jsonc"):
|
||||
cf = j(".config", "opencode", n)
|
||||
try:
|
||||
for ins in json.load(open(cf, encoding="utf-8")).get("instructions", []):
|
||||
q = os.path.expanduser(ins)
|
||||
if os.path.isfile(q):
|
||||
oc.append(("config instructions", q))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
oc += _dirmd(j(".config", "opencode", "agents"), "agent") + _dirmd(j(".config", "opencode", "commands"), "command")
|
||||
oc += _skills(j(".agents", "skills"), "skill (shared)")
|
||||
inv["opencode"] = oc
|
||||
mu = []
|
||||
for f in (j(".config", "muse", "AGENTS.md"),):
|
||||
if os.path.isfile(f):
|
||||
mu.append(("global instructions", f))
|
||||
mu += _skills(j(".agents", "skills"), "skill (shared)")
|
||||
inv["muse"] = mu
|
||||
return inv
|
||||
|
||||
|
||||
def main(args=()):
|
||||
inv = collect()
|
||||
grand = 0
|
||||
for tool, items in inv.items():
|
||||
print("%s" % tool)
|
||||
tot = 0
|
||||
for label, f in items:
|
||||
n = _lines(f) or 0
|
||||
tot += n
|
||||
print(" %6d %-34s %s" % (n, label[:34], f))
|
||||
if not items:
|
||||
print(" (none found)")
|
||||
print(" %6d total\n" % tot)
|
||||
grand += tot
|
||||
print("all tools: %d lines (shared files counted once per tool)" % grand)
|
||||
return 0
|
||||
+9
-45
@@ -21,22 +21,17 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
|
||||
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
|
||||
sisi promote [ID|lesson:N] [--apply] | --export [PATH]
|
||||
no ID: list core-tier items not yet in the product; an ID
|
||||
scrubs a personal overlay item into the source folder and
|
||||
drops the personal copy once the product contains it (dry
|
||||
run unless --apply); lesson:N promotes a core lesson on a
|
||||
developer install; --export writes a contribution file
|
||||
from the clone; --export writes a contribution file
|
||||
(universal text only; nothing is sent anywhere)
|
||||
sisi migrate move an older installation's personal data into the personal folder (safe to repeat)
|
||||
sisi update fast-forward the product clone, then back up, migrate and rebuild personal data
|
||||
sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it
|
||||
sisi build-canon regenerate the effective rulebook (base rules + your overlay)
|
||||
sisi canon cost size of what is always loaded: rulebook lines and characters against both budgets, lessons block maximum
|
||||
sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT
|
||||
learned changes to rules, verifiers and recipes; each one a commit in your personal repo
|
||||
sisi audit inventory of standing instructions per tool
|
||||
sisi retro --scope core|user|project --aim A --moment M --cause C --change-kind K --change X --when "csv, tsv, spreadsheet, tabular data, import, parse, delimited file" --pattern "the general failure of thinking, one line" [--pattern-id N] [--target ID] [--same-as ID | --new] [--short "one plain sentence"] [--topic "1-3 lower-case words"]
|
||||
(or --json - with the same keys on stdin)
|
||||
end of every piece of work: HOW it could have gone better; --when (at least
|
||||
@@ -59,8 +54,6 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
|
||||
when none is due; check/--dry-run prints what would change, changing
|
||||
nothing; help prints the full cycle file format
|
||||
sisi improve is it getting better? lessons, recurrence, send-backs, time, rulebook size
|
||||
sisi note TEXT (older; prefer retro) record something that went wrong
|
||||
sisi propose TEXT (older; prefer retro) suggest a rule change
|
||||
sisi learn --scope core|user|project TEXT
|
||||
record a human-stated preference; it takes effect at once.
|
||||
--scope is required, by two questions: (a) does it apply to
|
||||
@@ -212,18 +205,6 @@ def _commit_personal(path, msg):
|
||||
pdata.commit(msg, [os.path.basename(path)])
|
||||
|
||||
|
||||
def cmd_store(kind, args):
|
||||
from . import store
|
||||
text = " ".join(args).strip()
|
||||
if not text:
|
||||
print("usage: sisi %s TEXT" % {"notes": "note", "proposals": "propose"}[kind])
|
||||
return 1
|
||||
store.append(kind, store.stamp({"text": text}))
|
||||
_commit_personal(store.file_path(kind), "%s: %s" % ({"notes": "note", "proposals": "proposal"}[kind], " ".join(text.split())[:60]))
|
||||
print("recorded")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_oracle():
|
||||
from . import principles
|
||||
sys.stdout.write(principles.oracle_text())
|
||||
@@ -343,6 +324,11 @@ def cmd_wiring(name, args=()):
|
||||
if r.get("action"):
|
||||
line += " | you need to: " + r["action"]
|
||||
print(line)
|
||||
try:
|
||||
from . import overlay
|
||||
print("always loaded : " + overlay.cost_line())
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
rc, notes = getattr(wiring, name)()
|
||||
for n in notes:
|
||||
@@ -357,23 +343,6 @@ def cmd_personal(cmd, args):
|
||||
return overlay.main(args)
|
||||
if cmd == "update":
|
||||
return lifecycle.cmd_update(args)
|
||||
if cmd == "migrate":
|
||||
for n in lifecycle.run() or ["nothing to migrate: personal data is in place"]:
|
||||
print(n)
|
||||
return 0
|
||||
if cmd == "build-canon":
|
||||
b = overlay.build_canon()
|
||||
print("%s: %d lines, %d characters%s" % (b["path"], b["lines"], b["chars"], "" if b["changed"] else " (unchanged)"))
|
||||
if b["over_budget"]:
|
||||
print("sisi: over the %d-line budget; shorten or replace a rule" % overlay.MAX_LINES, file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
if cmd == "canon":
|
||||
if args[:1] == ["cost"]:
|
||||
print(overlay.cost_line())
|
||||
return 0
|
||||
print("usage: sisi canon cost")
|
||||
return 1
|
||||
if cmd == "export":
|
||||
print("exported to %s" % lifecycle.export(args[0] if args else None))
|
||||
return 0
|
||||
@@ -447,27 +416,22 @@ def main(argv):
|
||||
return verify.cmd_verify(args)
|
||||
if cmd in ("install", "uninstall", "doctor"):
|
||||
return cmd_wiring(cmd, args)
|
||||
if cmd in ("migrate", "update", "export", "import", "build-canon", "canon", "overlay"):
|
||||
if cmd in ("update", "export", "import", "overlay"):
|
||||
return cmd_personal(cmd, args)
|
||||
if cmd in ("release", "rollback", "dev", "promote"):
|
||||
if cmd in ("release", "rollback", "promote"):
|
||||
from . import release
|
||||
try:
|
||||
return {"release": release.cmd_release, "rollback": release.cmd_rollback,
|
||||
"dev": release.cmd_dev, "promote": release.cmd_promote}[cmd](args)
|
||||
"promote": release.cmd_promote}[cmd](args)
|
||||
except release.ReleaseError as e:
|
||||
print("sisi %s: %s" % (cmd, e), file=sys.stderr)
|
||||
return 1
|
||||
if cmd == "audit":
|
||||
from . import audit
|
||||
return audit.main(args)
|
||||
if cmd == "learn":
|
||||
from . import scope
|
||||
return scope.cmd_learn(args)
|
||||
if cmd == "handover":
|
||||
from . import handover
|
||||
return handover.main(args)
|
||||
if cmd in ("note", "propose"):
|
||||
return cmd_store({"note": "notes", "propose": "proposals"}[cmd], args)
|
||||
if cmd == "retro":
|
||||
from . import retro
|
||||
return retro.cmd_retro(args)
|
||||
|
||||
+4
-4
@@ -564,8 +564,8 @@ Notes - one object per decision; the same lesson may appear several times (split
|
||||
(b) would it be useful to every user who installs sisi? Both yes: core -
|
||||
examples: "write delimited files with a quoting writer"; "use what the host
|
||||
tool already provides instead of building a replacement". (a) yes, (b) no:
|
||||
user - examples: "always ask this owner questions as options with a
|
||||
recommendation"; "prefer this owner's flat-rate plans over per-use ones".
|
||||
user - examples: "always present questions as options with a
|
||||
recommendation"; "prefer flat-rate plans over per-use ones where available".
|
||||
(a) no: project - examples: "this product's settings page keeps advanced
|
||||
options behind one toggle"; "this app uses the left control key for search".
|
||||
Core and user require the delivered text (change, short, when) to be
|
||||
@@ -613,8 +613,8 @@ Learn statements - the equivalent for `sisi learn` statements ("learn" at the to
|
||||
project moves it to that project's handover pile, out of the global store. Tier by the two
|
||||
questions at set-scope above: a statement about how sisi itself should behave for everyone
|
||||
is core ("sisi should anticipate what is needed from what was already said"; "checks, not
|
||||
advice"); how this owner wants work done is user ("always ask questions as options with a
|
||||
recommendation"; "never set up scheduled jobs or timers"); a fact about one product is
|
||||
advice"); how the user wants work done is user ("always present questions as options with
|
||||
a recommendation"; "never set up scheduled jobs or timers"); a fact about one product is
|
||||
project ("this product's settings page keeps advanced options behind one toggle"; "this app
|
||||
uses the left control key for search").
|
||||
|
||||
|
||||
+4
-4
@@ -12,7 +12,7 @@ Files, all under <personal>/overlay/:
|
||||
done/disabled.txt ids of recipes switched off
|
||||
bases.json for each replacement: the hash of the base item it was made against
|
||||
|
||||
The effective rulebook (base + overlay) is generated to <personal>/generated/core.md by `build-canon`.
|
||||
The effective rulebook (base + overlay) is generated to <personal>/generated/core.md.
|
||||
Every command that changes the overlay is one commit in the personal git repository and is refused when the
|
||||
generated rulebook would exceed MAX_LINES.
|
||||
"""
|
||||
@@ -222,7 +222,7 @@ def render():
|
||||
base_h = sha(open(paths.canon("core.md"), "rb").read())[:8]
|
||||
except OSError:
|
||||
base_h = "missing"
|
||||
head = "<!-- generated by sisi build-canon from the product canon/core.md (%s) and the personal overlay (%s); " \
|
||||
head = "<!-- generated by sisi from the product canon/core.md (%s) and the personal overlay (%s); " \
|
||||
"do not edit -->" % (base_h, overlay_hash())
|
||||
parts = [head]
|
||||
if pre.strip():
|
||||
@@ -245,7 +245,7 @@ def build_canon(strict=False):
|
||||
over = lines > MAX_LINES or chars > MAX_CHARS
|
||||
if over and strict:
|
||||
raise OverlayError("the rulebook would be %d lines and %d characters; the budgets are %d lines and %d "
|
||||
"characters. Shorten or replace another rule first (`sisi canon cost` shows the size)"
|
||||
"characters. Shorten or replace another rule first (`sisi doctor` shows the size)"
|
||||
% (lines, chars, MAX_LINES, MAX_CHARS))
|
||||
pdata.ensure()
|
||||
p = paths.generated()
|
||||
@@ -294,7 +294,7 @@ def cost():
|
||||
def cost_line(c=None):
|
||||
c = c or cost()
|
||||
if c["rulebook_lines"] is None:
|
||||
return "rulebook not generated yet (run `sisi build-canon`); lessons block at most %d characters" % c["lessons_block_max_chars"]
|
||||
return "rulebook not generated yet (run `sisi update`); lessons block at most %d characters" % c["lessons_block_max_chars"]
|
||||
return "rulebook %d lines (budget %d), %d characters (budget %d); session-start lessons block at most %d characters, %d lines" % (
|
||||
c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], c.get("rulebook_budget_chars", MAX_CHARS), c["lessons_block_max_chars"], c["lessons_block_max_lines"])
|
||||
|
||||
|
||||
+3
-3
@@ -36,8 +36,8 @@ def data_file(*parts):
|
||||
|
||||
|
||||
def personal(name):
|
||||
"""A personal file. Until `sisi migrate` has moved it, a copy still sitting in the state dir is used,
|
||||
so an installation that has not been migrated yet keeps working."""
|
||||
"""A personal file. Until `sisi update` has moved it, a copy still sitting in the state dir is used,
|
||||
so an installation that has not been updated yet keeps working."""
|
||||
p = data_file(name)
|
||||
if not os.path.exists(p):
|
||||
old = state_file(name)
|
||||
@@ -139,5 +139,5 @@ def notes_dir():
|
||||
|
||||
|
||||
def legacy_notes_dir():
|
||||
"""Where earlier versions wrote field notes: inside the product. Read only, by `sisi migrate`."""
|
||||
"""Where earlier versions wrote field notes: inside the product. Read only, by `sisi update`."""
|
||||
return os.path.join(REPO, "notes")
|
||||
+15
-49
@@ -30,22 +30,14 @@ def is_source(d):
|
||||
return all(os.path.exists(os.path.join(d, p)) for p in ("bin/sisi", "sisi/cli.py", "canon/core.md"))
|
||||
|
||||
|
||||
def dev_source():
|
||||
s = (paths.personal_config().get("developer") or {}).get("source")
|
||||
return s if isinstance(s, str) and s else None
|
||||
|
||||
|
||||
def source(explicit=None):
|
||||
"""The source folder: the one given, else the folder sisi runs from (unless that is a release), else the
|
||||
developer setting."""
|
||||
"""The source folder: the one given, else the product folder of the launcher that is running."""
|
||||
if explicit:
|
||||
s = os.path.abspath(os.path.expanduser(explicit))
|
||||
elif not in_lib(paths.REPO):
|
||||
s = paths.REPO
|
||||
else:
|
||||
s = dev_source()
|
||||
if not s:
|
||||
raise ReleaseError("no source folder: run this from the source folder, or set it with `sisi dev on PATH`")
|
||||
raise ReleaseError("no source folder: run this from the source folder (bin/sisi release from the clone)")
|
||||
if not is_source(s):
|
||||
raise ReleaseError("%s does not look like the sisi source folder (bin/sisi, sisi/, canon/core.md)" % s)
|
||||
return s
|
||||
@@ -188,10 +180,13 @@ def prune(keep=KEEP):
|
||||
|
||||
|
||||
def _rebuild_rulebook():
|
||||
"""Regenerate the rulebook with the code that is now live (not the code that is switching it)."""
|
||||
launcher = os.path.join(paths.current_link(), "bin", "sisi")
|
||||
r = subprocess.run([sys.executable, launcher, "build-canon"], capture_output=True, text=True)
|
||||
return (r.stdout + r.stderr).strip(), r.returncode
|
||||
"""Regenerate the rulebook with the code that is now live."""
|
||||
try:
|
||||
from . import overlay
|
||||
b = overlay.build_canon()
|
||||
return ("%s: %d lines, %d characters" % (b["path"], b["lines"], b["chars"])), 0
|
||||
except Exception as e:
|
||||
return str(e), 1
|
||||
|
||||
|
||||
def run_checks(src, deep=False):
|
||||
@@ -252,40 +247,11 @@ def cmd_rollback(args):
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
# ---- developer mode ---------------------------------------------------------
|
||||
def cmd_dev(args):
|
||||
sub = args[0] if args else "status"
|
||||
if sub == "on":
|
||||
cand = args[1] if len(args) > 1 else (os.getcwd() if is_source(os.getcwd()) else
|
||||
(paths.REPO if not in_lib(paths.REPO) else None))
|
||||
if not cand:
|
||||
print("usage: sisi dev on PATH", file=sys.stderr)
|
||||
return 1
|
||||
cand = os.path.abspath(os.path.expanduser(cand))
|
||||
if not is_source(cand):
|
||||
print("sisi dev: %s does not look like the sisi source folder" % cand, file=sys.stderr)
|
||||
return 1
|
||||
paths.set_personal_config(("developer", "source"), cand, "developer mode on: " + cand)
|
||||
print("developer mode on: source is %s" % cand)
|
||||
return 0
|
||||
if sub == "off":
|
||||
paths.set_personal_config(("developer", "source"), None, "developer mode off")
|
||||
print("developer mode off")
|
||||
return 0
|
||||
if sub == "status":
|
||||
s = dev_source()
|
||||
print("developer mode: " + ("on, source %s%s" % (s, "" if is_source(s) else " (NOT a sisi source folder)") if s else "off"))
|
||||
print("live copy: " + live_text())
|
||||
return 0
|
||||
print("usage: sisi dev on [PATH] | off | status", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
def live_text():
|
||||
cur = current_name()
|
||||
if not cur or not os.path.isdir(paths.current_link()):
|
||||
return "the clone %s (no release made)" % paths.REPO
|
||||
s = dev_source() or (paths.REPO if not in_lib(paths.REPO) and is_source(paths.REPO) else None)
|
||||
s = paths.REPO if not in_lib(paths.REPO) and is_source(paths.REPO) else None
|
||||
txt = "release %s at %s" % (cur, os.path.realpath(paths.current_link()))
|
||||
if s and is_source(s):
|
||||
a, c, r = diff(s, paths.current_link())
|
||||
@@ -543,12 +509,12 @@ def _promote_lesson(lid, apply):
|
||||
"(`sisi cycle`) first, then promote it; or send it upstream with "
|
||||
"`sisi promote --export`." % lid, file=sys.stderr)
|
||||
return 1
|
||||
src = dev_source()
|
||||
if not src or not is_source(src):
|
||||
print("sisi promote: this is not a developer install (no developer source set): nothing "
|
||||
try:
|
||||
src = source()
|
||||
except ReleaseError:
|
||||
print("sisi promote: run this from the source folder (bin/sisi promote from the clone): nothing "
|
||||
"was written. `sisi promote --export` writes a contribution file you may send "
|
||||
"upstream; on a developer install (`sisi dev on PATH`) promote writes into the "
|
||||
"source tree.", file=sys.stderr)
|
||||
"upstream.", file=sys.stderr)
|
||||
return 1
|
||||
return _promote_overlay(pid, apply, src)
|
||||
|
||||
|
||||
+2
-2
@@ -3,7 +3,7 @@ import json, os, re, time
|
||||
|
||||
from . import paths
|
||||
|
||||
FILES = {"results": "results.jsonl", "notes": "notes.jsonl", "proposals": "proposals.jsonl",
|
||||
FILES = {"results": "results.jsonl",
|
||||
"learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl",
|
||||
"deliveries": "deliveries.jsonl"}
|
||||
|
||||
@@ -82,7 +82,7 @@ def session_id():
|
||||
return os.environ.get("SISI_SESSION_ID") or None
|
||||
|
||||
|
||||
PERSONAL = ("notes", "proposals", "learn", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch
|
||||
PERSONAL = ("learn", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch
|
||||
|
||||
|
||||
def file_path(name):
|
||||
|
||||
+6
-7
@@ -117,18 +117,17 @@ def read_ledger(home=None):
|
||||
|
||||
def worker_class(worker):
|
||||
w = (worker or "").lower()
|
||||
for c in ("haiku", "sonnet", "opus"):
|
||||
if w == c or w.startswith(c + "-"):
|
||||
return c
|
||||
return None
|
||||
if not w:
|
||||
return None
|
||||
return w.split("/")[0].split(":")[0] or None
|
||||
|
||||
|
||||
def sub_class(models, meta):
|
||||
found = set()
|
||||
for m in list(models) + [str((meta or {}).get("model") or "")]:
|
||||
for c in ("haiku", "sonnet", "opus"):
|
||||
if c in m.lower():
|
||||
found.add(c)
|
||||
c = worker_class(m)
|
||||
if c:
|
||||
found.add(c)
|
||||
return found
|
||||
|
||||
|
||||
|
||||
+5
-7
@@ -378,9 +378,7 @@ def _ours(p):
|
||||
return True
|
||||
if t.startswith(os.path.join(paths.lib(), "")):
|
||||
return True # the stable copy
|
||||
from . import release # a link made when the tools ran from the source folder
|
||||
src = release.dev_source()
|
||||
return bool(src) and t.startswith(os.path.join(src, ""))
|
||||
return False
|
||||
|
||||
|
||||
def _link(m, p, target, notes, label):
|
||||
@@ -698,12 +696,12 @@ def doctor():
|
||||
todo = lifecycle.pending()
|
||||
rows.append({"tool": "personal", "status": "ok" if pdata.exists() and not todo else "not ready",
|
||||
"detail": "%s (format %d)%s" % (paths.data(), pdata.version(),
|
||||
"; run `sisi migrate`: still to move: " + ", ".join(todo) if todo else ""),
|
||||
"; run `sisi update`: still to move: " + ", ".join(todo) if todo else ""),
|
||||
"blocking_hook": "-"})
|
||||
gen = paths.generated()
|
||||
cur = os.path.isfile(gen) and not overlay.is_stale()
|
||||
rows.append({"tool": "rulebook", "status": "current" if cur else ("stale" if os.path.isfile(gen) else "missing"),
|
||||
"detail": gen + ("" if cur else "; run `sisi build-canon`"), "blocking_hook": "-"})
|
||||
"detail": gen + ("" if cur else "; run `sisi update` to rebuild"), "blocking_hook": "-"})
|
||||
return rows
|
||||
|
||||
|
||||
@@ -715,11 +713,11 @@ def quick_problem():
|
||||
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()
|
||||
return "the generated rulebook is missing at %s (run `sisi update` to rebuild)" % core()
|
||||
if refs:
|
||||
from . import overlay
|
||||
if overlay.is_stale():
|
||||
return "the generated rulebook is out of date (run `sisi build-canon`)"
|
||||
return "the generated rulebook is out of date (run `sisi update` to rebuild)"
|
||||
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
|
||||
|
||||
+4
-10
@@ -154,7 +154,7 @@ class ImmediateEffectTests(LearningCase):
|
||||
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):
|
||||
def test_tool_lessons_backlog_order(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")
|
||||
@@ -163,12 +163,6 @@ class ImmediateEffectTests(LearningCase):
|
||||
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):
|
||||
@@ -1219,9 +1213,9 @@ class CycleGapTests(LearningCase):
|
||||
if r2.returncode != 0:
|
||||
self.assertNotIn("add `shortens`", r2.stdout)
|
||||
|
||||
def test_gap15_char_budget_rewrap_and_canon_cost(self):
|
||||
self.sisi("build-canon")
|
||||
self.assertIn("characters (budget %d)" % overlay.MAX_CHARS, self.sisi("canon", "cost").stdout)
|
||||
def test_gap15_char_budget_rewrap_and_doctor_size(self):
|
||||
overlay.build_canon()
|
||||
self.assertIn("characters (budget %d)" % overlay.MAX_CHARS, self.sisi("doctor").stdout)
|
||||
pre, base = overlay.base_rules()
|
||||
title = next(r["title"] for r in base if r["id"] == "know-done")
|
||||
body = ("Before non-trivial work write a contract listing the checks that decide success "
|
||||
|
||||
+24
-20
@@ -58,6 +58,9 @@ class PersonalCase(SisiCase):
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
return r
|
||||
|
||||
def build_canon(self):
|
||||
return overlay.build_canon()
|
||||
|
||||
def generated(self):
|
||||
with open(paths.generated()) as f:
|
||||
return f.read()
|
||||
@@ -80,19 +83,19 @@ class PersonalCase(SisiCase):
|
||||
|
||||
class OverlayTests(PersonalCase):
|
||||
def test_first_use_creates_personal_repo(self):
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
self.assertTrue(os.path.isdir(os.path.join(self.data, ".git")))
|
||||
self.assertEqual(open(os.path.join(self.data, "VERSION")).read().strip(), str(pdata.FORMAT_VERSION))
|
||||
self.assertIn("retro.db", open(os.path.join(self.data, ".gitignore")).read())
|
||||
g = self.generated()
|
||||
self.assertTrue(g.startswith("<!-- generated by sisi build-canon"))
|
||||
self.assertTrue(g.startswith("<!-- generated by sisi "))
|
||||
self.assertEqual(g.split("\n")[0].count("<!--"), 1)
|
||||
self.assertIn("## 1. Alpha rule {#alpha}", g)
|
||||
self.assertEqual(pdata.git("log", "--format=%an <%ae>").stdout.split("\n")[0], "sisi <sisi@localhost>")
|
||||
self.assertFalse(os.path.exists(os.path.join(self.p1, "oracle.md")))
|
||||
|
||||
def test_hooks_and_global_config_are_ignored(self):
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
hook = os.path.join(self.data, ".git", "hooks", "pre-commit")
|
||||
os.makedirs(os.path.dirname(hook), exist_ok=True)
|
||||
with open(hook, "w") as f:
|
||||
@@ -158,7 +161,7 @@ class OverlayTests(PersonalCase):
|
||||
self.assertRegex(self.ok("verifiers").stdout, r"\n mutmut ")
|
||||
|
||||
def test_size_budget_refuses_and_changes_nothing(self):
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
gen0, log0 = self.generated(), self.git_log()
|
||||
room = overlay.MAX_LINES - len(gen0.splitlines())
|
||||
big = rule_file("Big", "\n".join("line %d" % i for i in range(room + 30)))
|
||||
@@ -180,13 +183,13 @@ class OverlayTests(PersonalCase):
|
||||
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
|
||||
a = self.generated()
|
||||
for _ in range(2):
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
self.assertEqual(self.generated(), a)
|
||||
self.assertFalse(overlay.is_stale())
|
||||
t = os.stat(os.path.join(self.p1, "canon", "core.md")).st_mtime_ns - 5_000_000_000
|
||||
os.utime(paths.generated(), ns=(t, t)) # the product's core.md is now newer than the generated file
|
||||
self.assertTrue(overlay.is_stale())
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
self.assertFalse(overlay.is_stale())
|
||||
|
||||
def test_stale_rulebook_is_reported_by_tick_only_when_wired(self):
|
||||
@@ -195,13 +198,13 @@ class OverlayTests(PersonalCase):
|
||||
self.assertEqual(wiring.quick_problem(), None)
|
||||
os.remove(paths.generated())
|
||||
self.assertIn("generated rulebook is missing", wiring.quick_problem())
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
t = os.stat(os.path.join(self.p1, "canon", "core.md")).st_mtime_ns - 5_000_000_000
|
||||
os.utime(paths.generated(), ns=(t, t))
|
||||
self.assertIn("out of date", wiring.quick_problem())
|
||||
|
||||
def test_one_commit_per_change_and_revert_restores_bytes(self):
|
||||
self.ok("build-canon")
|
||||
self.build_canon()
|
||||
n0 = len(self.git_log())
|
||||
steps = [(("add-rule", "--id", "delta", "-"), rule_file("Delta", "Body.")),
|
||||
(("replace-rule", "alpha", "-"), rule_file("Alpha, mine", "Mine.")),
|
||||
@@ -237,14 +240,14 @@ class OverlayTests(PersonalCase):
|
||||
self.ok("overlay", "revert", pdata.git("rev-parse", "--short", "HEAD").stdout.strip())
|
||||
self.assertEqual(open(paths.generated(), "rb").read(), before)
|
||||
|
||||
def test_canon_cost_and_status(self):
|
||||
self.ok("build-canon")
|
||||
out = self.ok("canon", "cost").stdout
|
||||
def test_doctor_shows_always_loaded_size(self):
|
||||
self.build_canon()
|
||||
out = self.ok("doctor").stdout
|
||||
lines = len(self.generated().splitlines())
|
||||
self.assertIn("rulebook %d lines" % lines, out)
|
||||
self.assertIn("%d characters" % len(self.generated()), out)
|
||||
self.assertIn("lessons block at most %d characters" % retro.LIMIT, out)
|
||||
self.assertIn(out.strip(), self.ok("status").stdout)
|
||||
self.assertIn("rulebook %d lines" % lines, self.ok("status").stdout)
|
||||
|
||||
def test_core_md_rules_have_unique_ids_and_the_budget_holds(self):
|
||||
text = open(os.path.join(REPO, "canon", "core.md")).read()
|
||||
@@ -406,7 +409,7 @@ class MigrationTests(PersonalCase):
|
||||
self.legacy_state()
|
||||
before = self.lessons_of(os.path.join(self.state, "retro.db"))
|
||||
self.assertEqual(len(before[0]), 2)
|
||||
out = self.ok("migrate").stdout
|
||||
out = self.ok("update", "--post").stdout
|
||||
self.assertIn("backed up", out)
|
||||
for n in ("retro.db", "trusted.json", "config.json", "learn-quarantine.jsonl", "notes.jsonl", "proposals.jsonl", "manifest.json", "backups"):
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, n)), n + " should have moved")
|
||||
@@ -425,10 +428,11 @@ class MigrationTests(PersonalCase):
|
||||
self.assertIn(f, files)
|
||||
self.assertNotIn("retro.db", files)
|
||||
self.assertEqual(len(open(os.path.join(self.data, "lessons.jsonl")).read().splitlines()), 2 + len(before[1]))
|
||||
self.assertTrue(self.git_log()[0].startswith("migrate:"))
|
||||
self.assertTrue(any(l.startswith("migrate:") for l in self.git_log()))
|
||||
# the backup has what moved, before it moved
|
||||
bk = os.path.join(self.data, "backups")
|
||||
b = os.path.join(bk, os.listdir(bk)[0])
|
||||
b = next(os.path.join(bk, d) for d in sorted(os.listdir(bk))
|
||||
if os.path.exists(os.path.join(bk, d, "state", "retro.db")))
|
||||
self.assertEqual(self.lessons_of(os.path.join(b, "state", "retro.db")), before)
|
||||
self.assertTrue(os.path.exists(os.path.join(b, "state", "trusted.json")))
|
||||
self.assertTrue(os.path.exists(os.path.join(b, "product", "canon", "oracle.md")))
|
||||
@@ -436,7 +440,7 @@ class MigrationTests(PersonalCase):
|
||||
self.assertTrue(os.path.exists(os.path.join(self.p1, "canon", "oracle.md")))
|
||||
# a second run does nothing
|
||||
n = len(self.git_log())
|
||||
self.assertIn("nothing to migrate", self.ok("migrate").stdout)
|
||||
self.ok("update", "--post")
|
||||
self.assertEqual(len(self.git_log()), n)
|
||||
self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before)
|
||||
self.assertEqual(self.ok("lessons", "--json").stdout.count('"change_kind"'), 2)
|
||||
@@ -461,7 +465,7 @@ class MigrationTests(PersonalCase):
|
||||
change_kind="rule", change="Run sisi oracle before asking anything", target=None), self.proj, None)
|
||||
con.commit()
|
||||
con.close()
|
||||
self.ok("migrate")
|
||||
self.ok("update", "--post")
|
||||
rows, _ = self.lessons_of(os.path.join(self.data, "retro.db"))
|
||||
changes = sorted(r["change"] for r in rows)
|
||||
self.assertEqual(len(changes), len(set(changes)), "a lesson was duplicated")
|
||||
@@ -472,7 +476,7 @@ class MigrationTests(PersonalCase):
|
||||
self.legacy_state()
|
||||
os.makedirs(os.path.join(self.data, "notes"))
|
||||
open(os.path.join(self.data, "notes", "fuzz.md"), "w").write("# Field notes for fuzz\n\n- newer note\n")
|
||||
self.ok("migrate")
|
||||
self.ok("update", "--post")
|
||||
t = open(os.path.join(self.data, "notes", "fuzz.md")).read()
|
||||
self.assertIn("newer note", t)
|
||||
self.assertIn("a field note", t)
|
||||
@@ -736,10 +740,10 @@ class ProductIsReadOnlyTests(PersonalCase):
|
||||
out.seek(0), err.seek(0)
|
||||
return subprocess.CompletedProcess(a, p.returncode, out.read(), err.read())
|
||||
gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False})
|
||||
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",),
|
||||
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("status",),
|
||||
("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"),
|
||||
("learn", "--scope", "everywhere", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
|
||||
("contract", "init", "--goal", "g"), ("verify",), ("migrate",), ("update",),
|
||||
("contract", "init", "--goal", "g"), ("verify",), ("update", "--post"),
|
||||
("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)]
|
||||
for c in cmds:
|
||||
r = run(*c, stdin=rule_file("Z", "Zed.") if c[:2] == ("overlay", "add-rule") else (gate_in if c == ("gate",) else None))
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""The product is universal: no file that ships may name this owner, a home path, a price, or a
|
||||
specific AI model. Host tool names (Claude Code, Codex, OpenCode and the like) are legitimate
|
||||
where an adapter or its docs need them; model ids and model-family names used as instructions
|
||||
are not. Every exception is one allowlist line with its reason."""
|
||||
import os, re, subprocess, unittest
|
||||
|
||||
from support import REPO
|
||||
|
||||
# One line per exception: (relative path, exact text on the line, reason).
|
||||
ALLOWLIST = [
|
||||
("README.md", "github.com/swaits/sisi", "the project's own repository URL, needed to install"),
|
||||
("README.md", "Stephen Waits", "legal copyright attribution, matching LICENSE"),
|
||||
("SECURITY.md", "github.com/swaits/sisi", "the project's own repository URL, needed to report privately"),
|
||||
("sisi/gate.py", "Claude-Code-shaped", "host transcript format name, not a model id"),
|
||||
("verifiers/intent/domain-evidence-report.md", "", "worked example with test-data amounts, not a price"),
|
||||
("verifiers/intent/owner-acceptance-runbook.md", "", "worked example with test-data amounts, not a price"),
|
||||
("sisi/workers.py", "", "TEMPORARY: being rewritten by the orchestration worker under this same rule; remove at merge"),
|
||||
("sisi/routing.py", "", "TEMPORARY: being rewritten by the orchestration worker under this same rule; remove at merge"),
|
||||
]
|
||||
HOST_IDS = {"claude-code", "gemini-cli"}
|
||||
|
||||
OWNER_RES = [
|
||||
("owner handle or name", re.compile(r"swaits", re.I)),
|
||||
("owner given name", re.compile(r"\bStephen\b")),
|
||||
("owner surname", re.compile(r"\bWaits\b")),
|
||||
]
|
||||
HOME_RE = re.compile(r"(?<![\w.])/(?:home|Users)/([A-Za-z0-9_.-]+)")
|
||||
_ALLOWED_HOME_USERS = {"alice", "bob", "user", "you", "name", "username", "example", "me"}
|
||||
CURRENCY_RE = re.compile(r"[$£€]\s?\d{2,}(?:[.,]\d+)*|[$£€]\s?\d+\.\d{2}")
|
||||
MODEL_ID_RE = re.compile(r"\b(?:claude|gpt|gemini|llama|mistral|qwen|deepseek|kimi)-[a-z0-9.-]*\d[a-z0-9.-]*\b", re.I)
|
||||
MODEL_RES = [
|
||||
("model family name", re.compile(r"\b(?:haiku|sonnet|opus|fable)\b", re.I)),
|
||||
]
|
||||
|
||||
SCAN_PREFIXES = ("sisi/", "canon/", "done/", "verifiers/", "bin/")
|
||||
SCAN_FILES = {"config.default.json", "README.md", "CONTRIBUTING.md", "SECURITY.md"}
|
||||
SKIP_DIRS = {"docs/spec/", "docs/reconciliation/"}
|
||||
|
||||
|
||||
def _files():
|
||||
try:
|
||||
r = subprocess.run(["git", "ls-files"], cwd=REPO, capture_output=True, text=True, timeout=30)
|
||||
names = r.stdout.splitlines() if r.returncode == 0 else []
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
names = []
|
||||
if not names:
|
||||
names = []
|
||||
for dp, dns, fns in os.walk(REPO):
|
||||
dns[:] = [d for d in dns if d not in (".git", "__pycache__")]
|
||||
names += [os.path.relpath(os.path.join(dp, n), REPO) for n in fns]
|
||||
out = []
|
||||
for n in names:
|
||||
if any(n.startswith(p) for p in SKIP_DIRS):
|
||||
continue
|
||||
if n.startswith(SCAN_PREFIXES) or n in SCAN_FILES or (n.startswith("docs/") and n.endswith(".md")):
|
||||
if os.path.isfile(os.path.join(REPO, n)):
|
||||
out.append(n)
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def _allowed(rel, line):
|
||||
return any(rel == p and (not frag or frag in line) for p, frag, _ in ALLOWLIST)
|
||||
|
||||
|
||||
def findings(rel, text):
|
||||
out = []
|
||||
whole_file_skip = any(rel == p and not frag for p, frag, _ in ALLOWLIST)
|
||||
if whole_file_skip:
|
||||
return out
|
||||
for i, line in enumerate((text or "").splitlines(), 1):
|
||||
if _allowed(rel, line):
|
||||
continue
|
||||
for name, pat in OWNER_RES:
|
||||
if pat.search(line):
|
||||
out.append("%s:%d: %s: %s" % (rel, i, name, line.strip()[:90]))
|
||||
for m in HOME_RE.finditer(line):
|
||||
if m.group(1).rstrip(".-").lower() not in _ALLOWED_HOME_USERS:
|
||||
out.append("%s:%d: home path: %s" % (rel, i, line.strip()[:90]))
|
||||
if CURRENCY_RE.search(line):
|
||||
out.append("%s:%d: currency amount: %s" % (rel, i, line.strip()[:90]))
|
||||
for m in MODEL_ID_RE.finditer(line):
|
||||
if m.group(0).lower() not in HOST_IDS:
|
||||
out.append("%s:%d: model id: %s" % (rel, i, line.strip()[:90]))
|
||||
for name, pat in MODEL_RES:
|
||||
if pat.search(line):
|
||||
out.append("%s:%d: %s: %s" % (rel, i, name, line.strip()[:90]))
|
||||
return out
|
||||
|
||||
|
||||
class ProductIsUniversal(unittest.TestCase):
|
||||
def test_no_owner_specific_or_perishable_material(self):
|
||||
bad = []
|
||||
for rel in _files():
|
||||
try:
|
||||
with open(os.path.join(REPO, rel), encoding="utf-8", errors="replace") as f:
|
||||
text = f.read()
|
||||
except OSError:
|
||||
continue
|
||||
if "\0" in text:
|
||||
continue
|
||||
bad += findings(rel, text)
|
||||
self.assertEqual(bad, [], "\n".join(bad))
|
||||
|
||||
def test_the_scan_can_fail(self):
|
||||
self.assertTrue(findings("x.py", "ask swaits about it"))
|
||||
self.assertTrue(findings("x.py", "Stephen said so"))
|
||||
self.assertTrue(findings("x.py", "see /home/" + "charlie/project"))
|
||||
self.assertTrue(findings("x.py", "it costs $12 per run"))
|
||||
self.assertTrue(findings("x.py", "use claude-example-1 for this"))
|
||||
self.assertTrue(findings("x.py", "send it to the haiku worker"))
|
||||
self.assertEqual(findings("x.py", "run it in Claude Code or Codex"), [])
|
||||
self.assertEqual(findings("x.py", "see /home/alice/project"), [])
|
||||
# an added offender in a scanned file is caught
|
||||
self.assertTrue(findings("sisi/example.py", "TODO: ask Stephen to check"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -125,7 +125,7 @@ class ReadmeIsHonest(SisiCase):
|
||||
def test_readme_sub_subcommands_are_in_help(self):
|
||||
text = open(os.path.join(REPO, "README.md"), encoding="utf-8").read()
|
||||
help_text = self.sisi("help").stdout
|
||||
for m in set(re.findall(r"`sisi (contract|verifiers|canon|overlay|dev) ([a-z-]+)", text)):
|
||||
for m in set(re.findall(r"`sisi (contract|verifiers|overlay) ([a-z-]+)", text)):
|
||||
self.assertIn(m[1], help_text, " ".join(m))
|
||||
|
||||
def test_python_version_claim_matches_ci_and_code(self):
|
||||
@@ -152,8 +152,10 @@ class NoStaleValues(unittest.TestCase):
|
||||
|
||||
def test_docs_have_no_stale_values(self):
|
||||
rels = ["CONTRIBUTING.md", "SECURITY.md"]
|
||||
# docs/target.md is the reconciliation build reference: its start date and "as today"
|
||||
# describe that project, not the product, so they do not go stale with the product.
|
||||
rels += [os.path.join("docs", n) for n in sorted(os.listdir(os.path.join(REPO, "docs")))
|
||||
if n.endswith(".md")]
|
||||
if n.endswith(".md") and n != "target.md"]
|
||||
findings = []
|
||||
for rel in rels:
|
||||
findings += _stale_value_findings(_text(rel), rel, allow_version_evidence=True)
|
||||
|
||||
+19
-39
@@ -225,48 +225,29 @@ class TestInstallUsesStable(ReleaseCase):
|
||||
self.assertNotIn("run `sisi install`", r.stdout)
|
||||
|
||||
def test_doctor_reports_live_copy_and_source_ahead(self):
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.rel()
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("release " + release.current_name(), r.stdout)
|
||||
self.assertIn("in step", r.stdout)
|
||||
open(os.path.join(self.src, "docs", "more.md"), "w").write("x")
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("ahead (1 file differ)", r.stdout)
|
||||
with mock.patch.object(paths, "REPO", self.src):
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("release " + release.current_name(), r.stdout)
|
||||
self.assertIn("in step", r.stdout)
|
||||
open(os.path.join(self.src, "docs", "more.md"), "w").write("x")
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("ahead (1 file differ)", r.stdout)
|
||||
|
||||
|
||||
class TestDev(ReleaseCase):
|
||||
def test_on_off_status(self):
|
||||
self.assertIn("off", self.sisi("dev", "status").stdout)
|
||||
r = self.sisi("dev", "on", self.src)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(paths.personal_config()["developer"]["source"], self.src)
|
||||
self.assertEqual(store_cfg()["developer"]["source"], self.src)
|
||||
self.assertIn(self.src, self.sisi("dev", "status").stdout)
|
||||
self.assertEqual(self.sisi("dev", "off").returncode, 0)
|
||||
self.assertNotIn("developer", paths.personal_config())
|
||||
self.assertIn("off", self.sisi("dev", "status").stdout)
|
||||
class TestSource(ReleaseCase):
|
||||
def test_source_is_the_launcher_folder(self):
|
||||
self.assertEqual(release.source(), REPO)
|
||||
self.assertEqual(release.source(self.src), self.src)
|
||||
with self.assertRaises(release.ReleaseError):
|
||||
release.source(self.proj)
|
||||
|
||||
def test_on_rejects_non_source_and_keeps_other_config(self):
|
||||
r = self.sisi("dev", "on", self.proj)
|
||||
self.assertEqual(r.returncode, 1)
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
json.dump({"gate": {"budget_s": 5}, "developer": {"personal_terms": ["zed"]}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.sisi("dev", "off")
|
||||
cfg = paths.personal_config()
|
||||
self.assertEqual(cfg["gate"], {"budget_s": 5})
|
||||
self.assertEqual(cfg["developer"], {"personal_terms": ["zed"]})
|
||||
|
||||
def test_release_finds_source_from_release_copy(self):
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.assertEqual(self.sisi("release").returncode, 0)
|
||||
def test_release_from_stable_copy_is_refused(self):
|
||||
self.assertEqual(self.sisi("release", self.src).returncode, 0)
|
||||
with mock.patch.object(paths, "REPO", self.current()): # now running as the stable copy
|
||||
self.assertEqual(release.source(), self.src)
|
||||
self.assertEqual(self.sisi("release").returncode, 0)
|
||||
self.sisi("dev", "off")
|
||||
with self.assertRaises(release.ReleaseError):
|
||||
release.source()
|
||||
self.assertEqual(self.sisi("release").returncode, 1)
|
||||
|
||||
|
||||
def store_cfg():
|
||||
@@ -277,10 +258,9 @@ def store_cfg():
|
||||
class TestPromote(ReleaseCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.assertEqual(self.rel().returncode, 0)
|
||||
# run as the stable copy, so the source is found through developer mode and never the real repository
|
||||
p = mock.patch.object(paths, "REPO", self.current())
|
||||
# run from the clone: the launcher folder is the source, never the real repository
|
||||
p = mock.patch.object(paths, "REPO", self.src)
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
self.assertEqual(release.source(), self.src)
|
||||
@@ -297,7 +277,7 @@ class TestPromote(ReleaseCase):
|
||||
|
||||
def test_dry_run_lists_scrubbed_and_writes_nothing(self):
|
||||
self.put("done/my-recipe.md", "see /home/alice/Code/x and bob@example.com, alice said Acme rules\n")
|
||||
json.dump({"developer": {"source": self.src, "personal_terms": ["Acme"]}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
json.dump({"developer": {"personal_terms": ["Acme"]}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
r = self.promote("my-recipe")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
for t in ("/home/alice", "bob@example.com", "alice", "Acme", "dry run"):
|
||||
|
||||
+4
-4
@@ -673,12 +673,12 @@ class CliHookTests(SisiCase):
|
||||
self.assertEqual(cli._learn_cli("harvest", []), 70) # import of the module fails
|
||||
self.assertEqual(self.sisi("help").returncode, 0)
|
||||
|
||||
def test_help_points_to_retro_and_note_propose_still_work(self):
|
||||
def test_help_points_to_retro(self):
|
||||
out = self.sisi("help").stdout
|
||||
self.assertIn("sisi retro", out)
|
||||
self.assertIn("prefer retro", out)
|
||||
self.assertEqual(self.sisi("note", "still works").returncode, 0)
|
||||
self.assertEqual(self.sisi("propose", "still works").returncode, 0)
|
||||
for retired in ("note", "propose"):
|
||||
self.assertNotIn("sisi " + retired + " ", out)
|
||||
self.assertEqual(self.sisi(retired, "still works").returncode, 64)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+11
-27
@@ -81,23 +81,14 @@ class StoreTests(SisiCase):
|
||||
with open(os.path.join(self.data, name)) as f: # what the person taught sisi is personal data
|
||||
return [json.loads(l) for l in f]
|
||||
|
||||
def test_note_propose_learn_append_with_context(self):
|
||||
for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn.jsonl")):
|
||||
extra = ["--scope", "everywhere"] if cmd == "learn" else []
|
||||
self.assertEqual(self.sisi(cmd, *(extra + ["first", "entry"]), env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
|
||||
self.sisi(cmd, *(extra + ["second"]))
|
||||
recs = self.read(fn)
|
||||
self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
|
||||
self.assertEqual(recs[0]["cwd"], self.proj)
|
||||
self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9"))
|
||||
self.assertIn("ts", recs[0])
|
||||
# learn never reaches the other files
|
||||
self.assertEqual(len(self.read("notes.jsonl")), 2)
|
||||
self.assertEqual(len(self.read("proposals.jsonl")), 2)
|
||||
|
||||
def test_empty_text_rejected(self):
|
||||
self.assertEqual(self.sisi("note").returncode, 1)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.data, "notes.jsonl")))
|
||||
def test_learn_appends_with_context(self):
|
||||
self.assertEqual(self.sisi("learn", "--scope", "everywhere", "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
|
||||
self.sisi("learn", "--scope", "everywhere", "second")
|
||||
recs = self.read("learn.jsonl")
|
||||
self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
|
||||
self.assertEqual(recs[0]["cwd"], self.proj)
|
||||
self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9"))
|
||||
self.assertIn("ts", recs[0])
|
||||
|
||||
def test_oracle_prints_file(self):
|
||||
r = self.sisi("oracle")
|
||||
@@ -107,10 +98,10 @@ class StoreTests(SisiCase):
|
||||
import threading
|
||||
def w(i):
|
||||
for j in range(50):
|
||||
store.append("notes", {"i": i, "j": j, "pad": "x" * 200})
|
||||
store.append("learn", {"i": i, "j": j, "pad": "x" * 200})
|
||||
ts = [threading.Thread(target=w, args=(i,)) for i in range(6)]
|
||||
[t.start() for t in ts]; [t.join() for t in ts]
|
||||
self.assertEqual(len(self.read("notes.jsonl")), 300)
|
||||
self.assertEqual(len(self.read("learn.jsonl")), 300)
|
||||
|
||||
def test_status(self):
|
||||
self.write_contract(contract([check("a", "true", rung=2), check("b", "true", rung=3), human("h")]))
|
||||
@@ -128,7 +119,7 @@ class StoreTests(SisiCase):
|
||||
class HelpTests(SisiCase):
|
||||
def test_help_and_unknown(self):
|
||||
out = self.sisi("help").stdout
|
||||
for w in ("verify", "gate", "tick", "install", "audit", "learn", "verifiers"):
|
||||
for w in ("verify", "gate", "tick", "install", "learn", "verifiers"):
|
||||
self.assertIn(w, out)
|
||||
self.assertNotEqual(self.sisi("bogus").returncode, 0)
|
||||
|
||||
@@ -145,13 +136,6 @@ class HelpTests(SisiCase):
|
||||
r = self.sisi(a)
|
||||
self.assertEqual((r.returncode, r.stdout.strip()), (0, want), a)
|
||||
|
||||
def test_audit_runs_on_fake_home(self):
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
with open(os.path.join(self.home, ".claude", "CLAUDE.md"), "w") as f:
|
||||
f.write("a\nb\n")
|
||||
out = self.sisi("audit").stdout
|
||||
self.assertIn("claude-code", out)
|
||||
self.assertIn("global instructions", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Three tiers (core, user, project): round-trips, migration of `everywhere`, the sisi-name
|
||||
exemption, promote on a developer install, export, and exact cycle revert with tiers."""
|
||||
exemption, promote from the clone, export, and exact cycle revert with tiers."""
|
||||
import json, os, shutil, subprocess, unittest
|
||||
from support import *
|
||||
from sisi import retro, scope, store
|
||||
from sisi import paths, retro, scope, store
|
||||
from unittest import mock
|
||||
|
||||
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
|
||||
PATTERN = "Build the obvious thing instead of using what the environment already provides"
|
||||
@@ -115,7 +116,9 @@ class PromoteTierTests(SisiCase):
|
||||
open(os.path.join(self.src, "sisi", "cli.py"), "w").write("# cli\n")
|
||||
shutil.copy(os.path.join(REPO, "canon", "core.md"), os.path.join(self.src, "canon", "core.md"))
|
||||
os.makedirs(os.path.join(self.data), exist_ok=True)
|
||||
json.dump({"developer": {"source": self.src}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
_p = mock.patch.object(paths, "REPO", self.src) # run from the clone
|
||||
_p.start()
|
||||
self.addCleanup(_p.stop)
|
||||
|
||||
def core_lesson_folded_to_rule(self):
|
||||
r = retro_cli(self, "core")
|
||||
@@ -138,7 +141,7 @@ class PromoteTierTests(SisiCase):
|
||||
out = self.sisi("promote").stdout
|
||||
self.assertIn("lesson:1", out)
|
||||
|
||||
def test_promote_on_dev_install_edits_product_and_drops_personal_copy(self):
|
||||
def test_promote_from_clone_edits_product_and_drops_personal_copy(self):
|
||||
self.core_lesson_folded_to_rule()
|
||||
overlay_file = os.path.join(self.data, "overlay", "rules", "quoting-writer.md")
|
||||
self.assertTrue(os.path.exists(overlay_file))
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure sisi: size, always-loaded characters, hook cost, and test-suite cost.
|
||||
|
||||
Prints one JSON object and a short table. Everything runs in temporary homes;
|
||||
the user's real data is never written. With --live, the loaded characters are
|
||||
also measured against a temporary COPY of the user's real data.
|
||||
|
||||
Standard library only. Works against older checkouts: it copes with the old
|
||||
command set (for example a retired rulebook command) when it finds one.
|
||||
"""
|
||||
import json, os, re, shutil, statistics, subprocess, sys, tempfile, time
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
BIN = os.path.join(ROOT, "bin", "sisi")
|
||||
REQUESTS = ("fix a typo in the README", "why is the build slow?",
|
||||
"add multi-page map printing with selectable paper size")
|
||||
|
||||
|
||||
def run(args, env, cwd=None, stdin=""):
|
||||
return subprocess.run([sys.executable, BIN] + list(args), cwd=cwd or ROOT,
|
||||
input=stdin, capture_output=True, text=True, env=env, timeout=300)
|
||||
|
||||
|
||||
def temp_env(base):
|
||||
home = os.path.join(base, "home")
|
||||
for d in ("home/.claude", "home/.codex", "home/.config/opencode"):
|
||||
os.makedirs(os.path.join(base, d), exist_ok=True)
|
||||
env = dict(os.environ)
|
||||
env.update(SISI_HOME=home, SISI_DATA=os.path.join(base, "data"),
|
||||
SISI_STATE=os.path.join(base, "state"), SISI_LIB=os.path.join(base, "lib"),
|
||||
HOME=home)
|
||||
for k in ("SISI_TOOL", "SISI_SESSION_ID", "SISI_VERIFIERS", "SISI_DONE", "SISI_NOTES"):
|
||||
env.pop(k, None)
|
||||
return env
|
||||
|
||||
|
||||
def fresh_install(env):
|
||||
run(["install"], env)
|
||||
gen = os.path.join(env["SISI_DATA"], "generated", "core.md")
|
||||
if not os.path.isfile(gen):
|
||||
# Older checkouts generated the rulebook through a separate command.
|
||||
help_text = run(["help"], env).stdout
|
||||
if "build-canon" in help_text:
|
||||
run(["build-canon"], env)
|
||||
chars = None
|
||||
if os.path.isfile(gen):
|
||||
with open(gen, encoding="utf-8") as f:
|
||||
chars = len(f.read())
|
||||
return chars
|
||||
|
||||
|
||||
def hook_chars_and_times(env):
|
||||
tick = run(["tick"], env, stdin="{}")
|
||||
prompts = {r: run(["prompt", r], env).stdout for r in REQUESTS}
|
||||
times = {}
|
||||
for name, args, stdin in (("tick", ["tick"], "{}"),
|
||||
("prompt", ["prompt", REQUESTS[0]], ""),
|
||||
("gate", ["gate"], "{}")):
|
||||
samples = []
|
||||
for _ in range(5):
|
||||
t0 = time.perf_counter()
|
||||
run(args, env, stdin=stdin)
|
||||
samples.append(round(time.perf_counter() - t0, 4))
|
||||
times[name] = statistics.median(samples)
|
||||
return len(tick.stdout), {r: len(s) for r, s in prompts.items()}, times
|
||||
|
||||
|
||||
def count_commands(env):
|
||||
out = run(["help"], env).stdout
|
||||
cmds = set()
|
||||
for line in out.splitlines():
|
||||
m = re.match(r"\s{2}sisi ([a-z][a-z-]*)", line)
|
||||
if m:
|
||||
cmds.add(m.group(1))
|
||||
return len(cmds)
|
||||
|
||||
|
||||
def conformance():
|
||||
p = os.path.join(ROOT, "docs", "spec", "conformance.json")
|
||||
if not os.path.isfile(p):
|
||||
return None
|
||||
try:
|
||||
with open(p, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
rows = data if isinstance(data, list) else data.get("requirements", []) if isinstance(data, dict) else []
|
||||
by = {}
|
||||
for r in rows:
|
||||
if isinstance(r, dict):
|
||||
by[str(r.get("status", "unknown"))] = by.get(str(r.get("status", "unknown")), 0) + 1
|
||||
return by or None
|
||||
|
||||
|
||||
def main(argv):
|
||||
live = "--live" in argv
|
||||
py_files = []
|
||||
for dp, dns, fns in os.walk(os.path.join(ROOT, "sisi")):
|
||||
dns[:] = [d for d in dns if d != "__pycache__"]
|
||||
py_files += [os.path.join(dp, n) for n in fns if n.endswith(".py")]
|
||||
lines = 0
|
||||
for p in py_files:
|
||||
with open(p, encoding="utf-8", errors="replace") as f:
|
||||
lines += sum(1 for _ in f)
|
||||
lib_files = 0
|
||||
for d in ("verifiers", "done"):
|
||||
for dp, dns, fns in os.walk(os.path.join(ROOT, d)):
|
||||
lib_files += len([n for n in fns if n.endswith(".md")])
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env = temp_env(tmp)
|
||||
rulebook = fresh_install(env)
|
||||
tick_chars, prompt_chars, times = hook_chars_and_times(env)
|
||||
commands = count_commands(env)
|
||||
|
||||
result = {
|
||||
"python_lines_in_sisi": lines,
|
||||
"modules": len(py_files),
|
||||
"commands_in_help": commands,
|
||||
"library_files": lib_files,
|
||||
"rulebook_chars_fresh": rulebook,
|
||||
"tick_chars_fresh": tick_chars,
|
||||
"prompt_chars": prompt_chars,
|
||||
"hook_median_seconds": times,
|
||||
}
|
||||
|
||||
if live:
|
||||
src_data = os.environ.get("SISI_DATA") or os.path.join(os.path.expanduser("~"), ".local", "share", "sisi")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env = temp_env(tmp)
|
||||
if os.path.isdir(src_data):
|
||||
shutil.copytree(src_data, env["SISI_DATA"], dirs_exist_ok=True) # copy first; original never written
|
||||
rc = run(["doctor"], env)
|
||||
m = re.search(r"rulebook (\d+) lines.*?(\d+) characters", rc.stdout)
|
||||
result["rulebook_chars_live_copy"] = int(m.group(2)) if m else rulebook
|
||||
tick = run(["tick"], env, stdin="{}")
|
||||
result["tick_chars_live_copy"] = len(tick.stdout)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
suite = subprocess.run([sys.executable, os.path.join(ROOT, "tests", "run_parallel.py")],
|
||||
capture_output=True, text=True, timeout=900)
|
||||
result["test_suite_seconds"] = round(time.perf_counter() - t0, 2)
|
||||
counts = [int(x) for x in re.findall(r"Ran (\d+) tests in \d+ modules", suite.stdout + suite.stderr)]
|
||||
if not counts:
|
||||
counts = [int(x) for x in re.findall(r"Ran (\d+) tests", suite.stdout + suite.stderr)]
|
||||
result["test_count"] = max(counts) if counts else None
|
||||
conf = conformance()
|
||||
if conf is not None:
|
||||
result["conformance_by_status"] = conf
|
||||
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
print()
|
||||
print("%-28s %s" % ("python lines in sisi/", result["python_lines_in_sisi"]))
|
||||
print("%-28s %s" % ("modules", result["modules"]))
|
||||
print("%-28s %s" % ("commands in sisi help", result["commands_in_help"]))
|
||||
print("%-28s %s" % ("library files", result["library_files"]))
|
||||
print("%-28s %s" % ("rulebook chars (fresh)", result["rulebook_chars_fresh"]))
|
||||
print("%-28s %s" % ("tick chars (fresh)", result["tick_chars_fresh"]))
|
||||
for r in REQUESTS:
|
||||
print("%-28s %s" % ("prompt chars", "%d %s" % (result["prompt_chars"][r], r)))
|
||||
for k, v in sorted(result["hook_median_seconds"].items()):
|
||||
print("%-28s %s" % ("hook median s: " + k, v))
|
||||
print("%-28s %s" % ("test suite seconds", result["test_suite_seconds"]))
|
||||
print("%-28s %s" % ("test count", result["test_count"]))
|
||||
if conf is not None:
|
||||
print("%-28s %s" % ("conformance by status", json.dumps(conf, sort_keys=True)))
|
||||
if live:
|
||||
print("%-28s %s" % ("rulebook chars (live copy)", result.get("rulebook_chars_live_copy")))
|
||||
print("%-28s %s" % ("tick chars (live copy)", result.get("tick_chars_live_copy")))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Reference in new issue
Block a user