Compare commits
77
Commits
94178e9b04
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
361a850da5 | ||
|
|
6c48de5104 | ||
|
|
593dad8c74 | ||
|
|
08526a02b5 | ||
|
|
b95dddb13d | ||
|
|
13021cdde6 | ||
|
|
b5814dd104 | ||
|
|
ee333dedb9 | ||
|
|
894aeb7e4a | ||
|
|
10688425c9 | ||
|
|
7e0ff4f7bf | ||
|
|
6cd06055c3 | ||
|
|
308def95ca | ||
|
|
09a930d89f | ||
|
|
c39c9de25b | ||
|
|
75f3035141 | ||
|
|
2fcf281e8e | ||
|
|
00e29b57a8 | ||
|
|
1d4edfe011 | ||
|
|
e35dd49828 | ||
|
|
49375e76d0 | ||
|
|
b95c9ee37f | ||
|
|
8c4fdf944e | ||
|
|
f1dbc535a5 | ||
|
|
3a349a3859 | ||
|
|
2af7a5ae01 | ||
|
|
dec84678e9 | ||
|
|
f7f37dffe3 | ||
|
|
cb442e7d6f | ||
|
|
6477fc66d2 | ||
|
|
51ec1e1b75 | ||
|
|
87d5fb8336 | ||
|
|
f0ff5845ca | ||
|
|
caefb1eaa6 | ||
|
|
9ae16c17d0 | ||
|
|
8aa79ab492 | ||
|
|
62e79b8342 | ||
|
|
5f83524b5f | ||
|
|
91036fa6d2 | ||
|
|
3dc3ee3816 | ||
|
|
df744edc7c | ||
|
|
ffb38fc7f6 | ||
|
|
c2f94ac76c | ||
|
|
a03568ed46 | ||
|
|
c3dc6b6e35 | ||
|
|
a8974c02cc | ||
|
|
a3e717af36 | ||
|
|
cadae3cc8c | ||
|
|
2175b566a8 | ||
|
|
25b5e90c6b | ||
|
|
68b6226aa6 | ||
|
|
6edfa6d860 | ||
|
|
2e3a114c8e | ||
|
|
9f167f8f50 | ||
|
|
4b0326ba7c | ||
|
|
0660ee13d6 | ||
|
|
1e1f26616e | ||
|
|
2a68ead05f | ||
|
|
064cd6f5ca | ||
|
|
058d6e3e56 | ||
|
|
c07ce2176b | ||
|
|
bbf21ef178 | ||
|
|
64b748b32e | ||
|
|
d4e11600cb | ||
|
|
6632a82f77 | ||
|
|
33ca3d3c4d | ||
|
|
4e549dedde | ||
|
|
2083bbbd78 | ||
|
|
5e39baaa30 | ||
|
|
d65ee6e547 | ||
|
|
2055d4bb48 | ||
|
|
6e73cca4a1 | ||
|
|
c91d5ed8a5 | ||
|
|
62e494de8e | ||
|
|
6292f5c45e | ||
|
|
6477f22933 | ||
|
|
4c32469a58 |
No files matched your search
+13
-13
@@ -1,20 +1,20 @@
|
||||
- This repo is sisi itself: a learned rule that applies to every sisi user on every system goes into the product (canon/core.md) and is then deleted from the learned lists, so the sisi people download is effective at once; only rules about this owner or this machine stay in the learned lists. [owner 2026-11-23]
|
||||
- In this repo, before merging any branch that adds lines to sisi/, run test_the_product_stays_small and the loaded-text budget check (they take seconds), measuring loaded text in characters per session (canon plus every header rules.py prints) and saying whether it grew or shrank. [retro 2026-11-25, 2026-12-02 p45]
|
||||
- In this repo, run the suite in a checkout nobody edits until it ends, give every release run a 60-minute limit, and treat the serial suite's run time as an open fault until the release gate runs in parallel. [retro 2026-12-02 p12]
|
||||
- Detached background workers must start with python3 -B and print no user-facing output whose only reader is a log; in tests send output to temp files, not pipes, and pass stdin explicitly. [retro 2026-11-23]
|
||||
- Add a test-base guard that fails any test modifying files under the repo product tree, and run hook-imported modules under python3 -X importtime, keeping added import time under 20 ms. [retro 2026-11-23]
|
||||
- In this repo, finished work that passed its checks goes to main and to both remotes (origin and github) in the same step as the final report; the report names the commit and the GitHub test run. [retro 2026-11-24]
|
||||
- In this repo a new piece that arrives while a worker is busy goes at once to another worker in its own checkout and branch; a brief asks for the one full test run inside 'sisi release' and only the tests for the change before that. [retro 2026-11-25]
|
||||
- In this repo, a change to the product is designed, briefed and asked about from an unknown user with other providers and plans: nothing tied to this owner's workers, harnesses, resellers or plans goes into canon/, and per-user choices are left to each user's sisi. [retro 2026-11-25]
|
||||
- In this repo, any trial of sisi against a throwaway store also sets HOME to a temp folder, since a rules write re-points every agent tool's rulebook at the store in use; the brief says so and ends by showing ~/.claude/CLAUDE.md unchanged. [retro 2026-11-26]
|
||||
- In this repo a test that calls sisi functions in-process goes through the in_process helper (temp home as well as temp store), every test class carries the guard that fails when the person's own rules file changes, and the lead compares ~/.claude/CLAUDE.md before and after any worker run that adds tests. [retro 2026-11-28]
|
||||
- sisi is a self-improvement loop (forced retros, each improvement a rule at once, rules organized) and nothing more — keep it simple and small, never over-build; anything beyond costs the person attention. [owner 2026-11-23]
|
||||
- sisi must work globally, for any agent in any harness (T3 Code or otherwise): rules, hooks and the loops are installed and enforced in every agent tool on the machine, not only Claude Code. [owner 2026-11-23]
|
||||
- Use no external dependencies and no cron jobs; run periodic upkeep from a counter or chance check during a normal turn, so the system improves just by being used. [owner 2026-11-23]
|
||||
- The real objective function is the one in SPEC.md; sisi always optimizes it by mechanisms (hooks, checks), never by good intentions, and never hard-codes a model or a harness. [owner 2026-11-23]
|
||||
- Measure size budgets in the unit actually paid for (characters loaded per session), and say plainly whether loaded text grew or shrank after a change. [retro 2026-11-23]
|
||||
- For classifier, matcher or lookup changes, have a different worker write the labelled set and report only held-out accuracy, prototype on a blind set, give three real rows and three real inputs from the live data as test cases, and name every flag the matcher takes — a tuner scoring its own labels or a made-up row overstates accuracy. [retro 2026-11-23] [retro 2026-11-24]
|
||||
- Detached background workers must start with python3 -B (no bytecode in shared state) and print no user-facing output whose only reader is a log; in tests send output to temp files, not pipes, and pass stdin explicitly (input or DEVNULL) — open pipes or inherited stdin hang under some shells. [retro 2026-11-23]
|
||||
- Add a test-base guard that fails any test modifying files under the repo product tree, and run hook-imported modules under python3 -X importtime, keeping the added import time under 20 ms — stray writes and slow hooks go unnoticed. [retro 2026-11-23]
|
||||
- Test config-file-editing code against hostile pre-existing state: symlinks, read-only files, commented or trailing-comma JSON, duplicate entries, edits between install and uninstall — it fails on real user files otherwise. [retro 2026-11-23]
|
||||
- When a check fails, store and show the lines that identify the failure (FAIL and ERROR blocks, else first and last 40 lines) before the tail — the cause is often far above the end of the output. [retro 2026-11-23]
|
||||
- Scoring a piece of work: it can ALWAYS be done better, so every retro names a concrete way it could have scored better even when nothing went wrong; and scores are kept in the terms the objective lists (value, verified evidence, elapsed time, compute and tool cost, attention, getting better), never in terms of its own. [owner 2026-11-23]
|
||||
- For a brief with a numeric acceptance value or check-skipping limit, compute the number from the formula and put the worked figure in the brief, name the event the count starts from, and require a test where that event happens twice. [retro 2026-11-24]
|
||||
- Never pass --help or any probe argument to a command that changes things until its usage is known from the source or the README; read the usage there first. [retro 2026-11-24]
|
||||
- A project's rules and learning live inside that project, in .sisi/ at the project root, never in a subfolder; whether .sisi/ is git-ignored is the user's choice, and sisi must work either way (owner: 'Personally I'd want this checked in and permanent'). [owner 2026-11-24]
|
||||
- In this repo, finished work that passed its checks goes to main and to both remotes (origin and github) in the same step as the final report; the report names the commit and the GitHub test run [retro 2026-11-24]
|
||||
- In this repo a new piece that arrives while a worker is busy goes at once to another worker in its own checkout and branch; a brief asks for one full test run per commit, the one inside 'sisi release', and only the tests for the change before that [retro 2026-11-25]
|
||||
- In this repo, a change to the product is designed, briefed and asked about from an unknown user with other providers and plans: nothing tied to this owner's workers, harnesses, resellers or plans goes into canon/, and per-user choices (which model to use, what it costs them) are left to each user's sisi, never asked of the owner [retro 2026-11-25]
|
||||
- In this repo, count loaded text as canon plus every header rules.py prints into a session, and check the budget against the diff before each merge, not only at the end [retro 2026-11-25]
|
||||
- In this repo, any trial of sisi against a throwaway store also sets HOME to a temp folder (as the tests do), since a rules write re-points every agent tool's rulebook at the store in use; the brief says so and ends by showing ~/.claude/CLAUDE.md unchanged [retro 2026-11-26]
|
||||
- sisi should occasionally automatically audit all the rules, especially the user rules, to see if any project-level rules snuck into there -- and the secondarily project rules to see if any are more broadly applicable to everything the user might work on even beyond that project. This should be a regular audit. The user never has to trigger this (or anything!) manually!!!! [owner 2026-12-01]
|
||||
- sisi's gates can't ever get in the way. They should be there to HELP. [owner 2026-11-25]
|
||||
- Move or rewrite stored data under one lock that every writer holds from read to commit; readers and session start never wait; read only bounded ordinary files, never links. [retro 2026-11-24]
|
||||
- In this repo, a brief that adds code says: if test_the_product_stays_small fails, report the line count and stop; never reflow or compress code you were not asked to change; the lead sets the cap to the measured count at the join [retro 2026-12-03 p55]
|
||||
@@ -7,19 +7,20 @@ the objective, names the gap and its cause, and states the instruction that woul
|
||||
instruction becomes a rule at once, and the next session reads it. Now and then a cheap worker audits and
|
||||
organizes the rules.
|
||||
|
||||
**Delegation.** The lead agent is told to delegate everything, and is stopped when it does the work itself.
|
||||
**Delegation.** The lead agent is told to delegate everything, and is reminded when it does the work itself.
|
||||
It routes by a models table: which workers you have, what each is good at, what it costs. A research worker
|
||||
rebuilds that table when it gets old, and every judged delegation feeds the next research. The lead does not
|
||||
choose the worker: `sisi pick CLASS` spins a wheel over the workers of that class (a capability tier: each model is
|
||||
in exactly one class, so the wheel never mixes tiers; weighted by table order and by the square of the speed ratio),
|
||||
and a delegation to a worker the wheel did not give is refused. One pick, one delegation. A worker that failed for a
|
||||
in exactly one class, so the wheel never mixes tiers; weighted by table order and by the cube of the speed ratio),
|
||||
and a delegation to a worker the wheel did not give gets a note. Recent `bad` verdicts over a worker's last 10
|
||||
good/bad jobs also scale its weight down (never to zero), while workers with no bad runs keep their full weight. One pick, one delegation. A worker that failed for a
|
||||
limit is judged `out` with the provider's message: it is off the wheel for 6 hours, then the wheel tries it again (at most
|
||||
4 times a day), and the pick that hands it out says it is a retry. A host that names its models
|
||||
shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker
|
||||
by its full model id (`claude-sonnet-5-5`); anywhere else the name must match whole.
|
||||
|
||||
**Done.** Nothing starts before `sisi done` has recorded the goal, the checks that decide success and what the
|
||||
person will need next: delegating or editing is refused until then. Every check needs a verdict
|
||||
person will need next: delegating or editing gets a note until then. Every check needs a verdict
|
||||
(`sisi done --pass N` or `--fail N`) before the turn ends; a turn that changed things, or failed a check,
|
||||
is sent to the retro, and any other closes itself, as does work that took under `retro_minutes`, passed every check and delegated nothing. While a delegated job is open and not late, a stop is not held up for checks without a verdict. Each record in `retro.jsonl` carries `session_id`, `retro_seconds` (when demanded),
|
||||
the numbers (minutes, messages, tool calls, delegations, checks), the `term` it fell short on (`value`, `evidence`, `time`, `cost`,
|
||||
@@ -48,6 +49,11 @@ what `install` put in. `sisi update` fetches the newest sisi from the repository
|
||||
`sisi release` run through the installed command never copies that release onto itself: it releases the checkout the
|
||||
release records it came from when that is a local checkout, and otherwise says to run it from a checkout.
|
||||
|
||||
sisi keeps itself current: about once a day, at session start, it checks https://github.com/swaits/sisi in the background
|
||||
(no network in the hook itself); when main there is newer than the release in use and its tests pass, it releases it and
|
||||
says so once at the next session start (`sisi rollback` goes back). A local release that is not an ancestor of that main
|
||||
(newer or diverged) is never replaced. Turn it off or point it elsewhere with `auto_update`, `update_hours` and `update_url`.
|
||||
|
||||
## Which agent tools
|
||||
|
||||
`sisi install` looks at the tools in `canon/harnesses.json` (plain data: add a tool by adding a line). A tool that is
|
||||
@@ -87,14 +93,17 @@ its limits are.
|
||||
| `sisi fault "<what is wrong>"` / `--started\|--blocked\|--fixed N "…"` | Record an open fault in this project, start a fix, name a blocker, or close it; `sisi fault` alone lists them |
|
||||
| `sisi pick routine\|ordinary\|hard [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker; a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) |
|
||||
| `sisi retro` | Print what happened in this piece of work and known problems, to set against the objective |
|
||||
| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" [--scope user]` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault |
|
||||
| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" --level core\|user\|project` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault |
|
||||
| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) |
|
||||
| `sisi retro --later …` | The work is not finished yet |
|
||||
| `sisi learn [--project] "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it |
|
||||
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
|
||||
| `sisi models` / `sisi models research [--record FILE]` | The workers table (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it |
|
||||
| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest |
|
||||
| `sisi judge WORKER extend MINUTES "<reason>" [--newest]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest) gets MINUTES more from now, and its late fault clears |
|
||||
| `sisi learn --level core\|user\|project "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it |
|
||||
| `sisi rules move "<start of a rule>" core\|user\|project\|canon [--project PATH]` | Move one rule line, verbatim, to another level, and print the command that moves it back: `sisi rules revert` does not undo a move (core is a queue for the product, in force as a user rule until it is added to canon/core.md, then `canon` takes it out of the queue); a level is always named, `project` needs a git repo, and organize also audits placement every `audit_after` (12) retros |
|
||||
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; after `sisi rules move`, or an `organize` that moved lines between levels, it changes nothing and prints the command(s) that move them back, which that command also printed; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
|
||||
| `sisi plan brief` / `sisi plan --record FILE` / `sisi plan` / `sisi plan --done\|--fail ID "…"` | The dependency graph of a piece of work, recorded before any delegation: `\| node \| class \| needs \| branch \| files \| check \| why \|`, one join every node reaches; refused on a cycle, a missing need, a shared branch, or overlapping files between nodes that can run at once. Prints the waves to dispatch together. `sisi pick --node ID` gives the worker and a header for the brief; the hook denies a lead's delegation outside the plan, out of order, unpicked, or without its own worktree, and the end of a turn sends the lead back while ready nodes wait. `sisi judge` closes or reopens the node. A `sisi chore:` brief (models research, plan brief) needs no plan. `"enforce": false` turns denials into reminders |
|
||||
| `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class, the one whose published allowance goes furthest, with its source and quota windows (`5h: N req; week: N req`); the wheel picks a plan less the more of its windows sisi's own delegations have used (never below 5%); research is redone every 3 days by a hard worker. (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it |
|
||||
| `sisi models offered [--record FILE]` | Save the host's raw offered-model list from stdin and print the chore to match it against the table; `--record FILE` saves the harness's wheel so `sisi pick` only returns models this harness offers |
|
||||
| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first (and if another open job has `--node`/`--chore`, a note names the closed job and the remaining ones with their targeting flags), `--newest` the newest, `--node ID` closes or reopens the job running that plan node, and `--chore ID` closes that chore job |
|
||||
| `sisi judge WORKER extend MINUTES "<reason>" [--newest] [--node ID \| --chore ID]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest, or the job for `--node ID` / `--chore ID`) gets MINUTES more from now, and its late fault clears |
|
||||
| `sisi direct "…"` | Allow more direct tool calls this turn, with the reason |
|
||||
|
||||
## Where things live
|
||||
@@ -129,9 +138,9 @@ Rules live at three levels:
|
||||
Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`.
|
||||
|
||||
Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8),
|
||||
`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `worker_minutes` (90: a delegation is late after this many minutes, or its own `--limit`),
|
||||
`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `offered_hours` (24: hours before a saved list of offered models is stale), `worker_minutes` (90: a delegation is late after this many minutes, or its own `--limit`),
|
||||
`shell_workers` (false), `retro_minutes` (5: work that passed every check, delegated nothing and took less than this many minutes from `sisi done` closes without a retro),
|
||||
`disk_free_percent` (20), `disk_drop_percent` (5), `checkouts` (8; setting any of these three to 0 turns that tripwire off). Workers are started with the host's own delegation tool, so by default a shell command
|
||||
that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) is
|
||||
refused. Set `"shell_workers": true` to allow it: it is then free on the meter, and needs a pick like any
|
||||
that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) gets a
|
||||
note. Set `"shell_workers": true` to allow it: it is then free on the meter, and needs a pick like any
|
||||
delegation, and `sisi pick` prints the command line.
|
||||
+21
-25
@@ -67,28 +67,24 @@ buy speed with a weaker check.
|
||||
|
||||
## 5. Delegate everything (lead only)
|
||||
|
||||
You own the outcome; workers do the work. Delegate reading, searching, building, testing, research and
|
||||
first reviews, and keep your own context for intent, design, judgement and the final call. Do something
|
||||
yourself only when briefing it would cost more than doing it. `sisi models` lists the workers you have.
|
||||
Decide the class of the task (routine, ordinary, hard), counting rework as cost, then `sisi pick CLASS`
|
||||
spins the wheel over the workers of that class and gives you one: use it. A class holds models of like
|
||||
strength from different makers; the wheel never mixes classes. A review always goes to a different maker
|
||||
than the author: `sisi pick CLASS --review-of WORKER`. Start the worker with the host's own delegation
|
||||
tool; do not shell out to a worker's command line. Run independent work in parallel. Brief a worker as a
|
||||
peer who starts cold: the outcome, what is known and ruled out, what done looks like, the files it may
|
||||
change, what it may create, and a time limit (`sisi pick CLASS --limit MINUTES [--branch NAME]`). At the
|
||||
limit it stops and reports as it stands: what is proven, what failed, what did not run. Extending is the
|
||||
lead's call, made once, with a reason (`sisi judge WORKER extend MINUTES "<reason>"`). Decide the
|
||||
central mechanism in the brief, set against the person's standing rules on its subject, and say what a
|
||||
failed or gamed job does to each number it optimizes. For anything the person will look at, the brief
|
||||
states the look (type, colours, spacing, layout at each width), chosen with the person from previews.
|
||||
For a reported fault, the report's exact inputs are an acceptance test. For a replacement, list each
|
||||
behaviour of the old thing as keep, change or drop, with a check for every keep. Always use the newest
|
||||
version of a model within its maker and class. Its report is evidence for you to judge, not a fact to
|
||||
pass on; record how it went with `sisi judge`. When a worker fails for a limit, a login or a connection,
|
||||
judge it `out` with the provider's message (sisi retries it by itself) and give the same brief to the
|
||||
next one at once: do not ask the person and do not report it. Rebuild the models table in the background
|
||||
when session start says it is old.
|
||||
You own the outcome. You are the dearest model, so delegate reading,
|
||||
searching, measuring, building, testing, research, first reviews and the fact-finding a brief needs, and keep your context for intent, design, judgement and the final call. Choose each piece's
|
||||
class (routine, ordinary, hard) by total cost (your specifying, the work, the redo). Near-free routine models take anything specified exactly (files, change, a check that decides) and keep being tried on such work; judgement and design go to hard: a cheap job redone is waste. Plan first: `sisi plan brief` goes to a hard worker, and `sisi plan --record FILE` keeps the
|
||||
graph: many small exact nodes (class, needs, branch, files, quick check); joins merge and run slow checks.
|
||||
Nodes that run together get their own worktrees and disjoint files. Before the first pick, and whenever sisi asks, give `sisi models offered` the host's full raw list of models its delegation tool can start, and hand its brief to a routine worker. For each ready node `sisi pick --node ID` spins the wheel over that class, among models the host offers (new ones tried at once), and gives a worker and brief header; dispatch every
|
||||
ready node in one message. sisi refuses a handoff outside the plan, out of order or unpicked. The wheel keeps one most-efficient model per provider and class and spreads load so no quota runs out. A review goes to a different maker than the author (`--review-of WORKER`). Start
|
||||
workers with the host's delegation tool, never a worker's command line. Brief a worker as a peer who
|
||||
starts cold: the outcome, what is known and ruled out, what done looks like, the files it may change, what
|
||||
it may create, and a time limit (`--limit MINUTES`). At the limit it stops and reports what is proven, failed and not run. The lead may extend once, with a reason (`sisi
|
||||
judge WORKER extend MINUTES "<reason>"`). Decide the central mechanism in the brief, set against the
|
||||
person's standing rules on its subject, and say what a failed or gamed job does to each number it
|
||||
optimizes. For anything the person will see, the brief states the look (type, colours, spacing, layout
|
||||
at each width), chosen with the person from previews. For a reported fault, the report's exact inputs are
|
||||
an acceptance test. For a replacement, list each behaviour of the old thing as keep, change or drop, with a
|
||||
check for every keep. Its report is evidence to judge, not a fact to pass on; record how it went
|
||||
with `sisi judge`, which closes or reopens its node. When a worker fails on a limit, login or connection, judge it `out` with the provider's message (sisi retries it) and give the same brief
|
||||
to the next at once, without asking or reporting. Rebuild the models table in the
|
||||
background when session start says it is old.
|
||||
|
||||
## 6. Report plainly
|
||||
|
||||
@@ -112,11 +108,11 @@ tests, evidence and completion.
|
||||
|
||||
When work ends, the lead runs `sisi retro` to see what happened and known problems. Set it against
|
||||
the objective by term: where did work fall short, why, and what instruction prevents it? Record
|
||||
`sisi retro --gap … --cause … --improve … --term T --problem N|"<name>"` (`--problem` is required with `--gap` or refused: cite `N` or name a new one; each citation after opening is a miss; at the 2nd miss a fault opens). The improvement becomes a rule at
|
||||
once: product (every user, in the product), user (how this person works across projects, in their store), or project (`.sisi/rules.md` at root, in git its main checkout's, which may be checked in). Name the root cause, not general
|
||||
`sisi retro --gap … --cause … --improve … --term T --problem N|"<name>" --level L` (`--problem` is required with `--gap` or refused: cite `N` or name a new one; each citation after opening is a miss; at the 2nd miss a fault opens). The improvement becomes a rule at
|
||||
once, at the --level you name: core (every sisi user; queued), user (how this person works across projects), or project (`.sisi/rules.md` at root, in git its main checkout's). Name the root cause, not general
|
||||
advice. Prefer a rule that makes next work do more by itself over a caution; a caution says what stays allowed
|
||||
without asking. Work can always be done better: when nothing fell short, name the one thing that would have scored better (`--no-gap … --term T --better …`).
|
||||
When the person states a lasting preference, record their words at once with `sisi learn`. When session start says
|
||||
Record a stated lasting preference in the person's words at once: `sisi learn --level L`. When session start says
|
||||
rules need organizing, have a cheap worker do it in the background.
|
||||
|
||||
## 9. Fix what you see
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[
|
||||
{"name": "claude", "detect": "~/.claude", "env": "CLAUDE_CONFIG_DIR", "rules": "CLAUDE.md", "import": true, "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "The built-in Explore and Plan subagents do not load CLAUDE.md."},
|
||||
{"name": "claude", "detect": "~/.claude", "env": "CLAUDE_CONFIG_DIR", "here": "CLAUDE_CODE_ENTRYPOINT","rules": "CLAUDE.md", "import": true, "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "The built-in Explore and Plan subagents do not load CLAUDE.md."},
|
||||
{"name": "codex", "detect": "~/.codex", "env": "CODEX_HOME", "rules": "AGENTS.md", "hooks": {"file": "hooks.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "Hooks run only after the person trusts them once in Codex's /hooks; AGENTS.override.md shadows the rulebook; hosted web search is not metered."},
|
||||
{"name": "qwen", "detect": "~/.qwen", "rules": "QWEN.md", "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "A tool Qwen names differently from canon/tools.json is not metered."},
|
||||
{"name": "grok", "detect": "~/.grok", "rules": "AGENTS.md", "limits": "Grok already runs the hooks in ~/.claude/settings.json; its session-start and prompt output is discarded, though it reads the project's AGENTS.md note."},
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
researched 2026-11-25 — baseline ranking of models (by class, then score descending; score is vals.ai Terminal-Bench 4.0 %, blank if unranked)
|
||||
researched 2026-12-02 — baseline ranking of models (by class, then score descending; score is vals.ai Terminal-Bench 4.0 %, blank if unranked; leaderboard last updated 2026-11-19)
|
||||
|
||||
| model | maker | class | score | released | list price | benchmarks | good at, bad at |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
|
||||
+26
-9
@@ -12,26 +12,39 @@ Before and after the work
|
||||
|
||||
The learning loop
|
||||
sisi retro what happened in this piece of work, to set against the objective
|
||||
sisi retro --gap G --cause C --improve I --term T --problem N|"..." [--scope user]
|
||||
sisi retro --gap G --cause C --improve I --term T --problem N|"..." --level core|user|project
|
||||
record the gap and problem; the improvement is a rule at once
|
||||
sisi retro --no-gap TEXT --term T --better B | --later TEXT
|
||||
nothing fell short; or the work is not finished yet
|
||||
sisi learn [--project] TEXT the person's own words become a rule at once
|
||||
sisi learn --level core|user|project TEXT [--means HOW]
|
||||
the person's own words become a rule at once
|
||||
sisi rules the learned rules in force here
|
||||
sisi rules organize [--record FILE]
|
||||
the brief for a cheap worker to audit and organize them; record its answer
|
||||
sisi rules revert undo the last rule change made with learn, a retro or organize (user or project;
|
||||
not the move of old rules; a second re-applies it); declines if the project file changed
|
||||
sisi rules move "<start>" core|user|project|canon [--project PATH]
|
||||
move one rule to another level (canon: out of the queue once in canon/core.md)
|
||||
sisi rules revert undo the last learn, retro or organize (a second re-applies it); declines if the
|
||||
project file changed since; a move is not undone: both print the command back
|
||||
|
||||
Delegation
|
||||
sisi models the workers you have: what each is good at and what it costs
|
||||
sisi models research [--record FILE]
|
||||
the brief for a research worker to rebuild that table; record its answer
|
||||
sisi models offered [--record FILE]
|
||||
save the host's raw model list (stdin); record the worker's table of those models
|
||||
sisi plan brief | --record FILE the brief for a planning worker; record its graph (| node | class | needs | branch
|
||||
| files | check | why |) before handing out any work; `sisi plan` shows each node
|
||||
sisi plan --done ID EVIDENCE | --fail ID WHY
|
||||
a node you did yourself (the join) is done; or reopen a node
|
||||
sisi chore show ID print the chore brief under this one-time id; delegate just its first line plus "Run `sisi chore show <id>` and do what it says"
|
||||
sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES]
|
||||
sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]
|
||||
the wheel gives you one worker of that class; one pick, one delegation
|
||||
sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest]
|
||||
the wheel gives you one worker for a ready plan node (or of a class, for a
|
||||
`sisi chore:` brief); one pick, one delegation
|
||||
sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest] [--node ID | --chore ID]
|
||||
how a delegation went (`out` with the provider's own message when it hit a
|
||||
limit: sisi tries it again by itself), or give a running job more time
|
||||
limit: sisi tries it again by itself), or give a running job more time;
|
||||
--node ID or --chore ID names the job itself when a worker runs several
|
||||
sisi direct REASON allow yourself more direct tool calls this turn, with the reason
|
||||
|
||||
Setting up
|
||||
@@ -46,7 +59,8 @@ Hooks (the agent tool calls these): sisi tick | prompt | watch | gate
|
||||
Your own rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository;
|
||||
a project's rules live in its .sisi/rules.md. Settings: "core" in
|
||||
its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after,
|
||||
research_days, shell_workers, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts)."""
|
||||
research_days, shell_workers, enforce, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts,
|
||||
auto_update, update_hours, update_url, offered_hours)."""
|
||||
|
||||
|
||||
def main(argv):
|
||||
@@ -64,6 +78,9 @@ def main(argv):
|
||||
if cmd in ("retro", "done"):
|
||||
from . import retro
|
||||
return (retro.run if cmd == "retro" else retro.done)(args)
|
||||
if cmd in ("plan", "chore"):
|
||||
from . import plan
|
||||
return plan.run(args) if cmd == "plan" else plan.chore(args)
|
||||
if cmd == "fault":
|
||||
from . import faults
|
||||
return faults.run(args)
|
||||
@@ -74,7 +91,7 @@ def main(argv):
|
||||
if cmd in ("install", "uninstall", "release", "update", "rollback", "doctor"):
|
||||
from . import install
|
||||
cmd == "release" and models.sync_shared()
|
||||
return getattr(install, cmd)()
|
||||
return install.update(auto="--auto" in args) if cmd == "update" else getattr(install, cmd)()
|
||||
if cmd in ("rulebook", "version"):
|
||||
print(rules.build_rulebook() if cmd == "rulebook" else store.read(os.path.join(store.ROOT, "VERSION")).strip())
|
||||
return 0
|
||||
|
||||
+64
-23
@@ -12,16 +12,16 @@ DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call
|
||||
|
||||
METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your workers and `sisi pick routine|ordinary|hard` "
|
||||
"chooses one; if doing this yourself costs less than briefing it, say why with `sisi direct \"<reason>\"` (%d more).")
|
||||
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"<gap>\" --cause \"<cause>\" --improve \"<rule>\" --term <term> --problem N|\"<name>\"` "
|
||||
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"<gap>\" --cause \"<cause>\" --improve \"<rule>\" --term <term> --problem N|\"<name>\" --level core|user|project` "
|
||||
"or `sisi retro --no-gap \"<evidence>\" --term <term> --better \"<what would score better>\"` (or pause: `sisi retro --later \"<what it waits for>\"`).")
|
||||
NODONE = "sisi: no done is recorded yet. Define what the person wants and what comes next now: `sisi done --goal \"<their goal>\" --check \"<a check that can fail>\" [--check ...] --next \"<what comes next and what you do about it>\"`."
|
||||
NOPICK = ("sisi: this delegation went to a worker the wheel did not give you (recorded so `sisi judge` still works). Use `sisi pick routine|ordinary|hard` next time "
|
||||
"(--review-of WORKER for a review, --not WORKER if one is out); one pick, one delegation.")
|
||||
UNPICKED = ("sisi: the wheel did not give you this worker (or no model is named, so it would run on your own). Run `sisi pick --node ID` "
|
||||
"(`sisi pick routine|ordinary|hard` for a `sisi chore:` brief) and name the model it gives.")
|
||||
NOLOOK = ("sisi: this brief asks for something the person will look at but states no look (typefaces, sizes, colours, spacing, layout at each width). "
|
||||
"Choose it with the person from previews and put it in the brief, or add a line 'Look: <the existing design it follows>'.")
|
||||
UNKNOWN = "sisi: the worker you named is not in the models table (recorded so `sisi judge` still works), so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), and use `sisi pick` next time."
|
||||
UNKNOWN = "sisi: the worker you named is not in the models table, so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), and use `sisi pick` next time."
|
||||
NOSHELL = "sisi: do not shell out to a worker; start it with the host's delegation tool next time."
|
||||
FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term> --problem N|\"<name>\"` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term> --problem N|\"<name>\" --level core|user|project` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
OPEN = "sisi: these checks have no verdict yet: %s. Give each one: `sisi done --pass N \"<evidence>\"` or `sisi done --fail N \"<why>\"` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
LATE = "%s was started %s and has not reported. Check it: if still running, let it finish (this reminder is shown once); if dead or unwanted, cancel it and run `sisi judge WORKER bad \"<why>\"`; if it reported, run `sisi judge WORKER good|bad \"<why>\"`."
|
||||
|
||||
@@ -88,7 +88,7 @@ def own(command):
|
||||
def say(text):
|
||||
"""A hook message, naming sisi by its full path when `sisi` is not on PATH."""
|
||||
import shutil
|
||||
return text if shutil.which("sisi") else re.sub(r"(?<![\w/-])sisi(?= [a-z-])", os.path.join(store.LIB, "current", "bin", "sisi"), text)
|
||||
return text if shutil.which("sisi") else "`".join(p if i % 2 == 0 else re.sub(r"(?<![\w/-])sisi(?= (?!chore:|node:)[a-z-])", os.path.join(store.LIB, "current", "bin", "sisi"), p) for i, p in enumerate(text.split("`")))
|
||||
|
||||
|
||||
def _begin(state, cwd):
|
||||
@@ -110,6 +110,7 @@ def _faults(cwd, gate=False, free=None, sid=""):
|
||||
def tick(p):
|
||||
"""Session start: remember where the work began; print this project's learned rules and what is due."""
|
||||
sid, cwd, worker, free = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"], None
|
||||
__import__("sisi.install", fromlist=["maybe_auto_update"]).maybe_auto_update() # lazy: keeps importing this module free of install's heavier imports
|
||||
if sid:
|
||||
with store.session(sid) as s:
|
||||
_begin(s, cwd)
|
||||
@@ -119,7 +120,7 @@ def tick(p):
|
||||
store.append(env, "export SISI_SESSION_ID=%s" % sid, once=True) # so `sisi retro` knows its session
|
||||
if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")):
|
||||
rules.build_rulebook()
|
||||
(text := "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text)
|
||||
(text := "\n".join(x for x in (rules.project_text(cwd), rules.core_note(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -174,43 +175,78 @@ def watch(p):
|
||||
return 0
|
||||
kind, cfg = tool_class(tool), store.config()
|
||||
command = next((v for k in ("command", "cmd", "CommandLine") if isinstance(v := ti.get(k), str) and v), "")
|
||||
notes = []
|
||||
notes, deny = [], []
|
||||
with store.session(sid) as s:
|
||||
_begin(s, p["cwd"] or os.getcwd())
|
||||
if s.get("worker") or (kind == "shell" and own(command)):
|
||||
return 0
|
||||
shell = kind == "shell" and models.is_call(command)
|
||||
shell and not cfg["shell_workers"] and notes.append(NOSHELL)
|
||||
(kind in ("delegate", "edit") or shell) and not s.get("done") and notes.append(NODONE)
|
||||
if kind == "delegate" or shell:
|
||||
brief = command if shell else " ".join(v for k in ("prompt", "task", "message", "instructions", "description", "content", "text") if isinstance(v := ti.get(k), str))
|
||||
screen_brief_without_look(brief) and notes.append(NOLOOK)
|
||||
brief = command if shell else max((v[:64000] for v in ti.values() if isinstance(v, str)), key=len, default="") # the longest text field is the brief
|
||||
target = ti.get("target") if isinstance(ti.get("target"), dict) else {}
|
||||
names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent"))
|
||||
text = command if shell else next((n for n in names if n and isinstance(n, str)), "")
|
||||
table_text = store.read(models.table())
|
||||
if tool != "workflow" and not models.claim(s, text, not shell and bool(names[0])):
|
||||
known = models.claim(probe := {"picked": [models.short(r[0]) for r in models.rows(table_text)]}, text, True)
|
||||
if models.usable(table_text):
|
||||
not shell and text.strip() and not known and models.stale(text)
|
||||
notes.append(UNKNOWN if not shell and text.strip() and not known else NOPICK)
|
||||
w = (probe.get("workers_since") or [models.short(text) if not shell else ""])[0]
|
||||
if re.fullmatch(r"[a-z0-9._/:+-]{1,80}", w):
|
||||
d = {"picked": [w], "starts": s.get("starts"), "workers_since": s.get("workers_since") if isinstance(s.get("workers_since"), list) else []}
|
||||
models.claim(d, w) and s.update(starts=d["starts"], workers_since=d["workers_since"])
|
||||
stop, soft, node, chore, probe = _outside(s, tool, ti, brief, text, shell, names, cfg)
|
||||
# deny only a lead (it has had a request) whose call sisi can read; anything else is reminded, never stopped
|
||||
if stop and cfg["enforce"] and s.get("prompts") and brief.strip():
|
||||
deny = stop + soft
|
||||
else:
|
||||
notes += stop + soft
|
||||
screen_brief_without_look(brief) and notes.append(NOLOOK)
|
||||
s.update(probe) # the pick this delegation spent, if any
|
||||
cid = s["chores"].pop(chore)[3] if chore is not None else None
|
||||
if (c := probe.get("claimed")) and cid:
|
||||
k, m = "%s %r" % c, s.get("meta") if isinstance(s.get("meta"), dict) else {}
|
||||
s["meta"] = {**m, k: {**(m.get(k) if isinstance(m.get(k), dict) else {}), "chore": cid}}
|
||||
if node and probe.get("claimed"):
|
||||
from . import plan
|
||||
plan.start(s, node, *probe["claimed"])
|
||||
s.pop("claimed", None)
|
||||
s["delegations_since"] = s.get("delegations_since", 0) + 1
|
||||
s.pop("paused", None)
|
||||
elif kind in DIRECT:
|
||||
elif kind == "edit" and not s.get("done"):
|
||||
notes.append(NODONE)
|
||||
if kind in DIRECT and not shell:
|
||||
limit = cfg["direct_calls"] + s.get("extra", 0)
|
||||
cfg["meter"] and s.get("direct", 0) >= limit and notes.append(METER % (s.get("direct", 0), limit, cfg["direct_extension"]))
|
||||
if kind == "edit":
|
||||
s["changed"] = True
|
||||
s.pop("paused", None)
|
||||
s["direct"], s["direct_since"] = s.get("direct", 0) + 1, s.get("direct_since", 0) + 1
|
||||
if deny: # Claude Code, Codex and Qwen Code all read this shape; the reason goes to the model
|
||||
return print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
||||
"permissionDecisionReason": say("\n".join(deny + notes))}})) or 0
|
||||
notes and print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": say("\n".join(notes))}}))
|
||||
return 0
|
||||
|
||||
|
||||
def _outside(s, tool, ti, brief, text, shell, names, cfg):
|
||||
"""(why it strays, reminder lines, the plan node it starts, the issued chore it spends, the state with its pick spent)."""
|
||||
from . import plan
|
||||
why, soft = [], []
|
||||
stray, node, chore = plan.deny(s, brief, shell)
|
||||
shell and not cfg["shell_workers"] and why.append(NOSHELL)
|
||||
s.get("done") or chore is not None or why.append(NODONE)
|
||||
stray and (cfg["enforce"] or plan.get(s)) and why.append(stray) # as reminders, plan notes only once there is a plan
|
||||
offered_chore = chore is not None and isinstance(s.get("chores"), list) and s["chores"][chore][0] == "models offered"
|
||||
probe = json.loads(json.dumps({k: s.get(k) for k in ("picked", "starts", "pending", "meta", "workers_since") if k in s}))
|
||||
table_text = store.read(models.table()) + "\n" + models.wheel()[0]
|
||||
if tool != "workflow" and not models.claim(probe, text, not shell and bool(names[0]), node):
|
||||
known = models.known(table_text, text)
|
||||
if not offered_chore and models.usable(table_text): # with no usable table there is nothing to pick from: `sisi models` says to research it
|
||||
not shell and text.strip() and not known and models.stale(text)
|
||||
why.append(UNKNOWN if not shell and text.strip() and not known else UNPICKED)
|
||||
elif tool != "workflow":
|
||||
w = probe["workers_since"][-1]
|
||||
probe["claimed"] = (w, probe["starts"][w][-1])
|
||||
m = (probe.get("meta") or {}).get("%s %r" % probe["claimed"]) or {}
|
||||
node and m.get("node") not in (None, node) and why.append("sisi: this worker was picked for node %s, not %s; pick again with `sisi pick --node %s`." % (m["node"], node, node))
|
||||
if node and plan.concurrent(s, node) and ti.get("isolation") != "worktree":
|
||||
(why if tool in ("agent", "task") or tool.endswith("delegate_task") else soft).append(
|
||||
"sisi: node %s runs beside others: start it with isolation \"worktree\" so it gets its own checkout." % node)
|
||||
return why, soft, node, chore, probe
|
||||
|
||||
|
||||
def direct(args, cwd=None):
|
||||
"""`sisi direct "<reason>"`: the lead says why doing more itself costs less than delegating it."""
|
||||
reason, sid, cfg = " ".join(" ".join(args).split()), store.current_session(cwd), store.config()
|
||||
@@ -239,6 +275,9 @@ def gate(p, for_subagent=False):
|
||||
if isinstance(x, list) and len(x) == 2 and x[1] in (starts.get(x[0]) if isinstance(starts.get(x[0]), list) else ())]
|
||||
late = models.overdue({"starts": {w: [t for t in v if [w, t] not in seen] for w, v in starts.items() if isinstance(v, list)}, "meta": s.get("meta")})
|
||||
reason, demand = " ".join("sisi: " + LATE % (w, time.strftime("%H:%M", time.localtime(t))) for w, t in late), False
|
||||
if not reason and isinstance(s.get("plan"), dict): # ready worker nodes not started: dispatch them before the turn ends
|
||||
from . import plan
|
||||
reason = plan.gate(s)
|
||||
if not reason and not s.get("paused"):
|
||||
checks = (s.get("done") or {}).get("checks") or []
|
||||
unsaid = ["%d. %s" % (i, c["text"]) for i, c in enumerate(checks, 1) if not c["verdict"]]
|
||||
@@ -259,5 +298,7 @@ def gate(p, for_subagent=False):
|
||||
return 0
|
||||
s["blocks"] = s.get("blocks", 0) + 1
|
||||
demand and s.setdefault("retro_demanded", time.time())
|
||||
if unjudged := models.unjudged(s):
|
||||
reason += "\nsisi: unjudged jobs: " + ", ".join(unjudged)
|
||||
print(json.dumps({"decision": "block", "reason": say(reason)}))
|
||||
return 0
|
||||
+97
-3
@@ -214,6 +214,59 @@ def _source():
|
||||
return ""
|
||||
|
||||
|
||||
SHA = r"[0-9a-f]{40}"
|
||||
|
||||
|
||||
def _head(root):
|
||||
"""The commit a release of this checkout is of: HEAD, with "-dirty" when the tree differs from it (a developer's
|
||||
unpushed release is never auto-replaced), "" outside git."""
|
||||
rc, sha = store.git(["rev-parse", "HEAD"], root)
|
||||
return sha.strip() + ("-dirty" if store.git(["status", "--porcelain", "--", ":(top)", ":(top,exclude).sisi"], root)[1].strip() else "") if not rc and re.fullmatch(SHA, sha.strip()) else ""
|
||||
|
||||
|
||||
def _current_commit():
|
||||
"""The commit the release in use records (SOURCE line three), "" when it records none (an old release)."""
|
||||
return (store.read(os.path.join(_current(), "SOURCE")).split("\n") + ["", "", ""])[2].strip()
|
||||
|
||||
|
||||
def _auto_log(result, old="", new=""):
|
||||
try:
|
||||
store.append(os.path.join(store.STATE, "auto-update.log"), "%s %s %s->%s" % (time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()), result, (old or "?")[:7], (new or "?")[:7]))
|
||||
except OSError:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def _float(text, default):
|
||||
try:
|
||||
return float(text)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def maybe_auto_update():
|
||||
"""Session start: print a pending updated-itself notice once, and when a check is due start `sisi update --auto`
|
||||
fully detached. No network or git here, silent on any failure, and the new timestamp is written before starting."""
|
||||
try:
|
||||
path = os.path.join(store.STATE, "auto-update-notice")
|
||||
try:
|
||||
os.replace(path, taken := "%s.taken-%d" % (path, os.getpid())) # claim it first: only one session start wins
|
||||
new, _, old = store.read(taken).strip().partition(" ")
|
||||
os.remove(taken)
|
||||
new and print("sisi: updated itself to %s (was %s); `sisi rollback` goes back." % (new[:7], old[:7] if old else "unknown"))
|
||||
except OSError:
|
||||
pass
|
||||
cfg, exe = store.config(), os.path.join(_current(), "bin", "sisi")
|
||||
stamp = os.path.join(store.STATE, "auto-update-check")
|
||||
if not cfg.get("auto_update") or not os.path.isfile(exe) or time.time() - _float(store.read(stamp).strip() or 0, 0) < _float(cfg.get("update_hours"), 24) * 3600:
|
||||
return # off, nothing installed to update yet, or not due (no stamp is spent before an install exists)
|
||||
store.write(stamp, str(time.time()))
|
||||
with open(os.path.join(store.STATE, "auto-update.log"), "ab") as log:
|
||||
subprocess.Popen([sys.executable, "-B", exe, "update", "--auto"], stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _switch(dest):
|
||||
tmp = _current() + ".new"
|
||||
if os.path.lexists(tmp):
|
||||
@@ -232,13 +285,14 @@ def release():
|
||||
return subprocess.run([sys.executable, os.path.join(src, "bin", "sisi"), "release"]).returncode
|
||||
print("sisi release: run it from the source checkout.")
|
||||
return 1
|
||||
head = _head(store.ROOT) # before the test run: it leaves __pycache__ behind, which is not a change to the product
|
||||
if subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests", "-q"], cwd=store.ROOT).returncode:
|
||||
print("sisi release: the tests fail. Nothing was released.")
|
||||
return 1
|
||||
name = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + "%03dZ" % (time.time() % 1 * 1000) # two in one second differ
|
||||
dest = os.path.join(folder, name)
|
||||
shutil.copytree(store.ROOT, dest, ignore=shutil.ignore_patterns(".git", ".agent-work", ".sisi", "__pycache__"))
|
||||
store.write(os.path.join(dest, "SOURCE"), "%s\n%s\n" % (_source(), os.path.abspath(store.ROOT)))
|
||||
store.write(os.path.join(dest, "SOURCE"), "%s\n%s\n%s\n" % (_source(), os.path.abspath(store.ROOT), head))
|
||||
_switch(dest)
|
||||
subprocess.run([os.path.join(dest, "bin", "sisi"), "rulebook"])
|
||||
for old in [o for o in sorted(os.listdir(folder)) if o != name][:-3]: # never the one just put in use, even when the clock is behind
|
||||
@@ -263,8 +317,12 @@ def rollback():
|
||||
return 0
|
||||
|
||||
|
||||
def update():
|
||||
"""Fetch the newest sisi from where the release in use came from, and release it. No checkout needed."""
|
||||
def update(auto=False):
|
||||
"""Fetch the newest sisi from where the release in use came from, and release it. No checkout needed.
|
||||
With auto=True (the detached background job): silent, locked, and it skips anything but a straight
|
||||
move forward along the remote's main branch."""
|
||||
if auto:
|
||||
return _auto_update()
|
||||
url = store.read(os.path.join(_current(), "SOURCE")).split("\n")[0].strip()
|
||||
if not url:
|
||||
print("sisi update: the release in use does not record where it came from. Run `sisi release` from a checkout that has a remote.")
|
||||
@@ -277,6 +335,42 @@ def update():
|
||||
return subprocess.run([sys.executable, os.path.join(src, "bin", "sisi"), "release"]).returncode
|
||||
|
||||
|
||||
def _auto_update():
|
||||
"""One background check: ls-remote, and only a known ancestor (or an unknown commit) moves forward through the
|
||||
usual tested release. One log line per run, nothing to any terminal; always exits 0."""
|
||||
with store.lock("auto-update", wait=False) as held:
|
||||
if not held:
|
||||
return 0
|
||||
old, new = _current_commit(), ""
|
||||
try:
|
||||
url = str(store.config().get("update_url") or "").strip()
|
||||
rc, out = store.git(["ls-remote", url, "refs/heads/main"], store.ROOT, timeout=60) if url else (1, "")
|
||||
new = out.split()[0] if rc == 0 and out.split() else ""
|
||||
if not re.fullmatch(SHA, new):
|
||||
return _auto_log("failed ls-remote" if url else "skipped no update_url", old, new)
|
||||
if old == new:
|
||||
return _auto_log("current", old, new)
|
||||
if old and not re.fullmatch(SHA, old): # e.g. a "-dirty" developer release
|
||||
return _auto_log("skipped local commit is not an ancestor (unrecorded changes)", old, new)
|
||||
with tempfile.TemporaryDirectory(prefix="sisi-update-") as tmp:
|
||||
src = os.path.join(tmp, "sisi")
|
||||
if subprocess.run(["git", "clone", "-q", url, src], stdin=subprocess.DEVNULL, capture_output=True).returncode:
|
||||
return _auto_log("failed fetch", old, new)
|
||||
head = store.git(["rev-parse", "HEAD"], src)[1].strip()
|
||||
new = head if re.fullmatch(SHA, head) else new
|
||||
if old and store.git(["merge-base", "--is-ancestor", old, new], src)[0] != 0:
|
||||
return _auto_log("skipped local commit is not an ancestor of remote main", old, new)
|
||||
if subprocess.run([sys.executable, "-B", os.path.join(src, "bin", "sisi"), "release"], stdin=subprocess.DEVNULL, capture_output=True).returncode:
|
||||
return _auto_log("failed tests, nothing switched", old, new)
|
||||
landed = _current_commit()
|
||||
if landed and landed != old:
|
||||
store.write(os.path.join(store.STATE, "auto-update-notice"), "%s %s\n" % (landed, old))
|
||||
return _auto_log("updated", old, landed)
|
||||
return _auto_log("failed release, nothing switched", old, new)
|
||||
except Exception as e: # a background job never breaks or talks to a session
|
||||
return _auto_log("failed %r" % (e,), old, new)
|
||||
|
||||
|
||||
def _wired(h, d):
|
||||
"""Does the tool's hooks file hold every current sisi entry?"""
|
||||
hooks = _load(os.path.join(d, h["hooks"]["file"]))[2]
|
||||
|
||||
+277
-97
@@ -2,35 +2,42 @@
|
||||
|
||||
A research worker writes it, the lead reads it to route, and `sisi judge` adds how each delegation went so the
|
||||
next research knows. The table is plain text a person can read and correct."""
|
||||
import json, math, os, re, time
|
||||
import json, math, os, re, sys, time
|
||||
from . import rules, store
|
||||
|
||||
ASK_FRESH = ("which providers and models from the shipped baseline table below are usable on this machine, how to call each, and what each costs here; map them to whatever providers this user has",
|
||||
"Reuse the shipped baseline table below for class (`use for`), baseline score, benchmarks, list price, and public good-at/bad-at — do not re-research them online. Combine them with our own judged record below, which outranks a benchmark.",
|
||||
"Order rows within each class by baseline score descending (the picker's row weighting uses row order); break ties or unranked models by cheapest capable first.")
|
||||
"Use the baseline score to decide which models truly perform at a class; then choose and order by efficiency (step 3).")
|
||||
ASK_STALE = ("which AI models this machine can delegate work to, what each is good at and what it costs",
|
||||
"What each is good at. Use current public software-engineering benchmarks and the maker's own description (search the web), then our own record below, which outranks a benchmark.",
|
||||
"Only the newest version of each model belongs in the table. A smaller or faster variant is a different model.")
|
||||
"Only the newest version of each model belongs in the table. A smaller or faster variant is a different model. Then choose and order by efficiency (step 3).")
|
||||
EXTRA_SHARED = ("\nThen a second, separately marked section starting on its own line with `=== Shared models ===`, followed by `researched YYYY-MM-DD` on its first line and a baseline ranking table "
|
||||
"(`| model | maker | class | score | released | list price | benchmarks | good at, bad at |`) with one row per model (keyed by model id, never provider route), sorted by class then score descending, "
|
||||
"holding only shared public facts (no plans, allowances, availability, judged records, or personal notes).\n")
|
||||
|
||||
RESEARCH = """You are a worker. Do this task yourself; do not delegate it further.
|
||||
RESEARCH = """sisi chore: models research
|
||||
You are a worker. Do this task yourself; do not delegate it further.
|
||||
|
||||
Find out %(intro)s, and write the personal table an engineering lead will route by.
|
||||
|
||||
1. What is there. Look for AI coding command-line tools on PATH and run each one's own model listing. Add the
|
||||
models the host offers its own subagents. Do not log in, change a setting or run a paid task.
|
||||
1. What is there: every provider (the account or plan a call draws its allowance or bill from) the host's delegation
|
||||
tool can start, and each one every AI coding tool on PATH routes to (run its auth/provider list and model list; a
|
||||
second plan behind one tool is a separate provider). Do not log in, change a setting or run a paid task.
|
||||
2. %(step2)s
|
||||
3. What it costs here: free, a flat plan with an allowance, or paid per use, and anything that limits it.
|
||||
3. Efficiency: how much work at its class one unit of this person's allowance or money buys. The `efficiency` cell
|
||||
quotes the provider's own published allowance or price for that model with the plan/pricing page URL (or
|
||||
"measured: ..." from our record), and its quota windows exactly as `5h: N req; week: N req; month: N req` (`req`
|
||||
only when N counts requests; else name the unit). sisi spreads delegations by these so no plan runs dry early.
|
||||
Among models that truly perform at a class, keep the one whose allowance goes furthest (flat plan: most requests
|
||||
per window; per use: lowest cost per benchmark task): at most one row per provider per class; drop the rest.
|
||||
Notes hold `usage: <the read-only command or page that shows current usage>` where one exists.
|
||||
4. %(step4)s
|
||||
5. What the person has said, below, stands exactly: their limits and preferences are not yours to change.
|
||||
5. What the person has said, below, stands exactly and outranks all of this: it is not yours to change.
|
||||
|
||||
List only workers the host's delegation tool can actually start: check the host's own list of enabled providers.
|
||||
Answer with exactly this and nothing else. First a markdown table of at most 40 rows, the cheapest capable
|
||||
worker first within each level (or ordered by baseline score descending when reusing the baseline), with these columns:
|
||||
| worker | maker | how to call it | use for | cost | good at, bad at | notes |
|
||||
"maker" is the company or lab that trained the model, lower case, one word. "use for" is exactly one of: routine,
|
||||
Answer with exactly this and nothing else. First a markdown table of at most 40 rows, at most one row per provider
|
||||
per class, ordered within each class most efficient first (the wheel weights by row order), with these columns:
|
||||
| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |
|
||||
"provider" names the account or plan as the person knows it. "maker" is the company or lab that trained the model, lower case, one word. "use for" is exactly one of: routine,
|
||||
ordinary, hard. It is the model's capability class, not a list of tasks it could do. Routine is the small, fast,
|
||||
cheap tier (the level of a maker's smallest current model); ordinary is the mid tier (a maker's main everyday
|
||||
model); hard is the top tier (a maker's strongest model). Place each model by comparing it with its peers from
|
||||
@@ -55,8 +62,25 @@ Then one line starting "Fallback order:" that says who takes over when a worker
|
||||
=== How delegations went here, newest last ===
|
||||
%(outcomes)s
|
||||
"""
|
||||
ASK = ("In the background, give the output of `sisi models research` to a research worker and record its "
|
||||
"answer with `sisi models research --record FILE`.")
|
||||
REFRESH = "ask the host for every model its delegation tool can start, save its raw answer to a file and run `sisi models offered < FILE`."
|
||||
OFFERED = """sisi chore: models offered
|
||||
You are a worker. Do this task yourself; do not delegate it further.
|
||||
|
||||
Below is the host's raw list of the models it offers, and the researched table. Write one table row per offered model (at most 80)
|
||||
in the table's columns (| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |). A known model: copy
|
||||
its row, with "how to call it" replaced by the exact dispatch from the list. An unknown model: a provisional row (provider, maker, use for
|
||||
exactly one of routine|ordinary|hard as a guess, the dispatch, notes starting `new: <one-line reason for the class>`). Skip any provider the list marks
|
||||
disabled or unable to run child tasks. An id like default that names no specific model is never a row. Never invent an id: each worker id must appear verbatim in the list and in its dispatch. Write the table to a
|
||||
file and run `sisi models offered --record FILE`.
|
||||
|
||||
=== The table now ===
|
||||
%s
|
||||
|
||||
=== Offered by this harness ===
|
||||
%s
|
||||
"""
|
||||
ASK = ("In the background, delegate just the first line of the output of `sisi models research` plus \"Run `sisi chore show <id>` and do what it says\" "
|
||||
"to a hard-class worker that can search the web (`sisi pick hard`: choosing models well pays for itself) and record its answer with `sisi models research --record FILE`.")
|
||||
|
||||
|
||||
def table(): return store.data("models.md")
|
||||
@@ -88,27 +112,42 @@ def sync_shared(cwd=None):
|
||||
|
||||
|
||||
def age_days():
|
||||
try:
|
||||
return (time.time() - os.path.getmtime(table())) / 86400.0
|
||||
except OSError:
|
||||
return None
|
||||
try: return (time.time() - os.path.getmtime(table())) / 86400.0
|
||||
except OSError: return None
|
||||
|
||||
|
||||
def _has(raw, i): return bool(i) and bool(re.search(r"(?<![^\s\"'`,\[\]{}<>|=/])%s(?![^\s\"'`,\[\]{}<>|=])" % re.escape(i), raw))
|
||||
def offered(ext): return store.data("offered", store.harness() + "." + ext)
|
||||
|
||||
|
||||
def wheel():
|
||||
"""(text, why): the rows to pick from, only models this harness offers (its saved raw list is the truth, the table a hint);
|
||||
why is set when there is no list, it is old, or no row is offered."""
|
||||
raw, age = store.read(offered("txt")), 1e9
|
||||
try: age = (time.time() - time.mktime(time.strptime(raw.split()[1], "%Y-%m-%dT%H:%M:%S"))) / 3600
|
||||
except (ValueError, IndexError, OverflowError): pass
|
||||
body = raw.partition("\n")[2]
|
||||
text = store.read(offered("wheel.md")) or "".join(l + "\n" for l in store.read(table()).splitlines() if l.startswith("|") and (
|
||||
set(l) <= set("|-: ") or l.lower().startswith("| worker") or any(_has(body, first(r[0])) for r in rows(l))))
|
||||
return text, ("no list of the models this harness offers" if not body.strip() else "the list of offered models is %d h old" % age if age > store.config()["offered_hours"]
|
||||
else "" if usable(text) else "no offered model has a row")
|
||||
|
||||
|
||||
def stale(mark=None):
|
||||
"""One line when the table is missing, old, or missed a worker, else ""."""
|
||||
who = re.sub(r"[^\w./:+-]", "", str(store.read(store.data("models.stale")) if mark is None else mark), flags=re.A)[:80]
|
||||
if mark is not None and who:
|
||||
try:
|
||||
store.write(store.data("models.stale"), who + "\n")
|
||||
except Exception: # best effort: a refusal never depends on it
|
||||
pass
|
||||
try: store.write(store.data("models.stale"), who + "\n")
|
||||
except Exception: pass # best effort: a refusal never depends on it
|
||||
age = age_days()
|
||||
wtext, why = wheel()
|
||||
if why: return "sisi: %s: %s" % (why, REFRESH)
|
||||
if age is None or age > store.config()["research_days"]:
|
||||
return "sisi: " + ("there is no models table yet. " if age is None else "the models table is %d days old. " % age) + ASK
|
||||
return ("sisi: a delegation named `%s`, which the models table does not list. " % who + ASK) if who and not known(store.read(table()), who) else ""
|
||||
return ("sisi: a delegation named `%s`, which the models table does not list. " % who + ASK) if who and not known(store.read(table()) + "\n" + wtext, who) else ""
|
||||
|
||||
|
||||
KEYS = ("worker", "how", "use", "cost", "good", "notes", "maker") # a column is known by its header's first word
|
||||
KEYS = ("worker", "how", "use", "cost", "good", "notes", "maker", "provider", "efficiency") # a column is known by its header's first word
|
||||
LAUNCHERS = {"python", "python3", "bash", "sh", "zsh", "cd", "env", "npx", "npm", "node", "uv", "uvx", "make", "ssh",
|
||||
"git", "docker", "sudo"}
|
||||
|
||||
@@ -128,7 +167,8 @@ def rows(text):
|
||||
def usable(text): return any(re.search(r"routine|ordinary|hard", r[2].lower()) for r in rows(text))
|
||||
|
||||
|
||||
def short(cell): return (str(cell).split() or [""])[0].lower()
|
||||
first = lambda cell: (str(cell).split() or [""])[0] # a worker's id as its row writes it: it must appear so in the host's list
|
||||
short = lambda cell: first(cell).lower()
|
||||
|
||||
|
||||
def maker(r):
|
||||
@@ -143,7 +183,7 @@ def command(row): return "<brief>" in row[1] and "host subagent" not in row[1].l
|
||||
|
||||
def is_call(command_line):
|
||||
"""Does any segment of this shell command start a worker in the table (after nohup, exec, time, env, VAR=)?"""
|
||||
starts = {(r[1].replace("`", "").split() or [""])[0] for r in rows(store.read(table())) if command(r)} - LAUNCHERS
|
||||
starts = {(r[1].replace("`", "").split() or [""])[0] for r in rows(store.read(table()) + "\n" + store.read(offered("wheel.md"))) if command(r)} - LAUNCHERS
|
||||
for seg in re.split(r"&&|\|\||[;|&\n]", command_line):
|
||||
words = [w for w in seg.split()]
|
||||
while words and (words[0] in ("nohup", "exec", "time", "env") or re.match(r"[A-Za-z_]\w*=", words[0])):
|
||||
@@ -156,8 +196,8 @@ def is_call(command_line):
|
||||
def known(table_text, text): return claim({"picked": [short(r[0]) for r in rows(table_text)]}, text, True)
|
||||
|
||||
|
||||
def claim(s, text, segment=False):
|
||||
"""Spend the pick that this delegation's model text names; False when none of the picks fits. With `segment` (the
|
||||
def claim(s, text, segment=False, node=None):
|
||||
"""Spend the pick that this delegation's model text names (the one made for `node` first); False when none fits. With `segment` (the
|
||||
host names its models shortly: `fast` for `maker-fast-2`) one whole `-` segment of a picked id's last `/` part that has a letter fits."""
|
||||
for name in s.get("picked") or []:
|
||||
if any(re.search(r"(?<![a-z0-9.-])%s(?![a-z0-9.-])" % re.escape(n), text.lower()) for n in (name, name.rsplit("/", 1)[-1])) or (
|
||||
@@ -166,7 +206,8 @@ def claim(s, text, segment=False):
|
||||
t, starts = time.time(), (s["starts"] if isinstance(s.get("starts"), dict) else {})
|
||||
starts[name] = (starts[name] if isinstance(starts.get(name), list) else []) + [t]
|
||||
s["starts"] = starts # `sisi judge` times the job from here
|
||||
if isinstance(s.get("pending"), dict) and isinstance(q := s["pending"].get(name), list) and q and isinstance(meta := q.pop(0), dict):
|
||||
if isinstance(s.get("pending"), dict) and isinstance(q := s["pending"].get(name), list) and q and isinstance(meta := q.pop(
|
||||
next((i for i, m in enumerate(q) if isinstance(m, dict) and node and m.get("node") == node), 0)), dict):
|
||||
s["meta"] = {**(s["meta"] if isinstance(s.get("meta"), dict) else {}), "%s %r" % (name, t): meta}
|
||||
s.setdefault("workers_since", []).append(name)
|
||||
return True
|
||||
@@ -195,6 +236,30 @@ def overdue(s):
|
||||
return list(by_w.items())
|
||||
|
||||
|
||||
def _job_info(s, w, t):
|
||||
"""(tag, flag, hhmm) for the open job of worker w started at t: tag is `node X`, `chore Y` or empty."""
|
||||
meta = s["meta"] if isinstance(s.get("meta"), dict) else {}
|
||||
m = meta.get("%s %r" % (w, t))
|
||||
m = m if isinstance(m, dict) else {}
|
||||
nid = m.get("node") or next((k for k, v in ((s.get("plan") or {}).get("state") or {}).items()
|
||||
if isinstance(v, dict) and v.get("st") == "running" and v.get("worker") == w and v.get("since") == t), None)
|
||||
cid, hhmm = m.get("chore"), time.strftime("%H:%M", time.localtime(t))
|
||||
if nid: return "node %s" % nid, "--node %s" % nid, hhmm
|
||||
if cid: return "chore %s" % cid, "--chore %s" % cid, hhmm
|
||||
return "", "", hhmm
|
||||
|
||||
|
||||
def unjudged(s):
|
||||
"""['WORKER (node X | chore Y, started HH:MM)', ...] for the open jobs in `s["starts"]`, oldest first."""
|
||||
starts, jobs = s.get("starts") if isinstance(s.get("starts"), dict) else {}, []
|
||||
for w, v in starts.items():
|
||||
for t in (v if isinstance(v, list) else ()):
|
||||
if type(t) in (int, float) and math.isfinite(t):
|
||||
tag, _, hhmm = _job_info(s, w, t)
|
||||
jobs.append((t, "%s (%sstarted %s)" % (w, tag + ", " if tag else "", hhmm)))
|
||||
return [text for _, text in sorted(jobs)]
|
||||
|
||||
|
||||
def waiting(s):
|
||||
"""A delegation of this piece of work is open: started and not yet judged."""
|
||||
return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values())
|
||||
@@ -205,28 +270,20 @@ clock = lambda t: time.strftime("%m-%d %H:%M", time.localtime(t))
|
||||
SINCE = "out since %s, back on the wheel at %s"
|
||||
|
||||
|
||||
def outs(text, log, written, today=None, now=None):
|
||||
"""{worker: (since, why)}: each worker last said to be out, and when. An `out` verdict in the log says it, and any
|
||||
later verdict takes it back. A table from before `out` verdicts says it with a note, `out until DATE` (DATE today or
|
||||
later), unless the log holds a verdict for that worker newer than the table (`written`); the note dates from the table. A time OUT or more ahead of `now` is a wrong clock and says nothing."""
|
||||
last, today, now = {}, today or time.strftime("%Y-%m-%d"), now or time.time()
|
||||
def outs(log, now=None):
|
||||
"""{worker: (since, why)}: each worker last said to be out, and when: an `out` verdict in the log says it, and any
|
||||
later verdict takes it back. A time OUT or more ahead of `now` is a wrong clock and says nothing."""
|
||||
last, now = {}, now or time.time()
|
||||
for o in log:
|
||||
try:
|
||||
t = time.mktime(time.strptime(o["ts"], "%Y-%m-%dT%H:%M:%S"))
|
||||
t - now < OUT and last.__setitem__(short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), (t, o.get("verdict"), str(o.get("why") or "")))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
pass # a damaged line is no verdict
|
||||
gone = {w: (t, why) for w, (t, verdict, why) in last.items() if verdict == "out"}
|
||||
for r in rows(text):
|
||||
w, until = short(r[0]), [d for d in re.findall(r"out until (\d{4}-\d{2}-\d{2})", " ".join(r).lower()) if d >= today]
|
||||
if until and written is not None and written - now < OUT and not (w in last and last[w][0] >= int(written)): # the log keeps whole seconds
|
||||
gone[w] = (written, "out until " + until[0])
|
||||
return gone
|
||||
return {w: (t, why) for w, (t, verdict, why) in last.items() if verdict == "out"}
|
||||
|
||||
|
||||
def away():
|
||||
"""`outs` for the table and the log as they are now."""
|
||||
return outs(store.read(table()), store.records("outcomes.jsonl"), os.path.getmtime(table()) if os.path.exists(table()) else None, now=time.time())
|
||||
def away(): return outs(store.records("outcomes.jsonl"), time.time())
|
||||
|
||||
|
||||
def out(r, skip, bad, gone, now):
|
||||
@@ -241,40 +298,87 @@ def median(v):
|
||||
return (v[len(v) // 2] + v[(len(v) - 1) // 2]) / 2
|
||||
|
||||
|
||||
def speeds():
|
||||
"""Each worker's last 10 timed minutes from its good outcomes, oldest first."""
|
||||
out = {}
|
||||
def track():
|
||||
"""One pass over the log: (each worker's last 10 timed minutes from its good outcomes, oldest first; its quality factor
|
||||
over its last 10 good/bad outcomes: ((good+1)/(n+2))/((n+1)/(n+2)) = (good+1)/(n+1); how many good/bad outcomes it has)."""
|
||||
sp, ql, n = {}, {}, {}
|
||||
for o in store.records("outcomes.jsonl"):
|
||||
if o.get("verdict") == "good" and type(o.get("minutes")) is int and 0 < o["minutes"] <= 10000 and isinstance(o.get("worker"), str):
|
||||
out.setdefault(short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), []).append(o["minutes"])
|
||||
return {w: v[-10:] for w, v in out.items()}
|
||||
w = short(o["model"] if isinstance(o.get("model"), str) and o["model"].strip() else o["worker"] if isinstance(o.get("worker"), str) else "")
|
||||
if w and o.get("verdict") == "good" and type(o.get("minutes")) is int and 0 < o["minutes"] <= 10000: sp.setdefault(w, []).append(o["minutes"])
|
||||
if w and o.get("verdict") in ("good", "bad"): ql.setdefault(w, []).append(o["verdict"] == "good"); n[w] = n.get(w, 0) + 1
|
||||
return {w: v[-10:] for w, v in sp.items()}, {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in ql.items()}, n
|
||||
|
||||
|
||||
def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None):
|
||||
"""One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1)
|
||||
times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs).
|
||||
def speeds(): return track()[0]
|
||||
def qualities(): return track()[1]
|
||||
|
||||
|
||||
WINDOWS, FLOOR = {"5h": 5 * 3600, "week": 7 * 86400, "month": 30 * 86400}, 0.05
|
||||
pkey = lambda provider: " ".join(str(provider).lower().split())
|
||||
|
||||
|
||||
def budgets(cell):
|
||||
"""{window: N} from `5h: N req; week: N req; month: N req` in a cell; only counts of requests, which a delegation is counted as."""
|
||||
return {w: int(n.replace(",", "")) for w, n in re.findall(
|
||||
r"\b(5h|week|month)\s*:\s*(\d[\d,]*)\s*(?:req|requests|prompts|messages|calls|delegations)\b", cell.lower()) if int(n.replace(",", ""))}
|
||||
|
||||
|
||||
def plan_use(text, cwd=None, now=None):
|
||||
"""{provider: {window: share used}} by sisi's own delegations: each started in the window spends 1/N of its plan's
|
||||
window, N the allowance its row gives (outcomes.jsonl, plus the current session's open jobs)."""
|
||||
now, by, times, sid = now or time.time(), {short(r[0]): r for r in rows(text) if r[7]}, [], store.current_session(cwd)
|
||||
try: starts = json.loads(store.read(store._session_path(sid)) or "{}").get("starts") if sid else None
|
||||
except (ValueError, AttributeError): starts = None
|
||||
for o in store.records("outcomes.jsonl"):
|
||||
try:
|
||||
w = o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]
|
||||
times.append((short(w), time.mktime(time.strptime(o.get("started") or o["ts"], "%Y-%m-%dT%H:%M:%S"))))
|
||||
except (KeyError, TypeError, ValueError, AttributeError): pass # a damaged line spends nothing
|
||||
for w, v in (starts.items() if isinstance(starts, dict) else ()):
|
||||
times += [(short(w), t) for t in (v if isinstance(v, list) else ()) if type(t) in (int, float)]
|
||||
out, bud = {}, {w: budgets(r[3] + " " + r[8]) for w, r in by.items()}
|
||||
[out.setdefault(pkey(r[7]), {}).update(dict.fromkeys(bud[w], 0.0)) for w, r in by.items()]
|
||||
for w, t in times:
|
||||
if (r := by.get(w)) and t <= now:
|
||||
for win, n in bud[w].items():
|
||||
if now - t < WINDOWS[win]: out[pkey(r[7])][win] += 1.0 / n
|
||||
return {p: u for p, u in out.items() if u}
|
||||
|
||||
|
||||
def shares(use): return {p: max(FLOOR, min(1 - x for x in u.values())) for p, u in use.items()}
|
||||
|
||||
|
||||
def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None, quality=None, share=None, tried=None):
|
||||
"""One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1; a worker with
|
||||
fewer than 3 judged good/bad outcomes (`tried`, from `track`) has the first's weight, so a new model is tried)
|
||||
times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs),
|
||||
times its quality factor over its last 10 good/bad outcomes ((good+1)/(n+1), so no bad runs keeps weight 1),
|
||||
times its provider's share of plan left (`share`, from `shares`: at least FLOOR), so no plan runs dry early.
|
||||
A worker last said out less than OUT seconds ago (`gone`, from `outs`) is not on the wheel."""
|
||||
table_rows, gone, now = rows(text), gone or {}, now or time.time()
|
||||
bad = next((maker(r) for r in table_rows if short(r[0]) == short(review)), None) if review else None
|
||||
left = [r for r in table_rows if r[2].strip().lower() == cls and not out(r, skip, bad, gone, now)]
|
||||
if not left:
|
||||
return None
|
||||
if not left: return None
|
||||
if rand is None:
|
||||
import random
|
||||
rand = random.random
|
||||
med = {short(r[0]): median(speed[short(r[0])]) for r in left if (speed or {}).get(short(r[0]))}
|
||||
fast = min(med.values(), default=1)
|
||||
weights = [w * max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else w for w, r in zip(range(len(left), 0, -1), left)]
|
||||
fast, qual = min(med.values(), default=1), quality or {}
|
||||
weights = [(len(left) if (tried or {}).get(short(r[0]), 0) < 3 else w) * (max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else 1)
|
||||
* max(1 / 11, qual.get(short(r[0]), 1)) * (share or {}).get(pkey(r[7]), 1) for w, r in zip(range(len(left), 0, -1), left)]
|
||||
x = rand() * sum(weights)
|
||||
for weight, r in zip(weights, left):
|
||||
x -= weight
|
||||
if x < 0:
|
||||
return r
|
||||
if (x := x - weight) < 0: return r
|
||||
return left[-1]
|
||||
|
||||
|
||||
def pick(args, cwd=None, rand=None):
|
||||
"""`sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]`: the wheel gives one worker."""
|
||||
node = None
|
||||
if args[:1] == ["--node"]: # the class and branch come from the plan node
|
||||
from . import plan
|
||||
args, node = plan.for_pick(args, cwd)
|
||||
if node is None: return 1
|
||||
cls, skip, review, limit, branch, i = (args[0] if args and args[0] in ("routine", "ordinary", "hard") else None), set(), None, None, None, 1
|
||||
while cls and i < len(args):
|
||||
if args[i] == "--not" and i + 1 < len(args): skip.add(short(args[i + 1]))
|
||||
@@ -286,16 +390,14 @@ def pick(args, cwd=None, rand=None):
|
||||
if not cls:
|
||||
print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]")
|
||||
return 1
|
||||
text = store.read(table())
|
||||
text, why = wheel()
|
||||
if why: return print("sisi pick: %s: %s" % (why, "run `sisi models offered < FILE` and hand the printed `models offered` chore to any model the host offers." if why == "no offered model has a row" else REFRESH)) or 1
|
||||
mine = [r for r in rows(text) if r[2].strip().lower() == cls]
|
||||
for r in rows(text):
|
||||
if len(re.findall(r"routine|ordinary|hard", r[2].lower())) > 1:
|
||||
print("%s is in more than one class and is on no wheel: rebuild the table" % short(r[0]))
|
||||
if review is not None and not any(short(r[0]) == short(review) for r in rows(text)):
|
||||
print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review)
|
||||
return 1
|
||||
speed, gone, now = speeds(), away(), time.time()
|
||||
r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now)
|
||||
(speed, qual, tried), gone, now = track(), away(), time.time()
|
||||
r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual, share=shares(plan_use(text, cwd, now)), tried=tried)
|
||||
if not r:
|
||||
bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None)
|
||||
again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard."}.get(cls, "")
|
||||
@@ -305,14 +407,21 @@ def pick(args, cwd=None, rand=None):
|
||||
else "sisi pick: the models table has no worker of class %s." % cls)
|
||||
+ (" The first is back on the wheel at %s." % clock(first) if first is not None else "") + again)
|
||||
return 1
|
||||
sid = store.current_session(cwd)
|
||||
for x in rows(text):
|
||||
if len(re.findall(r"routine|ordinary|hard", x[2].lower())) > 1:
|
||||
print("%s is in more than one class and is on no wheel: rebuild the table" % short(x[0]))
|
||||
sid, also = store.current_session(cwd), []
|
||||
if sid:
|
||||
with store.session(sid) as s:
|
||||
s.setdefault("picked", []).append(w := short(r[0]))
|
||||
w = short(r[0])
|
||||
if node:
|
||||
st = (s.get("plan") or {}).get("state") or {}
|
||||
also = list(dict.fromkeys([k for k, v in st.items() if isinstance(v, dict) and v.get("st") == "running" and v.get("worker") == w and k != node]
|
||||
+ [m["node"] for m in (s.get("pending") or {}).get(w, []) if isinstance(m, dict) and m.get("node") and m.get("node") != node]))
|
||||
s.setdefault("picked", []).append(w)
|
||||
q = s["pending"] if isinstance(s.get("pending"), dict) else {}
|
||||
s["pending"] = {**q, w: (q[w] if isinstance(q.get(w), list) else []) + [{"limit": limit, "branch": branch}]} # one entry per pick, claimed in order
|
||||
s["pending"] = {**q, w: (q[w] if isinstance(q.get(w), list) else []) + [{"limit": limit, "branch": branch, "node": node}]} # one entry per pick, claimed in order
|
||||
print("worker: %s (model id: %s)\nstart it with the host's delegation tool; one pick buys one delegation" % (r[0], short(r[0])))
|
||||
if store.config()["shell_workers"] or not command(r):
|
||||
print("how to call it: " + r[1])
|
||||
print("good at, bad at: %s\nnotes: %s" % (r[4], r[5]))
|
||||
t = speed.get(short(r[0]))
|
||||
@@ -320,6 +429,11 @@ def pick(args, cwd=None, rand=None):
|
||||
if g := gone.get(short(r[0])): # its last verdict was `out`: a retry, so a quick failure is expected and cheap
|
||||
print("retry: this worker hit a limit at %s: %s; if it fails for the limit again, judge it out again and pick another" % (
|
||||
clock(g[0]), g[1][:160] + ("…" if len(g[1]) > 160 else "")))
|
||||
from . import plan
|
||||
print(plan.record_line())
|
||||
also and print("this worker already runs node %s: judge with --node %s" % (", ".join(also), node))
|
||||
if node and sid:
|
||||
with store.session(sid) as s: print(plan.header(s["plan"], node))
|
||||
return 0
|
||||
|
||||
|
||||
@@ -340,7 +454,7 @@ def research_brief():
|
||||
intro, step2, step4 = ASK_FRESH if fresh else ASK_STALE
|
||||
return RESEARCH % {"intro": intro, "step2": step2, "step4": step4, "extra": "" if fresh else EXTRA_SHARED,
|
||||
"shared": shipped or "(none yet)", "table": store.read(table()).rstrip() or "(none yet)",
|
||||
"owner": "\n".join(owner) or "(nothing)", "outcomes": "\n".join(outcomes(60)) or "(none yet)"}
|
||||
"owner": "\n".join(owner) or "(nothing)", "outcomes": "\n".join(outcomes(60)) or "(none yet)"} + "\n=== Offered by this harness ===\n" + store.read(offered("txt"))
|
||||
|
||||
|
||||
def research_record(answer_file):
|
||||
@@ -349,11 +463,16 @@ def research_record(answer_file):
|
||||
lines = [l for l in text.splitlines() if l.startswith("|")]
|
||||
if "| worker" not in text.lower() or "fallback order:" not in text.lower() or len(lines) < 3:
|
||||
return "the answer needs the table (a `| worker |` header and at least one row) and a `Fallback order:` line"
|
||||
seen = {}
|
||||
for r in rows(text):
|
||||
if not r[7] or not r[8]:
|
||||
return "each row needs its %s: | %s |" % ("provider (a `provider` column: the account or plan the call draws on)" if not r[7] else "efficiency (the published allowance or price, with its URL, or \"measured: ...\")", " | ".join(r[:6]))
|
||||
key = (pkey(r[7]), r[2].strip().lower())
|
||||
if key in seen:
|
||||
return "keep at most one row per provider per class, the most efficient: %s and %s are both %s at %s" % (seen[key], r[0], r[2].strip(), r[7])
|
||||
seen[key] = r[0]
|
||||
if len(re.findall(r"routine|ordinary|hard", r[2].lower())) != 1:
|
||||
return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6])
|
||||
if re.search(r"\bout (?:until|till)\b", " ".join(r), re.I): # what the wheel would read as a legacy note
|
||||
return "a row may not say who is out: delete the `out until` note from it (the agent that delegates judges a worker that hit a limit: `sisi judge WORKER out \"<the provider's message>\"`): | %s |" % " | ".join(r[:6])
|
||||
if len(lines) > 42 or len(text) > 12000:
|
||||
return "the answer is too long (at most 40 rows and 12,000 characters)"
|
||||
if shared and ("|" not in shared or not _shared_date(shared)[0]):
|
||||
@@ -381,27 +500,60 @@ def sync_late(s, cwd, sid, add=True):
|
||||
|
||||
|
||||
def judge(args, cwd=None):
|
||||
"""`sisi judge WORKER good|bad|out "<why>" [--minutes N] [--newest] | extend MINUTES "<why>" [--newest]`."""
|
||||
"""`sisi judge WORKER good|bad|out "<why>" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "<why>" [--newest] [--node ID | --chore ID]`.
|
||||
Without --node/--chore a verdict closes the worker's oldest open job (--newest: its newest); with --node, the job that runs that
|
||||
plan node; with --chore, the job started under that chore id."""
|
||||
from . import retro # not at the top: hooks import this module and must stay quick
|
||||
args, newest, minutes, note = [a for a in args if a != "--newest"], "--newest" in args, None, ""
|
||||
args, newest, minutes, note, node, chore, warn = [a for a in args if a != "--newest"], "--newest" in args, None, "", None, None, ""
|
||||
if "--minutes" in args:
|
||||
i = args.index("--minutes")
|
||||
v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:]
|
||||
minutes = int(v) if re.fullmatch(r"[1-9]\d{0,3}|10000", v) else 0
|
||||
if "--node" in args: # the plan node whose job is judged: one worker may run several
|
||||
i = args.index("--node")
|
||||
node, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:]
|
||||
if "--chore" in args: # the chore whose job is judged
|
||||
i = args.index("--chore")
|
||||
chore, args = (args[i + 1:i + 2] or [""])[0].lower(), args[:i] + args[i + 2:]
|
||||
ext = len(args) == 4 and args[1] == "extend" and minutes is None and re.fullmatch(r"[1-9]\d{0,3}|10000", args[2])
|
||||
if not args or not args[0].strip() or not (ext or (len(args) == 3 and args[1] in ("good", "bad", "out") and minutes != 0)) or len(args[-1].split()) < 3:
|
||||
print('usage: sisi judge WORKER good|bad|out "<what it did well or badly, or the provider\'s message when it hit a limit, in a sentence>" [--minutes N] [--newest] | extend MINUTES "<reason, 3+ words>" [--newest]')
|
||||
if not args or not args[0].strip() or not (ext or (len(args) == 3 and args[1] in ("good", "bad", "out") and minutes != 0)) or len(args[-1].split()) < 3 \
|
||||
or (node is not None and not re.fullmatch(r"[a-z0-9-]{1,30}", node)) or chore == "" or (node is not None and chore is not None):
|
||||
print('usage: sisi judge WORKER good|bad|out "<what it did well or badly, or the provider\'s message when it hit a limit, in a sentence>" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "<reason, 3+ words>" [--newest] [--node ID | --chore ID]')
|
||||
return 1
|
||||
trows = rows(store.read(table()))
|
||||
wrows = rows(wheel()[0]) # a worker's wheel row wins over its table row (the list is the truth), and is counted once
|
||||
trows = wrows + [r for r in rows(store.read(table())) if short(r[0]) not in {short(x[0]) for x in wrows}]
|
||||
hits = [r for r in trows if short(r[0]) == short(args[0])] or [r for r in trows if claim({"picked": [short(r[0])]}, args[0], True)]
|
||||
if args[1] == "out" and len(hits) != 1: # a verdict that names no one worker would change nothing
|
||||
sid, ohits = store.current_session(cwd), []
|
||||
if not hits and sid:
|
||||
try: st = json.loads(store.read(store._session_path(sid)) or "{}")
|
||||
except ValueError: st = {}
|
||||
open_w = sorted({w for w, v in (st.get("starts") or {}).items() if isinstance(v, list) and v} | set(st.get("picked") or ()))
|
||||
ohits = [w for w in open_w if w == short(args[0])] or [w for w in open_w if claim({"picked": [w]}, args[0], True)]
|
||||
if args[1] == "out" and len(hits) != 1 and len(ohits) != 1: # a verdict that names no one worker would change nothing
|
||||
return print("sisi judge: %r is not one worker of the models table; name it as the table does." % args[0]) or 1
|
||||
model = (hits[0][0].split() or [""])[0] if len(hits) == 1 else args[0]
|
||||
wkey, sid, now, began = short(model), store.current_session(cwd), time.time(), None
|
||||
model = first(hits[0][0]) if len(hits) == 1 else ohits[0] if len(ohits) == 1 else args[0]
|
||||
wkey, now, began = short(model), time.time(), None
|
||||
if sid:
|
||||
with store.session(sid) as s:
|
||||
starts = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None
|
||||
cand = (starts.pop(-1 if newest else 0) if not ext else starts[-1 if newest else 0]) if isinstance(starts, list) and starts else None
|
||||
open_ = starts if isinstance(starts, list) else [] # this worker's open starts
|
||||
if node is not None: # --node: the job that runs this plan node
|
||||
from . import plan
|
||||
v = ((plan.get(s) or {}).get("state") or {}).get(node)
|
||||
if not (isinstance(v, dict) and v.get("st") == "running" and v.get("worker") == wkey):
|
||||
return print("sisi judge: node %s is not a job %s is running here, so --node names nothing. Nothing was changed." % (node, wkey)) or 1
|
||||
cand = v["since"] if type(v.get("since")) in (int, float) and v["since"] in open_ else None
|
||||
not ext and cand is not None and open_.remove(cand)
|
||||
elif chore is not None: # --chore: the job started under this chore id
|
||||
meta = s["meta"] if isinstance(s.get("meta"), dict) else {}
|
||||
cand = next((t for t in open_ if isinstance(m := meta.get("%s %r" % (wkey, t)), dict) and m.get("chore") == chore), None)
|
||||
if cand is None:
|
||||
infos = [_job_info(s, wkey, t) for t in open_ if type(t) in (int, float) and math.isfinite(t)]
|
||||
jobs = ["%s (started %s)" % (tag, hhmm) if tag else "started %s" % hhmm for tag, _, hhmm in infos]
|
||||
return print("sisi judge: chore %s is not an open job for %s (open: %s). Nothing was changed." % (chore, wkey, ", ".join(jobs) or "none")) or 1
|
||||
if not ext: open_.remove(cand)
|
||||
else:
|
||||
cand = (open_.pop(-1 if newest else 0) if not ext else open_[-1 if newest else 0]) if open_ else None
|
||||
if ext and not newest: # the job that is late, not just the oldest open one
|
||||
cand = next((min(t for w, t, *_ in l if w == wkey) for l in (late(s, 2), late(s, 1)) if any(w == wkey for w, *_ in l)), cand)
|
||||
ok_t = type(cand) in (int, float) and math.isfinite(cand) and cand <= now
|
||||
@@ -411,27 +563,34 @@ def judge(args, cwd=None):
|
||||
m[k], s["meta"] = {**(m[k] if isinstance(m.get(k), dict) else {}), "limit": lim, "extended": now, "reason": retro.clean(args[3])}, m
|
||||
isinstance(s.get("reminded"), list) and s.__setitem__("reminded", [x for x in s["reminded"] if x != [wkey, cand]])
|
||||
return sync_late(s, cwd, sid, False) or print("extended %s limit to %d min." % (wkey, lim)) or 0
|
||||
if ok_t and node is None and chore is None and open_: # no target named: say which job closed when it could have been another
|
||||
tag, flag, hhmm = _job_info(s, wkey, cand)
|
||||
others = [_job_info(s, wkey, t) for t in open_ if type(t) in (int, float) and math.isfinite(t)]
|
||||
if flag or any(f for _, f, _ in others):
|
||||
closed = "%s (started %s)" % (tag, hhmm) if tag else "started %s" % hhmm
|
||||
left = ", ".join("%s (started %s, %s)" % (k, h, f) if f else "started %s" % h for k, f, h in others)
|
||||
warn = "closed %s; still open: %s" % (closed, left)
|
||||
isinstance(s.get("meta"), dict) and s["meta"].pop("%s %r" % (wkey, cand), None)
|
||||
if node is not None: s["plan"]["state"][node] = {"st": "done", "evidence": "judged good"} if args[1] == "good" else {"st": "failed", "why": "judged " + args[1]} # as plan.judged moves the node its job started
|
||||
elif s.get("plan"): from . import plan; plan.judged(s, wkey, cand, args[1])
|
||||
if ok_t:
|
||||
began = cand
|
||||
minutes = minutes or max(1, int((now - began) / 60))
|
||||
note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(starts))
|
||||
note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(open_))
|
||||
sync_late(s, cwd, sid, False)
|
||||
elif ext: return print("sisi judge: no open job for %s." % args[0]) or 1
|
||||
elif ext or node is not None or chore is not None: return print("sisi judge: no open job for %s." % args[0]) or 1
|
||||
iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t))
|
||||
rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1],
|
||||
"why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)),
|
||||
"project_key": store.project_key(cwd)}
|
||||
if sid:
|
||||
rec["session_id"] = sid
|
||||
if began is not None:
|
||||
rec["started"] = iso(began)
|
||||
if minutes:
|
||||
rec["minutes"] = minutes
|
||||
if sid: rec["session_id"] = sid
|
||||
if began is not None: rec["started"] = iso(began)
|
||||
if minutes: rec["minutes"] = minutes
|
||||
log = store.data("outcomes.jsonl")
|
||||
store.append(log, json.dumps(rec, sort_keys=True))
|
||||
ok = store.commit("delegation judged", log)
|
||||
print("%s%s" % ("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.", "" if ok else " (store commit failed)"))
|
||||
if warn: print(warn)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -444,16 +603,37 @@ def run(args, cwd=None):
|
||||
gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)}
|
||||
if sitting := sorted((t, w) for w, (t, _) in gone.items() if w in listed and now - t < OUT):
|
||||
print("\nOff the wheel now:\n" + "\n".join("%s: %s" % (w, SINCE % (clock(t), clock(t + OUT))) for t, w in sitting))
|
||||
recent = outcomes(15)
|
||||
if recent:
|
||||
print("\nHow recent delegations went:\n" + "\n".join(recent))
|
||||
if stale():
|
||||
print("\n" + stale())
|
||||
if use := plan_use(text, cwd, now):
|
||||
print("\nPlan use by sisi's own delegations (an estimate; the plan's own usage page is exact):\n" + "\n".join(
|
||||
"%s: %s" % (p, ", ".join("%s %d%%" % (w, round(100 * x)) for w, x in u.items())) for p, u in sorted(use.items())))
|
||||
if recent := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent))
|
||||
if stale(): print("\n" + stale())
|
||||
return 0
|
||||
if args == ["research"]:
|
||||
return print(research_brief()) or 0
|
||||
from . import plan
|
||||
return plan.issue("models research", research_brief(), cwd) or 0
|
||||
if len(args) == 3 and args[:2] == ["research", "--record"]:
|
||||
why = research_record(args[2])
|
||||
return (print("sisi models: %s. Nothing was changed." % why) or 1) if why else 0
|
||||
print("usage: sisi models | sisi models research [--record FILE]")
|
||||
if args == ["offered"]:
|
||||
raw = sys.stdin.read(200001).strip()
|
||||
if not raw or len(raw) > 200000: return print("sisi models: give the host's raw list of offered models on stdin (1 to 200,000 characters). Nothing was changed.") or 1
|
||||
with store.lock("models"):
|
||||
store.write(offered("txt"), "listed %s by harness %s\n%s\n" % (time.strftime("%Y-%m-%dT%H:%M:%S"), os.path.basename(offered("txt"))[:-4], raw))
|
||||
os.path.isfile(offered("wheel.md")) and os.remove(offered("wheel.md"))
|
||||
store.commit("offered models listed", offered("txt"), offered("wheel.md"))
|
||||
from . import plan
|
||||
return plan.issue("models offered", OFFERED % (store.read(table()).rstrip() or "(none yet)", raw), cwd) or 0
|
||||
if len(args) == 3 and args[:2] == ["offered", "--record"]:
|
||||
raw, text = store.read(offered("txt")).partition("\n")[2], store.read(args[2])
|
||||
bad = [r[0] for r in rows(text) if not (_has(raw, first(r[0])) and _has(r[1].lower(), short(r[0])) and len(re.findall(r"routine|ordinary|hard", r[2].lower())) == 1)]
|
||||
if not raw.strip() or not rows(text) or bad or len(rows(text)) > 80:
|
||||
return print("sisi models: %s. Nothing was changed." % ("needs the list first (`sisi models offered < FILE`) and 1 to 80 rows" if not raw or not rows(text) or len(rows(text)) > 80 else "not in the list verbatim, in the how-to-call cell, or not one class: " + ", ".join(bad))) or 1
|
||||
with store.lock("models"):
|
||||
store.write(offered("wheel.md"), text.strip() + "\n")
|
||||
store.commit("offered models table", offered("wheel.md"))
|
||||
new = [short(r[0]) for r in rows(text) if r[5].lower().startswith("new:")]
|
||||
print("recorded %d offered models.%s" % (len(rows(text)), " " + ASK.replace("sisi models research`", "sisi models research` (its brief names: %s)" % ", ".join(new), 1) if new else ""))
|
||||
return 0
|
||||
print("usage: sisi models | sisi models research [--record FILE] | sisi models offered [--record FILE]")
|
||||
return 1
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
"""The plan: a dependency graph of the pieces of one piece of work, recorded before anything is handed out.
|
||||
|
||||
Each node says what it needs first, its own branch, the files it may change and its check; one join brings everything
|
||||
back. The hooks hold the lead to it: no delegation outside the plan or out of order, no turn ending while a node is
|
||||
ready and not started. The plan lives in the session state and closes with the piece of work."""
|
||||
import contextlib, fnmatch, hashlib, os, re, time
|
||||
from . import store
|
||||
|
||||
CLASSES = ("routine", "ordinary", "hard", "lead")
|
||||
COLS = ("node", "class", "needs", "branch", "files", "check", "why")
|
||||
NODE_LINE = re.compile(r"\W{0,6}sisi node:\s*([a-z0-9-]{1,30})\s*$", re.I)
|
||||
CHORE_LINE = re.compile(r"\W{0,6}sisi chore:\s*(.+?)(?:\s+([0-9a-f]{8}))?\s*$", re.I)
|
||||
CHORE_CMD = {"plan": "sisi plan brief", "models research": "sisi models research", "models offered": "sisi models offered < FILE", "rules organize": "sisi rules organize"}
|
||||
USAGE = ('usage: sisi plan | sisi plan --record FILE | sisi plan brief | sisi plan --done ID "<evidence>" | sisi plan --fail ID "<why>"\n'
|
||||
" FILE holds one markdown table: | node | class | needs | branch | files | check | why | (why is optional)")
|
||||
|
||||
BRIEF = """sisi chore: plan
|
||||
You are a worker. Do this task yourself; do not delegate it further.
|
||||
|
||||
Plan this piece of work as a dependency graph for an engineering lead who hands each node to a worker. Read the
|
||||
code you need; change nothing.
|
||||
|
||||
Goal: %(goal)s
|
||||
Checks that decide success:
|
||||
%(checks)s
|
||||
Next: %(next)s
|
||||
|
||||
Answer with exactly one markdown table and nothing else:
|
||||
| node | class | needs | branch | files | check | why |
|
||||
- node: a short id, [a-z0-9-], at most 30 characters, unique.
|
||||
- class: routine, ordinary, hard, or lead (done by the lead itself: the final join, and judgement only it can make).
|
||||
- needs: the node ids that must be done first, comma-separated, or -.
|
||||
- branch: its own git branch (each worker node gets its own worktree and build folder); - for a lead node.
|
||||
- files: the paths, folders or globs it may change, comma-separated (- for none). Nodes that can run at the same
|
||||
time must have disjoint files.
|
||||
- check: how its result is proven, a check that can fail.
|
||||
- why: a few words on the class choice, e.g. "exact spec, test decides" or "design judgement, redo costly".
|
||||
Shape: maximize parallelism: prefer many small nodes, each specified so exactly that a near-free model does it well
|
||||
and fast, to a few complex ones. A small node's check is the quick test of its own change; slow checks (the full
|
||||
suite) wait for a join node downstream that merges its needs, runs them once and fixes what broke. The smallest
|
||||
releasable piece comes first; a review is a node that needs the node it reviews; one final join needs everything.
|
||||
Class by total cost: the lead's cost to write a fully specified brief, plus the worker's cost, plus the expected
|
||||
redo. A cheap model's bad job that must be redone is waste; so is a top model on a mechanical job; so is the lead
|
||||
spending its own quota on meta work. The lead is almost always the most expensive model, so reading, searching and
|
||||
measuring that feed a brief (gather the facts for node X, list call sites, measure) are routine nodes whenever their
|
||||
output can be checked; the lead keeps only the judgement. Near-free routine models take any task that can be
|
||||
specified exactly (exact files, exact change, a test that decides), and keep being tried on such tasks so their
|
||||
record grows; judgement-heavy or design work goes straight to hard.
|
||||
%(record)s
|
||||
"""
|
||||
|
||||
|
||||
def _cells(line): return [c.strip() for c in line.strip().strip("|").split("|")]
|
||||
def _list(cell): return [] if cell.strip() in ("", "-") else [x.strip() for x in cell.split(",") if x.strip()]
|
||||
|
||||
|
||||
def parse(text):
|
||||
"""(nodes, "") from the table in `text`, or (None, why)."""
|
||||
cols, nodes = None, []
|
||||
for line in text.splitlines():
|
||||
if not line.strip().startswith("|"):
|
||||
continue
|
||||
c = _cells(line)
|
||||
if c and c[0].lower() == "node":
|
||||
cols = [x.lower() for x in c]
|
||||
if cols[:6] != list(COLS[:6]) or cols[6:] not in ([], ["why"]):
|
||||
return None, "the header must be | node | class | needs | branch | files | check | (and optionally | why |)"
|
||||
elif cols and not set("".join(c)) <= set("-: "):
|
||||
if len(c) != len(cols):
|
||||
return None, "row %r has %d cells, the header %d" % (c[0], len(c), len(cols))
|
||||
r = dict(zip(cols, c))
|
||||
nodes.append({"id": r["node"], "cls": r["class"].lower(), "needs": _list(r["needs"]), "branch": r["branch"],
|
||||
"files": _list(r["files"]), "check": store.clean(r["check"]), "why": store.clean(r.get("why", ""))})
|
||||
return (nodes, "") if nodes else (None, "no table found (a `| node | class | needs | branch | files | check |` header and rows)")
|
||||
|
||||
|
||||
def reach(nodes):
|
||||
"""{id: every id it needs, directly or not}; None when the needs hold a cycle."""
|
||||
by, out, busy = {n["id"]: n for n in nodes}, {}, set()
|
||||
def walk(i):
|
||||
if i in busy: raise ValueError(i)
|
||||
if i not in out:
|
||||
busy.add(i)
|
||||
out[i] = set(by[i]["needs"]).union(*(walk(j) for j in by[i]["needs"]))
|
||||
busy.discard(i)
|
||||
return out[i]
|
||||
try: return {i: walk(i) for i in by}
|
||||
except ValueError: return None
|
||||
|
||||
|
||||
def overlap(a, b):
|
||||
a, b = a.strip("/").removeprefix("./"), b.strip("/").removeprefix("./")
|
||||
return a == b or b.startswith(a + "/") or a.startswith(b + "/") or fnmatch.fnmatch(a, b) or fnmatch.fnmatch(b, a)
|
||||
|
||||
|
||||
def beside(r, a, b): return a != b and a not in r[b] and b not in r[a]
|
||||
|
||||
|
||||
def check(nodes):
|
||||
"""The first problem with this plan, or ""."""
|
||||
ids, seen = {n["id"] for n in nodes}, set()
|
||||
branches = [n["branch"] for n in nodes if n["cls"] != "lead"]
|
||||
for n in nodes:
|
||||
why = ("node id %r is not [a-z0-9-]{1,30}" % n["id"] if not re.fullmatch(r"[a-z0-9-]{1,30}", n["id"])
|
||||
else "node %s appears twice" % n["id"] if n["id"] in seen
|
||||
else "node %s has class %r; use one of %s" % (n["id"], n["cls"], ", ".join(CLASSES)) if n["cls"] not in CLASSES
|
||||
else "node %s needs %s, which is not a node" % (n["id"], ", ".join(sorted(set(n["needs"]) - ids))) if set(n["needs"]) - ids
|
||||
else "" if n["cls"] == "lead"
|
||||
else "node %s needs a branch of its own" % n["id"] if not re.fullmatch(r"[A-Za-z0-9._/-]{1,100}", n["branch"]) or n["branch"].startswith("-")
|
||||
else "branch %s is given to more than one node; each worker node gets its own" % n["branch"] if branches.count(n["branch"]) > 1
|
||||
else "worker node %s needs files it may change and a check" % n["id"] if not n["files"] or n["check"] in ("", "-") else "")
|
||||
if why: return why
|
||||
seen.add(n["id"])
|
||||
r = reach(nodes)
|
||||
if r is None:
|
||||
return "the needs hold a cycle"
|
||||
for a in nodes:
|
||||
for b in nodes:
|
||||
hit = a["id"] < b["id"] and beside(r, a["id"], b["id"]) and next(((x, y) for x in a["files"] for y in b["files"] if overlap(x, y)), None)
|
||||
if hit:
|
||||
return "nodes %s and %s can run at the same time but both may change %s / %s: make the files disjoint or make one need the other" % (a["id"], b["id"], *hit)
|
||||
sinks = [n for n in nodes if not any(n["id"] in m["needs"] for m in nodes)]
|
||||
if len(sinks) != 1:
|
||||
return "the plan needs exactly one final join that every node leads to; it ends in %d nodes: %s" % (len(sinks), ", ".join(n["id"] for n in sinks))
|
||||
return "" if sinks[0]["cls"] == "lead" else "the final join %s must be class lead: the lead brings everything back" % sinks[0]["id"]
|
||||
|
||||
|
||||
def waves(nodes):
|
||||
w, by = {}, {n["id"]: n for n in nodes}
|
||||
def wave(i): return w[i] if i in w else w.setdefault(i, 1 + max((wave(j) for j in by[i]["needs"]), default=0))
|
||||
[wave(n["id"]) for n in nodes]
|
||||
return w
|
||||
|
||||
|
||||
def get(s):
|
||||
"""The session's plan with its state cleaned (a damaged entry counts as not started); None if there is none or it is damaged."""
|
||||
p = s.get("plan")
|
||||
ok = lambda n: isinstance(n, dict) and all(isinstance(n.get(k), t) for k, t in (("id", str), ("cls", str), ("needs", list), ("branch", str), ("files", list), ("check", str)))
|
||||
if not (isinstance(p, dict) and isinstance(p.get("nodes"), list) and p["nodes"] and all(map(ok, p["nodes"]))):
|
||||
return None
|
||||
ids = {n["id"] for n in p["nodes"]}
|
||||
for n in p["nodes"]:
|
||||
n["needs"], n["files"] = [x for x in n["needs"] if x in ids], [x for x in n["files"] if isinstance(x, str)]
|
||||
p["state"] = {k: v for k, v in p["state"].items() if isinstance(v, dict) and k in ids} if isinstance(p.get("state"), dict) else {}
|
||||
return p
|
||||
|
||||
|
||||
def st(p, i): return p["state"].get(i, {}).get("st")
|
||||
|
||||
|
||||
def ready(p):
|
||||
"""Ids of nodes whose needs are all done and that are neither running nor done, in plan order."""
|
||||
return [n["id"] for n in p["nodes"] if st(p, n["id"]) not in ("running", "done") and all(st(p, x) == "done" for x in n["needs"])]
|
||||
|
||||
|
||||
def node(p, i): return next((n for n in p["nodes"] if n["id"] == i), None)
|
||||
|
||||
|
||||
def record_line():
|
||||
"""sisi's own record per class: good of judged, over the last 20 judged jobs of each class."""
|
||||
from . import models
|
||||
cls = {}
|
||||
for r in models.rows(store.read(models.table())):
|
||||
c = re.findall(r"routine|ordinary|hard", r[2].lower())
|
||||
len(c) == 1 and cls.setdefault(models.short(r[0]), c[0])
|
||||
by = {}
|
||||
for o in store.records("outcomes.jsonl"):
|
||||
w = o.get("model") if isinstance(o.get("model"), str) and o["model"].strip() else o.get("worker")
|
||||
if o.get("verdict") in ("good", "bad") and isinstance(w, str) and (c := cls.get(models.short(w))):
|
||||
by.setdefault(c, []).append(o["verdict"] == "good")
|
||||
parts = ["%s %d/%d good" % (c, sum(by[c][-20:]), len(by[c][-20:])) if by.get(c) else "%s none judged yet" % c for c in CLASSES[:3]]
|
||||
return "record (last 20 judged per class): " + ", ".join(parts)
|
||||
|
||||
|
||||
def show(p):
|
||||
rd, now, out = ready(p), time.time(), []
|
||||
for n in p["nodes"]:
|
||||
v, s = p["state"].get(n["id"], {}), st(p, n["id"])
|
||||
t = v.get("since") if type(v.get("since")) in (int, float) else now
|
||||
label = ("running (%s, since %s, %d min)" % (v.get("worker"), time.strftime("%H:%M", time.localtime(t)), (now - t) / 60) if s == "running"
|
||||
else "done" if s == "done" else "failed: %s" % v.get("why", "") if s == "failed" and n["id"] in rd else "ready" if n["id"] in rd else "waiting")
|
||||
out.append(" %s [%s] %s needs: %s" % (n["id"], n["cls"], label, ", ".join(n["needs"]) or "-"))
|
||||
return out + ["ready: " + (", ".join(rd) or "none")]
|
||||
|
||||
|
||||
def _sum(text): return hashlib.sha1(text.encode("utf-8", "replace")).hexdigest()
|
||||
_chore_path = lambda cid: os.path.join(store.STATE, "chores", cid + ".txt") if re.fullmatch(r"[0-9a-f]{8}", cid or "") else ""
|
||||
|
||||
|
||||
def issue(name, text, cwd=None):
|
||||
"""Print a chore brief with a one-time id and record it in this session: one delegation carrying its first line (or the full text) may go without a plan."""
|
||||
cid, text = os.urandom(4).hex(), text.strip()
|
||||
text = "sisi chore: %s %s\n%s" % (name, cid, text.split("\n", 1)[1] if "\n" in text else "") if text.startswith("sisi chore:") else "sisi chore: %s %s\n%s" % (name, cid, text)
|
||||
store.write(_chore_path(cid), text + "\n")
|
||||
if sid := store.current_session(cwd):
|
||||
with store.session(sid) as s:
|
||||
s["chores"] = (s["chores"] if isinstance(s.get("chores"), list) else [])[-9:] + [[name, _sum(text), len(text), cid]]
|
||||
print(text)
|
||||
|
||||
|
||||
def chore(args): # `sisi chore show ID`: print the brief printed under this one-time id (any session may read it)
|
||||
if len(args) == 2 and args[0] == "show" and (text := store.read(_chore_path(args[1])) if _chore_path(args[1]) else ""):
|
||||
return print(text, end="") or 0
|
||||
return print("sisi chore: no brief with id %r: print the brief again (`sisi plan brief`, `sisi models research` or `sisi rules organize`)." % (args[1] if len(args) > 1 else "")) or 1
|
||||
|
||||
|
||||
def run(args, cwd=None):
|
||||
sid = store.current_session(cwd)
|
||||
if args == ["brief"]:
|
||||
d = {}
|
||||
if sid:
|
||||
with store.session(sid) as s:
|
||||
d = s.get("done") or {}
|
||||
if not d:
|
||||
return print('sisi plan: record done first (`sisi done --goal ... --check ... --next ...`); the planning brief is built from it.') or 1
|
||||
return issue("plan", BRIEF % {"goal": d["goal"], "next": d["next"], "record": "sisi's " + record_line(),
|
||||
"checks": "\n".join(" %d. %s" % (i, c["text"]) for i, c in enumerate(d["checks"], 1))}, cwd) or 0
|
||||
if len(args) == 2 and args[0] == "--record":
|
||||
nodes, why = parse(store.read(args[1]))
|
||||
why = why or check(nodes) or ("" if sid else "no session; run this from the agent's session")
|
||||
with store.session(sid) if sid else contextlib.nullcontext({}) as s:
|
||||
old, new = get(s) or {"nodes": [], "state": {}}, {n["id"]: n for n in nodes or []}
|
||||
moved = [i for i, v in old["state"].items() if v.get("st") == "running" and (i not in new or (
|
||||
new[i]["branch"], new[i]["files"]) != (node(old, i)["branch"], node(old, i)["files"]))]
|
||||
why = why or (moved and "node %s is running: keep its id, branch and files in the new plan, or judge it first" % moved[0])
|
||||
if why:
|
||||
return print("sisi plan: %s. Nothing was recorded." % why) or 1
|
||||
keep = {i for i, v in old["state"].items() if v.get("st") == "running" or node(old, i) == new.get(i)}
|
||||
s["plan"] = p = {"nodes": nodes, "state": {i: v for i, v in old["state"].items() if i in keep and i in new}}
|
||||
w = waves(nodes)
|
||||
print("plan recorded: %d nodes, critical path %d wave(s)." % (len(nodes), max(w.values())))
|
||||
for k in range(1, max(w.values()) + 1):
|
||||
print(" wave %d: %s" % (k, ", ".join("%s (%s%s)" % (n["id"], n["cls"], ": " + n["why"] if n["why"] else "") for n in nodes if w[n["id"]] == k)))
|
||||
rd = ready(p)
|
||||
go, mine = [i for i in rd if node(p, i)["cls"] != "lead"], [i for i in rd if node(p, i)["cls"] == "lead"]
|
||||
go and print("dispatch wave 1 now, all in one message: %s (`sisi pick --node ID` for each)" % ", ".join(go))
|
||||
mine and print("yours to do now: %s" % ", ".join(mine))
|
||||
print(record_line())
|
||||
return 0
|
||||
if len(args) == 3 and args[0] in ("--done", "--fail") and len(args[2].split()) >= 3 and sid:
|
||||
with store.session(sid) as s:
|
||||
p = get(s)
|
||||
n = node(p, args[1]) if p else None
|
||||
why = ("no node %r in the plan" % args[1] if not n else "node %s is running: only its worker's verdict closes or reopens it (`sisi judge WORKER good|bad \"<why>\"`)" % args[1]
|
||||
if st(p, args[1]) == "running" else "")
|
||||
if why:
|
||||
return print("sisi plan: %s." % why) or 1
|
||||
p["state"][args[1]] = {"st": "done", "evidence": store.clean(args[2])} if args[0] == "--done" else {"st": "failed", "why": store.clean(args[2])}
|
||||
print("\n".join(show(p)))
|
||||
return 0
|
||||
if not args:
|
||||
p = None
|
||||
if sid:
|
||||
with store.session(sid) as s: p = get(s)
|
||||
return print("\n".join(show(p)) if p else "no plan recorded. `sisi plan brief` prints the brief for a planning worker; `sisi plan --record FILE` records its table.") or 0
|
||||
return print(USAGE) or 1
|
||||
|
||||
|
||||
why_not = lambda p, i: "already " + st(p, i) if st(p, i) in ("running", "done") else "needs not done: " + ", ".join(x for x in node(p, i)["needs"] if st(p, x) != "done")
|
||||
|
||||
|
||||
def for_pick(args, cwd=None):
|
||||
"""`sisi pick --node ID [rest]` as (the class pick's args, the node id), or (None, None) after saying why."""
|
||||
i, sid, p = (args[1] if len(args) > 1 else ""), store.current_session(cwd), None
|
||||
if sid:
|
||||
with store.session(sid) as s:
|
||||
p = get(s)
|
||||
n = node(p, i) if p else None
|
||||
why = ("no plan is recorded: `sisi plan brief`, then `sisi plan --record FILE`" if not p else "no node %r in the plan" % i if not n
|
||||
else "node %s is the lead's own: do it and run `sisi plan --done %s \"<evidence>\"`" % (i, i) if n["cls"] == "lead"
|
||||
else "node %s is not ready (%s)" % (i, why_not(p, i)) if i not in ready(p) else "")
|
||||
if why: return print("sisi pick: %s." % why) or (None, None)
|
||||
return [n["cls"]] + args[2:] + ["--branch", n["branch"]], i
|
||||
|
||||
|
||||
def header(p, i):
|
||||
return "\n".join(["paste at the top of the brief (its first line):", "sisi node: " + i, "branch: %s (its own worktree and build folder)" % (n := node(p, i))["branch"],
|
||||
"may change: " + (", ".join(n["files"]) or "nothing"), "check: " + n["check"],
|
||||
"needs done: " + (", ".join("%s on %s (%s)" % (x, node(p, x)["branch"], p["state"].get(x, {}).get("evidence", "")) for x in n["needs"]) or "-")])
|
||||
|
||||
|
||||
def start(s, i, worker, t):
|
||||
if (p := get(s)) and node(p, i):
|
||||
p["state"][i] = {"st": "running", "worker": worker, "since": t}
|
||||
|
||||
|
||||
def judged(s, worker, t, verdict):
|
||||
"""A verdict on a worker's job moves the node that job started, matched by worker and start: good to done, bad or out back to ready."""
|
||||
p = get(s)
|
||||
hit = next((i for i, v in p["state"].items() if v.get("st") == "running" and v.get("worker") == worker and v.get("since") == t), None) if p and t is not None else None
|
||||
if hit:
|
||||
p["state"][hit] = {"st": "done", "evidence": "judged good"} if verdict == "good" else {"st": "failed", "why": "judged " + verdict}
|
||||
|
||||
|
||||
def starts(brief, shell):
|
||||
"""Where the brief's lines may begin: its first non-empty line, or for a shell command any line (its first is the launcher)."""
|
||||
out, at = [], 0
|
||||
for line in brief.splitlines(True):
|
||||
line.strip() and out.append(at + len(line) - len(line.lstrip()))
|
||||
at += len(line)
|
||||
return out if shell else out[:1]
|
||||
|
||||
|
||||
def deny(s, brief, shell=False):
|
||||
"""(why this delegation strays from the plan or "", the plan node it starts, the index of the issued chore it spends)."""
|
||||
p, at = get(s), starts(brief, shell)
|
||||
line = lambda rx: next((m for i in at if (m := rx.match(brief[i:].split("\n", 1)[0].strip()))), None)
|
||||
chores, c = (s["chores"] if isinstance(s.get("chores"), list) else []), line(CHORE_LINE)
|
||||
if c:
|
||||
name, cid = c.group(1), c.group(2)
|
||||
hit = next((k for k, x in enumerate(chores) if isinstance(x, list) and len(x) == 4 and x[0] == name and x[3] == cid and type(x[2]) is int
|
||||
and (any(_sum(brief[i:i + x[2]]) == x[1] for i in at) or any(len(brief) - i < x[2] for i in at))), None)
|
||||
return ("", None, hit) if hit is not None else (("sisi: this `sisi chore: %s` brief is not one sisi printed in this session (a wrong, reused or other-session id): print the chore's brief again with `%s` and delegate just its first line plus \"Run `sisi chore show %s` and do what it says\"." % (name, CHORE_CMD.get(name, "sisi plan brief`, `sisi models research` or `sisi rules organize"), cid or "<id>")), None, None)
|
||||
if not p:
|
||||
return ("sisi: no plan is recorded. Before handing out work, plan it: `sisi plan brief` prints the brief for a hard planning worker "
|
||||
"(it carries its `sisi chore: plan` line), then `sisi plan --record FILE`."), None, None
|
||||
m = line(NODE_LINE)
|
||||
i = m.group(1).lower() if m else None
|
||||
n = node(p, i) if i else None
|
||||
why = ("sisi: the brief's first line must be `sisi node: ID`: pick with `sisi pick --node ID` and paste the header it prints at the top. Ready: %s." % (", ".join(ready(p)) or "none") if not m
|
||||
else "sisi: the brief names node %s, which is not in the plan (`sisi plan` shows it)." % i if not n
|
||||
else "sisi: node %s is the lead's own; do it yourself and run `sisi plan --done %s \"<evidence>\"`." % (i, i) if n["cls"] == "lead"
|
||||
else "sisi: node %s is not ready (%s). Ready now: %s (`sisi plan` shows all)." % (i, why_not(p, i), ", ".join(ready(p)) or "none") if i not in ready(p) else "")
|
||||
return why, (None if why else i), None
|
||||
|
||||
|
||||
def concurrent(s, i):
|
||||
"""Can this worker node run at the same time as another worker node?"""
|
||||
p = get(s)
|
||||
r = reach(p["nodes"]) if p else None
|
||||
return bool(r) and any(n["cls"] != "lead" and beside(r, i, n["id"]) for n in p["nodes"])
|
||||
|
||||
|
||||
def gate(s):
|
||||
"""End of turn: the ready worker nodes not started, as a message, or ""."""
|
||||
p = get(s)
|
||||
rd = ready(p) if p else []
|
||||
go = [i for i in rd if node(p, i)["cls"] != "lead"]
|
||||
if go:
|
||||
return "sisi: nodes %s are ready and not started: pick and dispatch them all now in one message (%s)." % (
|
||||
", ".join(go), " ".join("`sisi pick --node %s`" % i for i in go))
|
||||
return ""
|
||||
+61
-21
@@ -1,12 +1,12 @@
|
||||
"""The retro: what happened, set against the objective; the gap, its cause, and the instruction that would have
|
||||
prevented it. That instruction becomes a learned rule at once."""
|
||||
import json, math, os, re, time
|
||||
import hashlib, json, math, os, re, time
|
||||
from . import rules, store
|
||||
|
||||
DONE_USAGE = """usage: sisi done --goal "<the goal in their words, 5+ words>" --check "<a check that can fail, 4+ words>" [--check ...] \\
|
||||
--next "<what they will need next and what you do about it: now, room, follow-up or drop; 4+ words>"
|
||||
sisi done --pass N "<evidence>" | --fail N "<why>" sisi done: show it"""
|
||||
FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--term", "--better", "--problem")
|
||||
FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--level", "--term", "--better", "--problem")
|
||||
TERMS = {"value": "what the person wanted", "evidence": "verified by checks that fit the risk", "time": "elapsed time",
|
||||
"cost": "compute and tool cost", "attention": "the person's attention", "learning": "getting better at the next piece of work"}
|
||||
TERM_HELP = "--term is one of: %s." % ", ".join(TERMS)
|
||||
@@ -14,8 +14,8 @@ clean = store.clean
|
||||
USAGE = """Record one of these:
|
||||
sisi retro --gap "<where the work fell short of the objective, with the evidence>" \\
|
||||
--cause "<the root cause>" \\
|
||||
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." [--scope user]
|
||||
Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: in this project, or with --scope user in all your work.
|
||||
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." --level core|user|project
|
||||
Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: --level project: this git repo only; user: all your work; core: queued for the sisi product (a user rule until it is in the product). --scope works as --level.
|
||||
sisi retro --no-gap "<what shows the work met the objective>" --term TERM \\
|
||||
--better "<one concrete thing that would have scored better on that term, 5+ words>"
|
||||
TERM is where the work fell short, or could most have scored better: %s.
|
||||
@@ -78,23 +78,47 @@ def trend():
|
||||
return ["measured (pieces of work with numbers):"] + out if len(units) >= 2 else []
|
||||
|
||||
|
||||
def _alias_root(amap, n, seen=()):
|
||||
while n in amap and n not in seen:
|
||||
seen, n = (*seen, n), amap[n]
|
||||
return n
|
||||
|
||||
|
||||
def _aliases():
|
||||
why, raw = store.regular(store.data(rules.PROBLEMS), True)
|
||||
try:
|
||||
doc = json.loads(raw.decode("utf-8", "replace")) if not why and raw else {}
|
||||
except ValueError:
|
||||
doc = {}
|
||||
amap = {int(k): v for k, v in doc.items() if str(k).isascii() and str(k).isdigit() and type(v) is int and int(k) >= 1 and v >= 1 and int(k) != v} if isinstance(doc, dict) else {}
|
||||
return {k: r for k in amap if (r := _alias_root(amap, k)) != k}
|
||||
|
||||
|
||||
def _problems(recs=None):
|
||||
"""Known problems derived from retro.jsonl in order of first appearance (1-based number)."""
|
||||
"""Known problems derived from retro.jsonl in order of first appearance (1-based number), folding merged aliases."""
|
||||
by_key, out = {}, []
|
||||
for idx, r in enumerate(store.records("retro.jsonl", 64000000) if recs is None else recs):
|
||||
if not (isinstance(r.get("problem"), str) and (name := clean(r["problem"]))):
|
||||
continue
|
||||
date, key = str(r.get("ts") or "")[:10] or "?", name.lower()
|
||||
p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": []})
|
||||
p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": [], "merged": []})
|
||||
p not in out and out.append(p)
|
||||
p["attempts"].append({"date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")})
|
||||
p["attempts"].append({"idx": idx, "date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")})
|
||||
p["last"], p["last_idx"] = date, idx
|
||||
for m, n in (_aliases() if recs is None else {}).items():
|
||||
if m <= len(out) and n <= len(out):
|
||||
src, dst = out[m - 1], out[n - 1]
|
||||
src["into"] = n
|
||||
dst["merged"].append((m, src["name"]))
|
||||
dst["attempts"] = sorted(dst["attempts"] + src["attempts"], key=lambda a: a["idx"])
|
||||
dst["last"], dst["last_idx"] = dst["attempts"][-1]["date"], dst["attempts"][-1]["idx"]
|
||||
return out
|
||||
|
||||
|
||||
def _problem_lines(probs):
|
||||
recent = sorted(probs, key=lambda p: (-p["last_idx"], -p["num"]))[:15]
|
||||
return [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n := len(p["attempts"]), "" if n == 1 else "s", p["last"]) for p in recent]
|
||||
recent = sorted((p for p in probs if not p.get("into")), key=lambda p: (-p["last_idx"], -p["num"]))[:15]
|
||||
return [l for p in recent for n in [len(p["attempts"])]
|
||||
for l in [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n, "" if n == 1 else "s", p["last"]), *[" merged: %s (#%d)" % (name, m) for m, name in p["merged"]]]]
|
||||
|
||||
|
||||
def _resolve_problem(problem, probs):
|
||||
@@ -104,10 +128,11 @@ def _resolve_problem(problem, probs):
|
||||
return None, "sisi retro: name the problem in plain words (no secrets, tokens, or long hex/digit strings)."
|
||||
if len(norm) > 400:
|
||||
return None, "sisi retro: problem name is at most 400 characters."
|
||||
canon = lambda p: probs[p["into"] - 1] if p and p.get("into") else p
|
||||
if re.fullmatch(r"[+-]?\d+", norm):
|
||||
n = int(norm)
|
||||
return (probs[n - 1], "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm)
|
||||
return next((p for p in probs if p["name"].lower() == norm.lower()), {"num": len(probs) + 1, "name": norm, "attempts": []}), ""
|
||||
return (canon(probs[n - 1]), "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm)
|
||||
return canon(next((p for p in probs if p["name"].lower() == norm.lower()), None)) or {"num": len(probs) + 1, "name": norm, "attempts": []}, ""
|
||||
|
||||
|
||||
def report(sid, cwd):
|
||||
@@ -127,12 +152,19 @@ def report(sid, cwd):
|
||||
print("\n" + "\n".join(trend()))
|
||||
|
||||
|
||||
def rulebook(cwd):
|
||||
"""The rulebook the work ran under: hash, size and rule count of the loaded core file and the project's rules."""
|
||||
p = rules.path(rules.PROJECT, cwd)
|
||||
t = store.read(store.data("generated", "core.md")) + ((p and store.regular(p, True)[1] or b"").decode("utf-8", "replace"))
|
||||
return {"hash": hashlib.sha256(t.encode()).hexdigest()[:12], "chars": len(t), "lines": len(rules._parse(t))}
|
||||
|
||||
|
||||
def record(s, cwd, opt, sid=None):
|
||||
"""Append one record for the piece of work in this session state, and begin the next one."""
|
||||
d, now, dem = s.get("done") or {}, time.time(), s.get("retro_demanded")
|
||||
entry = dict(opt, ts=time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(now)),
|
||||
project=os.path.basename(store.project_root(cwd)), unit=counts(s, cwd),
|
||||
goal=d.get("goal", ""), workers=s.get("workers_since", []))
|
||||
goal=d.get("goal", ""), workers=s.get("workers_since", []), rules=rulebook(cwd))
|
||||
if d:
|
||||
entry["done"] = d
|
||||
if sid:
|
||||
@@ -142,10 +174,10 @@ def record(s, cwd, opt, sid=None):
|
||||
log = store.data("retro.jsonl")
|
||||
store.append(log, json.dumps(entry, sort_keys=True))
|
||||
if not store.commit("retro recorded", log):
|
||||
print("sisi: retro saved, but store git commit failed.")
|
||||
print("sisi: retro saved, but store git commit failed (%s)." % store.GIT_ERROR)
|
||||
s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now
|
||||
for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused",
|
||||
"fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began"):
|
||||
"fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began", "plan"):
|
||||
s.pop(key, None)
|
||||
|
||||
|
||||
@@ -203,9 +235,12 @@ def run(args, cwd=None):
|
||||
if not args:
|
||||
return report(sid, cwd) or 0
|
||||
opt = _options(args)
|
||||
scope, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "term", "better", "problem")]
|
||||
scope = scope or rules.PROJECT
|
||||
kind = (None if not opt or scope not in (rules.USER, rules.PROJECT)
|
||||
scope, level, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "level", "term", "better", "problem")]
|
||||
if level and scope and level != scope:
|
||||
print("sisi retro: --level %s and --scope %s disagree; give one of them." % (level, scope))
|
||||
return 1
|
||||
scope = level or scope
|
||||
kind = (None if not opt or (scope is not None and scope not in (rules.CORE, rules.USER, rules.PROJECT))
|
||||
else "later" if set(opt) == {"later"} and _words(opt, "later", 3)
|
||||
else "no-gap" if set(opt) == {"no-gap"} and _words(opt, "no-gap", 5)
|
||||
else "gap" if set(opt) == {"gap", "cause", "improve"} and all(_words(opt, k, 4) for k in opt) else None)
|
||||
@@ -214,6 +249,9 @@ def run(args, cwd=None):
|
||||
print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most "
|
||||
"400 characters).\n" + USAGE)
|
||||
return 1
|
||||
if kind == "gap" and (why := rules.refuse_level(scope, cwd, "sisi retro --gap ...")):
|
||||
print("sisi retro: " + why)
|
||||
return 1
|
||||
if kind != "gap" and problem is not None:
|
||||
print("sisi retro: --problem goes only with --gap.")
|
||||
return 1
|
||||
@@ -248,7 +286,7 @@ def run(args, cwd=None):
|
||||
elif kind != "later":
|
||||
record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt)
|
||||
if kind == "gap":
|
||||
found = next((p for p in _problems() if p["name"].lower() == opt["problem"].lower()), None)
|
||||
found = next((p for p in _problems() if not p.get("into") and p["name"].lower() == opt["problem"].lower()), None)
|
||||
prior = found["attempts"][:-1] if found else prob["attempts"]
|
||||
prob, misses = found or prob, len(prior)
|
||||
if misses:
|
||||
@@ -262,9 +300,10 @@ def run(args, cwd=None):
|
||||
else:
|
||||
print("opened problem %d '%s'." % (prob["num"], prob["name"]))
|
||||
try:
|
||||
added, warn = rules.add(opt["improve"], scope, "retro", cwd)
|
||||
print(warn or "recorded. In force from the next session%s: %s" % (
|
||||
" in every project" if scope == rules.USER else " in this project", added))
|
||||
added, warn = rules.add(opt["improve"], scope, "retro", cwd, problem=prob["num"])
|
||||
print(warn or ("recorded. In force from the next session%s: %s" % (
|
||||
" in every project" if scope == rules.USER else " in this project", added) if scope != rules.CORE else "recorded, queued for the product: %s" % added))
|
||||
print(rules.filed(scope, opt["improve"], cwd))
|
||||
except OSError as e:
|
||||
print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e))
|
||||
if misses >= 2:
|
||||
@@ -279,4 +318,5 @@ def run(args, cwd=None):
|
||||
print(rules.due(cwd))
|
||||
else:
|
||||
print("recorded." if kind == "no-gap" else "noted: the retro waits until this work ends.")
|
||||
scope and print("(--level goes only with --gap; it was ignored.)")
|
||||
return 0
|
||||
+316
-107
@@ -3,10 +3,12 @@
|
||||
A rule is one line. It is in force as soon as it is added: rules for all of the person's work become the last
|
||||
section of the rulebook every session loads, and a project's rules live in `.sisi/rules.md` at its root.
|
||||
Now and then a cheap worker audits and organizes them. Store changes are committed and can be undone."""
|
||||
import contextlib, hashlib, json, os, re, time
|
||||
import contextlib, hashlib, json, os, re, shlex, time
|
||||
from . import store
|
||||
|
||||
USER, PROJECT = "user", "project"
|
||||
USER, PROJECT, CORE = "user", "project", "core"
|
||||
LEVELS = """The three levels: core = the sisi product itself, for every sisi user anywhere, nothing personal (queued for its maintainers, loaded as a user rule until then);
|
||||
user = how this person works across all projects, their machine, accounts, providers; project = this one git repo only (its .sisi/rules.md)."""
|
||||
OWNER = re.compile(r"\[owner\b[^\]]*\]")
|
||||
_owner, _retro = lambda l: bool(OWNER.search(l)), lambda ls: [l for l in ls if not _owner(l)]
|
||||
_snap = lambda u, p: hashlib.sha1(("\n".join(u) + "\0" + "\n".join(p)).encode()).hexdigest()[:16]
|
||||
@@ -14,11 +16,14 @@ _TAGS = " [owner] lines are the person's words; [agent ...] lines are an agent's
|
||||
HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them." + _TAGS + "\n"
|
||||
HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them)." + _TAGS
|
||||
SMELL = re.compile(r"(?i)\bone (?:build|test|run|worker|job)\b.{0,60}\bat a time|\bflock\b|\b(?:shared?|one)\b.{0,30}\bbuild (?:folder|dir)")
|
||||
DROPS = "rules/drops.jsonl"
|
||||
DROPS, PROBLEMS = "rules/drops.jsonl", "rules/problems.json"
|
||||
_DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$")
|
||||
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip()).lower().split())
|
||||
_NOTE = re.compile(r"(?:\s+\(p\d+: (?:came back \d+x|not seen) since(?:; p\d+: (?:came back \d+x|not seen) since)*\))+$")
|
||||
_RETRO_TAG, _DATE = re.compile(r"(?:\s*\[retro\b[^\]]*\])+$"), re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", _NOTE.sub("", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip())).lower().split())
|
||||
|
||||
ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further.
|
||||
ORGANIZE = """sisi chore: rules organize
|
||||
You are a worker. Do this task yourself; do not delegate it further.
|
||||
|
||||
Audit and organize the learned rules below. They are instructions an AI engineering agent reads at the start
|
||||
of every session: the first list in every project, the second only in the project "%(name)s". Retros add to
|
||||
@@ -30,15 +35,18 @@ Rewrite both lists so they serve that objective best:
|
||||
- Merge rules that say the same thing. Drop fragments, rules that are stale or contradicted by a later one,
|
||||
and rules too specific to come up again.
|
||||
- Word each rule as a direct instruction with its reason, on one line, standing on its own.
|
||||
- A rule seen in more than one project, or about how the person wants to be worked with, belongs in the
|
||||
first list. A rule about this project's own code belongs in the second.
|
||||
- Audit where each rule is filed. %(levels)s Move a rule that sits at the wrong level, in either direction,
|
||||
with its words byte-identical: a user line about one project goes to `## project` (this one; if it names another
|
||||
project leave it and flag it); a project line that applies to all the person's work goes to `## user`; a line
|
||||
that applies to every sisi user goes under `## core` (a queue for the product's maintainers). [owner ...] lines
|
||||
may move between levels too, never reworded.
|
||||
- Lines marked [owner ...] are the person's own words: copy every one of them verbatim, unchanged by even
|
||||
one character (you may reorder them). Only the other lines ([retro ...], [agent ...]) may be merged, reworded or dropped.
|
||||
- Flag, but do not change, any [owner ...] line whose text does not read as the person's own words (a paraphrase, an
|
||||
agent's conclusion, third person), and any rule that limits builds, tests or workers to one at a time or tells
|
||||
checkouts to share one build folder. List each under a final `## flags` section with its proposed corrected or
|
||||
retagged form, for the person to accept.
|
||||
- Keep the [source date] mark at the end of every line.
|
||||
- Keep the [source date] mark (and any pN tag, including on merged rules) at the end of every line, without any trailing (pN: ...) note. A rule whose problem came back after it was written should be reworked or turned into a check.
|
||||
- A `better` that recurs across retros has earned a rule: add it, worded as an instruction, marked [retro <date>].
|
||||
- Non-owner ([retro ...]) lines in each list: at most %(lines)d lines and %(chars)d characters. Fewer is better.
|
||||
- When you drop or merge away a non-owner rule, you can list `- <old rule copied as it is> | #<N or -> | <reason>` under `## drops` (#- if no problem matches; optional: a missing line is recorded as 'none given').
|
||||
@@ -48,8 +56,12 @@ Answer with exactly this shape and nothing else:
|
||||
- ...
|
||||
## project
|
||||
- ...
|
||||
## core
|
||||
- ... (only lines moved to the product queue)
|
||||
## drops
|
||||
- <old rule> | #<N or -> | <reason> (optional; only if any non-owner rules were dropped)
|
||||
## same problems
|
||||
N = M (optional; merge duplicate problem M into older N)
|
||||
## flags
|
||||
- ... (only if there are any)
|
||||
|
||||
@@ -70,7 +82,31 @@ Answer with exactly this shape and nothing else:
|
||||
def path(scope, cwd=None):
|
||||
"""Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept."""
|
||||
top, inside = store.root(cwd) if scope == PROJECT else ("", False)
|
||||
return store.data("rules", "user.md") if scope == USER else "" if inside else os.path.join(top, ".sisi", "rules.md")
|
||||
return store.data("rules", scope + ".md") if scope in (USER, CORE) else "" if inside else os.path.join(top, ".sisi", "rules.md")
|
||||
|
||||
|
||||
def has_project(cwd=None):
|
||||
"""True inside a git repository whose root is not the home folder: the only place a project list may be written."""
|
||||
top, inside = store.root(cwd)
|
||||
return not inside and os.path.lexists(os.path.join(top, ".git")) and os.path.realpath(top) != os.path.realpath(store.HOME)
|
||||
|
||||
|
||||
def refuse_level(level, cwd, cmd):
|
||||
"""Why a rule may not be filed at this level (with the command to rerun), or ""."""
|
||||
if level not in (CORE, USER, PROJECT):
|
||||
return "name the level of this rule. %s\nRerun with --level core|user|project, e.g. `%s --level user ...`." % (LEVELS, cmd)
|
||||
return "no project here (not inside a git repository, or it is the home folder), use user: `%s --level user ...`." % cmd if level == PROJECT and not has_project(cwd) else ""
|
||||
|
||||
|
||||
def filed(level, text, cwd):
|
||||
return 'filed as %s rule in %s. Wrong level? sisi rules move "%s" core|user|project' % (level, path(level, cwd), " ".join(text.split()[:5]))
|
||||
|
||||
|
||||
def core_note(cwd):
|
||||
"""At session start in the sisi repo itself: how many rules wait in the product queue."""
|
||||
top = store.project_root(cwd)
|
||||
n = len(lines(path(CORE))) if all(os.path.isfile(os.path.join(top, *f)) for f in (("canon", "core.md"), ("sisi", "rules.py"))) else 0
|
||||
return "sisi: %d rule%s proposed for the product: add each to canon/core.md, then `sisi rules move \"<start>\" canon`; or move it elsewhere." % (n, "" if n == 1 else "s") if n else ""
|
||||
|
||||
|
||||
def _legacy(cwd=None):
|
||||
@@ -93,19 +129,31 @@ def _text(p):
|
||||
try:
|
||||
return None if raw is None else raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise OSError(".sisi/rules.md is not valid UTF-8")
|
||||
raise OSError("%s is not valid UTF-8" % p)
|
||||
|
||||
|
||||
def _append(text, new):
|
||||
return (text or "") + ("\n" if text and not text.endswith("\n") else "") + "".join(l + "\n" for l in new)
|
||||
|
||||
|
||||
def _check_writable(p):
|
||||
def _drops_text(p, limit=2000000):
|
||||
"""Read a non-link drops log up to `limit` bytes, or None when absent; OSError if unreadable or oversize."""
|
||||
try:
|
||||
with open(p, "rb", opener=lambda q, f: os.open(q, f | os.O_NOFOLLOW)) as f:
|
||||
raw = f.read(limit + 1)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if len(raw) > limit:
|
||||
raise OSError("%s is over %d bytes" % (os.path.join(*p.split(os.sep)[-2:]), limit))
|
||||
return raw.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _check_writable(p, capped=True):
|
||||
if not p:
|
||||
raise OSError("this folder is inside a git directory or a bare repository")
|
||||
for t, label, folder in ((os.path.dirname(p), ".sisi", True), (p, ".sisi/rules.md", False)):
|
||||
for t, label, folder in ((os.path.dirname(p), os.path.basename(os.path.dirname(p)), True), (p, os.path.join(*p.split(os.sep)[-2:]), False)):
|
||||
why = (("a symlink" if os.path.islink(t) else "not a directory" if os.path.lexists(t) and not os.path.isdir(t) else "") if folder
|
||||
else store.regular(t)[0]) or ("read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
|
||||
else ("" if not capped and store.regular(t)[0] == "over 64,000 bytes" else store.regular(t)[0])) or ("read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
|
||||
if why:
|
||||
raise OSError("%s is %s" % (label, why))
|
||||
if not os.path.exists(os.path.dirname(p)) and not os.access(os.path.dirname(os.path.dirname(p)), os.W_OK):
|
||||
@@ -142,9 +190,8 @@ def _move(dest, old):
|
||||
_check_writable(dest)
|
||||
before = _text(dest)
|
||||
extra = [l for l in dict.fromkeys(_parse(raw)) if l not in set(_parse(before or ""))]
|
||||
rel = os.path.relpath(old, store.DATA)
|
||||
uncommitted = not os.path.isdir(os.path.join(store.DATA, ".git")) or store.git(["status", "--porcelain", "--", rel], store.DATA)[1].strip()
|
||||
if uncommitted and not store.commit("project rules before move to .sisi/rules.md", old):
|
||||
store.history()
|
||||
if store.git(["status", "--porcelain", "--", old], store.DATA)[1].strip() and not store.commit("project rules before move to .sisi/rules.md", old):
|
||||
raise OSError("could not commit store")
|
||||
extra and store.write(dest, _append(before, extra))
|
||||
(extra or _parse(raw)) and note(dest)
|
||||
@@ -163,7 +210,7 @@ def _migrate(cwd=None, wait=True):
|
||||
msg = ("sisi: project rules are not kept inside a git directory or a bare repository." if not dest
|
||||
else "sisi: %s is a link, and sisi does not use a linked .sisi; its rules are not read." % d if os.path.islink(d := os.path.dirname(dest))
|
||||
else "sisi: %s is %s; its rules are not read." % (dest, why) if not os.path.isfile(old) and (why := "not a directory" if os.path.lexists(d) and not os.path.isdir(d) else store.regular(dest)[0]) else "")
|
||||
if not msg and os.path.isfile(old):
|
||||
if not msg and os.path.isfile(old) and os.path.realpath(store.project_root(cwd)) != os.path.realpath(store.HOME):
|
||||
with store.lock(dest, wait=wait) as ok:
|
||||
msg = _move(dest, old) if ok else ""
|
||||
return scope_lines(PROJECT, cwd, migrate=False), msg
|
||||
@@ -175,26 +222,59 @@ def scope_lines(scope, cwd=None, migrate=True):
|
||||
if migrate:
|
||||
return _migrate(cwd)[0]
|
||||
dest, old = path(PROJECT, cwd), _legacy(cwd)
|
||||
ls = lines(old) # store copy first: writers fill the project file before removing it, so a no-wait read never misses both
|
||||
raw = store.regular(dest, True)[1] if dest and not os.path.islink(os.path.dirname(dest)) else None
|
||||
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
|
||||
return list(dict.fromkeys(ls + ((_parse(raw.decode("utf-8", "replace"))) if raw is not None else [])))
|
||||
|
||||
|
||||
def _commit(msg, *paths, snap=None):
|
||||
if snap:
|
||||
p = store.data("rules", "last-project.json")
|
||||
store.write(p, json.dumps(dict(zip(("path", "before", "after"), snap))))
|
||||
paths = (p,) + paths
|
||||
if not store.commit(msg, *paths):
|
||||
raise OSError("store git commit failed")
|
||||
_in_store = lambda p: p.startswith(os.path.join(store.DATA, ""))
|
||||
|
||||
|
||||
def add(text, scope, source, cwd=None, log=None, means=""):
|
||||
def _apply(msg, change, record):
|
||||
"""Write {path: (before, after)}, files outside the store first, then one store commit with `record`; a failed write or commit restores every file before reporting."""
|
||||
rp = store.data("rules", "last-project.json")
|
||||
backs = list(change.items())
|
||||
def _undo():
|
||||
for p, (b, a) in backs:
|
||||
with contextlib.suppress(OSError):
|
||||
store.write(p, b) if b is not None else os.path.lexists(p) and os.remove(p)
|
||||
try:
|
||||
backs.append((rp, (_text(rp), None)))
|
||||
[store.write(p, a) for p, (b, a) in change.items() if not _in_store(p) and a is not None and a != b]
|
||||
ok = store.commit(msg, put={**{p: a for p, (b, a) in change.items() if _in_store(p)}, rp: json.dumps(record)})
|
||||
except OSError:
|
||||
_undo()
|
||||
raise
|
||||
if not ok:
|
||||
_undo()
|
||||
return "store git commit failed (%s)" % store.GIT_ERROR
|
||||
return ""
|
||||
|
||||
|
||||
def _back(line, now, old, lv):
|
||||
"""The command that moves `line` from file `now` back to file `old`, at level `lv`."""
|
||||
here, there = [] if _in_store(now) else [os.path.dirname(os.path.dirname(now))], [os.path.dirname(os.path.dirname(old))] if lv == PROJECT else []
|
||||
return ("cd %s && " % shlex.quote(here[0]) if here and there else "") + "sisi rules move %s %s" % (shlex.quote(line[2:]), lv) + "".join(" --project " + shlex.quote(r) for r in there or here)
|
||||
|
||||
|
||||
def _locks(*keys):
|
||||
st = contextlib.ExitStack()
|
||||
[st.enter_context(store.lock(k)) for k in sorted(set(keys))]
|
||||
return st
|
||||
|
||||
|
||||
def add(text, scope, source, cwd=None, log=None, means="", raw=None, problem=None):
|
||||
"""Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written."""
|
||||
line, *more = ["- %s [%s %s]" % (" ".join(str(t).split()), src, time.strftime("%Y-%m-%d")) for t, src in ((text, source), (means, "agent reading")) if t] # one commit holds both
|
||||
if scope == PROJECT and not has_project(cwd):
|
||||
raise OSError("no project here, use user")
|
||||
d = time.strftime("%Y-%m-%d")
|
||||
line, *more = ["- %s [%s %s%s]" % (" ".join(str(t).split()), src, d, " p%d" % p if p else "") for t, src, p in ((text, source, problem), (means, "agent reading", None)) if t] # one commit holds both
|
||||
line, more = (raw, []) if raw else (line, more)
|
||||
dest = path(scope, cwd)
|
||||
scope == PROJECT and not dest and _check_writable(dest)
|
||||
store.history()
|
||||
with store.lock(dest if scope == PROJECT else "user"):
|
||||
if scope == USER:
|
||||
if scope != PROJECT:
|
||||
[store.append(dest, l) for l in [line, *more]]
|
||||
else:
|
||||
_check_writable(dest)
|
||||
@@ -206,12 +286,13 @@ def add(text, scope, source, cwd=None, log=None, means=""):
|
||||
note(dest)
|
||||
try:
|
||||
log and store.append(*log)
|
||||
extra = ([dest] if scope == USER else []) + ([log[0]] if log else [])
|
||||
_commit("rule added (%s, %s)" % (scope, source), *extra, snap=(dest, before, after) if scope == PROJECT else None)
|
||||
warn = ""
|
||||
extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else [])
|
||||
rec = {store.data("rules", "last-project.json"): json.dumps({"path": dest, "before": before, "after": after})} if scope == PROJECT else {}
|
||||
warn = "" if store.commit("rule added (%s, %s)" % (scope, source), *extra, put=rec) else "store git commit failed (%s)" % store.GIT_ERROR
|
||||
except OSError as e:
|
||||
warn = "the rule is in %s; it could not be recorded for undo: %s" % (dest, e)
|
||||
scope == USER and build_rulebook()
|
||||
warn = str(e)
|
||||
warn = warn and "the rule is in %s; it could not be recorded for undo: %s" % (dest, warn)
|
||||
scope != PROJECT and build_rulebook()
|
||||
return line, warn
|
||||
|
||||
|
||||
@@ -234,7 +315,7 @@ def delivered(p):
|
||||
def build_rulebook():
|
||||
"""Write the always-loaded instructions: the product's rulebook, then the person's learned rules."""
|
||||
text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n"
|
||||
mine = delivered(path(USER))
|
||||
mine = _fit(lines(path(USER)) + lines(path(CORE))) # a rule queued for the product is in force here until it is in canon
|
||||
if mine:
|
||||
text += "\n" + HEAD_USER + "\n" + "\n".join(mine) + "\n"
|
||||
out = store.data("generated", "core.md")
|
||||
@@ -273,12 +354,13 @@ def due(cwd, claim=False):
|
||||
"""One line when the learned rules need organizing, else ""."""
|
||||
cfg, seen, cl, now, need = store.config(), _organized(), _organized(("locks", "organize.json")), time.time(), []
|
||||
active = lambda c, k: type(c.get("claim:" + k)) in (int, float) and 0 <= now - c["claim:" + k] < 1800
|
||||
for scope in (USER, PROJECT):
|
||||
for scope in (USER, PROJECT)[:2 if has_project(cwd) else 1]:
|
||||
ls, k = _retro(scope_lines(scope, cwd, migrate=False)), _mark_key(scope, cwd)
|
||||
prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0))
|
||||
over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]
|
||||
if not active(cl, k) and (over or len(ls) - prev >= cfg["organize_after"]):
|
||||
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev))))
|
||||
audit = scope == USER and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"]
|
||||
if not active(cl, k) and (over or audit or len(ls) - prev >= cfg["organize_after"]):
|
||||
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev) if len(ls) - prev >= cfg["organize_after"] else "time to audit their levels")))
|
||||
if not need:
|
||||
return ""
|
||||
if claim:
|
||||
@@ -289,29 +371,34 @@ def due(cwd, claim=False):
|
||||
cl.update({"claim:" + k: now for k, _ in need})
|
||||
with contextlib.suppress(OSError):
|
||||
store.write(store.data("locks", "organize.json"), json.dumps(cl))
|
||||
return ("sisi: the learned rules need organizing (%s). In the background, give the output of "
|
||||
"`sisi rules organize` to a cheap worker and record its answer with `sisi rules organize --record FILE`."
|
||||
return ("sisi: the learned rules need organizing (%s). In the background, delegate just the first line of the output of "
|
||||
"`sisi rules organize` plus \"Run `sisi chore show <id>` and do what it says\" to a cheap worker and record its answer with `sisi rules organize --record FILE`."
|
||||
% "; ".join(m for _, m in need))
|
||||
|
||||
|
||||
def drops_for(num=None):
|
||||
return [d for d in store.records(DROPS) if num is None or d.get("problem") == num]
|
||||
from . import retro
|
||||
amap = retro._aliases() if num is not None else {}
|
||||
return [d for d in store.records(DROPS) if num is None or amap.get(d.get("problem"), d.get("problem")) == num]
|
||||
|
||||
|
||||
def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
|
||||
if not probs:
|
||||
canon = [p for p in probs if not p.get("into")]
|
||||
if not canon:
|
||||
return ""
|
||||
cut = lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
|
||||
amap, cut = {p["num"]: p["into"] for p in probs if p.get("into")}, lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
|
||||
all_p = "\n\n=== Every known problem (list duplicates under ## same problems as N = M, older first) ===\n" + "\n".join(
|
||||
"#%d: %s | cause: %s" % (p["num"], cut(p["name"]), cut(next((a["cause"] for a in p["attempts"] if a["cause"]), "") or "(none)")) for p in canon)
|
||||
head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n"
|
||||
"How to use this evidence:\n"
|
||||
"- Problem has 0 misses: it has not come back yet, keep it. Has misses: the sentence did not hold, keep the latest attempt and note it in `## flags` (do not just reword).\n"
|
||||
"- When merging, keep the cause; never drop a rule as redundant while its problem keeps coming back. [owner ...] rules stay verbatim.\n")
|
||||
out, used = [head], len(head)
|
||||
for p in sorted(probs, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]:
|
||||
for p in sorted(canon, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]:
|
||||
n = len(p["attempts"])
|
||||
ls = (["#%d: %s (opened %s, %d attempt%s, %d miss%s, last %s)" % (p["num"], cut(p["name"]), p["opened"], n, "" if n == 1 else "s", n - 1, "" if n == 2 else "es", p["last"])]
|
||||
+ [" attempt [%s] cause: %s | rule: %s" % (a["date"], cut(a["cause"]), cut(a["improve"])) for a in p["attempts"]]
|
||||
+ [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if d.get("problem") == p["num"]])
|
||||
+ [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if amap.get(d.get("problem"), d.get("problem")) == p["num"]])
|
||||
blk = "\n".join(ls) + "\n"
|
||||
if used + len(blk) > cap_c:
|
||||
for l in (ls if len(out) == 1 else ()):
|
||||
@@ -319,39 +406,75 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
|
||||
out.append(l + "\n"); used += len(l) + 1
|
||||
break
|
||||
out.append(blk); used += len(blk)
|
||||
return "".join(out).rstrip("\n")
|
||||
return all_p + "".join(out).rstrip("\n")
|
||||
|
||||
|
||||
def _rule_probs(line):
|
||||
"""Return [(problem_num, rule_date), ...] from trailing [retro ...] tags, or []."""
|
||||
m = _RETRO_TAG.search(line)
|
||||
dates = _DATE.findall(m.group(0)) if m else []
|
||||
if not dates:
|
||||
return []
|
||||
cur, out = max(dates), {}
|
||||
for d, p in re.findall(r"(\d{4}-\d{2}-\d{2})|\bp(\d{1,6})\b", m.group(0)):
|
||||
if d:
|
||||
cur = d
|
||||
elif (n := int(p)) >= 1:
|
||||
out[n] = max(out.get(n, ""), cur)
|
||||
return list(out.items())
|
||||
|
||||
|
||||
def _annotate(ls, probs):
|
||||
"""Append per-rule problem recurrence notes for display in `sisi rules` and `organize_brief`."""
|
||||
out = []
|
||||
for l in ls:
|
||||
if not (ps := _rule_probs(l)):
|
||||
out.append(l)
|
||||
continue
|
||||
notes = []
|
||||
for n, d in ps:
|
||||
p = probs[n - 1] if 1 <= n <= len(probs) else None
|
||||
p = probs[p["into"] - 1] if p and p.get("into") else p
|
||||
c = sum(bool(_DATE.fullmatch(a["date"])) and a["date"] > d for a in (p["attempts"] if p else ()))
|
||||
notes.append("p%d: came back %dx since" % (n, c) if c else "p%d: not seen since" % n)
|
||||
out.append("%s (%s)" % (l, "; ".join(notes)))
|
||||
return out
|
||||
|
||||
|
||||
def organize_brief(cwd):
|
||||
from . import retro
|
||||
cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd)
|
||||
cfg, u, p, probs = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) if has_project(cwd) else [], retro._problems()
|
||||
with contextlib.suppress(OSError), store.lock("organize"):
|
||||
cl = _organized(("locks", "organize.json"))
|
||||
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
|
||||
store.write(store.data("locks", "organize.json"), json.dumps(cl))
|
||||
return ORGANIZE % {
|
||||
"name": os.path.basename(store.project_root(cwd)), "objective": objective(),
|
||||
"name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "objective": objective(),
|
||||
"lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
|
||||
"flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)",
|
||||
"user": "\n".join(u) or "(none)", "project": "\n".join(p) or "(none)",
|
||||
"user": "\n".join(_annotate(u, probs)) or "(none)",
|
||||
"project": "\n".join(_annotate(p, probs)) or "(none)" if has_project(cwd) else "(not in a git project: leave `## project` empty)",
|
||||
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)",
|
||||
"evidence": _evidence(retro._problems(), drops_for())}
|
||||
"evidence": _evidence(probs, drops_for())}
|
||||
|
||||
|
||||
def organize_record(answer_file, cwd):
|
||||
"""Replace both lists with the worker's answer. Returns why not, or None when it is done."""
|
||||
cfg = store.config()
|
||||
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project)[ \t]*|## [^\n]*)$", store.read(answer_file))
|
||||
got, flags, drops = {}, "", {}
|
||||
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops|same problems)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file))
|
||||
got, flags, drops, same_lines = {}, "", {}, []
|
||||
for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)):
|
||||
if re.fullmatch(r"## (user|project)[ \t]*", h):
|
||||
got[h[3:].strip()] = [l.rstrip() for l in chunk.splitlines() if l.startswith("- ")]
|
||||
if re.fullmatch(r"## (user|project|core)[ \t]*", h):
|
||||
got[h[3:].strip()] = [l if _owner(l) else _NOTE.sub("", l) for l in (x.rstrip() for x in chunk.splitlines() if x.startswith("- "))]
|
||||
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
|
||||
flags += chunk
|
||||
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
|
||||
for l in chunk.splitlines():
|
||||
if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]):
|
||||
drops.setdefault(rk, (m[2], why))
|
||||
elif re.match(r"(?i)#{2,3}[ \t]*same problems\b", h):
|
||||
same_lines += [x.strip() for x in chunk.splitlines() if x.strip() and x.strip().lower() not in ("none", "(none)") and not x.strip().startswith("```")]
|
||||
core = got.pop(CORE, [])
|
||||
if set(got) != {USER, PROJECT}:
|
||||
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
|
||||
for scope, ls in got.items():
|
||||
@@ -359,56 +482,70 @@ def organize_record(answer_file, cwd):
|
||||
if len(r) > cfg["rules_lines"] or sum(map(len, r)) > cfg["rules_chars"]:
|
||||
return "the %s list is over the budget of %d lines and %d characters (it has %d and %d)" % (
|
||||
scope, cfg["rules_lines"], cfg["rules_chars"], len(r), sum(map(len, r)))
|
||||
up, pp = path(USER), path(PROJECT, cwd)
|
||||
if not pp or os.path.islink(os.path.dirname(pp)):
|
||||
proj = has_project(cwd) # outside a git project only the user list is organized
|
||||
up, pp, cp = path(USER), path(PROJECT, cwd) if proj else None, path(CORE)
|
||||
if not proj and got[PROJECT]:
|
||||
return "no project here, so `## project` must be empty: put those lines under `## user`, or record it inside their git project"
|
||||
if proj and (not pp or os.path.islink(os.path.dirname(pp))):
|
||||
return _migrate(cwd)[1].removeprefix("sisi: ")
|
||||
with store.lock(pp):
|
||||
msg = _move(pp, _legacy(cwd))
|
||||
with _locks(USER, *filter(None, [pp])):
|
||||
msg = proj and _move(pp, _legacy(cwd))
|
||||
if msg:
|
||||
return msg.removeprefix("sisi: ")
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False) if proj else []}
|
||||
if (want := _organized(("locks", "organize.json")).get("snap:" + _mark_key(PROJECT, cwd))) and _snap(had[USER], had[PROJECT]) != want:
|
||||
return "the rules changed since `sisi rules organize` ran; run `sisi rules organize` again"
|
||||
for scope in (USER, PROJECT):
|
||||
if miss := [l for l in had[scope] if _owner(l) and got[scope].count(l) < had[scope].count(l)]:
|
||||
return "owner rule missing or changed (%s): %s" % (scope, miss[0])
|
||||
kept = list(got[USER]) + list(got[PROJECT])
|
||||
every = got[USER] + got[PROJECT] + core # an owner line may change level, never a word
|
||||
if miss := [l for l in had[USER] + had[PROJECT] if _owner(l) and every.count(l) < (had[USER] + had[PROJECT]).count(l)]:
|
||||
return "owner rule missing or changed: %s" % miss[0]
|
||||
kept = every[:]
|
||||
dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)]
|
||||
from . import retro
|
||||
nprobs = len(retro._problems()) if dropped else 0
|
||||
nprobs = len(retro._problems()) if dropped or same_lines else 0
|
||||
pnum = lambda s: n if s.isascii() and s.isdigit() and len(s) <= 6 and 1 <= (n := int(s)) <= nprobs else None
|
||||
recs = [(store.clean(r)[:300], pnum(h[0]), h[1]) if (h := drops.get(_DKEY(r))) else (store.clean(r)[:300], None, "none given") for r in dropped]
|
||||
no_why = sum(_DKEY(r) not in drops for r in dropped)
|
||||
if not any(got.values()) and any(had.values()):
|
||||
old_amap = retro._aliases() if same_lines else {}
|
||||
amap, bad_same = dict(old_amap), []
|
||||
for raw_l in same_lines:
|
||||
m = re.fullmatch(r"(?:[-*]\s+)?#?(\d{1,6})\s*=\s*#?(\d{1,6})(?:\s+(?:#|\(|//|-).*|\s*\|.*)?", raw_l)
|
||||
n, k = (int(m[1]), int(m[2])) if m else (0, 0)
|
||||
rn = retro._alias_root(amap, n) if m else 0
|
||||
why_bad = ("expected N = M" if not m else "unknown problem number" if not (1 <= n <= nprobs and 1 <= k <= nprobs)
|
||||
else "cycle" if rn == k else "already merged" if k in amap and retro._alias_root(amap, k) != rn else "")
|
||||
bad_same.append((raw_l, why_bad)) if why_bad else amap.__setitem__(k, rn)
|
||||
if not any(got.values()) and not core and any(had.values()):
|
||||
return "the answer holds no rules at all"
|
||||
try:
|
||||
before = _text(pp)
|
||||
after = "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None
|
||||
after is not None and _check_writable(pp)
|
||||
wrote = after is not None and after != before
|
||||
wrote and store.write(pp, after)
|
||||
except OSError as e:
|
||||
return "could not write %s (%s)" % (pp, e)
|
||||
after is not None and note(pp)
|
||||
wrote_u = False
|
||||
try:
|
||||
store.write(up, "".join(l + "\n" for l in got[USER]))
|
||||
wrote_u = True
|
||||
seen = _organized()
|
||||
seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))})
|
||||
seen, op, dp, ts = _organized(), store.data("rules", "organized.json"), store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
seen["retros"] = len(store.read(store.data("retro.jsonl")).splitlines())
|
||||
seen.update({_mark_key(USER): len(_retro(got[USER])), **({_mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))} if proj else {})})
|
||||
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
|
||||
marks = store.data("rules", "organized.json")
|
||||
store.write(marks, json.dumps(seen))
|
||||
dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
for r, pn, why in recs:
|
||||
store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True))
|
||||
_commit("rules organized", marks, up, *([dp] if recs else []), snap=(pp, before, after))
|
||||
change = {up: (_text(up), "".join(l + "\n" for l in got[USER])), op: (_text(op), json.dumps(seen))}
|
||||
if proj:
|
||||
before = _text(pp)
|
||||
change[pp] = (before, "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None)
|
||||
if core:
|
||||
change[cp] = (cb := _text(cp), "".join(l + "\n" for l in dict.fromkeys(_parse(cb or "") + core)))
|
||||
if recs:
|
||||
_check_writable(dp, capped=False)
|
||||
old = _drops_text(dp)
|
||||
change[dp] = (old, _append(old, [json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True) for r, pn, why in recs]))
|
||||
if amap != old_amap:
|
||||
ap = store.data(PROBLEMS)
|
||||
change[ap] = (_text(ap), json.dumps({str(k): v for k, v in sorted(amap.items())}, sort_keys=True))
|
||||
[_check_writable(p) for p in change if change[p][1] is not None and p != dp]
|
||||
now, home = {USER: got[USER], PROJECT: got[PROJECT], CORE: core}, {USER: up, PROJECT: pp, CORE: cp}
|
||||
flat = [l for sec in now.values() for l in sec]
|
||||
over = [l for l in dict.fromkeys(flat) if sum(l in sec for sec in now.values()) > 1]
|
||||
merged = [l for l in dict.fromkeys(had[USER] + had[PROJECT]) if l in had[USER] and l in had[PROJECT] and 1 <= flat.count(l) < (had[USER] + had[PROJECT]).count(l)]
|
||||
back = [_back(l, home[lv], home[f], f) for lv in now for l in dict.fromkeys(now[lv]) for f in (USER, PROJECT) if f != lv and l in had[f] and l not in now[f] + had.get(lv, []) and l not in over + merged]
|
||||
warn = _apply("rules organized" if proj else "rules organized (user only)", change,
|
||||
{"reverse": back} if back else {"path": pp, "before": before, "after": change[pp][1]} if proj else {})
|
||||
except OSError as e:
|
||||
wrote_u and build_rulebook()
|
||||
if not wrote and not wrote_u:
|
||||
return "could not write %s (%s)" % (up, e)
|
||||
print("the organized rules are in %s; they could not be recorded for undo: %s" % (pp if wrote else up, e))
|
||||
return None
|
||||
return "could not record the organized rules (%s)" % e
|
||||
if warn: return "could not record the organized rules (%s); the files are restored, so run `sisi rules organize --record %s` again once the store is free" % (warn, answer_file)
|
||||
proj and change[pp][1] is not None and note(pp)
|
||||
with contextlib.suppress(OSError), store.lock("organize"):
|
||||
cl = {k: v for k, v in _organized(("locks", "organize.json")).items()
|
||||
if k not in ("claim:" + _mark_key(USER), "claim:" + _mark_key(PROJECT, cwd), "snap:" + _mark_key(PROJECT, cwd))}
|
||||
@@ -417,13 +554,17 @@ def organize_record(answer_file, cwd):
|
||||
for scope in (USER, PROJECT):
|
||||
print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope])))
|
||||
no_why and print("%d dropped rule%s had no reason recorded" % (no_why, "" if no_why == 1 else "s"))
|
||||
[print("skipped same problems line '%s' (%s)" % b) for b in bad_same]
|
||||
[print("the same rule was in both user and project and is now one copy in %s: %s; add it back by hand if you want it at both levels (run `sisi rules` to see the lists)" % (next(lv for lv in now if l in now[lv]), l)) for l in merged]
|
||||
[print("the same rule now sits at two levels, so `sisi rules move` cannot pick one copy: %s; remove the copy you do not want by hand (run `sisi rules` to see the lists)" % l) for l in over if l not in merged]
|
||||
flags.strip() and print("Flagged for you (not changed):" + flags.rstrip())
|
||||
back and print("Moved between levels, which `sisi rules revert` does not undo; to move them back, run:\n" + "\n".join(" " + c for c in back))
|
||||
return None
|
||||
|
||||
|
||||
def revert():
|
||||
"""Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left."""
|
||||
files = ("rules/user.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS)
|
||||
"""Undo the last learn, retro or organize (a project's list only while it holds what that change left); not a move between levels."""
|
||||
files = ("rules/user.md", "rules/core.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS, PROBLEMS)
|
||||
advice = " (edit by hand or restore with git)"
|
||||
if os.path.isdir(os.path.join(store.DATA, ".git")) and store.git(["status", "--porcelain", "--", *files], store.DATA)[1].strip():
|
||||
return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice
|
||||
@@ -432,19 +573,25 @@ def revert():
|
||||
return "there is no change to the learned rules to undo"
|
||||
(commit, _, subject), changed = out.splitlines()[0].partition(" "), out.splitlines()[1:]
|
||||
redo = len(re.match(r'(Revert ")*', subject).group(0)) // 8 % 2
|
||||
snap = {}
|
||||
if "rules/last-project.json" in changed or "(project," in subject or "organized" in subject:
|
||||
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed else ""
|
||||
# every change that writes a project list or moves a rule writes this record, so it is read even when its bytes did not change
|
||||
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed or re.search(r'\(project,|organized"*$|^rule moved', subject) else "{}"
|
||||
try:
|
||||
snap = json.loads(raw)
|
||||
except ValueError:
|
||||
snap = None
|
||||
if (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str)
|
||||
if isinstance(snap, dict) and isinstance(snap.get("reverse"), list) and all(isinstance(c, str) for c in snap["reverse"]):
|
||||
print("to move them back, run:\n" + "\n".join(" " + c for c in snap["reverse"]))
|
||||
return "the last rule change, `%s`, moved rules between levels, which revert does not undo; the commands above move them back" % subject
|
||||
if isinstance(snap, dict) and snap.get("final"):
|
||||
return "the last rule change, `%s`, took the rule into canon/core.md, which is final and cannot be undone" % subject
|
||||
if snap != {} and (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str)
|
||||
or not os.path.isabs(sp) or os.path.normpath(sp) != sp or not sp.endswith("/.sisi/rules.md") or ".git" in sp.split(os.sep)
|
||||
or any(snap[k] is not None and not isinstance(snap[k], str) for k in ("before", "after"))):
|
||||
return "the undo record for `%s` is missing, corrupt or outside .sisi/rules.md, so it cannot be undone%s" % (subject, advice)
|
||||
if store.git(["rev-parse", "-q", "--verify", commit + "^"], store.DATA)[0]:
|
||||
return "there is no change to the learned rules to undo" # the first commit holds the rules from before sisi kept history
|
||||
p, (now, want) = snap.get("path"), (snap.get("before"), snap.get("after"))[::1 if redo else -1]
|
||||
with store.lock(p or "user"), store.lock("store"):
|
||||
with _locks(USER, *filter(None, [p])), store.lock("store"):
|
||||
if store.git(["log", "-1", "--format=%H", "--", *files], store.DATA)[1].strip() != commit:
|
||||
return "another rule change finished while waiting; run `sisi rules revert` again"
|
||||
try:
|
||||
@@ -468,8 +615,11 @@ def show(cwd):
|
||||
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
|
||||
proj, note = _migrate(cwd)
|
||||
note and print("\n" + note)
|
||||
for title, ls in (("Learned, all projects", lines(path(USER))), ("Learned, this project", proj)):
|
||||
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(ls) or " (none)"))
|
||||
groups = (("Learned, all projects", lines(path(USER))), ("Queued for the product (in force as user rules until then)", lines(path(CORE))), ("Learned, this project", proj))
|
||||
from . import retro
|
||||
probs = retro._problems() if any(_rule_probs(l) for _, ls in groups for l in ls) else []
|
||||
for title, ls in groups:
|
||||
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(_annotate(ls, probs)) or " (none)"))
|
||||
if due(cwd):
|
||||
print("\n" + due(cwd))
|
||||
|
||||
@@ -480,19 +630,72 @@ def run(args, cwd=None):
|
||||
show(cwd)
|
||||
return 0
|
||||
if args[0] == "organize" and len(args) == 1:
|
||||
print(organize_brief(cwd))
|
||||
from . import plan
|
||||
plan.issue("rules organize", organize_brief(cwd), cwd)
|
||||
return 0
|
||||
if args[0] == "organize" and len(args) == 3 and args[1] == "--record":
|
||||
why = organize_record(args[2], cwd)
|
||||
elif args[:1] == ["move"]:
|
||||
why = move(args[1:], cwd)
|
||||
elif args == ["revert"]:
|
||||
why = revert()
|
||||
else:
|
||||
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules revert"
|
||||
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules move \"<start of a rule>\" core|user|project|canon [--project PATH] | sisi rules revert"
|
||||
if why:
|
||||
print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why)
|
||||
return 1 if why else 0
|
||||
|
||||
|
||||
def move(args, cwd):
|
||||
"""`sisi rules move "<start of a rule line>" LEVEL|canon [--project PATH]`: one line, verbatim, to another level (canon: out of
|
||||
the product queue, once it is in canon/core.md); it prints the command that moves it back. Returns why not, or None."""
|
||||
top, usage = None, 'usage: sisi rules move "<start of a rule line>" core|user|project|canon [--project PATH]'
|
||||
if "--project" in args:
|
||||
i = args.index("--project")
|
||||
if i + 1 >= len(args):
|
||||
return usage
|
||||
top, args = os.path.abspath(args[i + 1]), args[:i] + args[i + 2:]
|
||||
if not has_project(top) or os.path.realpath(store.root(top)[0]) != os.path.realpath(top):
|
||||
return "--project needs the folder of a git repository (its root)"
|
||||
if len(args) != 2 or args[1] not in (CORE, USER, PROJECT, "canon"):
|
||||
return usage
|
||||
start, to, to_cwd = " ".join(args[0].split()), args[1], top or cwd
|
||||
forms = [f for f in ([start, start[2:]] if start.startswith("- ") else [start]) if f]
|
||||
homes = {path(lv, c): (lv, c) for lv, c in [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in (cwd, top) if c and has_project(c)]}
|
||||
dst = path(to, to_cwd) if to != "canon" else None
|
||||
hits = [(p, lv, l) for p, (lv, c) in homes.items() for l in dict.fromkeys(scope_lines(lv, c) if lv == PROJECT else lines(p)) if any(" ".join(l[2:].split()).startswith(f) for f in forms)]
|
||||
hits = [h for h in hits if any(" ".join(h[2][2:].split()) == f for f in forms)] or hits
|
||||
hits = [h for h in hits if h[0] != dst] or hits
|
||||
if len(hits) != 1:
|
||||
return "no rule line starts with that; run `sisi rules` to see the rules" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for _, lv, l in hits)
|
||||
src, lv, line = hits[0]
|
||||
if to == "canon" and lv != CORE:
|
||||
return "only a rule queued for the product goes to canon, after it is added to canon/core.md; this is a %s rule" % lv
|
||||
if src == dst:
|
||||
return "that rule is already a %s rule" % to
|
||||
if dst and (why := refuse_level(to, to_cwd, "sisi rules move")):
|
||||
return why.split(": `")[0]
|
||||
try:
|
||||
with _locks(*(USER if _in_store(p) else p for p in filter(None, (src, dst)))):
|
||||
[_check_writable(p) for p in filter(None, (src, dst))]
|
||||
b_src, b_dst = _text(src), dst and _text(dst)
|
||||
rows = (b_src or "").lstrip("\ufeff").splitlines(True)
|
||||
keep = [x for x in rows if x.rstrip() != line] # every copy of the line: one rule
|
||||
if len(keep) == len(rows):
|
||||
return "that line is in %s only in an older copy; run `sisi rules` once, then move it" % src
|
||||
change = {src: (b_src, "".join(keep))}
|
||||
dst and change.update({dst: (b_dst, b_dst if line in _parse(b_dst or "") else _append(b_dst, [line]))})
|
||||
back = dst and _back(line, dst, src, lv)
|
||||
warn = _apply("rule moved (%s to %s)" % (lv, to), change, {"reverse": [back]} if dst else {"final": "canon"})
|
||||
except OSError as e:
|
||||
return "could not move it (%s)" % e
|
||||
if warn: return "could not move it (%s); the files are restored, so run it again once the store is free: sisi rules move %s %s%s" % (warn, shlex.quote(args[0]), args[1], " --project " + shlex.quote(top) if top else "")
|
||||
to == PROJECT and note(dst)
|
||||
build_rulebook()
|
||||
print("moved to %s: %s\nto move it back (`sisi rules revert` does not undo a move), run:\n %s" % (to, line, back) if dst else "removed from the product queue into canon/core.md, which is final: %s" % line)
|
||||
return None
|
||||
|
||||
|
||||
_norm = lambda t: " ".join(re.sub(r"[\W_]+", " ", t.lower()).split())
|
||||
|
||||
|
||||
@@ -507,14 +710,19 @@ def _said(words, cwd):
|
||||
|
||||
|
||||
def learn(args, cwd=None):
|
||||
"""`sisi learn [--project] "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
|
||||
"""`sisi learn --level core|user|project "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
|
||||
owner tag only when the words are found in the person's recent messages, else the agent's own tag."""
|
||||
args, scope = list(args), PROJECT if "--project" in args else None
|
||||
while (j := next((j for j, a in enumerate(args[:-1]) if a in ("--level", "--scope")), None)) is not None:
|
||||
scope, args[j:j + 2] = args[j + 1], []
|
||||
i = args.index("--means") if "--means" in args else len(args)
|
||||
args, means = list(args[:i]), " ".join(args[i + 1:])
|
||||
scope = PROJECT if "--project" in args else USER
|
||||
text = " ".join(a for a in args if a != "--project").strip()
|
||||
if len(text.split()) < 3 or (means and len(means.split()) < 3):
|
||||
print('usage: sisi learn [--project] "<what the person said, in their words>" [--means "<how I will apply it>"]')
|
||||
words, means = [a for a in args[:i] if a != "--project"], " ".join(args[i + 1:])
|
||||
text = " ".join(words).strip()
|
||||
if len(text.split()) < 3 or (i < len(args) and len(means.split()) < 3) or any(w.startswith("--") for w in words):
|
||||
print('usage: sisi learn --level core|user|project "<what the person said, in their words>" [--means "<how I will apply it>"]')
|
||||
return 1
|
||||
if why := refuse_level(scope, cwd, 'sisi learn'):
|
||||
print("sisi learn: " + why)
|
||||
return 1
|
||||
heard = _said(text, cwd)
|
||||
log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
|
||||
@@ -524,5 +732,6 @@ def learn(args, cwd=None):
|
||||
print("sisi learn: could not write %s (%s). Nothing was changed, and your words were not kept." % (path(scope, cwd) or cwd or os.getcwd(), e))
|
||||
return 1
|
||||
heard or print("sisi learn: these words were not found in the person's recent messages, so the rule carries the weaker tag [agent, attributed to owner]; a later owner statement or a measurement overrides it.")
|
||||
print(warn or "in force from the next session: %s" % line)
|
||||
print(warn or ("in force from the next session: %s" if scope != CORE else "queued for the product, in force as a user rule until then: %s") % line)
|
||||
print(filed(scope, text, cwd))
|
||||
return 0
|
||||
+32
-8
@@ -20,11 +20,13 @@ def _where(own, xdg, fallback):
|
||||
DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share"))
|
||||
STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state"))
|
||||
LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi")
|
||||
GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error
|
||||
|
||||
# Every setting there is. The person overrides one under "core" in config.json in their store.
|
||||
DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8,
|
||||
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False,
|
||||
"worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8}
|
||||
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 3, "shell_workers": False, "enforce": True,
|
||||
"worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8,
|
||||
"auto_update": True, "update_hours": 24, "update_url": "https://github.com/swaits/sisi", "offered_hours": 24}
|
||||
|
||||
def config():
|
||||
cfg = dict(DEFAULTS)
|
||||
@@ -36,6 +38,15 @@ def config():
|
||||
return cfg
|
||||
|
||||
|
||||
def harness():
|
||||
"""Name of the tool running this: the first canon entry whose "here" env var is set, else unknown."""
|
||||
try:
|
||||
table = json.loads(read(os.path.join(ROOT, "canon", "harnesses.json")) or "[]")
|
||||
except ValueError:
|
||||
table = []
|
||||
return next((re.sub(r"[^a-z0-9._-]+", "-", (h["name"] + "-" + v).lower())[:60] for h in table if isinstance(h, dict) and (v := os.environ.get(h.get("here") or ""))), "unknown")
|
||||
|
||||
|
||||
def data(*parts):
|
||||
path = os.path.join(DATA, *parts)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
@@ -98,24 +109,37 @@ def append(path, line, once=False):
|
||||
|
||||
def git(args, cwd, timeout=15):
|
||||
# A repository named by the caller's environment (a git hook sets GIT_DIR) must not decide which project this folder is.
|
||||
global GIT_ERROR
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")}
|
||||
env["GIT_OPTIONAL_LOCKS"] = "0" # a plain `git status` holds index.lock while it runs, and a commit started then fails on it
|
||||
try:
|
||||
r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env)
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
r = subprocess.CompletedProcess(args, 1, "", str(e))
|
||||
GIT_ERROR = (r.stderr.strip().partition("\n")[0] or "git exited with %d" % r.returncode) if r.returncode else ""
|
||||
return r.returncode, r.stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return 1, ""
|
||||
|
||||
|
||||
def commit(message, *paths):
|
||||
"""One commit in the person's store holding only these paths, so the change can be undone on its own."""
|
||||
def commit(message, *paths, put=None):
|
||||
"""One commit in the person's store holding only these paths, so the change can be undone on its own. `put` ({path: text})
|
||||
is written under the lock and committed too: another process's `git add` never reads a file as it is replaced."""
|
||||
history()
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA)
|
||||
rel = [os.path.relpath(p, DATA) for p in paths]
|
||||
[write(p, text) for p, text in (put or {}).items()]
|
||||
rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))]
|
||||
return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
|
||||
(git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or
|
||||
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0))
|
||||
|
||||
|
||||
def history():
|
||||
"""Start the store's git history once, holding the rules as they are, so no undo goes back past them."""
|
||||
if not os.path.isdir(os.path.join(DATA, ".git")):
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or [git(a, DATA) for a in (["init", "-q"], ["add", "-A", "--", "rules"], [
|
||||
"-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "--allow-empty", "-m", "rules before sisi kept history"])]
|
||||
|
||||
|
||||
_roots = {}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Auto-update: a detached background check at session start, the release it makes, and its one-line notice.
|
||||
|
||||
Everything runs against a local bare git repository as the remote, in a temporary home with temporary
|
||||
SISI_DATA/SISI_STATE/SISI_LIB, so the person's own files are never touched (guarded below)."""
|
||||
import glob, hashlib, json, os, shutil, subprocess, sys, tempfile, time, unittest
|
||||
from unittest import mock
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
|
||||
|
||||
def tree():
|
||||
"""A fingerprint of the product tree, so a test that writes into it is caught (as in test_core)."""
|
||||
out = hashlib.sha1()
|
||||
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
|
||||
if os.path.isfile(p):
|
||||
with open(p, "rb") as f:
|
||||
out.update(p.encode() + f.read())
|
||||
return out.hexdigest()
|
||||
|
||||
|
||||
class AutoUpdate(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine,
|
||||
"a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-test-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.state = os.path.join(self.tmp, "state")
|
||||
self.lib = os.path.join(self.tmp, "lib")
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=self.state,
|
||||
SISI_LIB=self.lib, CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"):
|
||||
self.env.pop(name, None)
|
||||
self.proj = self.project("alpha")
|
||||
|
||||
# helpers copied in shape from tests/test_core.py
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def write(self, path, text):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return path
|
||||
|
||||
def project(self, name):
|
||||
path = os.path.join(self.tmp, name)
|
||||
os.makedirs(path)
|
||||
for args in (["init", "-q", "-b", "main"], ["config", "gc.auto", "0"], ["config", "maintenance.auto", "false"],
|
||||
["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]):
|
||||
subprocess.run(["git"] + args, cwd=path, check=True, capture_output=True)
|
||||
return path
|
||||
|
||||
def git(self, cwd, *args):
|
||||
r = subprocess.run(["git"] + list(args), cwd=cwd, check=True, capture_output=True, text=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
def run_exe(self, exe, *args, stdin=""):
|
||||
return subprocess.run([sys.executable, exe] + list(args), cwd=self.proj, env=self.env,
|
||||
input=stdin, capture_output=True, text=True)
|
||||
|
||||
def in_process(self, fn, *args):
|
||||
"""Run fn in this process against the temp store and temp home (test_core's helper, plus the
|
||||
SISI_* variables so a child process fn starts lands in the same temp places); (result, output)."""
|
||||
import contextlib, io
|
||||
from sisi import store
|
||||
out, here = io.StringIO(), os.getcwd()
|
||||
os.chdir(self.tmp)
|
||||
try:
|
||||
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", self.state), \
|
||||
mock.patch.object(store, "LIB", self.lib), mock.patch.object(store, "HOME", self.tmp), \
|
||||
mock.patch.dict(os.environ, {k: self.env[k] for k in
|
||||
("HOME", "CLAUDE_CONFIG_DIR", "SISI_DATA", "SISI_STATE", "SISI_LIB")}), \
|
||||
contextlib.redirect_stdout(out):
|
||||
return fn(*args), out.getvalue()
|
||||
finally:
|
||||
os.chdir(here)
|
||||
|
||||
def config(self, **kw):
|
||||
core = {"update_url": "file://" + self.bare}
|
||||
core.update(kw)
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": core}))
|
||||
|
||||
def source(self, version="1.0.0", fail=False):
|
||||
"""A git repository (branch main) holding the product and one small test, plus its bare remote."""
|
||||
src = os.path.join(self.tmp, "source")
|
||||
if not os.path.isdir(src):
|
||||
for name in ("sisi", "bin", "canon"):
|
||||
shutil.copytree(os.path.join(REPO, name), os.path.join(src, name),
|
||||
ignore=shutil.ignore_patterns("__pycache__"))
|
||||
os.makedirs(os.path.join(src, "tests"))
|
||||
subprocess.run(["git", "init", "-q", "-b", "main"], cwd=src, check=True)
|
||||
for args in (["config", "gc.auto", "0"], ["config", "maintenance.auto", "false"]):
|
||||
subprocess.run(["git"] + args, cwd=src, check=True)
|
||||
self.write(os.path.join(src, "tests", "test_ok.py"),
|
||||
"import unittest\nclass T(unittest.TestCase):\n def test(self): %s\n" % ("self.fail('bad')" if fail else "pass"))
|
||||
self.write(os.path.join(src, "VERSION"), version + "\n")
|
||||
self.git(src, "add", "-A")
|
||||
self.git(src, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", version)
|
||||
self.bare = os.path.join(self.tmp, "remote.git")
|
||||
if not os.path.isdir(self.bare):
|
||||
subprocess.run(["git", "clone", "-q", "--bare", src, self.bare], check=True, capture_output=True)
|
||||
self.git(src, "remote", "add", "origin", self.bare)
|
||||
self.git(src, "push", "-q", "origin", "main")
|
||||
return src
|
||||
|
||||
def remote_sha(self):
|
||||
return self.git(self.bare, "rev-parse", "refs/heads/main")
|
||||
|
||||
def install_release(self):
|
||||
"""Release the version now on the remote, as the person's first install would."""
|
||||
mine = os.path.join(self.tmp, "mine")
|
||||
subprocess.run(["git", "clone", "-q", self.bare, mine], check=True, capture_output=True)
|
||||
r = self.run_exe(os.path.join(mine, "bin", "sisi"), "release")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
return os.path.join(self.lib, "current", "bin", "sisi")
|
||||
|
||||
def releases(self):
|
||||
folder = os.path.join(self.lib, "releases")
|
||||
return sorted(os.listdir(folder)) if os.path.isdir(folder) else []
|
||||
|
||||
def current(self, *parts):
|
||||
return self.read(self.lib, "current", *parts)
|
||||
|
||||
def current_commit(self):
|
||||
lines = (self.current("SOURCE").split("\n") + ["", "", ""])
|
||||
return lines[2].strip()
|
||||
|
||||
def log(self):
|
||||
path = os.path.join(self.state, "auto-update.log")
|
||||
return self.read(path) if os.path.exists(path) else ""
|
||||
|
||||
def auto(self, exe):
|
||||
return self.run_exe(exe, "update", "--auto")
|
||||
|
||||
def set_up_released(self):
|
||||
self.source("1.0.0")
|
||||
exe = self.install_release()
|
||||
self.config()
|
||||
return exe
|
||||
|
||||
# the tests
|
||||
def test_tick_starts_the_detached_job_only_when_due_and_only_when_on(self):
|
||||
from sisi import hooks, install
|
||||
self.bare = os.path.join(self.tmp, "remote.git") # config() names it; Popen is mocked, nothing fetches
|
||||
self.config()
|
||||
with mock.patch("sisi.install.subprocess.Popen") as popen: # no release in use yet: nothing is started
|
||||
self.in_process(install.maybe_auto_update)
|
||||
popen.assert_not_called()
|
||||
self.write(os.path.join(self.lib, "current", "bin", "sisi"), "# placeholder for the installed command\n")
|
||||
stamp = os.path.join(self.state, "auto-update-check")
|
||||
with mock.patch("sisi.install.subprocess.Popen") as popen:
|
||||
self.in_process(install.maybe_auto_update)
|
||||
self.assertEqual(popen.call_count, 1)
|
||||
args, kw = popen.call_args
|
||||
self.assertIn("-B", args[0])
|
||||
self.assertTrue(args[0][2].endswith(os.path.join("bin", "sisi")), args[0])
|
||||
self.assertEqual(args[0][3:], ["update", "--auto"])
|
||||
self.assertTrue(kw["start_new_session"])
|
||||
self.assertEqual(kw["stdin"], subprocess.DEVNULL)
|
||||
popen.return_value.wait.assert_not_called() # detached: never waited on
|
||||
stamp1 = float(self.read(stamp))
|
||||
self.in_process(install.maybe_auto_update) # not due yet
|
||||
self.assertEqual(popen.call_count, 1)
|
||||
self.write(stamp, str(time.time() - 25 * 3600)) # due again (default 24h)
|
||||
self.in_process(install.maybe_auto_update)
|
||||
self.assertEqual(popen.call_count, 2)
|
||||
self.assertGreater(float(self.read(stamp)), stamp1)
|
||||
self.write(stamp, str(time.time() - 25 * 3600))
|
||||
popen.side_effect = OSError("cannot start") # the stamp is written first: no retry storm
|
||||
self.in_process(install.maybe_auto_update)
|
||||
self.assertGreater(float(self.read(stamp)), time.time() - 60)
|
||||
popen.side_effect = None
|
||||
self.config(auto_update=False) # off: never started, however old the stamp
|
||||
self.write(stamp, str(time.time() - 99 * 3600))
|
||||
self.in_process(install.maybe_auto_update)
|
||||
self.assertEqual(popen.call_count, 3)
|
||||
with mock.patch.object(install, "maybe_auto_update") as called: # session start makes the call
|
||||
p = hooks.normalize({"session_id": "s1", "cwd": self.proj, "agent_id": "w"})
|
||||
self.in_process(hooks.tick, p)
|
||||
called.assert_called_once_with()
|
||||
|
||||
def test_release_records_its_commit_and_same_commit_releases_nothing(self):
|
||||
exe = self.set_up_released()
|
||||
self.assertEqual(self.current_commit(), self.remote_sha())
|
||||
before = self.releases()
|
||||
r = self.auto(exe)
|
||||
self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr)
|
||||
self.assertEqual(self.releases(), before)
|
||||
self.assertIn(self.remote_sha()[:7], self.log())
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, "auto-update-notice")))
|
||||
|
||||
def test_remote_ahead_is_released(self):
|
||||
exe = self.set_up_released()
|
||||
old = self.remote_sha()
|
||||
self.source("2.0.0")
|
||||
r = self.auto(exe)
|
||||
self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr)
|
||||
self.assertEqual(self.current("VERSION").strip(), "2.0.0")
|
||||
self.assertEqual(self.current_commit(), self.remote_sha())
|
||||
self.assertIn("%s->%s" % (old[:7], self.remote_sha()[:7]), self.log())
|
||||
self.assertTrue(os.path.exists(os.path.join(self.state, "auto-update-notice")))
|
||||
|
||||
def test_unknown_commit_is_treated_as_update(self):
|
||||
exe = self.set_up_released()
|
||||
lines = self.current("SOURCE").split("\n")
|
||||
self.write(os.path.join(os.path.realpath(os.path.join(self.lib, "current")), "SOURCE"),
|
||||
"\n".join(lines[:2]) + "\n") # an old release: no commit recorded
|
||||
self.source("2.0.0")
|
||||
r = self.auto(exe)
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""), r.stdout + r.stderr)
|
||||
self.assertEqual(self.current("VERSION").strip(), "2.0.0")
|
||||
self.assertEqual(self.current_commit(), self.remote_sha())
|
||||
|
||||
def test_local_commit_not_an_ancestor_is_skipped_and_logged(self):
|
||||
exe = self.set_up_released()
|
||||
other = self.git(self.proj, "rev-parse", "HEAD") # a commit the remote has never seen
|
||||
lines = self.current("SOURCE").split("\n") + ["", "", ""]
|
||||
lines[2] = other
|
||||
self.write(os.path.join(os.path.realpath(os.path.join(self.lib, "current")), "SOURCE"),
|
||||
"\n".join(lines[:3]) + "\n")
|
||||
self.source("2.0.0")
|
||||
before = self.releases()
|
||||
r = self.auto(exe)
|
||||
self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr)
|
||||
self.assertEqual(self.current("VERSION").strip(), "1.0.0")
|
||||
self.assertEqual(self.releases(), before)
|
||||
self.assertIn("not an ancestor", self.log())
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, "auto-update-notice")))
|
||||
|
||||
def test_failing_tests_in_the_new_version_switch_nothing(self):
|
||||
exe = self.set_up_released()
|
||||
self.source("2.0.0", fail=True)
|
||||
before = self.releases()
|
||||
r = self.auto(exe)
|
||||
self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr)
|
||||
self.assertEqual(self.current("VERSION").strip(), "1.0.0")
|
||||
self.assertEqual(self.releases(), before)
|
||||
self.assertIn("fail", self.log())
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, "auto-update-notice")))
|
||||
|
||||
def test_lock_held_exits_quietly(self):
|
||||
from sisi import store
|
||||
exe = self.set_up_released()
|
||||
self.source("2.0.0")
|
||||
with mock.patch.object(store, "DATA", self.data):
|
||||
with store.lock("auto-update") as held:
|
||||
self.assertTrue(held)
|
||||
r = self.auto(exe)
|
||||
self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr)
|
||||
self.assertEqual(self.current("VERSION").strip(), "1.0.0")
|
||||
|
||||
def test_the_notice_shows_once_at_the_next_session_start(self):
|
||||
exe = self.set_up_released()
|
||||
old = self.remote_sha()
|
||||
self.source("2.0.0")
|
||||
self.assertEqual(self.auto(exe).returncode, 0)
|
||||
new = self.remote_sha()
|
||||
exe = os.path.join(self.lib, "current", "bin", "sisi")
|
||||
self.write(os.path.join(self.state, "auto-update-check"), str(time.time())) # not due: no detached job
|
||||
want = "sisi: updated itself to %s (was %s); `sisi rollback` goes back." % (new[:7], old[:7])
|
||||
payload = json.dumps({"session_id": "s9", "cwd": self.proj})
|
||||
first = self.run_exe(exe, "tick", stdin=payload)
|
||||
self.assertEqual(first.returncode, 0, first.stdout + first.stderr)
|
||||
self.assertEqual(first.stdout.splitlines().count(want), 1, first.stdout)
|
||||
second = self.run_exe(exe, "tick", stdin=payload)
|
||||
self.assertNotIn(want, second.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+984
-114
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,290 @@
|
||||
"""Tests for fault18: organize --record revert and drops.jsonl failure handling."""
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
|
||||
|
||||
def tree():
|
||||
out = hashlib.sha1()
|
||||
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
|
||||
if os.path.isfile(p):
|
||||
with open(p, "rb") as f:
|
||||
out.update(p.encode() + f.read())
|
||||
return out.hexdigest()
|
||||
|
||||
|
||||
class Fault18(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-f18-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.env = dict(
|
||||
os.environ,
|
||||
HOME=self.tmp,
|
||||
SISI_DATA=self.data,
|
||||
SISI_STATE=os.path.join(self.tmp, "state"),
|
||||
SISI_LIB=os.path.join(self.tmp, "lib"),
|
||||
CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"),
|
||||
)
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME", "CLAUDE_CODE_ENTRYPOINT"):
|
||||
self.env.pop(name, None)
|
||||
self.proj = os.path.join(self.tmp, "alpha")
|
||||
os.makedirs(self.proj)
|
||||
for args in (["init", "-q"], ["config", "gc.auto", "0"], ["config", "maintenance.auto", "false"],
|
||||
["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]):
|
||||
subprocess.run(["git"] + args, cwd=self.proj, check=True, stdin=subprocess.DEVNULL, capture_output=True)
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False}}))
|
||||
|
||||
def sisi(self, *args, cwd=None, sid=None, stdin="", timeout=30):
|
||||
env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env
|
||||
out_f = os.path.join(self.tmp, "stdout.tmp")
|
||||
err_f = os.path.join(self.tmp, "stderr.tmp")
|
||||
with open(out_f, "w+", encoding="utf-8") as fo, open(err_f, "w+", encoding="utf-8") as fe:
|
||||
r = subprocess.run(
|
||||
[sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args),
|
||||
cwd=cwd or self.proj,
|
||||
env=env,
|
||||
input=stdin,
|
||||
stdout=fo,
|
||||
stderr=fe,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
fo.seek(0)
|
||||
fe.seek(0)
|
||||
return r.returncode, fo.read(), fe.read()
|
||||
|
||||
def write(self, *parts):
|
||||
path = os.path.join(*parts[:-1])
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(parts[-1])
|
||||
return path
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def _seed_rules(self, user_text, proj_text):
|
||||
up = self.write(self.data, "rules", "user.md", user_text)
|
||||
pp = self.write(self.proj, ".sisi", "rules.md", proj_text)
|
||||
return up, pp
|
||||
|
||||
def _organize(self, name, user_text, proj_text, extra="", timeout=30):
|
||||
ans = self.write(self.tmp, name, "## user\n" + user_text + "## project\n" + proj_text + extra)
|
||||
rc_b, out_b, err_b = self.sisi("rules", "organize")
|
||||
self.assertEqual((rc_b, err_b), (0, ""), out_b)
|
||||
return self.sisi("rules", "organize", "--record", ans, timeout=timeout)
|
||||
|
||||
# (1) Second organize --record leaving .sisi/rules.md unchanged, then revert
|
||||
def test_revert_after_second_organize_leaving_project_unchanged(self):
|
||||
up, pp = self._seed_rules(
|
||||
"- User rule one [retro 2026-11-20]\n- User rule two [retro 2026-11-20]\n",
|
||||
"- Keep project rule [owner 2026-11-20]\n",
|
||||
)
|
||||
rc, out, err = self._organize("a1.md", "- User rule first [retro 2026-11-20]\n", "- Keep project rule [owner 2026-11-20]\n")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
rc, out, err = self._organize("a2.md", "- User rule second [retro 2026-11-20]\n", "- Keep project rule [owner 2026-11-20]\n")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
|
||||
rc, out, err = self.sisi("rules", "revert")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertNotIn("missing", out)
|
||||
self.assertIn("undone:", out)
|
||||
self.assertEqual(self.read(up), "- User rule first [retro 2026-11-20]\n")
|
||||
self.assertEqual(self.read(pp), "- Keep project rule [owner 2026-11-20]\n")
|
||||
|
||||
# Second revert re-applies the second organize
|
||||
rc, out, err = self.sisi("rules", "revert")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertEqual(self.read(up), "- User rule second [retro 2026-11-20]\n")
|
||||
self.assertEqual(self.read(pp), "- Keep project rule [owner 2026-11-20]\n")
|
||||
|
||||
def test_revert_after_second_organize_with_only_metadata_change(self):
|
||||
up, pp = self._seed_rules(
|
||||
"- User rule one [retro 2026-11-20]\n",
|
||||
"- Keep project rule [owner 2026-11-20]\n",
|
||||
)
|
||||
rc, out, err = self._organize("a1.md", "- User rule kept [retro 2026-11-20]\n", "- Keep project rule [owner 2026-11-20]\n")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
# Add a retro record so organized.json changes on the second organize while both rule files stay identical
|
||||
self.write(self.data, "retro.jsonl", json.dumps({"ts": "2026-11-21T10:00:00", "no_gap": "ok", "term": "time", "better": "earlier"}) + "\n")
|
||||
rc, out, err = self._organize("a2.md", "- User rule kept [retro 2026-11-20]\n", "- Keep project rule [owner 2026-11-20]\n")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
|
||||
rc, out, err = self.sisi("rules", "revert")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertNotIn("missing", out)
|
||||
self.assertIn("undone:", out)
|
||||
self.assertEqual(self.read(up), "- User rule kept [retro 2026-11-20]\n")
|
||||
self.assertEqual(self.read(pp), "- Keep project rule [owner 2026-11-20]\n")
|
||||
|
||||
# (2) Failed drops.jsonl append during organize --record
|
||||
def test_organize_drops_symlink_refused_before_changes(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
ext = self.write(self.tmp, "outside.jsonl", '{"outside": 1}\n')
|
||||
dp = os.path.join(self.data, "rules", "drops.jsonl")
|
||||
os.symlink(ext, dp)
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertIn("symlink", out)
|
||||
self.assertTrue(os.path.islink(dp))
|
||||
self.assertEqual(self.read(ext), '{"outside": 1}\n')
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_dangling_symlink_refused_before_changes(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
dp = os.path.join(self.data, "rules", "drops.jsonl")
|
||||
os.symlink(os.path.join(self.tmp, "missing.jsonl"), dp)
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertIn("symlink", out)
|
||||
self.assertTrue(os.path.islink(dp))
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_readonly_refused_before_changes(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
dp = self.write(self.data, "rules", "drops.jsonl", '{"prior": 1}\n')
|
||||
os.chmod(dp, 0o444)
|
||||
self.addCleanup(lambda: os.path.exists(dp) and os.chmod(dp, 0o644))
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertEqual(self.read(dp), '{"prior": 1}\n')
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_unreadable_refused_without_wiping_history(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
dp = self.write(self.data, "rules", "drops.jsonl", '{"prior": 1}\n')
|
||||
os.chmod(dp, 0o000)
|
||||
self.addCleanup(lambda: os.path.exists(dp) and os.chmod(dp, 0o644))
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
os.chmod(dp, 0o644)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertEqual(self.read(dp), '{"prior": 1}\n')
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_directory_refused_before_changes(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
dp = os.path.join(self.data, "rules", "drops.jsonl")
|
||||
os.mkdir(dp)
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertTrue(os.path.isdir(dp))
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_readonly_rules_dir_no_half_written_state(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule to drop [retro 2026-11-20]\n- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
rules_dir = os.path.join(self.data, "rules")
|
||||
os.chmod(rules_dir, 0o555)
|
||||
self.addCleanup(lambda: os.path.exists(rules_dir) and os.chmod(rules_dir, 0o755))
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", "- Project rule kept [owner 2026-11-20]\n")
|
||||
os.chmod(rules_dir, 0o755)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
self.assertFalse(os.path.exists(os.path.join(rules_dir, "drops.jsonl")))
|
||||
|
||||
def test_organize_drops_writeonly_refused_without_wiping_history(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
dp = self.write(self.data, "rules", "drops.jsonl", '{"prior": 1}\n')
|
||||
os.chmod(dp, 0o200)
|
||||
self.addCleanup(lambda: os.path.exists(dp) and os.chmod(dp, 0o644))
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
os.chmod(dp, 0o644)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertEqual(self.read(dp), '{"prior": 1}\n')
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_fifo_refused_without_hanging(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
ans = self.write(self.tmp, "a.md", "## user\n- User rule kept [owner 2026-11-20]\n## project\n" + p_before)
|
||||
self.assertEqual(self.sisi("rules", "organize")[0], 0)
|
||||
dp = os.path.join(self.data, "rules", "drops.jsonl")
|
||||
os.mkfifo(dp)
|
||||
|
||||
rc, out, err = self.sisi("rules", "organize", "--record", ans, timeout=2)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertIn("not a regular file", out)
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
def test_organize_drops_over_64kb_still_succeeds(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
big_line = json.dumps({"ts": "2026-11-01T00:00:00", "rule": "x" * 200, "problem": None, "reason": "old"}) + "\n"
|
||||
dp = self.write(self.data, "rules", "drops.jsonl", big_line * 300) # > 64,000 bytes
|
||||
self.assertGreater(os.path.getsize(dp), 64000)
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
lines = self.read(dp).splitlines()
|
||||
self.assertEqual(len(lines), 301)
|
||||
self.assertEqual(json.loads(lines[-1])["rule"], "- User rule to drop [retro 2026-11-20]")
|
||||
|
||||
def test_organize_drops_over_limit_refused_before_changes(self):
|
||||
u_before = "- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n"
|
||||
p_before = "- Project rule kept [owner 2026-11-20]\n"
|
||||
up, pp = self._seed_rules(u_before, p_before)
|
||||
dp = self.write(self.data, "rules", "drops.jsonl", "x\n" * 1000005) # > 2,000,000 bytes
|
||||
|
||||
rc, out, err = self._organize("a.md", "- User rule kept [owner 2026-11-20]\n", p_before)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertNotIn("Traceback", out + err)
|
||||
self.assertEqual(self.read(up), u_before)
|
||||
self.assertEqual(self.read(pp), p_before)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Tests for `sisi judge --chore ID`, multi-job warnings, and stop-gate unjudged job lines.
|
||||
Black-box CLI tests in a temporary home and store."""
|
||||
import glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, time, unittest
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
HEADER = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n"
|
||||
ALPHA = "| alpha | host subagent model `alpha` | routine | free | quick | |\n"
|
||||
BETA = "| beta | host subagent model `beta` | routine | free | quick | |\n"
|
||||
|
||||
|
||||
def tree():
|
||||
"""A fingerprint of the product tree, so a test that writes into it is caught."""
|
||||
out = hashlib.sha1()
|
||||
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
|
||||
if os.path.isfile(p):
|
||||
with open(p, "rb") as f:
|
||||
out.update(p.encode() + f.read())
|
||||
return out.hexdigest()
|
||||
|
||||
|
||||
class JudgeChore(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine,
|
||||
"a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-test-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
os.makedirs(self.data)
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": True}}))
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=os.path.join(self.tmp, "state"),
|
||||
SISI_LIB=os.path.join(self.tmp, "lib"), CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME",
|
||||
"CLAUDE_CODE_ENTRYPOINT"):
|
||||
self.env.pop(name, None)
|
||||
self.proj = os.path.join(self.tmp, "proj")
|
||||
os.makedirs(self.proj)
|
||||
subprocess.run(["git", "init", "-q"], cwd=self.proj, check=True, capture_output=True)
|
||||
self.write(os.path.join(self.data, "models.md"), HEADER + ALPHA + BETA)
|
||||
os.makedirs(os.path.join(self.data, "offered"), exist_ok=True)
|
||||
self.write(os.path.join(self.data, "offered", "unknown.txt"),
|
||||
"listed %s by harness unknown\nalpha\nbeta\n" % time.strftime("%Y-%m-%dT%H:%M:%S"))
|
||||
self.hook("tick")
|
||||
self.hook("prompt", prompt="work on the project")
|
||||
rc, out, err = self.sisi("done", "--goal", "ship the chore judging fix cleanly",
|
||||
"--check", "chore judging tests pass cleanly",
|
||||
"--next", "run the full suite next")
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def write(self, path, text):
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return path
|
||||
|
||||
def sisi(self, *args, sid="s1", stdin=""):
|
||||
env = dict(self.env, SISI_SESSION_ID=sid)
|
||||
r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args), cwd=self.proj,
|
||||
env=env, input=stdin, capture_output=True, text=True)
|
||||
return r.returncode, r.stdout, r.stderr
|
||||
|
||||
def hook(self, cmd, sid="s1", **payload):
|
||||
body = json.dumps({"session_id": sid, "cwd": self.proj, **payload})
|
||||
return self.sisi(cmd, sid=sid, stdin=body)
|
||||
|
||||
def tool(self, name, sid="s1", tool_input=None):
|
||||
return self.hook("watch", sid=sid, hook_event_name="PreToolUse", tool_name=name, tool_input=tool_input or {})
|
||||
|
||||
def state(self, sid="s1"):
|
||||
return json.loads(self.read(self.tmp, "state", "core-sessions", sid + ".json"))
|
||||
|
||||
def outcomes(self):
|
||||
path = os.path.join(self.data, "outcomes.jsonl")
|
||||
return [json.loads(l) for l in self.read(path).splitlines() if l.strip()] if os.path.exists(path) else []
|
||||
|
||||
def start_chore(self, *cmd, worker="alpha"):
|
||||
rc, brief, err = self.sisi(*cmd)
|
||||
self.assertEqual(rc, 0, brief + err)
|
||||
m = re.match(r"sisi chore: .+? ([0-9a-f]{8})\b", brief.splitlines()[0])
|
||||
self.assertIsNotNone(m, brief)
|
||||
cid = m.group(1)
|
||||
rc_p, out_p, err_p = self.sisi("pick", "routine", "--not", "beta" if worker == "alpha" else "alpha")
|
||||
self.assertEqual(rc_p, 0, out_p + err_p)
|
||||
prompt = "%s\nRun `sisi chore show %s` and do what it says." % (brief.splitlines()[0], cid)
|
||||
rc_t, out_t, err_t = self.tool("Agent", tool_input={"model": worker, "prompt": prompt})
|
||||
self.assertEqual((rc_t, out_t), (0, ""), out_t + err_t)
|
||||
return cid
|
||||
|
||||
def test_1_judge_chore_closes_only_named_chore_and_refuses_unknown(self):
|
||||
cid1 = self.start_chore("plan", "brief")
|
||||
time.sleep(0.02)
|
||||
cid2 = self.start_chore("models", "research")
|
||||
starts = self.state()["starts"]["alpha"]
|
||||
self.assertEqual(len(starts), 2)
|
||||
t1, t2 = starts
|
||||
|
||||
before_state, before_out = self.state(), self.outcomes()
|
||||
for bad in (("good", "finished the chore cleanly", "--chore", "deadbeef"),
|
||||
("extend", "30", "needs more time here", "--chore", "deadbeef")):
|
||||
rc, out, _ = self.sisi("judge", "alpha", *bad)
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertEqual(len(out.strip().splitlines()), 1, out)
|
||||
self.assertIn(cid1, out)
|
||||
self.assertIn(cid2, out)
|
||||
rc_missing, out_missing, _ = self.sisi("judge", "alpha", "good", "finished the chore cleanly", "--chore")
|
||||
self.assertEqual(rc_missing, 1, out_missing)
|
||||
self.assertEqual((self.state(), self.outcomes()), (before_state, before_out))
|
||||
|
||||
rc_ext, out_ext, _ = self.sisi("judge", "alpha", "extend", "30", "needs more time here", "--chore", cid2)
|
||||
self.assertEqual(rc_ext, 0, out_ext)
|
||||
self.assertIn("extended alpha limit to 30 min.", out_ext)
|
||||
self.assertEqual(self.state()["meta"]["alpha %r" % t2].get("limit"), 30)
|
||||
self.assertIsNone(self.state()["meta"]["alpha %r" % t1].get("limit"))
|
||||
|
||||
rc_j, out_j, _ = self.sisi("judge", "alpha", "good", "models research finished cleanly", "--chore", cid2)
|
||||
self.assertEqual(rc_j, 0, out_j)
|
||||
self.assertEqual(self.state()["starts"]["alpha"], [t1])
|
||||
self.assertEqual(self.outcomes()[-1]["started"], time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t2)))
|
||||
|
||||
rc_again, out_again, _ = self.sisi("judge", "alpha", "good", "trying to judge closed chore", "--chore", cid2)
|
||||
self.assertEqual(rc_again, 1, out_again)
|
||||
self.assertEqual(len(out_again.strip().splitlines()), 1, out_again)
|
||||
self.assertIn(cid1, out_again)
|
||||
|
||||
rc_j1, out_j1, _ = self.sisi("judge", "alpha", "good", "plan brief finished cleanly", "--chore", cid1)
|
||||
self.assertEqual(rc_j1, 0, out_j1)
|
||||
self.assertEqual(self.state()["starts"]["alpha"], [])
|
||||
|
||||
def test_2_judge_without_flag_warns_with_closed_and_open_targets(self):
|
||||
cid1 = self.start_chore("plan", "brief")
|
||||
time.sleep(0.02)
|
||||
cid2 = self.start_chore("models", "research")
|
||||
t1, t2 = self.state()["starts"]["alpha"]
|
||||
|
||||
rc, out, _ = self.sisi("judge", "alpha", "good", "oldest chore finished cleanly")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(self.state()["starts"]["alpha"], [t2])
|
||||
lines = out.strip().splitlines()
|
||||
self.assertEqual(len(lines), 2, out)
|
||||
self.assertIn("job started %s" % time.strftime("%H:%M", time.localtime(t1)), lines[0])
|
||||
self.assertIn(cid1, lines[1])
|
||||
self.assertIn(cid2, lines[1])
|
||||
self.assertIn("--chore " + cid2, lines[1])
|
||||
|
||||
def test_3_stop_gate_lists_unjudged_jobs_on_one_line_without_blocking_on_them(self):
|
||||
graph = ("| node | class | needs | branch | files | check | why |\n|---|---|---|---|---|---|---|\n"
|
||||
"| a | routine | - | feat-a | sisi/a.py | test a passes | exact spec |\n"
|
||||
"| join | lead | a | - | - | suite passes | lead joins |\n")
|
||||
rc, out, _ = self.sisi("plan", "--record", self.write(os.path.join(self.tmp, "plan.md"), graph))
|
||||
self.assertEqual(rc, 0, out)
|
||||
rc_p, out_p, _ = self.sisi("pick", "--node", "a", "--not", "beta")
|
||||
self.assertEqual(rc_p, 0, out_p)
|
||||
self.assertEqual(self.tool("Agent", tool_input={"model": "alpha", "prompt": "sisi node: a\nDo node a."})[1], "")
|
||||
cid = self.start_chore("models", "research", worker="beta")
|
||||
ta = self.state()["starts"]["alpha"][0]
|
||||
tb = self.state()["starts"]["beta"][0]
|
||||
|
||||
# Open checks while workers run: stop gate does not block on unjudged jobs.
|
||||
self.assertEqual(self.hook("gate")[1], "")
|
||||
|
||||
# When the stop gate already blocks (e.g. changed files + passed checks, no retro yet),
|
||||
# it appends one line listing unjudged jobs in WORKER (node X | chore Y, started HH:MM) form.
|
||||
self.tool("Edit")
|
||||
self.assertEqual(self.sisi("done", "--pass", "1", "chore judging tests pass cleanly")[0], 0)
|
||||
rc_g, out_g, _ = self.hook("gate")
|
||||
self.assertEqual(rc_g, 0, out_g)
|
||||
doc = json.loads(out_g)
|
||||
self.assertEqual(doc["decision"], "block")
|
||||
extra_lines = [l for l in doc["reason"].splitlines() if "alpha (" in l or "beta (" in l]
|
||||
self.assertEqual(len(extra_lines), 1, doc["reason"])
|
||||
self.assertIn("alpha (node a, started %s)" % time.strftime("%H:%M", time.localtime(ta)), extra_lines[0])
|
||||
self.assertIn("beta (chore %s, started %s)" % (cid, time.strftime("%H:%M", time.localtime(tb))), extra_lines[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,192 @@
|
||||
"""`sisi pick` only returns models the running harness offers: the harness's raw model list is the source of truth,
|
||||
the researched table is a hint. Black-box CLI tests in a temporary home and store."""
|
||||
import glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, unittest
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
HEADER = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n"
|
||||
ALPHA = "| alpha | host subagent model `alpha` | routine | free | quick | |\n"
|
||||
BETA = "| beta | host subagent model `beta` | routine | free | quick | |\n"
|
||||
GAMMA = "| gamma | host subagent model `gamma` | routine | free | quick | |\n"
|
||||
RAW = "alpha\nbeta\n"
|
||||
|
||||
|
||||
def tree():
|
||||
"""A fingerprint of the product tree, so a test that writes into it is caught."""
|
||||
out = hashlib.sha1()
|
||||
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
|
||||
if os.path.isfile(p):
|
||||
with open(p, "rb") as f:
|
||||
out.update(p.encode() + f.read())
|
||||
return out.hexdigest()
|
||||
|
||||
|
||||
class Offered(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine,
|
||||
"a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-test-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
os.makedirs(self.data)
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False}}))
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=os.path.join(self.tmp, "state"),
|
||||
SISI_LIB=os.path.join(self.tmp, "lib"), CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME",
|
||||
"CLAUDE_CODE_ENTRYPOINT"):
|
||||
self.env.pop(name, None) # the harness is "unknown" unless a test sets it
|
||||
self.proj = os.path.join(self.tmp, "proj")
|
||||
os.makedirs(self.proj)
|
||||
subprocess.run(["git", "init", "-q"], cwd=self.proj, check=True, capture_output=True)
|
||||
|
||||
def sisi(self, *args, stdin="", env=None):
|
||||
r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args), cwd=self.proj,
|
||||
env=env or self.env, input=stdin, capture_output=True, text=True)
|
||||
return r.returncode, r.stdout, r.stderr
|
||||
|
||||
def table(self, text):
|
||||
self.write(os.path.join(self.data, "models.md"), text)
|
||||
|
||||
def offered_file(self, raw, harness="unknown", when=None):
|
||||
"""A stored list as `sisi models offered` writes it: a dated header line, then the raw text."""
|
||||
when = when or datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
os.makedirs(os.path.join(self.data, "offered"), exist_ok=True)
|
||||
self.write(os.path.join(self.data, "offered", harness + ".txt"), "listed %s by harness %s\n%s" % (when, harness, raw))
|
||||
|
||||
def picked(self, out):
|
||||
m = re.search(r"^worker: (\S+)", out, re.M)
|
||||
return m.group(1) if m else None
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def write(self, path, text):
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return path
|
||||
|
||||
def test_1_no_list_refuses_the_pick_with_one_line_naming_the_command(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
rc, out, _ = self.sisi("pick", "routine")
|
||||
self.assertEqual(rc, 1, out)
|
||||
lines = out.splitlines()
|
||||
self.assertEqual(len(lines), 1, out)
|
||||
self.assertIn("sisi models offered", lines[0])
|
||||
|
||||
def test_2_only_listed_workers_are_ever_picked(self):
|
||||
self.table(HEADER + GAMMA + ALPHA + BETA) # gamma is first in the table's order and is not on the list
|
||||
self.offered_file(RAW)
|
||||
seen = set()
|
||||
for _ in range(30):
|
||||
rc, out, _ = self.sisi("pick", "routine")
|
||||
self.assertEqual(rc, 0, out)
|
||||
seen.add(self.picked(out))
|
||||
self.assertNotIn("gamma", seen)
|
||||
self.assertTrue(seen <= {"alpha", "beta"}, seen)
|
||||
|
||||
def test_3_a_list_older_than_24_hours_refuses_the_pick(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
old = (datetime.now() - timedelta(hours=25)).strftime("%Y-%m-%dT%H:%M:%S")
|
||||
self.offered_file(RAW, when=old)
|
||||
rc, out, _ = self.sisi("pick", "routine")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("h old", out)
|
||||
|
||||
def test_4_a_list_stored_for_unknown_does_not_serve_another_harness(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
self.offered_file(RAW) # stored for "unknown"
|
||||
env = dict(self.env, CLAUDE_CODE_ENTRYPOINT="x")
|
||||
rc, out, _ = self.sisi("pick", "routine", env=env)
|
||||
self.assertEqual(rc, 1, out)
|
||||
|
||||
def test_5_a_record_naming_an_id_absent_from_the_list_changes_nothing(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
rc, out, err = self.sisi("models", "offered", stdin=RAW)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
bad = self.write(os.path.join(self.tmp, "bad.md"), HEADER + "| ghost | `ghost run \"<brief>\"` | routine | free | quick | |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", bad)
|
||||
self.assertEqual(rc, 1, out + err)
|
||||
self.assertIn("Nothing was changed", out + err)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.data, "offered", "unknown.wheel.md")))
|
||||
|
||||
def test_6_a_valid_record_makes_pick_print_the_wheel_rows_call(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
self.sisi("models", "offered", stdin=RAW)
|
||||
cell = "`alpha run \"<brief>\"`"
|
||||
good = self.write(os.path.join(self.tmp, "good.md"), HEADER + "| alpha | %s | routine | free | quick | |\n" % cell)
|
||||
rc, out, err = self.sisi("models", "offered", "--record", good)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
self.assertTrue(os.path.exists(os.path.join(self.data, "offered", "unknown.wheel.md")))
|
||||
rc, out, _ = self.sisi("pick", "routine")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("how to call it: " + cell, out)
|
||||
|
||||
def test_7_piped_list_prints_the_chore_line_with_an_id(self):
|
||||
self.table(HEADER + ALPHA)
|
||||
rc, out, err = self.sisi("models", "offered", stdin="list\n")
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
self.assertRegex(out, r"sisi chore: models offered [0-9a-f]{8}")
|
||||
|
||||
def test_8_a_provisional_row_for_a_new_offered_model_gets_picked(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
self.offered_file("alpha\nsubq/subq-savant-latest\n")
|
||||
cell = "`opencode run -m subq/subq-savant-latest \"<brief>\"`"
|
||||
rec = self.write(os.path.join(self.tmp, "rec.md"), HEADER + ALPHA +
|
||||
"| subq/subq-savant-latest | %s | routine | free trial | fast | new: listed by the harness, not yet researched |\n" % cell)
|
||||
rc, out, err = self.sisi("models", "offered", "--record", rec)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
self.assertIn("sisi models research", out + err)
|
||||
seen = set()
|
||||
for _ in range(30):
|
||||
rc, out, _ = self.sisi("pick", "routine")
|
||||
self.assertEqual(rc, 0, out)
|
||||
seen.add(self.picked(out))
|
||||
self.assertIn("subq/subq-savant-latest", seen)
|
||||
|
||||
def test_9_provider_prefix_slash_and_comma_boundaries_accepted_while_suffix_slash_rejected(self):
|
||||
self.sisi("models", "offered", stdin="opencode-go/deepseek-v4.1-flash\ngemini-2.5/extra\n")
|
||||
good = self.write(os.path.join(self.tmp, "good.md"), HEADER +
|
||||
"| deepseek-v4.1-flash | `delegate_task model=opencode-go/deepseek-v4.1-flash, fast` | routine | free | fast | |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", good)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
bad = self.write(os.path.join(self.tmp, "bad.md"), HEADER +
|
||||
"| gemini-2.5 | `delegate_task model=gemini-2.5` | routine | free | fast | |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", bad)
|
||||
self.assertEqual(rc, 1, out + err)
|
||||
|
||||
def test_10_models_offered_chore_allowed_with_default_subagent_while_research_chore_requires_pick(self):
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": True}}))
|
||||
self.table(HEADER + ALPHA)
|
||||
e = dict(self.env, SISI_SESSION_ID="s1")
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": "s1", "cwd": self.proj}), env=e)
|
||||
self.sisi("prompt", stdin=json.dumps({"session_id": "s1", "cwd": self.proj, "prompt": "go"}), env=e)
|
||||
self.sisi("done", "--goal", "ship the change cleanly", "--check", "unit tests pass cleanly", "--next", "merge to main", env=e)
|
||||
rc, out, _ = self.sisi("models", "offered", stdin="gamma\n", env=e)
|
||||
self.assertEqual(rc, 0, out)
|
||||
chore_line = out.splitlines()[0]
|
||||
rc_p, out_p, _ = self.sisi("pick", "routine", env=e)
|
||||
self.assertEqual(rc_p, 1, out_p)
|
||||
self.assertIn("hand the printed `models offered` chore to any model the host offers", out_p)
|
||||
_, out_w, _ = self.sisi("watch", stdin=json.dumps({
|
||||
"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse",
|
||||
"tool_name": "Agent", "tool_input": {"prompt": chore_line + "\nRun `sisi chore show`"},
|
||||
}), env=e)
|
||||
self.assertEqual(out_w.strip(), "", out_w)
|
||||
rc_r, out_r, _ = self.sisi("models", "research", env=e)
|
||||
self.assertEqual(rc_r, 0, out_r)
|
||||
res_line = out_r.splitlines()[0]
|
||||
_, out_w2, _ = self.sisi("watch", stdin=json.dumps({
|
||||
"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse",
|
||||
"tool_name": "Agent", "tool_input": {"prompt": res_line + "\nRun `sisi chore show`"},
|
||||
}), env=e)
|
||||
self.assertEqual(json.loads(out_w2)["hookSpecificOutput"]["permissionDecision"], "deny", out_w2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Tests for the efficiency-first models table: one row per provider per class, each with its evidence."""
|
||||
import contextlib
|
||||
import glob
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
sys.path.insert(0, REPO)
|
||||
from sisi import models, store
|
||||
|
||||
HEAD = ("| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |\n"
|
||||
"|---|---|---|---|---|---|---|---|---|\n")
|
||||
GO = "| go/qwen-flash | OpenCode Go | qwen | `opencode run -m go/qwen-flash \"<brief>\"` | routine | flat | 5,400 per 5h, 16,200 per week (https://example.test/go) | fast | |\n"
|
||||
ZAI = "| zai/glm-5 | z.ai coding plan | zhipu | `opencode run -m zai/glm-5 \"<brief>\"` | hard | flat | 600 prompts per 5h (https://example.test/zai) | strong | |\n"
|
||||
HOST = "| sonnet | Anthropic | anthropic | host subagent `sonnet` | ordinary | per use | measured: 12 good jobs at $0.40 each | broad | |\n"
|
||||
FALL = "Fallback order: routine: go/qwen-flash; ordinary: sonnet; hard: zai/glm-5.\n"
|
||||
|
||||
|
||||
def offered(data_dir, text):
|
||||
"""The offered-models list for the current harness, written beside models.md: pick refuses without it."""
|
||||
path = os.path.join(data_dir, "offered", "unknown.txt")
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write("listed %s by harness unknown\n%s" % (time.strftime("%Y-%m-%dT%H:%M:%S"), text))
|
||||
return path
|
||||
|
||||
|
||||
def tree():
|
||||
out = hashlib.sha1()
|
||||
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
|
||||
if os.path.isfile(p):
|
||||
with open(p, "rb") as f:
|
||||
out.update(p.encode() + f.read())
|
||||
return out.hexdigest()
|
||||
|
||||
|
||||
class ModelsResearch(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-models-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data,
|
||||
SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"),
|
||||
CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME", "CLAUDE_CODE_ENTRYPOINT"):
|
||||
self.env.pop(name, None)
|
||||
subprocess.run(["git", "init", "-q", self.data], check=True, capture_output=True, stdin=subprocess.DEVNULL)
|
||||
|
||||
def in_process(self, fn, *args):
|
||||
out, here = io.StringIO(), os.getcwd()
|
||||
os.chdir(self.tmp)
|
||||
try:
|
||||
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \
|
||||
mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \
|
||||
mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out):
|
||||
return fn(*args), out.getvalue()
|
||||
finally:
|
||||
os.chdir(here)
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def record(self, text):
|
||||
path = os.path.join(self.tmp, "answer.md")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return self.in_process(models.run, ["research", "--record", path])
|
||||
|
||||
def table(self):
|
||||
p = os.path.join(self.data, "models.md")
|
||||
return self.read(p) if os.path.exists(p) else None
|
||||
|
||||
def test_rows_read_provider_and_efficiency_and_keep_old_indices(self):
|
||||
r = models.rows(HEAD + GO)[0]
|
||||
self.assertEqual(r[6], "qwen") # maker stays at index 6
|
||||
self.assertEqual(r[7], "OpenCode Go")
|
||||
self.assertIn("5,400 per 5h", r[8])
|
||||
self.assertEqual(r[:3], ["go/qwen-flash", "`opencode run -m go/qwen-flash \"<brief>\"`", "routine"])
|
||||
old = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n| a | x | hard | flat | y | z |\n"
|
||||
self.assertEqual(models.rows(old)[0][7:], ["", ""]) # an older table still parses
|
||||
|
||||
def test_two_plans_behind_one_cli_record_as_two_providers(self):
|
||||
rc, out = self.record(HEAD + GO + ZAI + HOST + FALL)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual({r[7] for r in models.rows(self.table())}, {"OpenCode Go", "z.ai coding plan", "Anthropic"})
|
||||
|
||||
def test_refuses_a_missing_provider_column(self):
|
||||
old = ("| worker | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |\n|---|---|---|---|---|---|---|---|\n"
|
||||
"| a | x | host subagent `a` | hard | flat | 100 per day (https://example.test) | y | |\n")
|
||||
rc, out = self.record(old + FALL)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("provider", out)
|
||||
self.assertIn("Nothing was changed", out)
|
||||
self.assertIsNone(self.table())
|
||||
|
||||
def test_refuses_an_empty_provider_or_efficiency_cell_naming_the_row(self):
|
||||
for row in (GO.replace("| OpenCode Go |", "| |"), GO.replace("| 5,400 per 5h, 16,200 per week (https://example.test/go) |", "| |")):
|
||||
rc, out = self.record(HEAD + row + ZAI + FALL)
|
||||
self.assertEqual(rc, 1, row)
|
||||
self.assertIn("go/qwen-flash", out)
|
||||
self.assertIn("Nothing was changed", out)
|
||||
self.assertIsNone(self.table())
|
||||
|
||||
def test_refuses_two_rows_of_one_provider_in_one_class(self):
|
||||
twin = GO.replace("go/qwen-flash", "go/hy4-flash").replace("| OpenCode Go |", "| opencode GO |")
|
||||
rc, out = self.record(HEAD + GO + twin + FALL)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("go/qwen-flash", out)
|
||||
self.assertIn("go/hy4-flash", out)
|
||||
self.assertIsNone(self.table())
|
||||
other = twin.replace("| routine |", "| ordinary |") # the same provider in another class is fine
|
||||
self.assertEqual(self.record(HEAD + GO + other + FALL)[0], 0)
|
||||
|
||||
def test_brief_asks_for_provider_efficiency_and_one_row_per_provider_class(self):
|
||||
rc, brief = self.in_process(models.run, ["research"])
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertRegex(brief.splitlines()[0], r"^sisi chore: models research [0-9a-f]{8}$")
|
||||
self.assertIn("| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |", brief)
|
||||
self.assertIn("at most one row per provider per class", brief.lower())
|
||||
self.assertIn("most efficient first", brief.lower())
|
||||
self.assertIn("separate provider", brief.lower())
|
||||
with mock.patch.object(models, "_shared_date", return_value=("2000-01-01", 0.0)): # the stale variant too
|
||||
stale = self.in_process(models.research_brief)[0]
|
||||
with mock.patch.object(models, "_shared_date", return_value=("2999-01-01", 4e10)):
|
||||
fresh = self.in_process(models.research_brief)[0]
|
||||
self.assertNotEqual(stale, fresh)
|
||||
for b in (stale, fresh):
|
||||
self.assertTrue(b.startswith("sisi chore: models research\n"))
|
||||
self.assertIn("| worker | provider | maker |", b)
|
||||
self.assertIn("efficiency", b)
|
||||
|
||||
def test_ask_sends_the_brief_to_a_hard_worker_and_research_is_kept_current(self):
|
||||
self.assertIn("sisi pick hard", models.ASK)
|
||||
self.assertIn("web", models.ASK)
|
||||
self.assertEqual(store.DEFAULTS["research_days"], 3)
|
||||
|
||||
def test_budget_parser_reads_request_windows_only(self):
|
||||
self.assertEqual(models.budgets("5h: 60,700 req; week: 121,000 req (https://example.test/go)"), {"5h": 60700, "week": 121000})
|
||||
self.assertEqual(models.budgets("month: 300 prompts"), {"month": 300})
|
||||
self.assertEqual(models.budgets("5h: 2,000,000 tokens; week: 0 req"), {}) # tokens do not map to delegations
|
||||
self.assertEqual(models.budgets("flat plan, no numbers"), {})
|
||||
|
||||
def use_log(self, worker, n, hours_ago=1):
|
||||
import json, time
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
t = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(time.time() - hours_ago * 3600))
|
||||
with open(os.path.join(self.data, "outcomes.jsonl"), "a", encoding="utf-8") as f:
|
||||
for _ in range(n):
|
||||
f.write(json.dumps({"ts": t, "started": t, "worker": worker, "model": worker, "verdict": "good", "why": "did it well"}) + "\n")
|
||||
|
||||
BUSY = HEAD + ("| a/one | Plan A | qwen | `a one \"<brief>\"` | routine | flat | 5h: 10 req; week: 40 req (https://example.test/a) | x | |\n"
|
||||
"| b/two | Plan B | zhipu | `b two \"<brief>\"` | routine | flat | 5h: 10 req; week: 40 req (https://example.test/b) | x | |\n")
|
||||
|
||||
def test_a_heavily_used_plan_is_picked_less_and_never_below_the_floor(self):
|
||||
import random
|
||||
self.use_log("a/one", 8) # plan A: 80% of its 5h window spent
|
||||
use = self.in_process(models.plan_use, self.BUSY)[0]
|
||||
self.assertAlmostEqual(use["plan a"]["5h"], 0.8)
|
||||
self.assertAlmostEqual(use["plan a"]["week"], 0.2)
|
||||
self.assertEqual(use["plan b"], {"5h": 0.0, "week": 0.0})
|
||||
share = models.shares(use)
|
||||
self.assertAlmostEqual(share["plan a"], 0.2)
|
||||
rng = random.Random(1)
|
||||
picks = [models.choose(self.BUSY, "routine", rand=rng.random, share=share)[0] for _ in range(2000)]
|
||||
self.assertLess(picks.count("a/one"), picks.count("b/two") / 2) # without share a/one, listed first, wins 2:1
|
||||
self.use_log("a/one", 50) # past the whole allowance: the floor holds
|
||||
share = models.shares(self.in_process(models.plan_use, self.BUSY)[0])
|
||||
self.assertEqual(share["plan a"], models.FLOOR)
|
||||
picks = [models.choose(self.BUSY, "routine", rand=rng.random, share=share)[0] for _ in range(4000)]
|
||||
self.assertGreater(picks.count("a/one"), 0)
|
||||
|
||||
def test_two_models_of_one_plan_spend_the_same_windows(self):
|
||||
both = self.BUSY + "| a/big | Plan A | qwen | `a big \"<brief>\"` | hard | flat | 5h: 2 req; month: 4 req (https://example.test/a) | x | |\n"
|
||||
self.use_log("a/one", 1)
|
||||
self.use_log("a/big", 1)
|
||||
use = self.in_process(models.plan_use, both)[0]["plan a"]
|
||||
self.assertEqual({k: round(v, 3) for k, v in use.items()}, {"5h": 0.6, "week": 0.025, "month": 0.25})
|
||||
|
||||
def test_old_delegations_leave_the_window_and_models_prints_plan_use(self):
|
||||
self.use_log("a/one", 5, hours_ago=6) # outside 5h, inside the week
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
with open(os.path.join(self.data, "models.md"), "w", encoding="utf-8") as f:
|
||||
f.write(self.BUSY)
|
||||
offered(self.data, self.BUSY)
|
||||
use = self.in_process(models.plan_use, self.BUSY)[0]
|
||||
self.assertEqual((use["plan a"]["5h"], use["plan a"]["week"]), (0.0, 0.125))
|
||||
out = self.in_process(models.run, [])[1]
|
||||
self.assertIn("Plan use by sisi's own delegations", out)
|
||||
self.assertIn("plan a: 5h 0%, week 12%", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Adversarial attack tests for `sisi models offered` / `wheel()` / `pick()` / `judge()` / `hooks.watch`.
|
||||
|
||||
Tests that reproduce a bug assert the expected (safe) behavior so they FAIL while the bug is present.
|
||||
Tests for probes with no break found verify the invariant holds and PASS."""
|
||||
import glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, unittest
|
||||
from datetime import datetime
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
HEADER = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n"
|
||||
ALPHA = "| alpha | host subagent model `alpha` | routine | free | quick | |\n"
|
||||
BETA = "| beta | host subagent model `beta` | routine | free | quick | |\n"
|
||||
|
||||
|
||||
def tree():
|
||||
"""A fingerprint of the product tree, so a test that writes into it is caught."""
|
||||
out = hashlib.sha1()
|
||||
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
|
||||
if os.path.isfile(p):
|
||||
with open(p, "rb") as f:
|
||||
out.update(p.encode() + f.read())
|
||||
return out.hexdigest()
|
||||
|
||||
|
||||
class OfferedAttacks(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine,
|
||||
"a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-attack-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.state = os.path.join(self.tmp, "state")
|
||||
os.makedirs(self.data)
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=self.state,
|
||||
SISI_LIB=os.path.join(self.tmp, "lib"), CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME",
|
||||
"CLAUDE_CODE_ENTRYPOINT", "ANTIGRAVITY_AGENT", "T3CODE_THREAD_ID"):
|
||||
self.env.pop(name, None)
|
||||
self.proj = os.path.join(self.tmp, "proj")
|
||||
os.makedirs(self.proj)
|
||||
subprocess.run(["git", "init", "-q"], cwd=self.proj, check=True, capture_output=True)
|
||||
|
||||
def sisi(self, *args, stdin="", env=None):
|
||||
r = subprocess.run([sys.executable, "-B", os.path.join(REPO, "bin", "sisi")] + list(args), cwd=self.proj,
|
||||
env=env or self.env, input=stdin, capture_output=True, text=True)
|
||||
return r.returncode, r.stdout, r.stderr
|
||||
|
||||
def hook(self, event, payload, env=None):
|
||||
rc, out, err = self.sisi(event, stdin=json.dumps(payload), env=env)
|
||||
return rc, (json.loads(out) if out.strip() else {}), err
|
||||
|
||||
def table(self, text):
|
||||
self.write(os.path.join(self.data, "models.md"), text)
|
||||
|
||||
def write(self, path, text):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return path
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def offered_file(self, raw, harness="unknown", when=None):
|
||||
when = when or datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
self.write(os.path.join(self.data, "offered", harness + ".txt"), "listed %s by harness %s\n%s" % (when, harness, raw))
|
||||
|
||||
def start_session(self, sid="s1", env=None):
|
||||
e = dict(env or self.env, SISI_SESSION_ID=sid)
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj}), env=e)
|
||||
self.sisi("prompt", stdin=json.dumps({"session_id": sid, "cwd": self.proj, "prompt": "implement the feature"}), env=e)
|
||||
rc, out, err = self.sisi("done", "--goal", "ship the requested change cleanly", "--check",
|
||||
"relevant unit tests pass cleanly", "--next", "merge into main branch", env=e)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
return e
|
||||
|
||||
# --- Probe 1: id passes verbatim check without really being offered ---
|
||||
|
||||
@unittest.skip("Known limit (P1.1): cannot parse every host's list format; brief forbids disabled providers and 'default' ids, and bad rows are judged out.")
|
||||
def test_probe1_disabled_provider_model_and_default_should_be_rejected(self):
|
||||
raw = (
|
||||
"Provider: openai-1\n"
|
||||
"Status: Provider instance is disabled\n"
|
||||
"Models:\n"
|
||||
" - gpt-5.4\n"
|
||||
" - default\n"
|
||||
"Provider: anthropic-1\n"
|
||||
"Status: enabled\n"
|
||||
"Models:\n"
|
||||
" - claude-haiku-4\n"
|
||||
)
|
||||
rc, out, err = self.sisi("models", "offered", stdin=raw)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
bad = self.write(os.path.join(self.tmp, "bad.md"), HEADER +
|
||||
"| gpt-5.4 | `delegate_task target.model=gpt-5.4` | ordinary | paid | strong | |\n"
|
||||
"| default | `delegate_task target.model=default` | routine | free | fast | |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", bad)
|
||||
self.assertEqual(rc, 1, "disabled provider models should be rejected, got: " + out + err)
|
||||
|
||||
def test_probe1_substring_before_non_word_punctuation_should_be_rejected(self):
|
||||
rc, out, err = self.sisi("models", "offered", stdin="claude-sonnet+thinking\ngemini-2.5(free)\n")
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
bad = self.write(os.path.join(self.tmp, "bad.md"), HEADER +
|
||||
"| claude-sonnet | `delegate_task model=claude-sonnet` | ordinary | paid | strong | new: substring |\n"
|
||||
"| gemini-2.5 | `delegate_task model=gemini-2.5` | routine | free | fast | new: substring |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", bad)
|
||||
self.assertEqual(rc, 1, "substrings of ids with + or () should be rejected, got: " + out + err)
|
||||
|
||||
def test_probe1_header_word_unknown_from_txt_should_be_rejected(self):
|
||||
rc, out, err = self.sisi("models", "offered", stdin="alpha\n")
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
bad = self.write(os.path.join(self.tmp, "bad.md"), HEADER +
|
||||
"| unknown | `delegate_task model=unknown` | routine | free | quick | new: matched file header |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", bad)
|
||||
self.assertEqual(rc, 1, "word 'unknown' only in offered/unknown.txt line 1 header should be rejected, got: " + out + err)
|
||||
|
||||
def test_probe1_how_to_call_substring_and_prose_token_should_be_rejected(self):
|
||||
rc, out, err = self.sisi("models", "offered", stdin="plan: pro\ngemini-2.5-pro\n")
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
bad = self.write(os.path.join(self.tmp, "bad.md"), HEADER +
|
||||
"| pro | `delegate_task model=gemini-2.5-pro` | hard | paid | smart | new: only in how-to-call |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", bad)
|
||||
self.assertEqual(rc, 1, "worker 'pro' matching substring of how-to-call should be rejected, got: " + out + err)
|
||||
|
||||
# --- Probe 2: stale, missing, or changed harness still lets pick return a worker ---
|
||||
|
||||
@unittest.skip("Known limit (P2.1): non-Claude harnesses without harness detection share 'unknown'; follow-up needs a per-harness env var.")
|
||||
def test_probe2_changed_non_claude_harness_should_refuse_previous_harness_list(self):
|
||||
self.table(HEADER + ALPHA)
|
||||
env_agy = dict(self.env, ANTIGRAVITY_AGENT="1", T3CODE_THREAD_ID="t-1")
|
||||
rc, out, err = self.sisi("models", "offered", stdin="alpha\n", env=env_agy)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
rec = self.write(os.path.join(self.tmp, "rec.md"), HEADER + ALPHA)
|
||||
rc, out, err = self.sisi("models", "offered", "--record", rec, env=env_agy)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
# Switch to a different non-Claude harness (Codex)
|
||||
env_codex = dict(self.env, CODEX_HOME=os.path.join(self.tmp, "codex-home"))
|
||||
rc, out, _ = self.sisi("pick", "routine", env=env_codex)
|
||||
self.assertEqual(rc, 1, "changed harness (Antigravity -> Codex) should not reuse offered list: " + out)
|
||||
|
||||
def test_probe2_header_only_offered_list_should_not_pick_header_word(self):
|
||||
self.table(HEADER + "| unknown | host subagent model `unknown` | routine | free | quick | |\n")
|
||||
self.offered_file("") # empty raw body after header line
|
||||
rc, out, _ = self.sisi("pick", "routine")
|
||||
self.assertEqual(rc, 1, "empty raw list body should refuse pick, got: " + out)
|
||||
|
||||
# --- Probe 3: deadlock where matching chore cannot get a worker ---
|
||||
|
||||
def test_probe3_deadlock_matching_chore_when_table_has_no_offered_rows(self):
|
||||
e = self.start_session()
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
rc, out, err = self.sisi("models", "offered", stdin="gamma\ndelta\n", env=e)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
chore_line = out.splitlines()[0]
|
||||
self.assertTrue(chore_line.startswith("sisi chore: models offered "), chore_line)
|
||||
# Either `sisi pick routine` must give a worker, or `hooks.watch` must allow delegating the chore
|
||||
rc_pick, out_pick, _ = self.sisi("pick", "routine", env=e)
|
||||
_, decision, _ = self.hook("watch", {
|
||||
"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse",
|
||||
"tool_name": "Agent", "tool_input": {"model": "gamma", "prompt": chore_line + "\nRun `sisi chore show`"},
|
||||
}, env=e)
|
||||
blocked = decision.get("hookSpecificOutput", {}).get("permissionDecision") == "deny"
|
||||
self.assertFalse(rc_pick != 0 and blocked,
|
||||
"deadlock: pick failed (%s) AND hook denied delegating chore (%s)" % (out_pick.strip(), decision))
|
||||
|
||||
def test_probe3_deadlock_matching_chore_on_fresh_store_without_models_md(self):
|
||||
e = self.start_session()
|
||||
rc, out, err = self.sisi("models", "offered", stdin="gamma\n", env=e)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
chore_line = out.splitlines()[0]
|
||||
rc_pick, out_pick, _ = self.sisi("pick", "routine", env=e)
|
||||
_, decision, _ = self.hook("watch", {
|
||||
"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse",
|
||||
"tool_name": "Agent", "tool_input": {"model": "gamma", "prompt": chore_line + "\nRun `sisi chore show`"},
|
||||
}, env=e)
|
||||
blocked = decision.get("hookSpecificOutput", {}).get("permissionDecision") == "deny"
|
||||
self.assertFalse(rc_pick != 0 and blocked,
|
||||
"deadlock on fresh store: pick failed (%s) AND hook denied the chore (%s)" % (out_pick.strip(), decision))
|
||||
if rc_pick != 0:
|
||||
self.assertIn("any model the host offers", out_pick)
|
||||
|
||||
# --- Probe 4: weighting of untried rows (no break found; verify invariant) ---
|
||||
|
||||
def py(self, code):
|
||||
r = subprocess.run([sys.executable, "-B", "-c", code], cwd=REPO, env=self.env, capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
return r.stdout
|
||||
|
||||
def test_probe4_untried_and_known_rows_both_win(self):
|
||||
t = (HEADER + "| known | host subagent model `known` | routine | free | quick | |\n"
|
||||
"| untried | host subagent model `untried` | routine | free | quick | new: untried |\n")
|
||||
self.write(os.path.join(self.data, "outcomes.jsonl"),
|
||||
"".join(json.dumps({"ts": "2026-12-03T07:00:00", "worker": "known",
|
||||
"model": "known", "verdict": "good", "why": "ok ok ok"}) + "\n"
|
||||
for _ in range(5)))
|
||||
out = self.py(
|
||||
"import json\nfrom sisi import models\n"
|
||||
"t = %r\n"
|
||||
"seen = sorted({models.choose(t, 'routine', rand=lambda x=i/40.0: x, speed={'known': [1,1,1]})[0] for i in range(40)})\n"
|
||||
"print(json.dumps(seen))\n" % t
|
||||
)
|
||||
self.assertEqual(json.loads(out), ["known", "untried"])
|
||||
|
||||
# --- Probe 5: judge X out or delegation hook rejecting/mishandling wheel workers ---
|
||||
|
||||
def test_probe5_judge_out_fails_when_worker_in_table_and_wheel(self):
|
||||
self.table(HEADER + ALPHA + BETA)
|
||||
self.sisi("models", "offered", stdin="alpha\nprov\n")
|
||||
rec = self.write(os.path.join(self.tmp, "rec.md"), HEADER + ALPHA +
|
||||
"| prov | `opencode run -m prov \"<brief>\"` | routine | free | quick | new: provisional |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", rec)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
rc, out, err = self.sisi("judge", "alpha", "out", "provider rate limit exceeded")
|
||||
self.assertEqual(rc, 0, "judge out failed for model present in both table and wheel: " + out + err)
|
||||
|
||||
def test_probe5_watch_ignores_shell_call_to_provisional_wheel_worker(self):
|
||||
e = self.start_session()
|
||||
self.sisi("models", "offered", stdin="prov\n", env=e)
|
||||
rec = self.write(os.path.join(self.tmp, "rec.md"), HEADER +
|
||||
"| prov | `opencode run -m prov \"<brief>\"` | routine | free | quick | new: provisional |\n")
|
||||
rc, out, err = self.sisi("models", "offered", "--record", rec, env=e)
|
||||
self.assertEqual(rc, 0, out + err)
|
||||
_, decision, _ = self.hook("watch", {
|
||||
"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse",
|
||||
"tool_name": "Bash", "tool_input": {"command": "opencode run -m prov \"do task\""},
|
||||
}, env=e)
|
||||
self.assertEqual(decision.get("hookSpecificOutput", {}).get("permissionDecision"), "deny",
|
||||
"delegation hook missed shell call to provisional wheel-only worker: %s" % (decision,))
|
||||
|
||||
def test_probe5_stale_ignores_provisional_wheel_worker(self):
|
||||
self.offered_file("prov\n")
|
||||
self.write(os.path.join(self.data, "offered", "unknown.wheel.md"), HEADER +
|
||||
"| prov | `opencode run -m prov \"<brief>\"` | routine | free | quick | new: provisional |\n")
|
||||
self.table(HEADER + ALPHA)
|
||||
msg = self.py("from sisi import models\nprint(models.stale('prov'), end='')\n")
|
||||
self.assertEqual(msg, "", "stale() falsely flagged provisional wheel worker as unlisted: " + msg)
|
||||
|
||||
def test_probe5_judge_out_fails_after_refresh_deletes_wheel_for_provisional_worker(self):
|
||||
e = self.start_session()
|
||||
self.sisi("models", "offered", stdin="prov\n", env=e)
|
||||
rec = self.write(os.path.join(self.tmp, "rec.md"), HEADER +
|
||||
"| prov | `opencode run -m prov \"<brief>\"` | routine | free | quick | new: provisional |\n")
|
||||
self.sisi("models", "offered", "--record", rec, env=e)
|
||||
rc, out, _ = self.sisi("pick", "routine", env=e)
|
||||
self.assertEqual(rc, 0, out)
|
||||
# Re-listing offered models deletes unknown.wheel.md while provisional job is open
|
||||
self.sisi("models", "offered", stdin="prov\n", env=e)
|
||||
rc, out, err = self.sisi("judge", "prov", "out", "provider rate limit exceeded", env=e)
|
||||
self.assertEqual(rc, 0, "judge out failed after offered refresh deleted wheel.md: " + out + err)
|
||||
|
||||
# --- Probe 6: writes outside temp store or multi-line refusals ---
|
||||
|
||||
def test_probe6_pick_refusal_prints_multiple_lines_with_multi_class_row_in_table(self):
|
||||
self.table(HEADER + "| alpha | host subagent model `alpha` | routine, ordinary | free | quick | |\n")
|
||||
self.offered_file("alpha\n")
|
||||
rc, out, _ = self.sisi("pick", "hard")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertEqual(len(out.splitlines()), 1, "refusal printed more than one line:\n" + out)
|
||||
|
||||
def test_probe6_operations_stay_inside_temp_store(self):
|
||||
e = self.start_session()
|
||||
self.table(HEADER + ALPHA)
|
||||
self.sisi("models", "offered", stdin="alpha\nprov\n", env=e)
|
||||
rec = self.write(os.path.join(self.tmp, "rec.md"), HEADER + ALPHA +
|
||||
"| prov | `opencode run -m prov \"<brief>\"` | routine | free | quick | new: provisional |\n")
|
||||
self.sisi("models", "offered", "--record", rec, env=e)
|
||||
rc, out, _ = self.sisi("pick", "routine", env=e)
|
||||
self.assertEqual(rc, 0, out)
|
||||
rc, out, _ = self.sisi("judge", "prov", "out", "provider rate limit exceeded", env=e)
|
||||
self.assertEqual(rc, 0, out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -10,8 +10,9 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
GAP = ("--gap", "the export dropped rows with empty names until the person noticed",
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence")
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project")
|
||||
|
||||
|
||||
def tree():
|
||||
@@ -27,6 +28,9 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-orgev-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
@@ -61,11 +65,11 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
return f.read()
|
||||
|
||||
def test_brief_has_problem_evidence_and_respects_caps(self):
|
||||
self.assertEqual(self.sisi("retro", "--gap", "export dropped rows with empty names in table",
|
||||
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows with empty names in table",
|
||||
"--cause", "first cause missed null guard",
|
||||
"--improve", "Check null names before exporting rows",
|
||||
"--term", "evidence", "--problem", "row count mismatch")[0], 0)
|
||||
self.assertEqual(self.sisi("retro", "--gap", "export dropped rows again on blank fields",
|
||||
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows again on blank fields",
|
||||
"--cause", "second cause forgot whitespace trim",
|
||||
"--improve", "Strip whitespace and assert total row count matches",
|
||||
"--term", "evidence", "--problem", "1")[0], 0)
|
||||
@@ -85,7 +89,7 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
long_cause = "word " * 1000
|
||||
for i in range(2, 19):
|
||||
cause = long_cause if i == 18 else "cause number %02d in batch" % i
|
||||
self.assertEqual(self.sisi("retro", "--gap", "gap number %02d failed verification check" % i,
|
||||
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "gap number %02d failed verification check" % i,
|
||||
"--cause", cause,
|
||||
"--improve", "Rule number %02d for problem" % i,
|
||||
"--term", "evidence", "--problem", "problem item %02d" % i)[0], 0)
|
||||
@@ -115,8 +119,9 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
self.assertIn("copied as it is", brief)
|
||||
shape = brief.split("Answer with exactly this shape")[1].split("===")[0]
|
||||
self.assertLess(shape.index("## project"), shape.index("## drops"))
|
||||
self.assertLess(shape.index("## drops"), shape.index("## flags"))
|
||||
self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 35)
|
||||
self.assertLess(shape.index("## drops"), shape.index("## same problems"))
|
||||
self.assertLess(shape.index("## same problems"), shape.index("## flags"))
|
||||
self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 43)
|
||||
proj_line = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
|
||||
ans = self.write(os.path.join(self.tmp, "ans.md"),
|
||||
"## user\n## project\n- Kept project rule [retro 2026-11-26]\n"
|
||||
@@ -165,7 +170,7 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
|
||||
def test_owner_rules_stay_verbatim_with_drops_format(self):
|
||||
self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"}))
|
||||
self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Check row counts before export", "--problem", "empty names")[0], 0)
|
||||
own = self.read(self.data, "rules", "user.md").splitlines()[0]
|
||||
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
|
||||
@@ -297,7 +302,7 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
|
||||
def test_drops_ignore_kept_owner_and_invented_rules(self):
|
||||
self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"}))
|
||||
self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Kept retro rule always here", "--problem", "empty names")[0], 0)
|
||||
own = self.read(self.data, "rules", "user.md").splitlines()[0]
|
||||
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
|
||||
|
||||
@@ -0,0 +1,611 @@
|
||||
"""The plan: a dependency graph recorded before any work is handed out, and the hooks that hold the lead to it."""
|
||||
import io, json, os, shutil, sys, unittest
|
||||
from unittest import mock
|
||||
try: # the module, not its class: its tests must not run twice
|
||||
from tests import test_core
|
||||
except ImportError:
|
||||
import test_core
|
||||
sys.path.insert(0, test_core.REPO)
|
||||
|
||||
TABLE = test_core.HEADER + (
|
||||
"| alpha | host subagent model `alpha` | routine | free | quick | |\n"
|
||||
"| beta | host subagent model `beta` | ordinary | free | edits | |\n"
|
||||
"| gamma | host subagent model `gamma` | hard | per use | everything | |\n")
|
||||
COLS = "| node | class | needs | branch | files | check | why |\n|---|---|---|---|---|---|---|\n"
|
||||
PLAN = COLS + (
|
||||
"| a | routine | - | p-a | sisi/a.py | test a passes | exact spec, test decides |\n"
|
||||
"| b | ordinary | - | p-b | sisi/b.py | test b passes | some judgement |\n"
|
||||
"| c | hard | a, b | p-c | sisi/c.py | test c passes | design judgement, redo costly |\n"
|
||||
"| join | lead | c | - | - | full suite passes | the lead merges |\n")
|
||||
|
||||
|
||||
class Plan(unittest.TestCase):
|
||||
ENFORCE = True
|
||||
setUp, project, sisi, hook, tool, done, table, state, read, write, in_process = (
|
||||
test_core.Core.setUp, test_core.Core.project, test_core.Core.sisi, test_core.Core.hook, test_core.Core.tool, test_core.Core.done,
|
||||
test_core.Core.table, test_core.Core.state, test_core.Core.read, test_core.Core.write, test_core.Core.in_process)
|
||||
|
||||
def record(self, text, sid="s1"):
|
||||
return self.sisi("plan", "--record", self.write(os.path.join(self.tmp, "plan.md"), text), sid=sid)
|
||||
|
||||
def refused(self, text, why):
|
||||
rc, out, _ = self.record(text)
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn(why, out)
|
||||
self.assertIn("Nothing was recorded", out)
|
||||
self.assertNotIn("plan", self.state() if os.path.exists(os.path.join(self.tmp, "state", "core-sessions", "s1.json")) else {})
|
||||
|
||||
def ready_plan(self, sid="s1", text=PLAN):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", sid=sid, prompt="build it")
|
||||
self.done(sid)
|
||||
rc, out, _ = self.record(text, sid)
|
||||
self.assertEqual(rc, 0, out)
|
||||
return out
|
||||
|
||||
def pick(self, node, sid="s1"):
|
||||
rc, out, _ = self.sisi("pick", "--node", node, sid=sid)
|
||||
self.assertEqual(rc, 0, out)
|
||||
return out
|
||||
|
||||
def agent(self, model, brief, sid="s1", **extra):
|
||||
return self.tool("Agent", sid=sid, tool_input=dict({"model": model, "prompt": brief, "isolation": "worktree"}, **extra))
|
||||
|
||||
def decision(self, res):
|
||||
rc, out, err = res
|
||||
self.assertEqual((rc, err), (0, ""), res)
|
||||
return json.loads(out)["hookSpecificOutput"] if out.strip() else {}
|
||||
|
||||
def denied(self, res, why):
|
||||
d = self.decision(res)
|
||||
self.assertEqual(d.get("permissionDecision"), "deny", d)
|
||||
self.assertIn(why, d["permissionDecisionReason"])
|
||||
return d["permissionDecisionReason"]
|
||||
|
||||
def nodes(self, sid="s1"):
|
||||
return {i: v.get("st") for i, v in self.state(sid)["plan"]["state"].items()}
|
||||
|
||||
# recording: each refusal
|
||||
|
||||
def test_refuses_a_bad_node_id(self):
|
||||
self.refused(PLAN.replace("| a |", "| A_1 |"), "node id 'A_1' is not")
|
||||
|
||||
def test_refuses_a_duplicate_node(self):
|
||||
self.refused(PLAN.replace("| b | ordinary | - | p-b | sisi/b.py", "| a | ordinary | - | p-b | sisi/b.py"), "node a appears twice")
|
||||
|
||||
def test_refuses_a_missing_need(self):
|
||||
self.refused(PLAN.replace("| a, b |", "| a, zz |"), "node c needs zz, which is not a node")
|
||||
|
||||
def test_refuses_a_cycle(self):
|
||||
self.refused(PLAN.replace("| a | routine | - |", "| a | routine | c |"), "cycle")
|
||||
|
||||
def test_refuses_an_unknown_class(self):
|
||||
self.refused(PLAN.replace("| routine |", "| cheap |"), "class 'cheap'")
|
||||
|
||||
def test_refuses_two_worker_nodes_on_one_branch(self):
|
||||
self.refused(PLAN.replace("| p-b |", "| p-a |"), "branch p-a is given to more than one node")
|
||||
|
||||
def test_refuses_a_worker_node_without_a_branch(self):
|
||||
self.refused(PLAN.replace("| p-b |", "| - |"), "node b needs a branch of its own")
|
||||
|
||||
def test_refuses_parallel_nodes_that_share_files(self):
|
||||
for a, b in (("sisi/a.py", "sisi/a.py"), ("sisi", "sisi/b.py"), ("sisi/*.py", "sisi/b.py")):
|
||||
self.refused(PLAN.replace("| sisi/a.py |", "| %s |" % a).replace("| sisi/b.py |", "| %s |" % b),
|
||||
"nodes a and b can run at the same time")
|
||||
|
||||
def test_nodes_in_sequence_may_share_files(self):
|
||||
self.ready_plan(text=PLAN.replace("| sisi/c.py |", "| sisi/a.py, sisi/b.py |"))
|
||||
|
||||
def test_refuses_more_than_one_sink(self):
|
||||
self.refused(PLAN.replace("| c | hard | a, b |", "| c | hard | a |"), "exactly one final join")
|
||||
|
||||
def test_refuses_a_final_join_that_is_not_the_leads(self):
|
||||
self.refused(PLAN.replace("| join | lead | c | - | - |", "| join | hard | c | p-j | docs |"), "the final join join must be class lead")
|
||||
|
||||
def test_refuses_a_worker_node_without_files_or_check(self):
|
||||
self.refused(PLAN.replace("| sisi/b.py |", "| - |"), "worker node b needs files it may change and a check")
|
||||
self.refused(PLAN.replace("| test b passes |", "| - |"), "worker node b needs files it may change and a check")
|
||||
|
||||
def test_refuses_no_table(self):
|
||||
self.refused("just words", "no table found")
|
||||
|
||||
def test_record_prints_waves_critical_path_dispatch_line_why_and_record(self):
|
||||
out = self.ready_plan()
|
||||
self.assertIn("critical path 3 wave(s)", out)
|
||||
self.assertIn("wave 1: a (routine: exact spec, test decides), b (ordinary: some judgement)", out)
|
||||
self.assertIn("dispatch wave 1 now, all in one message: a, b", out)
|
||||
self.assertIn("record (last 20 judged per class): routine none judged yet", out)
|
||||
self.assertEqual(self.nodes(), {})
|
||||
|
||||
def test_a_table_without_the_why_column_records(self):
|
||||
six = "\n".join("|".join(l.split("|")[:-2]) + "|" if l.startswith("|") else l for l in PLAN.splitlines()) + "\n"
|
||||
self.assertNotIn("why", six)
|
||||
out = self.ready_plan(text=six)
|
||||
self.assertIn("wave 1: a (routine), b (ordinary)", out)
|
||||
|
||||
def test_record_line_counts_the_last_twenty_judged_per_class(self):
|
||||
self.table(TABLE)
|
||||
line = lambda w, v: json.dumps({"ts": "2026-11-20T10:00:00", "worker": w, "verdict": v, "why": "did it fine"})
|
||||
self.write(os.path.join(self.data, "outcomes.jsonl"), "\n".join(
|
||||
[line("alpha", "bad")] * 5 + [line("alpha", "good")] * 18 + [line("beta", "bad")] + [line("gamma", "out")] + [line("nobody", "good")]) + "\n")
|
||||
from sisi import plan
|
||||
self.assertEqual(self.in_process(plan.record_line)[0],
|
||||
"record (last 20 judged per class): routine 18/20 good, ordinary 0/1 good, hard none judged yet")
|
||||
|
||||
def test_rerecording_keeps_the_state_of_unchanged_nodes(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {})
|
||||
self.assertEqual(self.nodes(), {"a": "running"})
|
||||
self.assertEqual(self.record(PLAN.replace("test b passes", "test b and b2 pass"))[0], 0)
|
||||
self.assertEqual(self.nodes(), {"a": "running"})
|
||||
self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0)
|
||||
self.assertEqual(self.nodes(), {"a": "running"}) # a running node keeps its state by id
|
||||
rc, out, _ = self.record(PLAN.replace("| sisi/a.py |", "| sisi/a2.py |"))
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("node a is running", out)
|
||||
self.assertIn("a", self.nodes())
|
||||
rc, out, _ = self.record(PLAN.replace("| a | routine | - |", "| a2 | routine | - |").replace("| a, b |", "| a2, b |"))
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("node a is running", out)
|
||||
|
||||
def pick_header(self, node, sid="s1"):
|
||||
st = self.state(sid)
|
||||
n = next(x for x in st["plan"]["nodes"] if x["id"] == node)
|
||||
return "sisi node: %s\nbranch: %s\nYou are a worker.\nDo it." % (node, n["branch"])
|
||||
|
||||
def test_plan_brief_is_a_chore_built_from_done_with_the_total_cost_rule(self):
|
||||
self.ready_plan()
|
||||
rc, out, _ = self.sisi("plan", "brief", sid="s1")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertRegex(out.splitlines()[0], r"^sisi chore: plan [0-9a-f]{8}$")
|
||||
for want in ("export every row without losing any", "1. row counts match", "| node | class | needs | branch | files | check | why |",
|
||||
"Class by total cost", "routine nodes whenever their", "record (last 20 judged per class)",
|
||||
"prefer many small nodes", "quick test of its own change", "merges its needs, runs them once and fixes what broke"):
|
||||
self.assertIn(want, out)
|
||||
|
||||
def test_a_mid_graph_join_takes_the_slow_check_and_its_header_names_the_branches_to_merge(self):
|
||||
self.ready_plan(text=COLS + (
|
||||
"| a | routine | - | p-a | sisi/a.py | test a passes | exact spec |\n"
|
||||
"| b | routine | - | p-b | sisi/b.py | test b passes | exact spec |\n"
|
||||
"| merge | ordinary | a, b | p-m | sisi/a.py, sisi/b.py | full suite passes | merge, run once, fix |\n"
|
||||
"| join | lead | merge | - | - | released | the lead releases |\n"))
|
||||
for n in "ab":
|
||||
self.assertEqual(self.sisi("plan", "--done", n, "test %s ok" % n, sid="s1")[0], 0)
|
||||
self.assertIn("needs done: a on p-a (test a ok), b on p-b (test b ok)", self.pick("merge"))
|
||||
|
||||
def test_a_retro_clears_the_plan(self):
|
||||
self.ready_plan()
|
||||
self.assertEqual(self.sisi("retro", "--no-gap", "every check passed with the tests shown", *test_core.NG, sid="s1")[0], 0)
|
||||
self.assertNotIn("plan", self.state())
|
||||
|
||||
# pick --node
|
||||
|
||||
def test_pick_node_takes_class_and_branch_and_prints_the_header(self):
|
||||
self.ready_plan()
|
||||
out = self.pick("a")
|
||||
self.assertIn("worker: alpha", out)
|
||||
for want in ("sisi node: a", "branch: p-a (its own worktree and build folder)", "may change: sisi/a.py", "check: test a passes", "needs done: -"):
|
||||
self.assertIn(want, out)
|
||||
self.assertIn("record (last 20 judged per class)", out)
|
||||
self.assertEqual(self.state()["pending"]["alpha"], [{"limit": None, "branch": "p-a", "node": "a"}])
|
||||
|
||||
def test_pick_node_refuses_a_waiting_or_lead_node(self):
|
||||
self.ready_plan()
|
||||
rc, out, _ = self.sisi("pick", "--node", "c", sid="s1")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("node c is not ready (needs not done: a, b)", out)
|
||||
rc, out, _ = self.sisi("pick", "--node", "join", sid="s1")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn('sisi plan --done join', out)
|
||||
|
||||
# the hook: each reason to deny
|
||||
|
||||
def test_deny_without_done(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.denied(self.agent("alpha", "Do it."), "no done is recorded yet")
|
||||
|
||||
def test_deny_without_a_plan(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0)
|
||||
why = self.denied(self.agent("alpha", "Do it."), "no plan is recorded")
|
||||
self.assertIn("sisi plan brief", why)
|
||||
self.assertEqual(self.state().get("delegations_since", 0), 0) # a denied call is no delegation
|
||||
self.assertEqual(self.state()["picked"], ["alpha"]) # and spends no pick
|
||||
|
||||
def test_a_chore_brief_passes_without_a_plan(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.assertEqual(self.decision(self.agent("gamma", brief)), {})
|
||||
self.assertEqual(self.state().get("chores"), []) # spent
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.denied(self.agent("gamma", brief), "is not one sisi printed in this session")
|
||||
|
||||
def test_a_chore_line_must_carry_the_printed_brief(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.denied(self.tool("Agent", tool_input={"model": "gamma", "description": "sisi chore: plan", "prompt": "Arbitrary unplanned work"}),
|
||||
"no plan is recorded") # the longest field is the brief: no chore line in it
|
||||
self.denied(self.tool("Agent", tool_input={"model": "gamma", "description": "x", "prompt": "sisi chore: plan\nArbitrary unplanned work"}),
|
||||
"is not one sisi printed in this session")
|
||||
self.denied(self.agent("gamma", brief.replace("Goal:", "Goal: and also rewrite the installer")), "is not one sisi printed")
|
||||
self.assertNotIn("permissionDecision", self.decision(self.agent("gamma", brief + "\nAlso: the lead's own note after it.")))
|
||||
|
||||
def test_the_longest_field_is_the_brief(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.denied(self.tool("Agent", tool_input={"model": "alpha", "isolation": "worktree", "description": self.pick_header("a"),
|
||||
"prompt": "Unrelated work that is not in the plan at all, described at length here."}), "first line must be")
|
||||
self.assertNotIn("a", self.nodes())
|
||||
|
||||
def test_a_shell_worker_brief_carries_its_node_or_chore_on_any_line(self):
|
||||
self.ready_plan()
|
||||
self.table(test_core.WORKERS)
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True}}))
|
||||
self.pick("a")
|
||||
d = self.decision(self.tool("Bash", tool_input={"command": 'agy --print "\n%s"' % self.pick_header("a")}))
|
||||
self.assertNotIn("permissionDecision", d)
|
||||
self.assertEqual(self.nodes(), {"a": "running"})
|
||||
brief = self.sisi("models", "research", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0)
|
||||
self.assertNotIn("permissionDecision", self.decision(self.tool("Bash", tool_input={"command": 'agy --print "\n%s"' % brief})))
|
||||
self.assertEqual(self.state()["chores"], [])
|
||||
|
||||
def test_fail_refuses_a_running_node(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.agent("alpha", self.pick_header("a"))
|
||||
rc, out, _ = self.sisi("plan", "--fail", "a", "I think it went wrong", sid="s1")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("only its worker's verdict", out)
|
||||
self.assertEqual(self.nodes(), {"a": "running"})
|
||||
|
||||
def test_bad_needs_and_orphan_state_do_not_crash(self):
|
||||
self.ready_plan()
|
||||
path = os.path.join(self.tmp, "state", "core-sessions", "s1.json")
|
||||
s = self.state()
|
||||
s["plan"]["nodes"][2]["needs"] = ["a", 7, None, "b"]
|
||||
s["plan"]["state"] = {"ghost": {"st": "running", "worker": "alpha", "since": 1.0}}
|
||||
self.write(path, json.dumps(s))
|
||||
rc, out, err = self.sisi("plan", sid="s1")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertIn("ready: a, b", out)
|
||||
self.assertEqual(self.sisi("pick", "--node", "a", sid="s1")[0], 0)
|
||||
self.assertEqual(self.record(PLAN)[0], 0)
|
||||
|
||||
def test_an_invented_chore_line_is_denied(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
why = self.denied(self.agent("gamma", "sisi chore: anything\nDo it."), "`sisi chore: anything` brief is not one sisi printed")
|
||||
self.assertIn("no done is recorded", why)
|
||||
|
||||
def test_sisis_own_chore_briefs_carry_their_line_and_pass(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="tidy up")
|
||||
for args, line in ((("rules", "organize"), "sisi chore: rules organize"), (("models", "research"), "sisi chore: models research")):
|
||||
rc, brief, _ = self.sisi(*args, sid="s1")
|
||||
self.assertEqual(rc, 0, brief)
|
||||
self.assertRegex(brief.splitlines()[0], r"^%s [0-9a-f]{8}$" % line)
|
||||
self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0)
|
||||
self.assertNotIn("permissionDecision", self.decision(self.agent("alpha", brief)), line)
|
||||
self.assertEqual(self.state()["chores"], [])
|
||||
|
||||
def chore_id(self, brief):
|
||||
return brief.splitlines()[0].rsplit(" ", 1)[-1]
|
||||
|
||||
def short_brief(self, brief):
|
||||
return brief.splitlines()[0] + "\nRun `sisi chore show %s` and do what it says." % self.chore_id(brief)
|
||||
|
||||
def test_a_chore_id_is_issued_and_printed_on_the_first_line(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
cid = self.chore_id(brief)
|
||||
self.assertRegex(cid, r"^[0-9a-f]{8}$")
|
||||
self.assertIn(cid, [x[3] for x in self.state()["chores"]])
|
||||
|
||||
def test_a_short_delegation_with_the_id_passes_once(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.assertEqual(self.decision(self.agent("gamma", self.short_brief(brief))), {})
|
||||
self.assertEqual(self.state().get("chores"), [])
|
||||
|
||||
def test_a_reused_chore_id_is_denied(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.assertEqual(self.decision(self.agent("gamma", self.short_brief(brief))), {})
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.denied(self.agent("gamma", self.short_brief(brief)), "is not one sisi printed in this session")
|
||||
|
||||
def test_a_wrong_chore_id_is_denied(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
cid = self.chore_id(brief)
|
||||
wrong = ("0" if cid[0] != "0" else "1") + cid[1:]
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
why = self.denied(self.agent("gamma", "sisi chore: plan %s\nRun `sisi chore show %s` and do what it says." % (wrong, wrong)),
|
||||
"is not one sisi printed in this session")
|
||||
self.assertIn("sisi plan brief", why)
|
||||
|
||||
def test_another_sessions_chore_id_is_denied(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
self.hook("prompt", sid="s2", prompt="build it")
|
||||
self.done(sid="s2")
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s2")[0], 0)
|
||||
self.denied(self.agent("gamma", self.short_brief(brief), sid="s2"), "is not one sisi printed in this session")
|
||||
|
||||
def test_chore_show_prints_the_brief_and_unknown_id_fails(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
cid = self.chore_id(brief)
|
||||
rc, out, _ = self.sisi("chore", "show", cid, sid="s2")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(out, brief)
|
||||
rc, out, _ = self.sisi("chore", "show", "deadbeef")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("deadbeef", out)
|
||||
|
||||
def test_a_full_text_delegation_with_the_id_still_passes(self):
|
||||
self.table(TABLE)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("plan", "brief", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
|
||||
self.assertEqual(self.decision(self.agent("gamma", brief)), {})
|
||||
self.assertEqual(self.state().get("chores"), [])
|
||||
|
||||
def test_a_shell_worker_may_carry_the_id_line_on_any_line(self):
|
||||
self.table(test_core.WORKERS)
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True, "enforce": True}}))
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
brief = self.sisi("models", "research", sid="s1")[1]
|
||||
self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0)
|
||||
d = self.decision(self.tool("Bash", tool_input={"command": 'agy --print "\n%s"' % self.short_brief(brief)}))
|
||||
self.assertNotIn("permissionDecision", d)
|
||||
self.assertEqual(self.state()["chores"], [])
|
||||
|
||||
def test_deny_an_unpicked_model(self):
|
||||
self.ready_plan()
|
||||
self.denied(self.agent("alpha", self.pick_header("a")), "the wheel did not give you this worker")
|
||||
|
||||
def test_deny_a_call_with_no_model(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
res = self.tool("Agent", tool_input={"prompt": self.pick_header("a"), "isolation": "worktree"})
|
||||
self.denied(res, "no model is named")
|
||||
|
||||
def test_deny_a_model_not_in_the_table(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.denied(self.agent("zeta", self.pick_header("a")), "not in the models table")
|
||||
|
||||
def test_deny_a_brief_without_a_node_line(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.denied(self.agent("alpha", "You are a worker. Do it."), "first line must be `sisi node: ID`")
|
||||
|
||||
def test_deny_a_node_line_that_is_not_the_first_line(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.denied(self.agent("alpha", "Do this.\nsisi node: a"), "first line must be `sisi node: ID`")
|
||||
|
||||
def test_deny_a_node_that_is_not_ready(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.denied(self.agent("alpha", "sisi node: c\nDo it."), "node c is not ready (needs not done: a, b)")
|
||||
|
||||
def test_deny_a_node_already_running(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {})
|
||||
self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0)
|
||||
self.denied(self.agent("alpha", self.pick_header("a")), "node a is not ready (already running)")
|
||||
|
||||
def test_deny_a_worker_picked_for_another_node(self):
|
||||
self.ready_plan(text=PLAN.replace("| b | ordinary |", "| b | routine |"))
|
||||
self.pick("a")
|
||||
self.denied(self.agent("alpha", "sisi node: b\nDo it."), "picked for node a, not b")
|
||||
|
||||
def test_two_picks_of_one_worker_are_spent_by_node_not_by_order(self):
|
||||
self.ready_plan(text=PLAN.replace("| b | ordinary |", "| b | routine |"))
|
||||
self.pick("a")
|
||||
self.pick("b")
|
||||
self.assertEqual(self.decision(self.agent("alpha", self.pick_header("b"))), {})
|
||||
self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {})
|
||||
self.assertEqual(self.nodes(), {"a": "running", "b": "running"})
|
||||
|
||||
def test_deny_a_shell_out_to_a_worker(self):
|
||||
self.table(test_core.WORKERS)
|
||||
self.hook("prompt", prompt="build it")
|
||||
self.done()
|
||||
self.denied(self.tool("Bash", tool_input={"command": 'agy --print "sisi chore: x"'}), "do not shell out to a worker")
|
||||
|
||||
def test_deny_a_parallel_node_without_its_own_worktree(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.denied(self.agent("alpha", self.pick_header("a"), isolation=None), 'isolation "worktree"')
|
||||
self.pick("b")
|
||||
res = self.tool("mcp__t3-code__delegate_task", tool_input={"task": self.pick_header("b"), "target": {"model": "beta"}, "isolation": "shared"})
|
||||
self.denied(res, 'isolation "worktree"')
|
||||
|
||||
def test_the_deny_is_the_decision_not_a_reminder(self):
|
||||
"""Fails if watch stops printing a deny: the call would go through with only a note."""
|
||||
self.ready_plan()
|
||||
d = self.decision(self.agent("alpha", "Do it."))
|
||||
self.assertEqual(d.get("permissionDecision"), "deny")
|
||||
self.assertNotIn("additionalContext", d)
|
||||
|
||||
def test_the_planned_delegation_passes_and_runs_its_node(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.pick("b")
|
||||
self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {})
|
||||
res = self.tool("mcp__t3-code__delegate_task", tool_input={"task": self.pick_header("b"), "target": {"model": "beta"}, "isolation": "worktree"})
|
||||
self.assertEqual(self.decision(res), {})
|
||||
self.assertEqual(self.nodes(), {"a": "running", "b": "running"})
|
||||
self.assertEqual(self.state()["delegations_since"], 2)
|
||||
|
||||
def test_sisi_commands_and_direct_edits_are_never_denied(self):
|
||||
self.ready_plan()
|
||||
self.assertEqual(self.decision(self.tool("Bash", tool_input={"command": "sisi plan"})), {})
|
||||
d = self.decision(self.tool("Edit", tool_input={"file_path": "x"}))
|
||||
self.assertNotIn("permissionDecision", d)
|
||||
|
||||
def test_workers_are_never_denied(self):
|
||||
self.table(TABLE)
|
||||
self.assertEqual(self.decision(self.tool("Agent", sid="w1", agent_id="sub1", tool_input={"prompt": "Do it."})), {})
|
||||
self.hook("prompt", sid="w2", prompt="You are a worker. Do this task yourself.")
|
||||
self.assertEqual(self.decision(self.tool("Agent", sid="w2", tool_input={"prompt": "Do it."})), {})
|
||||
|
||||
def test_enforce_false_gives_reminders(self):
|
||||
self.ready_plan()
|
||||
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False}}))
|
||||
d = self.decision(self.agent("alpha", "Do it."))
|
||||
self.assertNotIn("permissionDecision", d)
|
||||
self.assertIn("first line must be `sisi node: ID`", d["additionalContext"])
|
||||
self.assertIn("the wheel did not give you", d["additionalContext"])
|
||||
self.assertEqual(self.state()["delegations_since"], 1)
|
||||
|
||||
def test_an_error_inside_watch_lets_the_call_through(self):
|
||||
self.ready_plan()
|
||||
from sisi import cli, plan
|
||||
stdin = io.StringIO(json.dumps({"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Agent",
|
||||
"tool_input": {"model": "alpha", "prompt": "Do it."}}))
|
||||
with mock.patch.object(plan, "deny", side_effect=RuntimeError("boom")), mock.patch.object(sys, "stdin", stdin):
|
||||
rc, out = self.in_process(cli.main, ["watch"])
|
||||
self.assertEqual((rc, out), (0, ""))
|
||||
self.assertIn("boom", self.read(self.tmp, "state", "core-errors.log"))
|
||||
|
||||
def test_a_brief_in_another_field_is_read(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
res = self.tool("subagent_spawn", tool_input={"objective": self.pick_header("a"), "model": "alpha"})
|
||||
d = self.decision(res)
|
||||
self.assertNotIn("permissionDecision", d) # a tool with no isolation field: reminded only
|
||||
self.assertIn('isolation "worktree"', d["additionalContext"])
|
||||
self.assertEqual(self.nodes(), {"a": "running"})
|
||||
|
||||
def test_a_call_with_no_text_is_reminded_not_denied(self):
|
||||
self.ready_plan()
|
||||
d = self.decision(self.tool("Workflow", tool_input={"steps": [1, 2]}))
|
||||
self.assertNotIn("permissionDecision", d)
|
||||
self.assertIn("first line must be", d["additionalContext"])
|
||||
|
||||
def test_a_session_with_no_request_yet_is_reminded_not_denied(self):
|
||||
self.table(TABLE)
|
||||
d = self.decision(self.agent("alpha", "Do it.", sid="fresh"))
|
||||
self.assertNotIn("permissionDecision", d)
|
||||
self.assertIn("no done is recorded", d["additionalContext"])
|
||||
|
||||
def test_a_node_in_sequence_needs_no_worktree(self):
|
||||
seq = COLS + ("| a | routine | - | p-a | sisi/a.py | test a passes | x |\n| b | routine | a | p-b | sisi/b.py | test b passes | x |\n"
|
||||
"| join | lead | b | - | - | suite passes | x |\n")
|
||||
self.ready_plan(text=seq)
|
||||
self.pick("a")
|
||||
self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"), isolation=None)), {})
|
||||
|
||||
def test_done_refuses_a_running_worker_node(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.agent("alpha", self.pick_header("a"))
|
||||
rc, out, _ = self.sisi("plan", "--done", "a", "it looks finished to me", sid="s1")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("sisi judge WORKER", out)
|
||||
self.assertEqual(self.nodes(), {"a": "running"})
|
||||
|
||||
def test_a_damaged_plan_state_does_not_crash(self):
|
||||
self.ready_plan()
|
||||
path = os.path.join(self.tmp, "state", "core-sessions", "s1.json")
|
||||
s = self.state()
|
||||
s["plan"]["state"] = {"a": "junk", "b": {"st": 5}, "c": None}
|
||||
self.write(path, json.dumps(s))
|
||||
rc, out, err = self.sisi("plan", sid="s1")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertIn("ready: a, b", out)
|
||||
self.assertEqual(self.sisi("pick", "--node", "a", sid="s1")[0], 0)
|
||||
s["plan"]["state"] = ["junk"]
|
||||
self.write(path, json.dumps(s))
|
||||
self.assertEqual(self.sisi("plan", sid="s1")[0], 0)
|
||||
|
||||
def test_judge_moves_only_the_node_its_job_started(self):
|
||||
from sisi import plan
|
||||
s = {"plan": {"nodes": [{"id": "a", "cls": "routine", "needs": [], "branch": "b", "files": ["x"], "check": "c"}],
|
||||
"state": {"a": {"st": "running", "worker": "alpha", "since": 100.0}}}}
|
||||
plan.judged(s, "alpha", 200.0, "good")
|
||||
self.assertEqual(s["plan"]["state"]["a"]["st"], "running")
|
||||
plan.judged(s, "alpha", 100.0, "good")
|
||||
self.assertEqual(s["plan"]["state"]["a"]["st"], "done")
|
||||
|
||||
# judge and the end of the turn
|
||||
|
||||
def test_judge_good_marks_done_and_bad_reopens(self):
|
||||
self.ready_plan()
|
||||
self.pick("a")
|
||||
self.pick("b")
|
||||
self.agent("alpha", self.pick_header("a"))
|
||||
self.tool("Agent", tool_input={"model": "beta", "prompt": self.pick_header("b"), "isolation": "worktree"})
|
||||
self.assertEqual(self.sisi("judge", "alpha", "good", "did the work well", sid="s1")[0], 0)
|
||||
self.assertEqual(self.sisi("judge", "beta", "bad", "broke the tests badly", sid="s1")[0], 0)
|
||||
self.assertEqual(self.nodes(), {"a": "done", "b": "failed"})
|
||||
out = self.sisi("plan", sid="s1")[1]
|
||||
self.assertIn("ready: b", out)
|
||||
self.assertIn("a [routine] done", out)
|
||||
|
||||
def test_gate_sends_the_lead_back_while_nodes_are_ready_and_not_started(self):
|
||||
self.ready_plan()
|
||||
rc, out, _ = self.hook("gate")
|
||||
self.assertIn('"block"', out)
|
||||
self.assertIn("nodes a, b are ready and not started", out)
|
||||
exe = "sisi" if shutil.which("sisi") else os.path.join(self.tmp, "lib", "current", "bin", "sisi")
|
||||
self.assertIn("`%s pick --node a` `%s pick --node b`" % (exe, exe), out)
|
||||
|
||||
def test_gate_lets_the_turn_end_while_nodes_only_run(self):
|
||||
self.ready_plan()
|
||||
for n, m in (("a", "alpha"), ("b", "beta")):
|
||||
self.pick(n)
|
||||
self.assertEqual(self.decision(self.agent(m, self.pick_header(n))), {})
|
||||
self.assertEqual(self.hook("gate")[1], "")
|
||||
|
||||
def test_gate_lets_the_turn_end_when_only_the_lead_join_is_ready(self):
|
||||
self.ready_plan()
|
||||
for n in ("a", "b", "c"):
|
||||
self.assertEqual(self.sisi("plan", "--done", n, "done by hand and tested", sid="s1")[0], 0)
|
||||
out = self.hook("gate")[1]
|
||||
self.assertNotIn("is yours and ready", out) # the lead may be waiting on its own job; unsaid checks still speak for themselves
|
||||
|
||||
def test_gate_still_blocks_on_a_ready_worker_node_beside_a_ready_lead_node(self):
|
||||
self.ready_plan()
|
||||
self.assertEqual(self.sisi("plan", "--done", "c", "done by hand and tested", sid="s1")[0], 0)
|
||||
self.assertEqual(self.sisi("plan", "--done", "a", "done by hand and tested", sid="s1")[0], 0)
|
||||
out = self.hook("gate")[1]
|
||||
self.assertIn('"block"', out)
|
||||
self.assertIn("nodes b are ready and not started", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+196
-5
@@ -13,10 +13,11 @@ import unittest
|
||||
from unittest import mock
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
sys.path.insert(0, REPO)
|
||||
from sisi import retro, store
|
||||
from sisi import retro, rules, store
|
||||
GAP = ("--gap", "the export dropped rows with empty names until the person noticed",
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence")
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project")
|
||||
|
||||
|
||||
def tree():
|
||||
@@ -32,11 +33,15 @@ class Problems(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-prob-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data,
|
||||
SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"))
|
||||
SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"),
|
||||
CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"):
|
||||
self.env.pop(name, None)
|
||||
self.proj = os.path.join(self.tmp, "alpha")
|
||||
@@ -44,6 +49,17 @@ class Problems(unittest.TestCase):
|
||||
for args in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]):
|
||||
subprocess.run(["git"] + args, cwd=self.proj, check=True, stdin=subprocess.DEVNULL, capture_output=True)
|
||||
|
||||
def in_process(self, fn, *args):
|
||||
out, here = io.StringIO(), os.getcwd()
|
||||
os.chdir(self.tmp)
|
||||
try:
|
||||
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \
|
||||
mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \
|
||||
mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out):
|
||||
return fn(*args), out.getvalue()
|
||||
finally:
|
||||
os.chdir(here)
|
||||
|
||||
def sisi(self, *args, cwd=None, sid=None, stdin=""):
|
||||
env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env
|
||||
out_f = os.path.join(self.tmp, "stdout.tmp")
|
||||
@@ -55,6 +71,10 @@ class Problems(unittest.TestCase):
|
||||
fe.seek(0)
|
||||
return r.returncode, fo.read(), fe.read()
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def records(self):
|
||||
p = os.path.join(self.data, "retro.jsonl")
|
||||
if not os.path.exists(p):
|
||||
@@ -87,7 +107,7 @@ class Problems(unittest.TestCase):
|
||||
self.assertNotIn("has come back", out)
|
||||
|
||||
# Open problem #2 by words
|
||||
rc, out, err = self.sisi("retro", "--gap", "build script left stale artifacts in output",
|
||||
rc, out, err = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts in output",
|
||||
"--cause", "clean step was skipped on incremental runs",
|
||||
"--improve", "Always clean output directory before packaging release",
|
||||
"--term", "value", "--problem", "stale build artifacts")
|
||||
@@ -125,7 +145,7 @@ class Problems(unittest.TestCase):
|
||||
# Add more non-problem records and cite #2; numbers stay stable
|
||||
self.assertEqual(self.sisi("retro", "--no-gap", "the build passed cleanly on first run",
|
||||
"--term", "time", "--better", "parallelize the test suite run here")[0], 0)
|
||||
rc, out, _ = self.sisi("retro", "--gap", "build script left stale artifacts again",
|
||||
rc, out, _ = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts again",
|
||||
"--cause", "incremental cache kept old binary",
|
||||
"--improve", "Hash inputs before reusing build artifacts",
|
||||
"--term", "value", "--problem", "2")
|
||||
@@ -354,6 +374,177 @@ class Problems(unittest.TestCase):
|
||||
self.assertTrue(any("alpha issue" in l for l in faults_lines), faults_lines)
|
||||
self.assertTrue(any("bravo issue" in l for l in faults_lines), faults_lines)
|
||||
|
||||
def test_organize_brief_lists_every_problem_and_same_problems_section(self):
|
||||
self.assertEqual(self.sisi("retro", "--level", "project",
|
||||
"--gap", "stated a remembered tool behaviour without running the command",
|
||||
"--cause", "stated a remembered tool behaviour without checking",
|
||||
"--improve", "Run the command before stating tool behaviour",
|
||||
"--term", "evidence",
|
||||
"--problem", "claimed tool behaviour or timing from memory in a question or fault brief")[0], 0)
|
||||
for i in range(2, 18):
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Rule number %02d for problem" % i,
|
||||
"--problem", "distinct item %02d" % i)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", "--level", "project",
|
||||
"--gap", "inferred driver behaviour from defaults without testing",
|
||||
"--cause", "Inferred driver behaviour from lpoptions defaults instead of running the filter chain",
|
||||
"--improve", "Push a known test page before claiming driver behaviour",
|
||||
"--term", "evidence",
|
||||
"--problem", "Unmeasured claims about tool behaviour")[0], 0)
|
||||
brief, _ = self.in_process(rules.organize_brief, self.proj)
|
||||
self.assertIn("## same problems", brief)
|
||||
self.assertIn("N = M", brief)
|
||||
# All 18 problems (beyond the 15-problem cap in _evidence) appear with number, name, and cause
|
||||
self.assertIn("#1:", brief)
|
||||
self.assertIn("claimed tool behaviour or timing from memory in a question or fault brief", brief)
|
||||
self.assertIn("stated a remembered tool behaviour without checking", brief)
|
||||
self.assertIn("#18:", brief)
|
||||
self.assertIn("Unmeasured claims about tool behaviour", brief)
|
||||
self.assertIn("Inferred driver behaviour from lpoptions defaults instead of running the filter chain", brief)
|
||||
self.assertIn("#2:", brief)
|
||||
self.assertIn("distinct item 02", brief)
|
||||
|
||||
def test_merge_problems_counts_misses_opens_fault_and_shows_in_report(self):
|
||||
p1_a = "claimed tool behaviour or timing from memory in a question or fault brief"
|
||||
p1_b = "Unmeasured claims about tool behaviour"
|
||||
p2_a = "push not gated on the test run's exit code"
|
||||
p2_b = "a gating command's exit status was hidden by a display filter"
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Run the command before claiming behaviour", "--problem", p1_a)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Gate every push on the test exit code", "--problem", p2_a)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Test the filter chain on a known page first", "--problem", p1_b)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Never pipe a gating command into a filter", "--problem", p2_b)[0], 0)
|
||||
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
proj_rules = [l for l in self.read(self.proj, ".sisi", "rules.md").splitlines() if l.startswith("- ")]
|
||||
ans = os.path.join(self.tmp, "merge.md")
|
||||
with open(ans, "w", encoding="utf-8") as f:
|
||||
f.write("## user\n## project\n" + "\n".join(proj_rules) + "\n## same problems\n1 = 3\n2 = 4\n")
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
|
||||
rep = self.sisi("retro")[1]
|
||||
self.assertIn("#1: " + p1_a + " (2 attempts", rep)
|
||||
self.assertIn("#2: " + p2_a + " (2 attempts", rep)
|
||||
self.assertNotIn("#3: " + p1_b, rep)
|
||||
self.assertNotIn("#4: " + p2_b, rep)
|
||||
self.assertIn(p1_b, rep)
|
||||
self.assertIn(p2_b, rep)
|
||||
self.assertLess(rep.index("#1: " + p1_a), rep.index(p1_b))
|
||||
self.assertLess(rep.index("#2: " + p2_a), rep.index(p2_b))
|
||||
|
||||
# Existing numbering stays valid: a new problem gets #5, not #3
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Separate problem rule five", "--problem", "separate fifth issue")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("opened problem 5 'separate fifth issue'", out)
|
||||
|
||||
# Citing merged number 3 counts as 2nd miss of #1 and opens its fault
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged number three", "--problem", "3")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 1 '%s' has come back: 2 misses" % p1_a, out)
|
||||
self.assertIn("opened fault #1", out)
|
||||
|
||||
# Citing merged name p2_b counts as 2nd miss of #2 and opens its fault
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged name p2_b", "--problem", p2_b)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 2 '%s' has come back: 2 misses" % p2_a, out)
|
||||
self.assertIn("opened fault #2", out)
|
||||
|
||||
# Citing merged number 4 a second time (event happens twice) counts 3 misses on #2 without opening a duplicate fault
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fifth rule via merged number four", "--problem", "4")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 2 '%s' has come back: 3 misses" % p2_a, out)
|
||||
self.assertEqual(len(self.sisi("fault")[1].strip().splitlines()), 2)
|
||||
|
||||
# Citing #5 still resolves to #5
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for fifth issue", "--problem", "5")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 5 'separate fifth issue' has come back: 1 miss", out)
|
||||
|
||||
def test_per_rule_note_counts_citations_through_alias(self):
|
||||
p3_a = "a long real-data run started without its read-only admission check"
|
||||
p3_b = "untested script left for unattended run"
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
retro_rows = [
|
||||
{"ts": "2026-11-20T10:00:00", "problem": p3_a, "cause": "no admission check", "improve": "Run read-only admission check first"},
|
||||
{"ts": "2026-11-21T10:00:00", "problem": p3_b, "cause": "never dry-ran script", "improve": "Dry-run one item end to end first"},
|
||||
]
|
||||
with open(os.path.join(self.data, "retro.jsonl"), "w", encoding="utf-8") as f:
|
||||
f.write("".join(json.dumps(r) + "\n" for r in retro_rows))
|
||||
os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True)
|
||||
with open(os.path.join(self.proj, ".sisi", "rules.md"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join([
|
||||
"- Run read-only admission check first [retro 2026-11-20 p1]",
|
||||
"- Dry-run one item end to end first [retro 2026-11-21 p2]",
|
||||
]) + "\n")
|
||||
ans = os.path.join(self.tmp, "merge3.md")
|
||||
with open(ans, "w", encoding="utf-8") as f:
|
||||
f.write("## user\n## project\n- Run read-only admission check first [retro 2026-11-20 p1]\n- Dry-run one item end to end first [retro 2026-11-21 p2]\n## same problems\n1 = 2\n")
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
|
||||
rc, retro_out, _ = self.sisi("retro", *GAP, "--improve", "Verify one sample output before batching", "--problem", "2")
|
||||
self.assertEqual(rc, 0, retro_out)
|
||||
self.assertIn("problem 1 '%s' has come back: 2 misses" % p3_a, retro_out)
|
||||
|
||||
_, listing_inproc = self.in_process(rules.show, self.proj)
|
||||
listing_cli = self.sisi("rules")[1]
|
||||
brief = self.sisi("rules", "organize")[1]
|
||||
for out_txt in (listing_inproc, listing_cli, brief):
|
||||
self.assertIn("[retro 2026-11-20 p1] (p1: came back 2x since)", out_txt)
|
||||
self.assertIn("[retro 2026-11-21 p2] (p2: came back 1x since)", out_txt)
|
||||
self.in_process(rules.build_rulebook)
|
||||
book = self.read(self.data, "generated", "core.md")
|
||||
self.assertNotIn("came back", book)
|
||||
|
||||
def test_bad_same_problems_skipped_and_revert_undoes_aliases(self):
|
||||
p_a = "a long real-data run started without its read-only admission check"
|
||||
p_b = "untested script left for unattended run"
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule before bad merge", "--problem", p_a)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule before bad merge", "--problem", p_b)[0], 0)
|
||||
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
|
||||
before = self.read(rules_path)
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
ans = os.path.join(self.tmp, "bad_merge.md")
|
||||
with open(ans, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join([
|
||||
"## user",
|
||||
"- Kept organized user rule [retro 2026-11-26]",
|
||||
"## project",
|
||||
"- Combined organized project rule [retro 2026-11-26 p1]",
|
||||
"## same problems",
|
||||
"1 = 99",
|
||||
"0 = 1",
|
||||
"1 = 1",
|
||||
"1 = 2",
|
||||
"2 = 1",
|
||||
"not a valid pair",
|
||||
]) + "\n")
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
self.assertIn("99", out)
|
||||
self.assertIn("0 = 1", out)
|
||||
self.assertIn("1 = 1", out)
|
||||
self.assertIn("2 = 1", out)
|
||||
self.assertIn("not a valid pair", out)
|
||||
# Rest of organize recorded
|
||||
self.assertIn("Combined organized project rule", self.read(rules_path))
|
||||
self.assertIn("Kept organized user rule", self.read(self.data, "rules", "user.md"))
|
||||
# Valid 1 = 2 took effect
|
||||
rep = self.sisi("retro")[1]
|
||||
self.assertIn("#1: " + p_a + " (2 attempts", rep)
|
||||
self.assertNotIn("#2: " + p_b, rep)
|
||||
|
||||
# Revert undoes the organize AND removes the alias
|
||||
rc, rev_out, _ = self.sisi("rules", "revert")
|
||||
self.assertEqual(rc, 0, rev_out)
|
||||
self.assertEqual(self.read(rules_path), before)
|
||||
rep_after = self.sisi("retro")[1]
|
||||
self.assertIn("#1: " + p_a + " (1 attempt", rep_after)
|
||||
self.assertIn("#2: " + p_b + " (1 attempt", rep_after)
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Post-revert citation of two", "--problem", "2")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 2 '%s' has come back: 1 miss" % p_b, out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user