22 Commits
Author SHA1 Message Date
swaitsandClaude Opus 5.5 25b5e90c6b Merge duplicate problems via rules organize alias map
ci / test (push) Waiting to run
- List every canonical problem (number, name, one cause) in organize_brief and ask for optional `## same problems` lines `N = M`.
- Record validated aliases into `rules/problems.json` with the organize commit, skipping unknown numbers, cycles, and bad lines with messages while still recording the rest of the organize; include `rules/problems.json` in `rules.revert()`.
- Resolve cited numbers, names, misses, 2nd-miss faults, drop lookups, and per-rule recurrence notes through the alias map while preserving existing problem numbers; show merged names under their canonical problem in `sisi retro`.
- Add tests with 3 real duplicate pairs from the blind set (watched failing on main first), update `test_the_product_stays_small` (2481 -> 2530, +49), and add CLAUDE.md guards to all touched test classes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:02:03 -07:00
swaits 68b6226aa6 Revert "Merge branch 'p3-problem-suggest'"
ci / test (push) Waiting to run
This reverts commit 2e3a114c8e, reversing
changes made to 0660ee13d6.
2026-12-01 16:51:04 -07:00
swaits 6edfa6d860 Merge branch 'p4-rule-problem'
# Conflicts:
#	tests/test_core.py
2026-12-01 16:50:48 -07:00
swaits 2e3a114c8e Merge branch 'p3-problem-suggest'
# Conflicts:
#	tests/test_core.py
2026-12-01 16:50:48 -07:00
swaitsandClaude Opus 5.5 9f167f8f50 Tag retro rules with problem number and show recurrence in rules listing and organize brief
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:50:15 -07:00
swaitsandClaude Opus 5.5 4b0326ba7c retro: suggest an existing problem when a new name looks like it
Content-word overlap (stemmed, filler dropped), threshold 0.3 picked on
12 labelled real pairs (11/12) with 12/12 held out. The retro always
records as given; the suggestion is one line, never a refusal. The
report listing annotates the top lookalike pair. Product 2426->2454 lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:49:23 -07:00
swaits 0660ee13d6 Move edge cases: exact match, dash-prefixed rules, two-level organize, final canon, rolled-back commit failures
ci / test (push) Waiting to run
- move prefers an exact whole-line match over a strict prefix,
  otherwise refuses listing the candidates; a leading '- ' on the
  prefix and extra spaces are accepted by collapsing whitespace.
- organize says plainly when identical lines from two levels become
  one copy, or now sit at two levels, instead of printing move-back
  commands that would lose one copy; those lines are excluded from
  the printed back commands.
- move to canon is final: it is recorded as such, revert says so
  plainly, and refusal messages name the exact command to run.
- A failed store git commit in _apply restores every file (store
  files and last-project.json included) so the store is clean, and
  both move and organize refuse naming the exact command to rerun.
- Tests: seven new reproducers (each watched failing on main), one
  updated commit-failure test whose organize half asserted the old
  leave-it-dirty behavior, size budget 2426 -> 2444.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:48:01 -07:00
swaitsandClaude Opus 5.5 1e1f26616e Project rules: two rules moved here from the user list (placement cleanup)
ci / test (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:31:39 -07:00
swaitsandClaude Opus 5.5 2a68ead05f revert no longer undoes moves between levels; it names the command back
A change that moves rules between levels (sisi rules move, or an organize
that moves lines across levels) prints the exact reverse command when it
succeeds, and revert after it changes nothing and prints the same command.
Revert keeps undoing learn, retro and single-level organize. The multi-file
undo record and its restore loop are gone.

Fixes the five findings of the fix review: a store with no .git starts its
history with the rules as they are (no undo goes past them); revert reads the
undo record even when its bytes did not change; a trailing slash in SISI_DATA
is still the store; organize takes the user lock and refuses a linked
drops.jsonl. Also: rules usage names canon; a non-UTF-8 file is named.
Product code 2427 -> 2426 lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:28:30 -07:00
swaitsandClaude Opus 5.5 064cd6f5ca rules move and organize never lose or duplicate a rule; one move is one undo
ci / test (push) Waiting to run
Validate source and target before any write; write project files then one store
commit carrying every project file's undo record, rolling all back on a failed
write. Queued core rules load as user rules until moved to canon. Organize
records user-only work outside git so the level audit runs there. Fixes the
ten findings of the strict-placement review, each with an acceptance test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:06:45 -07:00
swaits 058d6e3e56 Merge branch 'strict-placement'
ci / test (push) Waiting to run
# Conflicts:
#	tests/test_core.py
2026-12-01 15:46:08 -07:00
swaitsandClaude Opus 5.5 c07ce2176b Retro prompts and usage show --level, so the strict level never trips an agent that copies them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:45:56 -07:00
swaitsandClaude Opus 5.5 bbf21ef178 Strict rule placement: every rule names its level; core queue; rules move; level audit; unknown flags refused
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:45:21 -07:00
swaitsandClaude Opus 5.5 64b748b32e Project rule (owner): regular automatic placement audit
ci / test (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:34:31 -07:00
swaitsandClaude Opus 5.5 d4e11600cb Size budget back to the product's size (2288)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:31:33 -07:00
swaits 6632a82f77 Merge branch 'p5-wheel-bad' 2026-12-01 15:31:28 -07:00
swaitsandClaude Opus 5.5 33ca3d3c4d Scale wheel weight by recent good/bad quality factor
Multiply each worker's wheel weight by a normalized Laplace quality
factor over its last 10 good/bad verdicts, ((good+1)/(n+2))/((n+1)/(n+2))
= (good+1)/(n+1), ignoring out and extend. Workers with no bad runs keep
their full weight (factor 1.0); workers with all bad runs floor at 1/11
so they remain pickable and picks are never refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:24:09 -07:00
swaitsandClaude Opus 5.5 4e549dedde Shorter rulebook stamp; size budget 2290 for the approved proposal
ci / test (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:20:05 -07:00
swaitsandClaude Opus 5.5 2083bbbd78 Retro records name the rulebook they ran under
Each retro record carries rules: a 12-hex sha256 of the loaded core rulebook plus the project's rules, its char count and its rule-line count, so work before and after a rule change can be compared.

Known: tests/test_core.py test_the_product_stays_small now fails (2293 lines vs the 2283 budget; this adds 10 lines).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:16:52 -07:00
swaitsandClaude Opus 5.5 5e39baaa30 Project rules organized
ci / test (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:53:49 -07:00
swaitsandClaude Opus 5.5 d65ee6e547 README: hooks remind and note, they do not refuse (only the Stop hook blocks)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:53:49 -07:00
swaitsandClaude Fable 5.2 2055d4bb48 Project rule: in-process tests use the temp home; guard the person's rules file
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 16:41:53 -07:00
12 changed files with 1387 additions and 246 deletions

No files matched your search

+17 -14
View File
@@ -3,19 +3,22 @@
- 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] - 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] - 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] - 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] - 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] - 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] - 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]
- 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] - 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, and name every flag the matcher takes. [retro 2026-11-23, 2026-11-24]
- 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] - 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]
- 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] - 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, 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] - 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. [retro 2026-11-23]
- When a worker's report says availability is 'not confirmed', probe it with a one-line dispatch before accepting the table [retro 2026-11-27] - 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. [retro 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. [retro 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 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, count loaded text as canon plus every header rules.py prints into a session, and check the budget against the diff before each merge. [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 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]
+11 -9
View File
@@ -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 instruction becomes a rule at once, and the next session reads it. Now and then a cheap worker audits and
organizes the rules. 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 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 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 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), 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 is refused. One pick, one delegation. A worker that failed for a 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 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 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 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. 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 **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, (`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), 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`, the numbers (minutes, messages, tool calls, delegations, checks), the `term` it fell short on (`value`, `evidence`, `time`, `cost`,
@@ -87,11 +88,12 @@ 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 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 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` | 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 --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 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 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` / `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 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 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 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 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 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 |
@@ -132,6 +134,6 @@ Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `dir
`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), `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), `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 `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 that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) gets a
refused. Set `"shell_workers": true` to allow it: it is then free on the meter, and needs a pick like any 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. delegation, and `sisi pick` prints the command line.
+3 -3
View File
@@ -112,11 +112,11 @@ tests, evidence and completion.
When work ends, the lead runs `sisi retro` to see what happened and known problems. Set it against 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 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 `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: 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 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 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 …`). 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. rules need organizing, have a cheap worker do it in the background.
## 9. Fix what you see ## 9. Fix what you see
+7 -4
View File
@@ -12,16 +12,19 @@ Before and after the work
The learning loop The learning loop
sisi retro what happened in this piece of work, to set against the objective 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 record the gap and problem; the improvement is a rule at once
sisi retro --no-gap TEXT --term T --better B | --later TEXT sisi retro --no-gap TEXT --term T --better B | --later TEXT
nothing fell short; or the work is not finished yet 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 the learned rules in force here
sisi rules organize [--record FILE] sisi rules organize [--record FILE]
the brief for a cheap worker to audit and organize them; record its answer 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; sisi rules move "<start>" core|user|project|canon [--project PATH]
not the move of old rules; a second re-applies it); declines if the project file changed 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 Delegation
sisi models the workers you have: what each is good at and what it costs sisi models the workers you have: what each is good at and what it costs
+3 -3
View File
@@ -12,7 +12,7 @@ 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` " 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).") "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>\"`).") "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>\"`." 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 " 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 "
@@ -21,7 +21,7 @@ NOLOOK = ("sisi: this brief asks for something the person will look at but state
"Choose it with the person from previews and put it in the brief, or add a line 'Look: <the existing design it follows>'.") "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 (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."
NOSHELL = "sisi: do not shell out to a worker; start it with the host's delegation tool 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>\"`)." 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>\"`." 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>\"`."
@@ -119,7 +119,7 @@ def tick(p):
store.append(env, "export SISI_SESSION_ID=%s" % sid, once=True) # so `sisi retro` knows its session 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")): if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")):
rules.build_rulebook() 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 return 0
+28 -30
View File
@@ -88,20 +88,16 @@ def sync_shared(cwd=None):
def age_days(): def age_days():
try: try: return (time.time() - os.path.getmtime(table())) / 86400.0
return (time.time() - os.path.getmtime(table())) / 86400.0 except OSError: return None
except OSError:
return None
def stale(mark=None): def stale(mark=None):
"""One line when the table is missing, old, or missed a worker, else "".""" """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] 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: if mark is not None and who:
try: try: store.write(store.data("models.stale"), who + "\n")
store.write(store.data("models.stale"), who + "\n") except Exception: pass # best effort: a refusal never depends on it
except Exception: # best effort: a refusal never depends on it
pass
age = age_days() age = age_days()
if age is None or age > store.config()["research_days"]: 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: " + ("there is no models table yet. " if age is None else "the models table is %d days old. " % age) + ASK
@@ -250,26 +246,34 @@ def speeds():
return {w: v[-10:] for w, v in out.items()} return {w: v[-10:] for w, v in out.items()}
def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None): def qualities():
"""Each worker's quality factor over its last 10 good/bad outcomes: ((good+1)/(n+2))/((n+1)/(n+2)) = (good+1)/(n+1)."""
out = {}
for o in store.records("outcomes.jsonl"):
w = o["model"] if isinstance(o.get("model"), str) and o["model"].strip() else (o["worker"] if isinstance(o.get("worker"), str) else "")
if o.get("verdict") in ("good", "bad") and w.strip(): out.setdefault(short(w), []).append(o["verdict"] == "good")
return {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in out.items()}
def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None, quality=None):
"""One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1) """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). 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).
A worker last said out less than OUT seconds ago (`gone`, from `outs`) is not on the wheel.""" 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() 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 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)] left = [r for r in table_rows if r[2].strip().lower() == cls and not out(r, skip, bad, gone, now)]
if not left: if not left: return None
return None
if rand is None: if rand is None:
import random import random
rand = random.random rand = random.random
med = {short(r[0]): median(speed[short(r[0])]) for r in left if (speed or {}).get(short(r[0]))} 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) fast, qual = min(med.values(), default=1), quality or {}
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)] weights = [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)) for w, r in zip(range(len(left), 0, -1), left)]
x = rand() * sum(weights) x = rand() * sum(weights)
for weight, r in zip(weights, left): for weight, r in zip(weights, left):
x -= weight if (x := x - weight) < 0: return r
if x < 0:
return r
return left[-1] return left[-1]
@@ -294,8 +298,8 @@ def pick(args, cwd=None, rand=None):
if review is not None and not any(short(r[0]) == short(review) for r in rows(text)): 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) print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review)
return 1 return 1
speed, gone, now = speeds(), away(), time.time() speed, gone, qual, now = speeds(), away(), qualities(), time.time()
r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now) r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual)
if not r: if not r:
bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None) 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, "") again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard."}.get(cls, "")
@@ -422,12 +426,9 @@ def judge(args, cwd=None):
rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1], 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)), "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)),
"project_key": store.project_key(cwd)} "project_key": store.project_key(cwd)}
if sid: if sid: rec["session_id"] = sid
rec["session_id"] = sid if began is not None: rec["started"] = iso(began)
if began is not None: if minutes: rec["minutes"] = minutes
rec["started"] = iso(began)
if minutes:
rec["minutes"] = minutes
log = store.data("outcomes.jsonl") log = store.data("outcomes.jsonl")
store.append(log, json.dumps(rec, sort_keys=True)) store.append(log, json.dumps(rec, sort_keys=True))
ok = store.commit("delegation judged", log) ok = store.commit("delegation judged", log)
@@ -444,11 +445,8 @@ def run(args, cwd=None):
gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)} 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): 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)) 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 := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent))
if recent: if stale(): print("\n" + stale())
print("\nHow recent delegations went:\n" + "\n".join(recent))
if stale():
print("\n" + stale())
return 0 return 0
if args == ["research"]: if args == ["research"]:
return print(research_brief()) or 0 return print(research_brief()) or 0
+59 -19
View File
@@ -1,12 +1,12 @@
"""The retro: what happened, set against the objective; the gap, its cause, and the instruction that would have """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.""" 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 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 ...] \\ 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>" --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""" 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", 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"} "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) TERM_HELP = "--term is one of: %s." % ", ".join(TERMS)
@@ -14,8 +14,8 @@ clean = store.clean
USAGE = """Record one of these: USAGE = """Record one of these:
sisi retro --gap "<where the work fell short of the objective, with the evidence>" \\ sisi retro --gap "<where the work fell short of the objective, with the evidence>" \\
--cause "<the root cause>" \\ --cause "<the root cause>" \\
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." [--scope user] --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: in this project, or with --scope user in all your work. 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 \\ 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>" --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. 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 [] 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): 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 = {}, [] by_key, out = {}, []
for idx, r in enumerate(store.records("retro.jsonl", 64000000) if recs is None else recs): 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"]))): if not (isinstance(r.get("problem"), str) and (name := clean(r["problem"]))):
continue continue
date, key = str(r.get("ts") or "")[:10] or "?", name.lower() 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 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 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 return out
def _problem_lines(probs): def _problem_lines(probs):
recent = sorted(probs, key=lambda p: (-p["last_idx"], -p["num"]))[:15] recent = sorted((p for p in probs if not p.get("into")), 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] 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): 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)." return None, "sisi retro: name the problem in plain words (no secrets, tokens, or long hex/digit strings)."
if len(norm) > 400: if len(norm) > 400:
return None, "sisi retro: problem name is at most 400 characters." 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): if re.fullmatch(r"[+-]?\d+", norm):
n = int(norm) n = int(norm)
return (probs[n - 1], "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm) return (canon(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(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): def report(sid, cwd):
@@ -127,12 +152,19 @@ def report(sid, cwd):
print("\n" + "\n".join(trend())) 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): def record(s, cwd, opt, sid=None):
"""Append one record for the piece of work in this session state, and begin the next one.""" """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") 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)), 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), 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: if d:
entry["done"] = d entry["done"] = d
if sid: if sid:
@@ -203,9 +235,12 @@ def run(args, cwd=None):
if not args: if not args:
return report(sid, cwd) or 0 return report(sid, cwd) or 0
opt = _options(args) opt = _options(args)
scope, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "term", "better", "problem")] scope, level, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "level", "term", "better", "problem")]
scope = scope or rules.PROJECT if level and scope and level != scope:
kind = (None if not opt or scope not in (rules.USER, rules.PROJECT) 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 "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 "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) 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 " print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most "
"400 characters).\n" + USAGE) "400 characters).\n" + USAGE)
return 1 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: if kind != "gap" and problem is not None:
print("sisi retro: --problem goes only with --gap.") print("sisi retro: --problem goes only with --gap.")
return 1 return 1
@@ -248,7 +286,7 @@ def run(args, cwd=None):
elif kind != "later": elif kind != "later":
record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt) record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt)
if kind == "gap": 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"] prior = found["attempts"][:-1] if found else prob["attempts"]
prob, misses = found or prob, len(prior) prob, misses = found or prob, len(prior)
if misses: if misses:
@@ -262,9 +300,10 @@ def run(args, cwd=None):
else: else:
print("opened problem %d '%s'." % (prob["num"], prob["name"])) print("opened problem %d '%s'." % (prob["num"], prob["name"]))
try: try:
added, warn = rules.add(opt["improve"], scope, "retro", cwd) added, warn = rules.add(opt["improve"], scope, "retro", cwd, problem=prob["num"])
print(warn or "recorded. In force from the next session%s: %s" % ( print(warn or ("recorded. In force from the next session%s: %s" % (
" in every project" if scope == rules.USER else " in this project", added)) " 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: except OSError as e:
print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e)) print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e))
if misses >= 2: if misses >= 2:
@@ -279,4 +318,5 @@ def run(args, cwd=None):
print(rules.due(cwd)) print(rules.due(cwd))
else: else:
print("recorded." if kind == "no-gap" else "noted: the retro waits until this work ends.") 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 return 0
+299 -101
View File
@@ -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 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. 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.""" 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 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 = re.compile(r"\[owner\b[^\]]*\]")
_owner, _retro = lambda l: bool(OWNER.search(l)), lambda ls: [l for l in ls if not _owner(l)] _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] _snap = lambda u, p: hashlib.sha1(("\n".join(u) + "\0" + "\n".join(p)).encode()).hexdigest()[:16]
@@ -14,9 +16,11 @@ _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_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 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)") 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.*)$") _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 = """You are a worker. Do this task yourself; do not delegate it further.
@@ -30,15 +34,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, - 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. 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. - 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 - Audit where each rule is filed. %(levels)s Move a rule that sits at the wrong level, in either direction,
first list. A rule about this project's own code belongs in the second. 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 - 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. 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 - 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 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 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. 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>]. - 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. - 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'). - 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 +55,12 @@ Answer with exactly this shape and nothing else:
- ... - ...
## project ## project
- ... - ...
## core
- ... (only lines moved to the product queue)
## drops ## drops
- <old rule> | #<N or -> | <reason> (optional; only if any non-owner rules were dropped) - <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 ## flags
- ... (only if there are any) - ... (only if there are any)
@@ -70,7 +81,31 @@ Answer with exactly this shape and nothing else:
def path(scope, cwd=None): def path(scope, cwd=None):
"""Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept.""" """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) 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): def _legacy(cwd=None):
@@ -93,7 +128,7 @@ def _text(p):
try: try:
return None if raw is None else raw.decode("utf-8") return None if raw is None else raw.decode("utf-8")
except UnicodeDecodeError: 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): def _append(text, new):
@@ -103,7 +138,7 @@ def _append(text, new):
def _check_writable(p): def _check_writable(p):
if not p: if not p:
raise OSError("this folder is inside a git directory or a bare repository") 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 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 store.regular(t)[0]) or ("read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
if why: if why:
@@ -142,9 +177,8 @@ def _move(dest, old):
_check_writable(dest) _check_writable(dest)
before = _text(dest) before = _text(dest)
extra = [l for l in dict.fromkeys(_parse(raw)) if l not in set(_parse(before or ""))] extra = [l for l in dict.fromkeys(_parse(raw)) if l not in set(_parse(before or ""))]
rel = os.path.relpath(old, store.DATA) store.history()
uncommitted = not os.path.isdir(os.path.join(store.DATA, ".git")) or store.git(["status", "--porcelain", "--", rel], store.DATA)[1].strip() if store.git(["status", "--porcelain", "--", old], store.DATA)[1].strip() and not store.commit("project rules before move to .sisi/rules.md", old):
if uncommitted and not store.commit("project rules before move to .sisi/rules.md", old):
raise OSError("could not commit store") raise OSError("could not commit store")
extra and store.write(dest, _append(before, extra)) extra and store.write(dest, _append(before, extra))
(extra or _parse(raw)) and note(dest) (extra or _parse(raw)) and note(dest)
@@ -163,7 +197,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 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 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 "") 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: with store.lock(dest, wait=wait) as ok:
msg = _move(dest, old) if ok else "" msg = _move(dest, old) if ok else ""
return scope_lines(PROJECT, cwd, migrate=False), msg return scope_lines(PROJECT, cwd, migrate=False), msg
@@ -179,20 +213,54 @@ def scope_lines(scope, cwd=None, migrate=True):
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old))) return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
def _commit(msg, *paths, snap=None, put=None): _in_store = lambda p: p.startswith(os.path.join(store.DATA, ""))
# `put` and the undo snapshot are written inside the store lock: another process's `git add` read them mid-replace ("short read")
put = dict(put or {}, **({store.data("rules", "last-project.json"): json.dumps(dict(zip(("path", "before", "after"), snap)))} if snap else {}))
if not store.commit(msg, *paths, put=put):
raise OSError("store git commit failed (%s)" % store.GIT_ERROR)
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.""" """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) dest = path(scope, cwd)
scope == PROJECT and not dest and _check_writable(dest) scope == PROJECT and not dest and _check_writable(dest)
store.history()
with store.lock(dest if scope == PROJECT else "user"): with store.lock(dest if scope == PROJECT else "user"):
if scope == USER: if scope != PROJECT:
[store.append(dest, l) for l in [line, *more]] [store.append(dest, l) for l in [line, *more]]
else: else:
_check_writable(dest) _check_writable(dest)
@@ -204,12 +272,13 @@ def add(text, scope, source, cwd=None, log=None, means=""):
note(dest) note(dest)
try: try:
log and store.append(*log) log and store.append(*log)
extra = ([dest] if scope == USER else []) + ([log[0]] if log else []) extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else [])
_commit("rule added (%s, %s)" % (scope, source), *extra, snap=(dest, before, after) if scope == PROJECT else None) rec = {store.data("rules", "last-project.json"): json.dumps({"path": dest, "before": before, "after": after})} if scope == PROJECT else {}
warn = "" 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: except OSError as e:
warn = "the rule is in %s; it could not be recorded for undo: %s" % (dest, e) warn = str(e)
scope == USER and build_rulebook() 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 return line, warn
@@ -232,7 +301,7 @@ def delivered(p):
def build_rulebook(): def build_rulebook():
"""Write the always-loaded instructions: the product's rulebook, then the person's learned rules.""" """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" 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: if mine:
text += "\n" + HEAD_USER + "\n" + "\n".join(mine) + "\n" text += "\n" + HEAD_USER + "\n" + "\n".join(mine) + "\n"
out = store.data("generated", "core.md") out = store.data("generated", "core.md")
@@ -271,12 +340,13 @@ def due(cwd, claim=False):
"""One line when the learned rules need organizing, else "".""" """One line when the learned rules need organizing, else ""."""
cfg, seen, cl, now, need = store.config(), _organized(), _organized(("locks", "organize.json")), time.time(), [] 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 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) 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)) 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"] 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"]): audit = scope == USER and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"]
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev)))) 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: if not need:
return "" return ""
if claim: if claim:
@@ -293,23 +363,28 @@ def due(cwd, claim=False):
def drops_for(num=None): 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): 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 "" 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" head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n"
"How to use this evidence:\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" "- 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") "- 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) 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"]) 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"])] 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"]] + [" 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" blk = "\n".join(ls) + "\n"
if used + len(blk) > cap_c: if used + len(blk) > cap_c:
for l in (ls if len(out) == 1 else ()): for l in (ls if len(out) == 1 else ()):
@@ -317,39 +392,75 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
out.append(l + "\n"); used += len(l) + 1 out.append(l + "\n"); used += len(l) + 1
break break
out.append(blk); used += len(blk) 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): def organize_brief(cwd):
from . import retro 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"): with contextlib.suppress(OSError), store.lock("organize"):
cl = _organized(("locks", "organize.json")) cl = _organized(("locks", "organize.json"))
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p) cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
store.write(store.data("locks", "organize.json"), json.dumps(cl)) store.write(store.data("locks", "organize.json"), json.dumps(cl))
return ORGANIZE % { 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"], "lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
"flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)", "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)", "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): def organize_record(answer_file, cwd):
"""Replace both lists with the worker's answer. Returns why not, or None when it is done.""" """Replace both lists with the worker's answer. Returns why not, or None when it is done."""
cfg = store.config() 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)) 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 = {}, "", {} got, flags, drops, same_lines = {}, "", {}, []
for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)): 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): if re.fullmatch(r"## (user|project|core)[ \t]*", h):
got[h[3:].strip()] = [l.rstrip() for l in chunk.splitlines() if l.startswith("- ")] 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): elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
flags += chunk flags += chunk
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h): elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
for l in chunk.splitlines(): for l in chunk.splitlines():
if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]): if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]):
drops.setdefault(rk, (m[2], why)) 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}: if set(got) != {USER, PROJECT}:
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines" return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
for scope, ls in got.items(): for scope, ls in got.items():
@@ -357,52 +468,69 @@ def organize_record(answer_file, cwd):
if len(r) > cfg["rules_lines"] or sum(map(len, r)) > cfg["rules_chars"]: 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)" % ( 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))) scope, cfg["rules_lines"], cfg["rules_chars"], len(r), sum(map(len, r)))
up, pp = path(USER), path(PROJECT, cwd) proj = has_project(cwd) # outside a git project only the user list is organized
if not pp or os.path.islink(os.path.dirname(pp)): 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: ") return _migrate(cwd)[1].removeprefix("sisi: ")
with store.lock(pp): with _locks(USER, *filter(None, [pp])):
msg = _move(pp, _legacy(cwd)) msg = proj and _move(pp, _legacy(cwd))
if msg: if msg:
return msg.removeprefix("sisi: ") 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: 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" return "the rules changed since `sisi rules organize` ran; run `sisi rules organize` again"
for scope in (USER, PROJECT): every = got[USER] + got[PROJECT] + core # an owner line may change level, never a word
if miss := [l for l in had[scope] if _owner(l) and got[scope].count(l) < had[scope].count(l)]: 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): %s" % (scope, miss[0]) return "owner rule missing or changed: %s" % miss[0]
kept = list(got[USER]) + list(got[PROJECT]) 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)] 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 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 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] 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) 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" return "the answer holds no rules at all"
try: try:
before = _text(pp) seen, op, dp, ts = _organized(), store.data("rules", "organized.json"), store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
after = "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None seen["retros"] = len(store.read(store.data("retro.jsonl")).splitlines())
after is not None and _check_writable(pp) seen.update({_mark_key(USER): len(_retro(got[USER])), **({_mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))} if proj else {})})
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)
utext = "".join(l + "\n" for l in got[USER])
try:
seen = _organized()
seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))})
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S") change = {up: (_text(up), "".join(l + "\n" for l in got[USER])), op: (_text(op), json.dumps(seen))}
for r, pn, why in recs: if proj:
store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True)) before = _text(pp)
_commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, store.data("rules", "organized.json"): json.dumps(seen)}) 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:
old = store.read(dp) if os.path.exists(dp) else None
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 or os.path.islink(dp))] # the drops log may pass 64,000 bytes
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: except OSError as e:
(wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook() return "could not record the organized rules (%s)" % e
if not wrote and not wrote_u: 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)
return "could not write %s (%s)" % (up, e) proj and change[pp][1] is not None and note(pp)
print("the organized rules are in %s; they could not be recorded for undo: %s" % (pp if wrote else up, e))
return None
with contextlib.suppress(OSError), store.lock("organize"): with contextlib.suppress(OSError), store.lock("organize"):
cl = {k: v for k, v in _organized(("locks", "organize.json")).items() 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))} if k not in ("claim:" + _mark_key(USER), "claim:" + _mark_key(PROJECT, cwd), "snap:" + _mark_key(PROJECT, cwd))}
@@ -411,13 +539,17 @@ def organize_record(answer_file, cwd):
for scope in (USER, PROJECT): for scope in (USER, PROJECT):
print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope]))) 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")) 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()) 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 return None
def revert(): def revert():
"""Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left.""" """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/last-project.json", "rules/owner.log", "rules/organized.json", DROPS) 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)" 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(): 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 return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice
@@ -426,19 +558,25 @@ def revert():
return "there is no change to the learned rules to undo" return "there is no change to the learned rules to undo"
(commit, _, subject), changed = out.splitlines()[0].partition(" "), out.splitlines()[1:] (commit, _, subject), changed = out.splitlines()[0].partition(" "), out.splitlines()[1:]
redo = len(re.match(r'(Revert ")*', subject).group(0)) // 8 % 2 redo = len(re.match(r'(Revert ")*', subject).group(0)) // 8 % 2
snap = {} # 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
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 or re.search(r'\(project,|organized"*$|^rule moved', subject) else "{}"
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed else "" try:
try: snap = json.loads(raw)
snap = json.loads(raw) except ValueError:
except ValueError: snap = None
snap = None if isinstance(snap, dict) and isinstance(snap.get("reverse"), list) and all(isinstance(c, str) for c in snap["reverse"]):
if (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str) print("to move them back, run:\n" + "\n".join(" " + c for c in snap["reverse"]))
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) return "the last rule change, `%s`, moved rules between levels, which revert does not undo; the commands above move them back" % subject
or any(snap[k] is not None and not isinstance(snap[k], str) for k in ("before", "after"))): if isinstance(snap, dict) and snap.get("final"):
return "the undo record for `%s` is missing, corrupt or outside .sisi/rules.md, so it cannot be undone%s" % (subject, advice) 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] 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: 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" return "another rule change finished while waiting; run `sisi rules revert` again"
try: try:
@@ -462,8 +600,11 @@ def show(cwd):
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md")) print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
proj, note = _migrate(cwd) proj, note = _migrate(cwd)
note and print("\n" + note) note and print("\n" + note)
for title, ls in (("Learned, all projects", lines(path(USER))), ("Learned, this project", proj)): 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))
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(ls) or " (none)")) 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): if due(cwd):
print("\n" + due(cwd)) print("\n" + due(cwd))
@@ -478,15 +619,66 @@ def run(args, cwd=None):
return 0 return 0
if args[0] == "organize" and len(args) == 3 and args[1] == "--record": if args[0] == "organize" and len(args) == 3 and args[1] == "--record":
why = organize_record(args[2], cwd) why = organize_record(args[2], cwd)
elif args[:1] == ["move"]:
why = move(args[1:], cwd)
elif args == ["revert"]: elif args == ["revert"]:
why = revert() why = revert()
else: 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: if why:
print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why) print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why)
return 1 if why else 0 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)]}
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
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]
dst = path(to, to_cwd) if to != "canon" else None
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()) _norm = lambda t: " ".join(re.sub(r"[\W_]+", " ", t.lower()).split())
@@ -501,14 +693,19 @@ def _said(words, cwd):
def learn(args, cwd=None): 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.""" 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) i = args.index("--means") if "--means" in args else len(args)
args, means = list(args[:i]), " ".join(args[i + 1:]) words, means = [a for a in args[:i] if a != "--project"], " ".join(args[i + 1:])
scope = PROJECT if "--project" in args else USER text = " ".join(words).strip()
text = " ".join(a for a in args if a != "--project").strip() if len(text.split()) < 3 or (i < len(args) and len(means.split()) < 3) or any(w.startswith("--") for w in words):
if len(text.split()) < 3 or (means and len(means.split()) < 3): print('usage: sisi learn --level core|user|project "<what the person said, in their words>" [--means "<how I will apply it>"]')
print('usage: sisi learn [--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 return 1
heard = _said(text, cwd) 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 log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
@@ -518,5 +715,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)) 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 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.") 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 return 0
+10 -2
View File
@@ -24,7 +24,7 @@ GIT_ERROR = "" # why the last git call that failed did: the first line of its s
# Every setting there is. The person overrides one under "core" in config.json in their store. # 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, 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, "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 7, "shell_workers": False,
"worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8} "worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8}
def config(): def config():
@@ -113,8 +113,8 @@ def git(args, cwd, timeout=15):
def commit(message, *paths, put=None): 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}) """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.""" 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"): with lock("store"):
os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA)
[write(p, text) for p, text in (put or {}).items()] [write(p, text) for p, text in (put or {}).items()]
rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))] rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))]
return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
@@ -122,6 +122,14 @@ def commit(message, *paths, put=None):
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0)) 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 = {} _roots = {}
+741 -48
View File
@@ -3,13 +3,14 @@
Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are
organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the
models table is researched, read and kept fresh.""" models table is researched, read and kept fresh."""
import glob, hashlib, json, os, random, re, shutil, subprocess, sys, tempfile, time, unittest import glob, hashlib, json, os, random, re, shlex, shutil, subprocess, sys, tempfile, time, unittest
from unittest import mock from unittest import mock
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IMP = ("--improve", "Always name the level of a rule you file")
GAP = ("--gap", "the export dropped rows with empty names until the person noticed", 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",
"--problem", "export drops empty names") "--problem", "export drops empty names", "--level", "project")
NG = ("--term", "time", "--better", "start the first build in the same turn as research") NG = ("--term", "time", "--better", "start the first build in the same turn as research")
@@ -140,19 +141,35 @@ class Core(unittest.TestCase):
self.assertEqual(self.hook("gate")[1], "") # held: the turn may end self.assertEqual(self.hook("gate")[1], "") # held: the turn may end
self.assertIn("Compare row counts", self.hook("tick", sid="s2")[1]) # next session here self.assertIn("Compare row counts", self.hook("tick", sid="s2")[1]) # next session here
self.assertNotIn("Compare row counts", self.hook("tick", sid="s3", cwd=self.project("beta"))[1]) # not elsewhere self.assertNotIn("Compare row counts", self.hook("tick", sid="s3", cwd=self.project("beta"))[1]) # not elsewhere
self.sisi("retro", *GAP, "--improve", "Ask one question with options, never three open ones", "--scope", "user", sid="s1") self.sisi("retro", *GAP[:-2], "--improve", "Ask one question with options, never three open ones", "--scope", "user", sid="s1")
book = self.read(self.data, "generated", "core.md") book = self.read(self.data, "generated", "core.md")
self.assertIn("## 8. Close with a retro", book) self.assertIn("## 8. Close with a retro", book)
self.assertIn("## Learned here", book) self.assertIn("## Learned here", book)
self.assertIn("Ask one question with options", book) # for all projects: in the rulebook itself self.assertIn("Ask one question with options", book) # for all projects: in the rulebook itself
self.assertEqual(len(self.read(self.data, "retro.jsonl").splitlines()), 2) self.assertEqual(len(self.read(self.data, "retro.jsonl").splitlines()), 2)
def test_every_retro_record_names_the_rulebook_it_ran_under_and_a_new_rule_changes_it(self):
self.hook("tick")
self.hook("prompt", prompt="add the export")
self.done()
self.tool("Edit")
self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", sid="s1")
book = self.read(self.data, "generated", "core.md")
first = self.records()[-1]["rules"]
self.assertEqual(first, {"hash": hashlib.sha256(book.encode()).hexdigest()[:12], "chars": len(book),
"lines": sum(l.startswith("- ") for l in book.splitlines())})
self.assertEqual(self.sisi("learn", "--level", "user", "Always name the rulebook in every retro record", sid="s1")[0], 0)
self.sisi("retro", *GAP, "--improve", "Name the rulebook in every retro record", sid="s1")
second = self.records()[-1]["rules"]
self.assertNotEqual(second["hash"], first["hash"])
self.assertGreater(second["lines"], first["lines"])
def test_a_retro_needs_real_sentences_and_no_gap_needs_its_evidence(self): def test_a_retro_needs_real_sentences_and_no_gap_needs_its_evidence(self):
self.hook("tick") self.hook("tick")
self.done() self.done()
self.tool("Write") self.tool("Write")
for args in (["--gap", "bad"], ["--no-gap", "fine"], GAP + ("--improve", "be careful"), ["--later", "x"], for args in (["--gap", "bad"], ["--no-gap", "fine"], GAP + ("--improve", "be careful"), ["--later", "x"],
GAP + ("--improve", "Compare the row counts every time", "--scope", "everyone")): GAP[:-2] + ("--improve", "Compare the row counts every time", "--scope", "everyone")):
self.assertEqual(self.sisi("retro", *args, sid="s1")[0], 1, args) self.assertEqual(self.sisi("retro", *args, sid="s1")[0], 1, args)
self.assertIn('"block"', self.hook("gate")[1]) self.assertIn('"block"', self.hook("gate")[1])
self.assertEqual(self.sisi("retro", "--no-gap", "the person accepted it first time and every check passed", *NG, sid="s1")[0], 0) self.assertEqual(self.sisi("retro", "--no-gap", "the person accepted it first time and every check passed", *NG, sid="s1")[0], 0)
@@ -181,7 +198,7 @@ class Core(unittest.TestCase):
self.hook("tick") self.hook("tick")
self.done() self.done()
self.tool("Write") self.tool("Write")
base = GAP[:4] + ("--improve", "Compare row counts before and after every export change") base = GAP[:4] + ("--level", "project", "--improve", "Compare row counts before and after every export change")
for extra in ((), ("--term", "speed")): for extra in ((), ("--term", "speed")):
rc, out, _ = self.sisi("retro", *base, *extra, sid="s1") rc, out, _ = self.sisi("retro", *base, *extra, sid="s1")
self.assertEqual(rc, 1, extra) self.assertEqual(rc, 1, extra)
@@ -225,7 +242,7 @@ class Core(unittest.TestCase):
def test_a_secret_never_reaches_a_rule(self): def test_a_secret_never_reaches_a_rule(self):
self.hook("tick") self.hook("tick")
self.sisi("retro", "--gap", "the deploy failed because the key was pasted wrong", "--cause", "the key was typed by hand each time", self.sisi("retro", "--level", "project", "--gap", "the deploy failed because the key was pasted wrong", "--cause", "the key was typed by hand each time",
"--term", "evidence", "--problem", "deploy key typed by hand", "--improve", "Read the deploy key from the keyring, never paste api_key=sk-abcdefghijklmnopqrstuvwx into a command", sid="s1") "--term", "evidence", "--problem", "deploy key typed by hand", "--improve", "Read the deploy key from the keyring, never paste api_key=sk-abcdefghijklmnopqrstuvwx into a command", sid="s1")
stored = "".join(self.read(p) for p in glob.glob(os.path.join(self.data, "**", "*.*"), recursive=True)) stored = "".join(self.read(p) for p in glob.glob(os.path.join(self.data, "**", "*.*"), recursive=True))
proj_rules = self.read(self.proj, ".sisi", "rules.md") proj_rules = self.read(self.proj, ".sisi", "rules.md")
@@ -298,12 +315,10 @@ class Core(unittest.TestCase):
def test_outside_git_a_subfolder_is_its_own_project(self): def test_outside_git_a_subfolder_is_its_own_project(self):
root = self.mkdir(self.tmp, "plain-proj") root = self.mkdir(self.tmp, "plain-proj")
self.assertEqual(self.sisi("learn", "--project", "Rule of the outer plain folder", cwd=root)[0], 0)
sub = self.mkdir(root, "a", "b") sub = self.mkdir(root, "a", "b")
self.assertNotIn("Rule of the outer plain folder", self.hook("tick", sid="ng1", cwd=sub)[1]) for where in (root, sub): # outside git no folder is a project: nothing is written
self.assertEqual(self.sisi("learn", "--project", "Rule of the inner plain folder", cwd=sub)[0], 0) self.assertEqual(self.sisi("learn", "--project", "Rule of a plain folder", cwd=where)[0], 1)
self.assertIn("Rule of the inner plain folder", self.read(sub, ".sisi", "rules.md")) self.assertFalse(os.path.lexists(os.path.join(where, ".sisi")))
self.assertNotIn("Rule of the inner plain folder", self.read(root, ".sisi", "rules.md"))
def test_reading_project_with_no_rules_creates_no_sisi_dir(self): def test_reading_project_with_no_rules_creates_no_sisi_dir(self):
plain = self.mkdir(self.tmp, "plain-empty") plain = self.mkdir(self.tmp, "plain-empty")
@@ -312,8 +327,8 @@ class Core(unittest.TestCase):
self.assertEqual(self.sisi("rules", cwd=folder)[0], 0) self.assertEqual(self.sisi("rules", cwd=folder)[0], 0)
self.assertEqual(self.sisi("doctor", cwd=folder)[0], 0) self.assertEqual(self.sisi("doctor", cwd=folder)[0], 0)
self.assertFalse(os.path.lexists(os.path.join(folder, ".sisi")), folder) self.assertFalse(os.path.lexists(os.path.join(folder, ".sisi")), folder)
self.assertEqual(self.sisi("learn", "--project", "First rule creates the sisi directory", cwd=plain)[0], 0) self.assertEqual(self.sisi("learn", "--project", "First rule creates the sisi directory", cwd=plain)[0], 1)
self.assertTrue(os.path.isfile(os.path.join(plain, ".sisi", "rules.md"))) self.assertFalse(os.path.lexists(os.path.join(plain, ".sisi")))
def test_legacy_project_rules_migrate_on_read_and_stay_idempotent(self): def test_legacy_project_rules_migrate_on_read_and_stay_idempotent(self):
real_rows = [ real_rows = [
@@ -568,7 +583,7 @@ class Core(unittest.TestCase):
self.write(os.path.join(p, "app.txt"), "v2\n") self.write(os.path.join(p, "app.txt"), "v2\n")
for n, why in (("1", "row counts match at 10"), ("2", "empty name exported as row")): for n, why in (("1", "row counts match at 10"), ("2", "empty name exported as row")):
self.assertEqual(self.sisi("done", "--pass", n, why, cwd=p, sid=sid)[0], 0) self.assertEqual(self.sisi("done", "--pass", n, why, cwd=p, sid=sid)[0], 0)
rc, out, _ = self.sisi("retro", *GAP[:4], "--improve", rule_text, "--term", "time", "--problem", "problem-" + sid, cwd=p, sid=sid) rc, out, _ = self.sisi("retro", *GAP[:4], "--level", "project", "--improve", rule_text, "--term", "time", "--problem", "problem-" + sid, cwd=p, sid=sid)
self.assertEqual(rc, 0, out) self.assertEqual(rc, 0, out)
# 1. Exact four-step sequence: retro writes tracked .sisi/rules.md, commit that one file -> no demand # 1. Exact four-step sequence: retro writes tracked .sisi/rules.md, commit that one file -> no demand
@@ -620,7 +635,7 @@ class Core(unittest.TestCase):
self.assertIn('"block"', self.hook("gate", sid="r5", cwd=p5)[1]) self.assertIn('"block"', self.hook("gate", sid="r5", cwd=p5)[1])
for n, why in (("1", "row counts match at 10"), ("2", "empty name exported as row")): for n, why in (("1", "row counts match at 10"), ("2", "empty name exported as row")):
self.assertEqual(self.sisi("done", "--pass", n, why, cwd=p5, sid="r5")[0], 0) self.assertEqual(self.sisi("done", "--pass", n, why, cwd=p5, sid="r5")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Non-git project rules still record cleanly", cwd=p5, sid="r5")[0], 0) self.assertEqual(self.sisi("retro", *GAP[:-2], "--level", "user", "--improve", "Non-git project rules still record cleanly", cwd=p5, sid="r5")[0], 0)
self.assertEqual(self.hook("gate", sid="r5", cwd=p5)[1], "") self.assertEqual(self.hook("gate", sid="r5", cwd=p5)[1], "")
def test_doctor_reports_project_agents_note_without_writing(self): def test_doctor_reports_project_agents_note_without_writing(self):
@@ -980,7 +995,7 @@ class Core(unittest.TestCase):
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), rows) self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), rows)
beta = self.project("mig-with-prior") beta = self.project("mig-with-prior")
self.assertEqual(self.sisi("learn", "User rule recorded before migration")[0], 0) self.assertEqual(self.sisi("learn", "--level", "user", "User rule recorded before migration")[0], 0)
old_b = self.legacy(beta, rows) old_b = self.legacy(beta, rows)
self.hook("tick", sid="mb", cwd=beta) self.hook("tick", sid="mb", cwd=beta)
self.assertFalse(os.path.exists(old_b)) self.assertFalse(os.path.exists(old_b))
@@ -1009,7 +1024,7 @@ class Core(unittest.TestCase):
self.assertEqual(len(out.strip().splitlines()), 1, (label, out)) self.assertEqual(len(out.strip().splitlines()), 1, (label, out))
self.assertEqual(self.read(target), "keep me intact\n", label) self.assertEqual(self.read(target), "keep me intact\n", label)
self.assertEqual(subprocess.run(["git", "log", "--oneline"], cwd=self.data, capture_output=True, text=True, check=True).stdout, log_before, label) self.assertEqual(subprocess.run(["git", "log", "--oneline"], cwd=self.data, capture_output=True, text=True, check=True).stdout, log_before, label)
self.assertEqual(subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label) self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label)
def test_revert_declines_relative_dotdot_and_dotgit_paths(self): def test_revert_declines_relative_dotdot_and_dotgit_paths(self):
self.mkdir(self.data, "rules") self.mkdir(self.data, "rules")
@@ -1037,7 +1052,7 @@ class Core(unittest.TestCase):
self.assertIn("cannot be undone", out, label) self.assertIn("cannot be undone", out, label)
self.assertEqual(self.read(real_file), content, label) self.assertEqual(self.read(real_file), content, label)
self.assertEqual(subprocess.run(["git", "log", "--oneline"], cwd=self.data, capture_output=True, text=True, check=True).stdout, log_before, label) self.assertEqual(subprocess.run(["git", "log", "--oneline"], cwd=self.data, capture_output=True, text=True, check=True).stdout, log_before, label)
self.assertEqual(subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label) self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label)
def test_hostile_project_rules_and_agents_files_do_not_hang_or_leak(self): def test_hostile_project_rules_and_agents_files_do_not_hang_or_leak(self):
import stat import stat
@@ -1175,7 +1190,7 @@ class Core(unittest.TestCase):
([sys.executable, os.path.join(REPO, "bin", "sisi"), "learn", "--project", "Alpha one rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "learn", "--project", "Alpha one rule round %d" % rnd], pa, ""),
([sys.executable, os.path.join(REPO, "bin", "sisi"), "learn", "--project", "Alpha two rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "learn", "--project", "Alpha two rule round %d" % rnd], pa, ""),
([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--improve", "Beta one rule round %d" % rnd], pb, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--improve", "Beta one rule round %d" % rnd], pb, ""),
([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--scope", "user", "--improve", "User rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP[:-2], "--scope", "user", "--improve", "User rule round %d" % rnd], pa, ""),
([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--improve", "Retro rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--improve", "Retro rule round %d" % rnd], pa, ""),
([sys.executable, os.path.join(REPO, "bin", "sisi"), "tick"], pc, json.dumps({"session_id": "c1-%d" % rnd, "cwd": pc})), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "tick"], pc, json.dumps({"session_id": "c1-%d" % rnd, "cwd": pc})),
([sys.executable, os.path.join(REPO, "bin", "sisi"), "tick"], pc, json.dumps({"session_id": "c2-%d" % rnd, "cwd": pc})), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "tick"], pc, json.dumps({"session_id": "c2-%d" % rnd, "cwd": pc})),
@@ -1198,7 +1213,7 @@ class Core(unittest.TestCase):
self.sisi("learn", "--project", "Initial rule before race") self.sisi("learn", "--project", "Initial rule before race")
rules_file = os.path.join(self.proj, ".sisi", "rules.md") rules_file = os.path.join(self.proj, ".sisi", "rules.md")
started, second_done, errs = threading.Event(), threading.Event(), [] started, second_done, errs = threading.Event(), threading.Event(), []
real_commit, count = rules._commit, [0] real_commit, count = store.commit, [0]
def wrapped_commit(*a, **kw): def wrapped_commit(*a, **kw):
count[0] += 1 count[0] += 1
if count[0] == 1: if count[0] == 1:
@@ -1218,7 +1233,7 @@ class Core(unittest.TestCase):
os.chdir(self.tmp) os.chdir(self.tmp)
try: try:
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \ 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(rules, "_commit", wrapped_commit): mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "commit", wrapped_commit):
t1 = threading.Thread(target=worker, args=("First concurrent project rule",)) t1 = threading.Thread(target=worker, args=("First concurrent project rule",))
t1.start() t1.start()
self.assertTrue(started.wait(15)) self.assertTrue(started.wait(15))
@@ -1274,7 +1289,7 @@ class Core(unittest.TestCase):
# organize replaced rules/user.md under a project's lock; a user rule's concurrent `git add` read it as it # organize replaced rules/user.md under a project's lock; a user rule's concurrent `git add` read it as it
# shrank: "short read while indexing rules/user.md". # shrank: "short read while indexing rules/user.md".
from sisi import rules, store from sisi import rules, store
self.sisi("learn", "User rule before organizing") self.sisi("learn", "--level", "user", "User rule before organizing")
user, real_lock, seen = os.path.join(self.data, "rules", "user.md"), store.lock, [] user, real_lock, seen = os.path.join(self.data, "rules", "user.md"), store.lock, []
before = self.read(user) before = self.read(user)
@@ -1292,8 +1307,8 @@ class Core(unittest.TestCase):
def test_folders_outside_git_are_each_their_own_project(self): def test_folders_outside_git_are_each_their_own_project(self):
notes, other, thing = (self.mkdir(self.tmp, *p) for p in (("notes",), ("code", "other"), ("code", "thing"))) notes, other, thing = (self.mkdir(self.tmp, *p) for p in (("notes",), ("code", "other"), ("code", "thing")))
self.assertEqual(self.sisi("learn", "--project", "A rule written at the home folder", cwd=self.tmp)[0], 0) self.assertEqual(self.sisi("learn", "--project", "A rule written at the home folder", cwd=self.tmp)[0], 1)
self.assertEqual(self.sisi("learn", "--project", "A rule written in the notes folder", cwd=notes)[0], 0) self.assertEqual(self.sisi("learn", "--project", "A rule written in the notes folder", cwd=notes)[0], 1)
old = self.legacy(thing, "- Old rule of the thing folder [owner 2026-11-20]\n") old = self.legacy(thing, "- Old rule of the thing folder [owner 2026-11-20]\n")
out = self.hook("tick", sid="o1", cwd=other)[1] out = self.hook("tick", sid="o1", cwd=other)[1]
self.assertNotIn("home folder", out) self.assertNotIn("home folder", out)
@@ -1414,18 +1429,18 @@ cli.main(["tick"])
rc, out, err = self.sisi("learn", "--project", "Rule saved even when store rules dir is read only") rc, out, err = self.sisi("learn", "--project", "Rule saved even when store rules dir is read only")
self.assertEqual((rc, err), (0, ""), out) self.assertEqual((rc, err), (0, ""), out)
self.assertIn("Rule saved even when store rules dir is read only", self.read(self.proj, ".sisi", "rules.md")) self.assertIn("Rule saved even when store rules dir is read only", self.read(self.proj, ".sisi", "rules.md"))
self.assertEqual(len(out.strip().splitlines()), 2, out) self.assertEqual(len(out.strip().splitlines()), 3, out)
self.assertIn("the rule is in", out) self.assertIn("the rule is in", out)
self.assertIn("could not be recorded for undo", out) self.assertIn("could not be recorded for undo", out)
self.assertNotIn("Nothing was changed", out) self.assertNotIn("Nothing was changed", out)
def test_failed_store_commit_reports_failure_and_blocks_older_revert(self): def test_failed_store_commit_restores_files_and_reports_failure(self):
self.assertEqual(self.sisi("learn", "Older user rule that revert must not silently undo")[0], 0) self.assertEqual(self.sisi("learn", "--level", "user", "Older user rule that revert must not silently undo")[0], 0)
lock = self.write(os.path.join(self.data, ".git", "index.lock"), "") lock = self.write(os.path.join(self.data, ".git", "index.lock"), "")
rc, out, err = self.sisi("learn", "--project", "Project rule while index lock blocks commit") rc, out, err = self.sisi("learn", "--project", "Project rule while index lock blocks commit")
self.assertEqual((rc, err), (0, ""), out) self.assertEqual((rc, err), (0, ""), out)
self.assertIn("Project rule while index lock blocks commit", self.read(self.proj, ".sisi", "rules.md")) self.assertIn("Project rule while index lock blocks commit", self.read(self.proj, ".sisi", "rules.md"))
self.assertEqual(len(out.strip().splitlines()), 2, out) self.assertEqual(len(out.strip().splitlines()), 3, out)
self.assertIn("could not be recorded for undo", out) self.assertIn("could not be recorded for undo", out)
os.remove(lock) os.remove(lock)
rc_rev, out_rev, _ = self.sisi("rules", "revert") rc_rev, out_rev, _ = self.sisi("rules", "revert")
@@ -1441,21 +1456,23 @@ cli.main(["tick"])
"## project\n" + self.read(beta, ".sisi", "rules.md") + "- Organized beta rule [retro 2026-11-24]\n") "## project\n" + self.read(beta, ".sisi", "rules.md") + "- Organized beta rule [retro 2026-11-24]\n")
lock = self.write(os.path.join(self.data, ".git", "index.lock"), "") lock = self.write(os.path.join(self.data, ".git", "index.lock"), "")
rc_org, out_org, err_org = self.sisi("rules", "organize", "--record", ans, cwd=beta) rc_org, out_org, err_org = self.sisi("rules", "organize", "--record", ans, cwd=beta)
self.assertEqual((rc_org, err_org), (0, ""), out_org) self.assertEqual(rc_org, 1, out_org)
self.assertIn("could not be recorded for undo", out_org) self.assertIn("sisi rules organize --record", out_org)
self.assertIn("Organized beta rule", self.read(beta, ".sisi", "rules.md")) self.assertNotIn("Organized beta rule", self.read(beta, ".sisi", "rules.md"))
self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True).stdout, "")
os.remove(lock) os.remove(lock)
# the failed organize left nothing behind, so revert undoes the last committed change (gamma's learn), as usual
rc_rev2, out_rev2, _ = self.sisi("rules", "revert") rc_rev2, out_rev2, _ = self.sisi("rules", "revert")
self.assertNotEqual(rc_rev2, 0, out_rev2) self.assertEqual(rc_rev2, 0, out_rev2)
self.assertIn("Rule in gamma that revert must not undo", self.read(gamma, ".sisi", "rules.md")) self.assertFalse(os.path.exists(os.path.join(gamma, ".sisi", "rules.md")))
def test_retro_inside_dot_git_names_the_folder_when_it_cannot_write(self): def test_retro_inside_dot_git_names_the_folder_when_it_cannot_write(self):
dot_git = os.path.join(self.proj, ".git") dot_git = os.path.join(self.proj, ".git")
for where in (dot_git, os.path.join(dot_git, "refs")): for where in (dot_git, os.path.join(dot_git, "refs")):
rc, out, err = self.sisi("retro", *GAP, "--improve", "Never write rules inside a git directory", cwd=where) rc, out, err = self.sisi("retro", *GAP, "--improve", "Never write rules inside a git directory", cwd=where)
self.assertEqual((rc, err), (0, ""), (where, out)) self.assertEqual((rc, err), (1, ""), (where, out))
self.assertNotIn("could not write (", out) self.assertIn("no project here", out)
self.assertIn("could not write %s (" % where, out) self.assertFalse(os.path.lexists(os.path.join(where, ".sisi")))
def test_byte_order_mark_and_non_utf8_project_file(self): def test_byte_order_mark_and_non_utf8_project_file(self):
old = os.path.join(self.mkdir(self.data, "rules", "projects"), self.project_key_for(self.proj) + ".md") old = os.path.join(self.mkdir(self.data, "rules", "projects"), self.project_key_for(self.proj) + ".md")
@@ -1492,7 +1509,7 @@ cli.main(["tick"])
self.sisi("learn", "--project", "A rule that must not land here", cwd=where)): self.sisi("learn", "--project", "A rule that must not land here", cwd=where)):
rc, out = (r.returncode, r.stdout) if hasattr(r, "returncode") else r[:2] rc, out = (r.returncode, r.stdout) if hasattr(r, "returncode") else r[:2]
self.assertEqual((rc, len(out.strip().splitlines())), (1, 1), (where, out)) self.assertEqual((rc, len(out.strip().splitlines())), (1, 1), (where, out))
self.assertIn("inside a git directory or a bare repository", out) self.assertIn("no project here", out)
self.assertEqual(self.hook("tick", sid="b", cwd=where)[0], 0) self.assertEqual(self.hook("tick", sid="b", cwd=where)[0], 0)
self.assertFalse(os.path.lexists(os.path.join(where, ".sisi")), where) self.assertFalse(os.path.lexists(os.path.join(where, ".sisi")), where)
self.assertFalse(os.path.lexists(os.path.join(self.tmp, ".sisi"))) self.assertFalse(os.path.lexists(os.path.join(self.tmp, ".sisi")))
@@ -1593,7 +1610,7 @@ cli.main(["tick"])
def test_the_models_table_is_researched_recorded_and_goes_stale(self): def test_the_models_table_is_researched_recorded_and_goes_stale(self):
self.assertIn("no models table yet", self.hook("tick")[1]) self.assertIn("no models table yet", self.hook("tick")[1])
self.hook("prompt", prompt="Only the cheapest models on the shared plan") self.hook("prompt", prompt="Only the cheapest models on the shared plan")
self.sisi("learn", "Only the cheapest models on the shared plan", sid="s1") self.sisi("learn", "--level", "user", "Only the cheapest models on the shared plan", sid="s1")
brief = self.sisi("models", "research")[1] brief = self.sisi("models", "research")[1]
self.assertIn("Fallback order:", brief) self.assertIn("Fallback order:", brief)
self.assertIn("Only the cheapest models on the shared plan", brief) # the person's words bind the researcher self.assertIn("Only the cheapest models on the shared plan", brief) # the person's words bind the researcher
@@ -1982,6 +1999,60 @@ cli.main(["tick"])
wins = [models.choose(table, "ordinary", rand=rng.random, speed={"slow": [45], "fast": [9]})[0] for _ in range(2000)] wins = [models.choose(table, "ordinary", rand=rng.random, speed={"slow": [45], "fast": [9]})[0] for _ in range(2000)]
self.assertLess(wins.count("slow"), 100) # 2 * the 0.02 floor against 1: about 4%; it was a third self.assertLess(wins.count("slow"), 100) # 2 * the 0.02 floor against 1: about 4%; it was a third
def test_bad_verdicts_lower_wheel_weight_without_dropping_to_zero(self):
sys.path.insert(0, REPO)
from sisi import models
two = HEADER + "| alpha | `alpha \"<brief>\"` | ordinary | flat | x | |\n| beta | `beta \"<brief>\"` | ordinary | flat | x | |\n"
self.table(two)
# Same speed (10 min): alpha has 1 good + 4 bad (factor 2/6 = 1/3; weight 2/3 vs beta's 1 -> 40/60 split); out and extend are ignored.
self.jsonl("outcomes.jsonl",
self.outcome("alpha", "good", 10),
*[self.outcome("alpha", "bad", 10)] * 4,
self.outcome("alpha", "out", 1),
self.outcome("alpha", "extend", 1),
*[self.outcome("beta", "good", 10)] * 5)
picked = []
for i in range(100):
rc, out = self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)
self.assertEqual(rc, 0, out)
picked.append(out.splitlines()[0].split()[1])
self.assertEqual(picked.count("alpha"), 40)
self.assertEqual(picked.count("beta"), 60)
self.assertGreater(picked.count("alpha"), 0)
self.assertLess(picked.count("alpha"), picked.count("beta"))
# 12 straight bad runs: only the last 10 count (factor 1/11, weight 2/11 vs 1 -> 16/84 split, still pickable).
self.jsonl("outcomes.jsonl", *[self.outcome("alpha", "bad", 10)] * 12, *[self.outcome("beta", "good", 10)] * 5)
picked2 = [self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)[1].splitlines()[0].split()[1] for i in range(100)]
self.assertEqual(picked2.count("alpha"), 16)
self.assertGreater(picked2.count("alpha"), 0)
q, _ = self.in_process(models.qualities)
self.assertAlmostEqual(q["alpha"], 1 / 11)
self.assertEqual(q["beta"], 1.0)
# Never refuses a pick even when the sole worker has only bad verdicts.
self.table(HEADER + "| alpha | `alpha \"<brief>\"` | ordinary | flat | x | |\n")
rc, out = self.in_process(models.pick, ["ordinary"], self.proj, lambda: 0.99)
self.assertEqual((rc, out.splitlines()[0].split()[1]), (0, "alpha"))
def test_only_good_runs_keep_old_wheel_weight(self):
sys.path.insert(0, REPO)
from sisi import models
two = HEADER + "| alpha | `alpha \"<brief>\"` | ordinary | flat | x | |\n| beta | `beta \"<brief>\"` | ordinary | flat | x | |\n"
self.table(two)
spin = lambda: [self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)[1].splitlines()[0].split()[1] for i in range(100)]
baseline = spin()
self.assertEqual((baseline.count("alpha"), baseline.count("beta")), (67, 33)) # table order alone: weights 2 and 1
# Only good runs (and 5 older bad runs rolled off the last-10 window, plus ignored out/extend) keep the exact old weight.
self.jsonl("outcomes.jsonl",
*[self.outcome("alpha", "bad", 10)] * 5,
*[self.outcome("alpha", "good", 10)] * 10,
self.outcome("alpha", "out", 1),
self.outcome("alpha", "extend", 1),
*[self.outcome("beta", "good", 10)] * 4)
after = spin()
self.assertEqual((after.count("alpha"), after.count("beta")), (67, 33))
q, _ = self.in_process(models.qualities)
self.assertEqual((q["alpha"], q["beta"]), (1.0, 1.0))
def test_pick_and_models_show_the_minutes(self): def test_pick_and_models_show_the_minutes(self):
self.table(WORKERS) self.table(WORKERS)
self.hook("tick") self.hook("tick")
@@ -2486,7 +2557,7 @@ cli.main(["tick"])
book = self.read(self.data, "generated", "core.md") book = self.read(self.data, "generated", "core.md")
text = self.read(mine) text = self.read(mine)
self.assertEqual(text, "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\nno newline at the end" % book) self.assertEqual(text, "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\nno newline at the end" % book)
self.assertEqual(self.sisi("learn", "Always say which check proved it")[0], 0) # a rebuild refreshes the block self.assertEqual(self.sisi("learn", "--level", "user", "Always say which check proved it")[0], 0) # a rebuild refreshes the block
new = self.read(mine) new = self.read(mine)
self.assertIn("Always say which check proved it", new) self.assertIn("Always say which check proved it", new)
self.assertTrue(new.endswith("<!-- sisi:end -->\n# my notes\nno newline at the end")) self.assertTrue(new.endswith("<!-- sisi:end -->\n# my notes\nno newline at the end"))
@@ -2496,7 +2567,7 @@ cli.main(["tick"])
self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md"))) self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md")))
self.assertEqual(os.readlink(os.path.join(home, ".gemini", "GEMINI.md")), elsewhere) self.assertEqual(os.readlink(os.path.join(home, ".gemini", "GEMINI.md")), elsewhere)
# a rebuild alone never creates anything in a tool # a rebuild alone never creates anything in a tool
self.sisi("learn", "Name the check that failed first") self.sisi("learn", "--level", "user", "Name the check that failed first")
self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md"))) self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md")))
self.assertEqual(self.read(mine), "# my notes\nno newline at the end") self.assertEqual(self.read(mine), "# my notes\nno newline at the end")
@@ -2508,7 +2579,7 @@ cli.main(["tick"])
self.assertEqual(self.sisi("install")[0], 0) self.assertEqual(self.sisi("install")[0], 0)
book = self.read(self.data, "generated", "core.md") book = self.read(self.data, "generated", "core.md")
self.assertEqual(self.read(target), "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\n%s" % (book, second)) self.assertEqual(self.read(target), "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\n%s" % (book, second))
self.assertEqual(self.sisi("learn", "Keep second marked block in global instructions")[0], 0) self.assertEqual(self.sisi("learn", "--level", "user", "Keep second marked block in global instructions")[0], 0)
new_book = self.read(self.data, "generated", "core.md") new_book = self.read(self.data, "generated", "core.md")
self.assertIn("Keep second marked block in global instructions", new_book) self.assertIn("Keep second marked block in global instructions", new_book)
self.assertEqual(self.read(target), "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\n%s" % (new_book, second)) self.assertEqual(self.read(target), "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\n%s" % (new_book, second))
@@ -2602,7 +2673,7 @@ cli.main(["tick"])
subprocess.run(["git", "clone", "-q", src, mine], check=True, capture_output=True) # the person's checkout, with its remote subprocess.run(["git", "clone", "-q", src, mine], check=True, capture_output=True) # the person's checkout, with its remote
self.assertEqual(run(os.path.join(mine, "bin", "sisi"), "release").returncode, 0) self.assertEqual(run(os.path.join(mine, "bin", "sisi"), "release").returncode, 0)
self.assertEqual(self.read(self.env["SISI_LIB"], "current", "SOURCE").split("\n")[0], src) self.assertEqual(self.read(self.env["SISI_LIB"], "current", "SOURCE").split("\n")[0], src)
self.sisi("learn", "Always keep what the person wrote") self.sisi("learn", "--level", "user", "Always keep what the person wrote")
self.write(os.path.join(self.data, "models.md"), WORKERS) self.write(os.path.join(self.data, "models.md"), WORKERS)
self.write(os.path.join(self.data, "retro.jsonl"), '{"gap": "g"}\n') self.write(os.path.join(self.data, "retro.jsonl"), '{"gap": "g"}\n')
keep = {n: self.read(self.data, n) for n in ("models.md", "retro.jsonl", "rules/user.md")} keep = {n: self.read(self.data, n) for n in ("models.md", "retro.jsonl", "rules/user.md")}
@@ -3733,7 +3804,7 @@ cli.main(["tick"])
def test_owner_tag_means_the_persons_own_words(self): def test_owner_tag_means_the_persons_own_words(self):
said = "Please, ALWAYS name the check that failed first!" said = "Please, ALWAYS name the check that failed first!"
rc, out, _ = self.sisi("learn", "always name the check that failed first", sid="o1") # no message of the person yet rc, out, _ = self.sisi("learn", "--level", "user", "always name the check that failed first", sid="o1") # no message of the person yet
rules_u = lambda: self.read(self.data, "rules", "user.md") rules_u = lambda: self.read(self.data, "rules", "user.md")
self.assertEqual(rc, 0, out) self.assertEqual(rc, 0, out)
self.assertIn("[agent, attributed to owner", rules_u()) self.assertIn("[agent, attributed to owner", rules_u())
@@ -3741,11 +3812,11 @@ cli.main(["tick"])
self.assertIn("not found in the person's recent messages", out) self.assertIn("not found in the person's recent messages", out)
self.hook("prompt", sid="o1", prompt=said) self.hook("prompt", sid="o1", prompt=said)
self.hook("prompt", sid="w1", prompt="You are a worker. Do this task yourself.\nnever use tabs anywhere") self.hook("prompt", sid="w1", prompt="You are a worker. Do this task yourself.\nnever use tabs anywhere")
self.assertEqual(self.sisi("learn", "ALWAYS name the check -- that failed first", sid="o1")[0], 0) self.assertEqual(self.sisi("learn", "--level", "user", "ALWAYS name the check -- that failed first", sid="o1")[0], 0)
self.assertRegex(rules_u().splitlines()[-1], r"first \[owner \d{4}-\d\d-\d\d\]$") self.assertRegex(rules_u().splitlines()[-1], r"first \[owner \d{4}-\d\d-\d\d\]$")
self.assertEqual(self.sisi("learn", "never use tabs anywhere", sid="w1")[0], 0) # a worker records nothing self.assertEqual(self.sisi("learn", "--level", "user", "never use tabs anywhere", sid="w1")[0], 0) # a worker records nothing
self.assertIn("never use tabs anywhere [agent, attributed", rules_u()) self.assertIn("never use tabs anywhere [agent, attributed", rules_u())
rc, out, _ = self.sisi("learn", "ALWAYS name the check that failed first", "--means", "name the failing check in every report", sid="o1") rc, out, _ = self.sisi("learn", "--level", "user", "ALWAYS name the check that failed first", "--means", "name the failing check in every report", sid="o1")
last = rules_u().splitlines()[-2:] last = rules_u().splitlines()[-2:]
self.assertRegex(last[0], r"failed first \[owner \d{4}-\d\d-\d\d\]$") self.assertRegex(last[0], r"failed first \[owner \d{4}-\d\d-\d\d\]$")
self.assertRegex(last[1], r"^- name the failing check in every report \[agent reading \d{4}-\d\d-\d\d\]$") self.assertRegex(last[1], r"^- name the failing check in every report \[agent reading \d{4}-\d\d-\d\d\]$")
@@ -3873,7 +3944,7 @@ cli.main(["tick"])
self.assertEqual(self.sisi("fault", sid="s1")[1].strip(), "no open faults.") self.assertEqual(self.sisi("fault", sid="s1")[1].strip(), "no open faults.")
def test_learn_means_is_one_store_commit_so_revert_undoes_both(self): def test_learn_means_is_one_store_commit_so_revert_undoes_both(self):
self.assertEqual(self.sisi("learn", "always name the check that failed first", "--means", "name the failing check in every report")[0], 0) self.assertEqual(self.sisi("learn", "--level", "user", "always name the check that failed first", "--means", "name the failing check in every report")[0], 0)
rules_u = lambda: self.read(self.data, "rules", "user.md") rules_u = lambda: self.read(self.data, "rules", "user.md")
self.assertEqual(len(rules_u().strip().splitlines()), 2) self.assertEqual(len(rules_u().strip().splitlines()), 2)
self.assertEqual(self.sisi("rules", "revert")[0], 0) self.assertEqual(self.sisi("rules", "revert")[0], 0)
@@ -3930,9 +4001,631 @@ cli.main(["tick"])
with open(os.path.join(REPO, rel), "rb") as f: with open(os.path.join(REPO, rel), "rb") as f:
self.assertEqual(hashlib.sha256(f.read()).hexdigest(), digest, rel) self.assertEqual(hashlib.sha256(f.read()).hexdigest(), digest, rel)
# strict placement: every rule names its level
def user_file(self, text):
os.makedirs(os.path.join(self.data, "rules"), exist_ok=True)
return self.write(os.path.join(self.data, "rules", "user.md"), text)
def test_learn_and_retro_without_a_level_are_refused_and_write_nothing(self):
rc, out, _ = self.sisi("learn", "Always name the level of a rule")
self.assertEqual(rc, 1)
self.assertIn("core = ", out)
self.assertIn("--level core|user|project", out)
rc, out, _ = self.sisi("retro", *GAP[:-2], *IMP)
self.assertEqual(rc, 1)
self.assertIn("user = ", out)
self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "user.md")))
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi")))
self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row", *NG)[0], 0) # no rule, no level needed
self.assertEqual(self.sisi("retro", *GAP[:-2], *IMP, "--scope", "user")[0], 0) # --scope is an alias
def test_unknown_options_are_refused_not_folded_into_the_rule(self):
for args in (("learn", "--level", "user", "Always name the level", "--scopee", "project"),
("learn", "--level", "user", "--bogus", "Always name the level")):
rc, out, _ = self.sisi(*args)
self.assertEqual(rc, 1, args)
self.assertIn("usage: sisi learn", out)
self.assertEqual(self.sisi("retro", *GAP[:-2], *IMP, "--level", "user", "--bogus", "x")[0], 1)
self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "user.md")))
def test_project_level_needs_a_git_repo_and_never_creates_sisi_elsewhere(self):
plain = os.path.join(self.tmp, "plain")
os.makedirs(plain)
for where in (plain, self.tmp): # a plain folder, and the home folder
for args in (("learn", "--level", "project", "Always check this folder first"), ("retro", *GAP[:-2], *IMP, "--level", "project")):
rc, out, _ = self.sisi(*args, cwd=where)
self.assertEqual(rc, 1, args)
self.assertIn("no project here", out)
self.assertIn("use user", out)
self.assertFalse(os.path.exists(os.path.join(where, ".sisi")), where)
rc, out, _ = self.sisi("learn", "--level", "project", "Always check this folder first")
self.assertEqual(rc, 0, out)
self.assertIn('filed as project rule in %s' % os.path.join(self.proj, ".sisi", "rules.md"), out)
self.assertIn('Wrong level? sisi rules move "Always check this folder first"', out)
def test_core_rules_are_queued_shown_in_the_sisi_repo_and_loaded_as_user_rules(self):
rc, out, _ = self.sisi("learn", "--level", "core", "Every sisi user should see this line")
self.assertEqual(rc, 0, out)
self.assertIn("Every sisi user should see this line", self.read(self.data, "rules", "core.md"))
self.assertEqual(self.sisi("retro", *GAP[:-2], *IMP, "--level", "core")[0], 0)
self.assertEqual(len(self.read(self.data, "rules", "core.md").splitlines()), 2)
self.sisi("rulebook")
self.assertIn("Every sisi user", self.read(self.data, "generated", "core.md"))
repo = self.project("sisi-checkout")
for rel in (("canon", "core.md"), ("sisi", "rules.py")):
os.makedirs(os.path.join(repo, rel[0]), exist_ok=True)
self.write(os.path.join(repo, *rel), "x\n")
out = self.hook("tick", sid="c2", cwd=repo)[1]
self.assertIn("2 rules proposed for the product: add each to canon/core.md, then `sisi rules move", out)
def test_rules_move_carries_an_owner_line_verbatim_between_levels(self):
line = "- Keep the words exactly as spoken [owner 2026-11-20]"
self.user_file(line + "\n- Another user rule [retro 2026-11-21]\n")
rc, out, _e = self.sisi("rules", "move", "Keep the words", "project"); out += _e
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), line + "\n")
self.assertEqual(self.read(self.data, "rules", "user.md"), "- Another user rule [retro 2026-11-21]\n")
self.assertEqual(self.sisi("rules", "move", "Keep the words", "user")[0], 0)
self.assertEqual(self.read(self.data, "rules", "user.md").splitlines()[-1], line)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), "")
self.assertEqual(self.sisi("rules", "move", "Keep the words", "core")[0], 0)
self.assertEqual(self.read(self.data, "rules", "core.md"), line + "\n")
other = self.project("other")
self.assertEqual(self.sisi("rules", "move", "Keep the words", "project", "--project", other)[0], 0)
self.assertEqual(self.read(other, ".sisi", "rules.md"), line + "\n")
self.assertEqual(self.sisi("rules", "move", "Keep the words", "project", "--project", self.tmp)[0], 1) # not a repo root
def test_rules_move_refuses_no_match_or_several(self):
self.user_file("- Same start one [owner 2026-11-20]\n- Same start two [owner 2026-11-20]\n")
before = self.read(self.data, "rules", "user.md")
for start, want in (("Nothing like this", "no rule line"), ("Same start", "more than one")):
rc, out, _ = self.sisi("rules", "move", start, "project")
self.assertEqual(rc, 1)
self.assertIn(want, out)
self.assertIn("Same start two", self.sisi("rules", "move", "Same start", "core")[1])
self.assertEqual(self.read(self.data, "rules", "user.md"), before)
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi")))
def test_move_prefers_the_exact_line_when_one_rule_is_a_prefix_of_another(self): # undo review A
self.user_file("- Check logs\n")
self.write(os.path.join(self.data, "rules", "core.md"), "- Check logs in CI\n")
rc, out, _ = self.sisi("rules", "move", "Check logs", "project")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), "- Check logs\n")
self.assertEqual(self.read(self.data, "rules", "core.md"), "- Check logs in CI\n")
self.assertEqual(self.run_back(out), 1)
self.assertEqual(self.read(self.data, "rules", "user.md"), "- Check logs\n")
def test_move_runs_the_command_learn_suggests_for_a_text_starting_with_a_dash(self): # undo review B
self.assertEqual(self.sisi("learn", "--level", "user", "- always verify first")[0], 0)
line = self.read(self.data, "rules", "user.md")
rc, out, _ = self.sisi("rules", "move", "- always verify first", "project")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), line)
self.assertEqual(self.run_back(out), 1)
self.assertEqual(self.read(self.data, "rules", "user.md"), line)
def test_move_matches_a_line_with_two_spaces_after_the_dash(self): # undo review B
self.user_file("- two spaces after dash [owner 2026-11-20]\n")
rc, out, _ = self.sisi("rules", "move", "two spaces after dash", "project")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), "- two spaces after dash [owner 2026-11-20]\n")
self.assertEqual(self.read(self.data, "rules", "user.md"), "")
def test_move_with_a_blocked_store_commit_moves_nothing_and_leaves_no_trace(self): # undo review E
self.assertEqual(self.sisi("learn", "--level", "user", "A user rule that fails to move cleanly")[0], 0)
before_user = self.read(self.data, "rules", "user.md")
lock = self.write(os.path.join(self.data, ".git", "index.lock"), "")
rc, out, _ = self.sisi("rules", "move", "A user rule that fails", "project")
self.assertEqual(rc, 1, out)
self.assertIn("sisi rules move", out)
self.assertIn("Nothing was changed", out)
self.assertEqual(self.read(self.data, "rules", "user.md"), before_user)
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "rules.md")))
self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True).stdout, "")
os.remove(lock)
self.assertEqual(self.sisi("rules", "move", "A user rule that fails", "project")[0], 0)
def test_organize_moves_an_owner_line_across_levels_but_never_rewords_it(self):
mine = "- Words about this one project [owner 2026-11-20]"
self.user_file(mine + "\n")
self.assertEqual(self.sisi("rules", "organize")[0], 0)
ok = self.write(os.path.join(self.tmp, "ok.md"), "## user\n## project\n%s\n## core\n" % mine)
rc, out, _ = self.sisi("rules", "organize", "--record", ok)
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), mine + "\n")
self.assertEqual(self.read(self.data, "rules", "user.md"), "")
self.assertEqual(self.sisi("rules", "organize")[0], 0)
bad = self.write(os.path.join(self.tmp, "bad.md"), "## user\n- Words about this one project, reworded [owner 2026-11-20]\n## project\n")
rc, out, _ = self.sisi("rules", "organize", "--record", bad)
self.assertEqual(rc, 1)
self.assertIn("owner rule missing or changed", out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), mine + "\n")
def test_organize_says_when_identical_rules_from_two_levels_become_one(self): # undo review C
l = "- Shared retro line [retro 2026-11-20]"
self.user_file(l + "\n- Other user rule [retro 2026-11-20]\n")
self.mkdir(self.proj, ".sisi")
self.write(os.path.join(self.proj, ".sisi", "rules.md"), l + "\n")
user_before = self.read(self.data, "rules", "user.md")
proj_before = self.read(self.proj, ".sisi", "rules.md")
ans = self.write(os.path.join(self.tmp, "shared.md"), "## user\n- Other user rule [retro 2026-11-20]\n## project\n## core\n%s\n" % l)
rc, out, _ = self.sisi("rules", "organize", "--record", ans)
self.assertEqual(rc, 0, out)
self.assertIn("both user and project", out)
self.assertNotIn("to move them back", out)
self.assertEqual(self.read(self.data, "rules", "core.md"), l + "\n")
self.assertEqual(self.sisi("rules", "revert")[0], 0)
self.assertEqual(self.read(self.data, "rules", "user.md"), user_before)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), proj_before)
def test_organize_says_when_one_rule_is_filed_at_two_levels(self): # undo review C
l = "- Split owner line [owner 2026-11-20]"
self.user_file(l + "\n")
user_before = self.read(self.data, "rules", "user.md")
ans = self.write(os.path.join(self.tmp, "split.md"), "## user\n## project\n%s\n## core\n%s\n" % (l, l))
rc, out, _ = self.sisi("rules", "organize", "--record", ans)
self.assertEqual(rc, 0, out)
self.assertIn("two levels", out)
self.assertNotIn("to move them back", out)
self.assertEqual(self.sisi("rules", "revert")[0], 0)
self.assertEqual(self.read(self.data, "rules", "user.md"), user_before)
self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "core.md")))
def test_the_level_audit_becomes_due_by_a_retro_count(self):
self.user_file("- A user rule [retro 2026-11-20]\n")
os.makedirs(self.data, exist_ok=True)
self.write(os.path.join(self.data, "retro.jsonl"), '{"x": 1}\n' * 3)
self.assertNotIn("need organizing", self.hook("tick", sid="a1")[1])
self.write(os.path.join(self.data, "retro.jsonl"), '{"x": 1}\n' * 12)
out = self.hook("tick", sid="a2")[1]
self.assertIn("need organizing", out)
self.assertIn("time to audit their levels", out)
# sisi rules move and organize --record: the adversarial review's failing inputs (strict-review.md), each an acceptance test
def sides(self, *paths):
return [self.read(p) if os.path.exists(p) else None for p in paths]
def test_a_move_names_the_command_that_moves_it_back_in_every_direction(self): # finding 1, invariant 2; fix review: revert does not undo a move
other = self.project("beta")
user, core = os.path.join(self.data, "rules", "user.md"), os.path.join(self.data, "rules", "core.md")
here, there = os.path.join(self.proj, ".sisi", "rules.md"), os.path.join(other, ".sisi", "rules.md")
self.assertEqual(self.sisi("learn", "--level", "user", "A first user rule stays put")[0], 0)
self.assertEqual(self.sisi("learn", "--level", "project", "A first project rule stays put")[0], 0)
self.assertEqual(self.sisi("learn", "--level", "project", "A first other rule stays put", cwd=other)[0], 0)
for n, (frm, to, src, dst, extra, lcwd) in enumerate((
("user", "project", user, here, (), None), ("project", "user", here, user, (), None),
("project", "project", here, there, ("--project", other), None), ("user", "core", user, core, (), None),
("core", "user", core, user, (), None), ("project", "core", here, core, (), None),
("core", "project", core, here, (), None), ("project", "user", there, user, (), other))):
text = "Rule number %d travels from %s to %s" % (n, frm, to)
self.assertEqual(self.sisi("learn", "--level", frm, text, cwd=lcwd)[0], 0)
before = self.sides(src, dst)
rc, out, err = self.sisi("rules", "move", "Rule number %d" % n, to, *extra, cwd=lcwd)
self.assertEqual((rc, err), (0, ""), out)
moved = self.sides(src, dst)
self.assertEqual((moved[0] or "").count(text), 0, (frm, to))
self.assertEqual(moved[1].count(text), 1, (frm, to))
rc, back, _ = self.sisi("rules", "revert", cwd=lcwd)
self.assertEqual(rc, 1, back)
self.assertIn("Nothing was changed", back)
self.assertEqual(self.sides(src, dst), moved, (frm, to))
self.assertEqual(self.run_back(out), 1)
self.assertEqual(self.sides(src, dst)[0], before[0], (frm, to))
self.assertEqual((self.sides(src, dst)[1] or "").count(text), 0, (frm, to))
def test_a_move_that_cannot_write_safely_changes_nothing_and_says_why(self): # findings 2 and 5, invariant 1
user, core = os.path.join(self.data, "rules", "user.md"), os.path.join(self.data, "rules", "core.md")
proj = os.path.join(self.proj, ".sisi", "rules.md")
self.assertEqual(self.sisi("learn", "--level", "user", "Target rule for moving around")[0], 0)
self.assertEqual(self.sisi("learn", "--level", "project", "Read only project rule here")[0], 0)
self.assertEqual(self.sisi("learn", "--level", "core", "Queued core rule for the product")[0], 0)
files = (user, core, proj)
def refused(start, to, why):
before = self.sides(*files)
rc, out, err = self.sisi("rules", "move", start, to)
self.assertEqual((rc, err), (1, ""), out)
self.assertIn(why, out)
self.assertIn("Nothing was changed", out)
self.assertEqual(self.sides(*files), before)
os.chmod(proj, 0o444)
refused("Read only project", "user", "read-only")
os.chmod(proj, 0o644)
os.chmod(core, 0o444)
refused("Target rule", "core", "read-only")
os.chmod(core, 0o644)
real = self.write(os.path.join(self.tmp, "real-core.md"), self.read(core))
os.remove(core), os.symlink(real, core)
refused("Target rule", "core", "symlink")
refused("Queued core rule", "user", "symlink")
os.remove(core), self.write(core, self.read(real))
big = self.read(user) + "- %s [retro 2026-11-20]\n" % ("x" * 64000)
self.write(user, big)
refused("Target rule", "core", "64,000 bytes")
self.write(user, "- Target rule for moving around [owner 2026-11-20]\n")
os.rename(proj, proj + ".real"), os.symlink(proj + ".real", proj)
refused("Target rule", "project", "symlink")
def test_move_matches_lines_with_trailing_spaces_a_bom_or_from_the_old_store_file(self): # finding 2
proj = os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md")
self.write(proj, "- Bom rule at the top [owner 2026-11-20]\n- Trailing spaces rule here [owner 2026-11-20] \n- Stays [owner 2026-11-20]\n")
for start in ("Trailing spaces", "Bom rule"):
rc, out, err = self.sisi("rules", "move", start, "user")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.read(proj), "- Stays [owner 2026-11-20]\n")
self.assertEqual(self.read(self.data, "rules", "user.md"),
"- Trailing spaces rule here [owner 2026-11-20]\n- Bom rule at the top [owner 2026-11-20]\n")
other = self.project("legacy")
old = self.legacy(other, "- Legacy project rule [owner 2026-11-20]\n")
rc, out, err = self.sisi("rules", "move", "Legacy project rule", "user", cwd=other)
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.read(self.data, "rules", "user.md").count("Legacy project rule"), 1)
self.assertFalse(os.path.exists(old))
self.assertNotIn("Legacy", self.read(other, ".sisi", "rules.md"))
def test_move_from_a_subfolder_with_its_project_named_and_with_a_doubled_line(self): # finding 6
sub = self.mkdir(self.proj, "sub")
self.assertEqual(self.sisi("learn", "--level", "project", "Subdir project rule here")[0], 0)
rc, out, err = self.sisi("rules", "move", "Subdir project rule", "user", "--project", self.proj, cwd=sub)
self.assertEqual((rc, err), (0, ""), out)
proj = os.path.join(self.proj, ".sisi", "rules.md")
self.write(proj, "- Twice the same [owner 2026-11-20]\n- Twice the same [owner 2026-11-20]\n")
self.assertEqual(self.sisi("rules", "move", "Twice the same", "user")[0], 0)
self.assertEqual(self.read(proj), "")
self.assertEqual(self.read(self.data, "rules", "user.md").count("Twice the same"), 1)
def test_a_move_that_fails_part_way_puts_both_sides_back(self): # invariant 1
from sisi import rules, store
self.assertEqual(self.sisi("learn", "--level", "project", "Project rule that must not be lost")[0], 0)
self.assertEqual(self.sisi("learn", "--level", "user", "Some user rule already there")[0], 0)
files = (os.path.join(self.proj, ".sisi", "rules.md"), os.path.join(self.data, "rules", "user.md"))
before = self.sides(*files)
real = store.write
def half(p, text): # the project side is written, then the store side fails
if p.endswith("user.md"):
raise OSError("disk full")
real(p, text)
with mock.patch.object(store, "write", half):
why, out = self.in_process(rules.move, ["Project rule that must", "user"], self.proj)
self.assertIn("disk full", why)
self.assertEqual(self.sides(*files), before)
def test_organize_never_loses_a_line_it_moves_and_may_move_all_to_core(self): # findings 3 and 4, invariant 3
from sisi import rules, store
self.user_file("- Kept user rule [owner 2026-11-20]\n")
proj = os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md")
self.write(proj, "- Project rule moving to core [owner 2026-11-20]\n")
core = self.mkdir(self.data, "rules", "core.md") # a folder where the queue should be
ans = self.write(os.path.join(self.tmp, "a.md"), "## user\n- Kept user rule [owner 2026-11-20]\n## project\n## core\n- Project rule moving to core [owner 2026-11-20]\n")
self.assertEqual(self.sisi("rules", "organize")[0], 0)
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (1, ""), out)
self.assertIn("Project rule moving to core", self.read(proj))
os.rmdir(core)
real = store.write
with mock.patch.object(store, "write", lambda p, t: (_ for _ in ()).throw(OSError("disk full")) if p.endswith("core.md") else real(p, t)):
self.in_process(rules.organize_brief, self.proj)
why, out = self.in_process(rules.organize_record, ans, self.proj)
self.assertIn("disk full", why or out)
self.assertIn("Project rule moving to core", self.read(proj))
self.write(proj, "")
allcore = self.write(os.path.join(self.tmp, "b.md"), "## user\n## project\n## core\n- Kept user rule [owner 2026-11-20]\n")
self.assertEqual(self.sisi("rules", "organize")[0], 0)
rc, out, _ = self.sisi("rules", "organize", "--record", allcore)
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.data, "rules", "core.md"), "- Kept user rule [owner 2026-11-20]\n")
self.assertEqual(self.read(self.data, "rules", "user.md"), "")
rc, back, _ = self.sisi("rules", "revert") # fix review: a move between levels is not undone; its command back is named
self.assertEqual((rc, self.read(self.data, "rules", "user.md")), (1, ""), back)
self.assertEqual(self.run_back(back), 1)
self.assertEqual((self.read(self.data, "rules", "core.md"), self.read(self.data, "rules", "user.md")), ("", "- Kept user rule [owner 2026-11-20]\n"))
def test_outside_git_the_user_rules_are_organized_and_audited(self): # finding 7, invariant 4
notes = self.mkdir(self.tmp, "notes")
self.user_file("".join("- User rule number %d is here [retro 2026-11-20]\n" % i for i in range(32)))
for args in (["init", "-q"], ["add", "-A"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "start"]):
subprocess.run(["git"] + args, cwd=self.data, check=True, capture_output=True)
self.assertIn("need organizing", self.hook("tick", sid="n1", cwd=notes)[1])
rc, out, _ = self.sisi("rules", "organize", cwd=notes)
self.assertEqual(rc, 0, out)
ans = self.write(os.path.join(self.tmp, "ans.md"), "## user\n- One merged user rule [retro 2026-11-20]\n## project\n")
rc, out, err = self.sisi("rules", "organize", "--record", ans, cwd=notes)
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.read(self.data, "rules", "user.md"), "- One merged user rule [retro 2026-11-20]\n")
self.assertFalse(os.path.exists(os.path.join(notes, ".sisi")))
self.assertEqual(self.sisi("rules", "revert", cwd=notes)[0], 0)
self.assertEqual(len(self.read(self.data, "rules", "user.md").splitlines()), 32)
bad = self.write(os.path.join(self.tmp, "bad.md"), "## user\n## project\n- A project line with no project [retro 2026-11-20]\n")
rc, out, _ = self.sisi("rules", "organize", "--record", bad, cwd=notes)
self.assertEqual(rc, 1, out)
self.assertIn("## user", out)
self.user_file("- A user rule [retro 2026-11-20]\n")
self.write(os.path.join(self.data, "retro.jsonl"), '{"x": 1}\n' * 12)
self.assertIn("time to audit their levels", self.hook("tick", sid="n2", cwd=notes)[1])
def test_queued_core_rules_load_as_user_rules_until_put_in_canon(self): # invariant 5, finding 8
self.assertEqual(self.sisi("learn", "--level", "core", "Every sisi user should see this line")[0], 0)
self.assertIn("Every sisi user should see this line", self.read(self.data, "generated", "core.md"))
rc, out, _ = self.sisi("rules")
self.assertIn("Every sisi user should see this line", out)
self.assertIn("product", out)
rc, out, _ = self.sisi("rules", "move", "Every sisi user", "canon")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(self.data, "rules", "core.md"), "")
self.assertNotIn("Every sisi user", self.read(self.data, "generated", "core.md"))
self.assertEqual(self.sisi("learn", "--level", "user", "A user rule cannot go to canon")[0], 0)
self.assertEqual(self.sisi("rules", "move", "A user rule cannot", "canon")[0], 1)
help_text = self.sisi("--help")[1]
self.assertIn("learn --level", help_text)
self.assertIn("rules move", help_text)
self.assertTrue("sisi learn --level" in self.read(REPO, "canon", "core.md"))
def test_move_to_canon_is_final_and_revert_says_so(self): # undo review D
self.assertEqual(self.sisi("learn", "--level", "core", "Every sisi user should see this line")[0], 0)
rc, out, _ = self.sisi("rules", "move", "Every sisi user", "canon")
self.assertEqual(rc, 0, out)
self.assertIn("final", out)
self.assertEqual(self.read(self.data, "rules", "core.md"), "")
rc, out, _ = self.sisi("rules", "revert")
self.assertEqual(rc, 1)
self.assertIn("final", out)
self.assertEqual(self.read(self.data, "rules", "core.md"), "")
def test_option_edge_cases_are_parsed_or_refused(self): # finding 9
rc, out, _ = self.sisi("learn", "Always check this first", "--means", "check it every time", "--level", "user")
self.assertEqual(rc, 0, out)
self.assertIn("check it every time [agent reading", self.read(self.data, "rules", "user.md"))
self.assertEqual(self.sisi("learn", "--level", "user", "Always check this second", "--means")[0], 1)
self.assertEqual(self.sisi("rules", "move", "Always check", "project", "--project")[0], 1)
rc, out, _ = self.sisi("retro", *GAP[:-2], *IMP, "--level", "user", "--scope", "project")
self.assertEqual(rc, 1, out)
notes = self.mkdir(self.tmp, "notes")
rc, out, _ = self.sisi("retro", "--no-gap", "the export kept every row in the check", *NG, "--level", "project", cwd=notes)
self.assertEqual(rc, 0, out)
self.assertIn("--level goes only with --gap", out)
def test_old_rules_are_never_moved_into_the_home_folder(self): # finding 10
subprocess.run(["git", "init", "-q"], cwd=self.tmp, check=True, capture_output=True)
self.legacy(self.tmp, "- Old rule of the home folder [owner 2026-11-20]\n")
self.hook("tick", sid="h1", cwd=self.tmp)
self.assertFalse(os.path.exists(os.path.join(self.tmp, ".sisi")))
self.assertFalse(os.path.exists(os.path.join(self.tmp, "AGENTS.md")))
# the fix review (fix-review.md): a change across files is not undone by revert, which names the command that moves it back
def run_back(self, out):
"""Run each reverse command an output names (`sisi rules move ...`, maybe after `cd DIR &&`); returns how many."""
cmds = [l.strip() for l in out.splitlines() if l.startswith(" ") and "sisi rules move " in l]
for c in cmds:
words = shlex.split(c)
cwd = words[1] if words[0] == "cd" else None
words = words[words.index("sisi") + 1:]
rc, o, e = self.sisi(*words, cwd=cwd)
self.assertEqual((rc, e), (0, ""), (c, o))
return len(cmds)
def test_revert_after_a_move_in_a_store_without_history_loses_nothing(self): # fix review 1
user, proj = os.path.join(self.data, "rules", "user.md"), os.path.join(self.proj, ".sisi", "rules.md")
self.user_file("- Manual user rule [owner 2026-11-20]\n")
rc, out, err = self.sisi("rules", "move", "Manual user rule", "project")
self.assertEqual((rc, err), (0, ""), out)
self.assertIn("sisi rules move", out)
rc, out, _ = self.sisi("rules", "revert")
self.assertEqual(rc, 1, out)
self.assertIn("Nothing was changed", out)
self.assertEqual((self.read(user), self.read(proj)), ("", "- Manual user rule [owner 2026-11-20]\n"))
self.assertEqual(self.run_back(out), 1)
self.assertEqual((self.read(user), self.read(proj)), ("- Manual user rule [owner 2026-11-20]\n", ""))
shutil.rmtree(os.path.join(self.data, ".git")) # a first learn into a store with no history: its revert keeps what was there
self.assertEqual(self.sisi("learn", "--level", "user", "A new user rule after the manual one")[0], 0)
self.assertEqual(self.sisi("rules", "revert")[0], 0)
self.assertEqual(self.read(user), "- Manual user rule [owner 2026-11-20]\n")
def test_revert_after_two_organizes_that_leave_the_project_list_alone(self): # fix review 2
user, proj = os.path.join(self.data, "rules", "user.md"), os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md")
self.write(proj, "- Keep project rule [owner 2026-11-20]\n")
self.user_file("- User rule one [retro 2026-11-20]\n- User rule two [retro 2026-11-20]\n")
for n, users in enumerate(("- User rule one merged [retro 2026-11-20]\n", "- User rule one merged again [retro 2026-11-20]\n")):
ans = self.write(os.path.join(self.tmp, "a%d.md" % n), "## user\n" + users + "## project\n- Keep project rule [owner 2026-11-20]\n")
self.assertEqual(self.sisi("rules", "organize")[0], 0)
rc, out, _ = self.sisi("rules", "organize", "--record", ans)
self.assertEqual(rc, 0, out)
rc, out, _ = self.sisi("rules", "revert")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(user), "- User rule one merged [retro 2026-11-20]\n")
self.assertEqual(self.read(proj), "- Keep project rule [owner 2026-11-20]\n")
def test_a_store_path_with_a_trailing_slash_is_still_the_store(self): # fix review 3
self.env["SISI_DATA"] = self.data + os.sep
self.assertEqual(self.sisi("learn", "--level", "user", "Trailing slash rule stays one rule")[0], 0)
rc, out, err = self.sisi("rules", "move", "Trailing slash rule", "project")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True).stdout, "")
rc, out, _ = self.sisi("rules", "revert")
self.assertIn("sisi rules move", out)
self.assertEqual(self.read(self.proj, ".sisi", "rules.md").count("Trailing slash rule"), 1)
self.assertEqual(self.sisi("learn", "--level", "user", "Another rule with the slash")[0], 0)
self.assertEqual(self.sisi("rules", "revert")[0], 0)
self.assertNotIn("Another rule", self.read(self.data, "rules", "user.md"))
def test_revert_after_a_move_between_projects_changes_neither(self): # fix review 4
from sisi import rules, store
pf, pe = self.project("pf"), self.project("pe")
self.assertEqual(self.sisi("learn", "--level", "project", "Rule E already there", cwd=pe)[0], 0)
self.assertEqual(self.sisi("learn", "--level", "project", "Rule F to E revert fail", cwd=pf)[0], 0)
rc, out, err = self.sisi("rules", "move", "Rule F to E", "project", "--project", pe, cwd=pf)
self.assertEqual((rc, err), (0, ""), out)
fpath, epath = os.path.join(pf, ".sisi", "rules.md"), os.path.join(pe, ".sisi", "rules.md")
before, real = self.sides(fpath, epath), store.write
with mock.patch.object(store, "write", lambda p, t: (_ for _ in ()).throw(OSError("disk full")) if p == epath else real(p, t)):
why, out = self.in_process(rules.revert)
self.assertIn("sisi rules move", out)
self.assertEqual(self.sides(fpath, epath), before)
self.assertEqual(self.run_back(out), 1)
self.assertEqual([(s or "").count("Rule F to E") for s in self.sides(fpath, epath)], [1, 0])
def test_organize_takes_the_user_lock_and_refuses_a_linked_drops_file(self): # fix review 5
from sisi import rules, store
self.user_file("- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n")
real_lock, keys = store.lock, []
ans = self.write(os.path.join(self.tmp, "a.md"), "## user\n- User rule kept [owner 2026-11-20]\n## project\n")
self.in_process(rules.organize_brief, self.proj)
with mock.patch.object(store, "lock", lambda key, wait=True: keys.append(key) or real_lock(key, wait=wait)):
why, out = self.in_process(rules.organize_record, ans, self.proj)
self.assertIsNone(why, out)
self.assertIn("user", keys)
self.assertEqual(self.sisi("rules", "revert")[0], 0)
ext = self.write(os.path.join(self.tmp, "elsewhere.jsonl"), '{"outside": 1}\n')
dp = os.path.join(self.data, "rules", "drops.jsonl")
os.path.lexists(dp) and os.remove(dp)
os.symlink(ext, dp)
self.assertEqual(self.sisi("rules", "organize")[0], 0)
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (1, ""), out)
self.assertIn("symlink", out)
self.assertTrue(os.path.islink(dp))
self.assertEqual(self.read(ext), '{"outside": 1}\n')
self.assertIn("User rule to drop", self.read(self.data, "rules", "user.md"))
def test_rules_usage_names_canon_and_a_bad_file_is_named(self): # fix review 7
self.assertIn("|canon", self.sisi("rules", "nonsense")[1])
with open(self.user_file(""), "wb") as f:
f.write(b"- bad \xff byte [retro 2026-11-20]\n")
rc, out, _ = self.sisi("rules", "move", "bad", "project")
self.assertEqual(rc, 1, out)
self.assertIn("user.md is not valid UTF-8", out)
def test_gap_retro_writes_problem_tag_and_loaded_text_has_no_recurrence_note(self):
from sisi import rules
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Compare row counts before every export", sid="p1")
self.assertEqual(rc, 0, out)
self.assertRegex(self.read(self.proj, ".sisi", "rules.md").strip(), r"Compare row counts before every export \[retro \d{4}-\d{2}-\d{2} p1\]$")
rc, out, _ = self.sisi("retro", *GAP[:-4], "--problem", "stale cache key", "--level", "user",
"--improve", "Bust cache keys on every schema bump", sid="p1")
self.assertEqual(rc, 0, out)
self.assertRegex(self.read(self.data, "rules", "user.md").strip(), r"Bust cache keys on every schema bump \[retro \d{4}-\d{2}-\d{2} p2\]$")
rc, out, _ = self.sisi("retro", *GAP[:-4], "--problem", "1", "--level", "core",
"--improve", "Check row counts in every product export", sid="p1")
self.assertEqual(rc, 0, out)
self.assertRegex(self.read(self.data, "rules", "core.md").strip(), r"Check row counts in every product export \[retro \d{4}-\d{2}-\d{2} p1\]$")
self.assertEqual(self.sisi("learn", "--level", "user", "Keep learned rules short and clear", sid="p1")[0], 0)
self.assertNotRegex(self.read(self.data, "rules", "user.md").splitlines()[-1], r"\bp\d+\]")
self.in_process(rules.build_rulebook)
book = self.read(self.data, "generated", "core.md")
tick = self.hook("tick", sid="p2")[1]
for loaded in (book, tick):
self.assertNotIn("came back", loaded)
self.assertNotIn("not seen since", loaded)
self.assertRegex(book, r"Bust cache keys on every schema bump \[retro \d{4}-\d{2}-\d{2} p2\]")
self.assertRegex(tick, r"Compare row counts before every export \[retro \d{4}-\d{2}-\d{2} p1\]")
def test_rules_listing_and_organize_brief_show_problem_recurrence_since_rule_date(self):
from sisi import rules
os.makedirs(self.data, exist_ok=True)
retro_rows = [
{"ts": "2026-11-20T10:00:00", "problem": "export drops empty names", "cause": "c1", "improve": "r1"},
{"ts": "2026-11-21T10:00:00", "problem": "stale cache key", "cause": "c2", "improve": "r2"},
{"ts": "2026-11-22T10:00:00", "problem": "export drops empty names", "cause": "c3", "improve": "r3"},
{"ts": "2026-11-23T10:00:00", "problem": "missing lock cleanup", "cause": "c4", "improve": "r4"},
{"ts": "2026-11-23T15:00:00", "problem": "missing lock cleanup", "cause": "c4b", "improve": "r4b"},
{"problem": "missing lock cleanup", "cause": "c4c", "improve": "r4c"},
{"ts": "2026-11-24T10:00:00", "problem": "stale cache key", "cause": "c5", "improve": "r5"},
{"ts": "2026-11-25T10:00:00", "problem": "export drops empty names", "cause": "c6", "improve": "r6"},
]
self.write(os.path.join(self.data, "retro.jsonl"), "".join(json.dumps(r) + "\n" for r in retro_rows))
self.write(os.path.join(self.mkdir(self.data, "rules"), "user.md"), "\n".join([
"- User rule for p1 early [retro 2026-11-20 p1]",
"- User rule for p1 middle [retro 2026-11-22 p1]",
"- User rule for p1 latest [retro 2026-11-25 p1]",
]) + "\n")
self.write(os.path.join(self.data, "rules", "core.md"), "- Core rule for p2 early [retro 2026-11-21 p2]\n")
self.write(os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md"), "\n".join([
"- Project rule for p2 latest [retro 2026-11-24 p2]",
"- Project rule for p3 same day [retro 2026-11-23 p3]",
]) + "\n")
_, listing_inproc = self.in_process(rules.show, self.proj)
rc, listing_cli, err = self.sisi("rules")
self.assertEqual((rc, err), (0, ""), listing_cli)
rc_b, brief, err_b = self.sisi("rules", "organize")
self.assertEqual((rc_b, err_b), (0, ""), brief)
for out in (listing_inproc, listing_cli):
self.assertIn("- User rule for p1 early [retro 2026-11-20 p1] (p1: came back 2x since)", out)
self.assertIn("- User rule for p1 middle [retro 2026-11-22 p1] (p1: came back 1x since)", out)
self.assertIn("- User rule for p1 latest [retro 2026-11-25 p1] (p1: not seen since)", out)
self.assertIn("- Core rule for p2 early [retro 2026-11-21 p2] (p2: came back 1x since)", out)
self.assertIn("- Project rule for p2 latest [retro 2026-11-24 p2] (p2: not seen since)", out)
self.assertIn("- Project rule for p3 same day [retro 2026-11-23 p3] (p3: not seen since)", out)
self.assertIn("- User rule for p1 early [retro 2026-11-20 p1] (p1: came back 2x since)", brief)
self.assertIn("- User rule for p1 latest [retro 2026-11-25 p1] (p1: not seen since)", brief)
self.assertIn("- Project rule for p2 latest [retro 2026-11-24 p2] (p2: not seen since)", brief)
self.assertIn("came back", brief.split("=== The first list now")[0])
self.in_process(rules.build_rulebook)
book = self.read(self.data, "generated", "core.md")
tick = self.hook("tick", sid="rec1")[1]
for loaded in (book, tick):
self.assertNotIn("came back", loaded)
self.assertNotIn("not seen since", loaded)
def test_old_tags_without_problem_and_organize_merge_keeps_problem_tags(self):
os.makedirs(self.data, exist_ok=True)
retro_rows = [
{"ts": "2026-11-20T10:00:00", "problem": "export drops empty names", "cause": "c1", "improve": "r1"},
{"ts": "2026-11-21T10:00:00", "problem": "stale cache key", "cause": "c2", "improve": "r2"},
{"ts": "2026-11-22T10:00:00", "problem": "export drops empty names", "cause": "c3", "improve": "r3"},
{"ts": "2026-11-24T10:00:00", "problem": "stale cache key", "cause": "c4", "improve": "r4"},
{"ts": "2026-11-25T10:00:00", "problem": "export drops empty names", "cause": "c5", "improve": "r5"},
]
self.write(os.path.join(self.data, "retro.jsonl"), "".join(json.dumps(r) + "\n" for r in retro_rows))
own = "- Owner rule stays verbatim [owner 2026-11-20]"
old_u = "- Old user rule without problem [retro 2026-11-20]"
old_m = "- Old merged rule without problem [retro 2026-11-20, 2026-11-21]"
p1_a = "- Check row counts before export [retro 2026-11-20 p1]"
p1_b = "- Check row counts after export [retro 2026-11-22 p1]"
p2_a = "- Clear cache on schema change [retro 2026-11-21 p2]"
self.write(os.path.join(self.mkdir(self.data, "rules"), "user.md"), "\n".join([own, old_u, old_m, p1_a, p1_b]) + "\n")
self.write(os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md"), "\n".join([p2_a, "- Old project rule [retro 2026-11-20]"]) + "\n")
listing = self.sisi("rules")[1]
for plain in (own, old_u, old_m, "- Old project rule [retro 2026-11-20]"):
self.assertIn(plain + "\n", listing + "\n")
self.assertNotIn(plain + " (p", listing)
brief = self.sisi("rules", "organize")[1]
self.assertIn(p1_a + " (p1: came back 2x since)", brief)
self.assertIn(p2_a + " (p2: came back 1x since)", brief)
# Worker merges p1_a + p1_b keeping p1, merges p1 + p2 keeping both, and accidentally copies a (pN: ...) note on a kept line and drop line
ans = self.write(os.path.join(self.tmp, "merge.md"), "\n".join([
"## user",
own,
old_u,
"- Check row counts before and after export [retro 2026-11-20, 2026-11-22 p1]",
"## project",
"- Check export counts and clear cache [retro 2026-11-20 p1, 2026-11-21 p2] (p1: came back 2x since; p2: came back 1x since)",
"## drops",
"- %s | #- | old merged replaced" % old_m[2:],
"- %s (p1: came back 2x since) | #1 | merged into combined count check" % p1_a[2:],
"- %s | #1 | merged into combined count check" % p1_b[2:],
"- %s (p2: came back 1x since) | #2 | merged with count check" % p2_a[2:],
"- Old project rule [retro 2026-11-20] | #- | obsolete",
]) + "\n")
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (0, ""), out)
self.assertNotIn("no reason recorded", out)
user_after = self.read(self.data, "rules", "user.md")
proj_after = self.read(self.proj, ".sisi", "rules.md")
book_after = self.read(self.data, "generated", "core.md")
self.assertIn("- Check row counts before and after export [retro 2026-11-20, 2026-11-22 p1]", user_after)
self.assertIn("- Check export counts and clear cache [retro 2026-11-20 p1, 2026-11-21 p2]", proj_after)
for saved in (user_after, proj_after, book_after):
self.assertNotIn("came back", saved)
self.assertNotIn("not seen since", saved)
listing2 = self.sisi("rules")[1]
self.assertIn("- Check row counts before and after export [retro 2026-11-20, 2026-11-22 p1] (p1: came back 1x since)", listing2)
self.assertIn("- Check export counts and clear cache [retro 2026-11-20 p1, 2026-11-21 p2] (p1: came back 2x since; p2: came back 1x since)", listing2)
def test_the_product_stays_small(self): def test_the_product_stays_small(self):
code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py")))
self.assertLessEqual(code, 2283, "sisi is two loops. If it needs more than this, find the simpler shape.") self.assertLessEqual(code, 2530, "sisi is two loops. If it needs more than this, find the simpler shape.")
rulebook = self.read(REPO, "canon", "core.md") rulebook = self.read(REPO, "canon", "core.md")
self.assertLess(len(rulebook.splitlines()), 139) self.assertLess(len(rulebook.splitlines()), 139)
self.assertLessEqual(len(rulebook), 10711) self.assertLessEqual(len(rulebook), 10711)
+13 -8
View File
@@ -10,8 +10,9 @@ import tempfile
import unittest import unittest
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 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", 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(): def tree():
@@ -27,6 +28,9 @@ class OrganizeEvidence(unittest.TestCase):
def setUp(self): def setUp(self):
before = tree() before = tree()
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product 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.tmp = tempfile.mkdtemp(prefix="sisi-orgev-")
self.addCleanup(shutil.rmtree, self.tmp, True) self.addCleanup(shutil.rmtree, self.tmp, True)
self.data = os.path.join(self.tmp, "data") self.data = os.path.join(self.tmp, "data")
@@ -61,11 +65,11 @@ class OrganizeEvidence(unittest.TestCase):
return f.read() return f.read()
def test_brief_has_problem_evidence_and_respects_caps(self): 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", "--cause", "first cause missed null guard",
"--improve", "Check null names before exporting rows", "--improve", "Check null names before exporting rows",
"--term", "evidence", "--problem", "row count mismatch")[0], 0) "--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", "--cause", "second cause forgot whitespace trim",
"--improve", "Strip whitespace and assert total row count matches", "--improve", "Strip whitespace and assert total row count matches",
"--term", "evidence", "--problem", "1")[0], 0) "--term", "evidence", "--problem", "1")[0], 0)
@@ -85,7 +89,7 @@ class OrganizeEvidence(unittest.TestCase):
long_cause = "word " * 1000 long_cause = "word " * 1000
for i in range(2, 19): for i in range(2, 19):
cause = long_cause if i == 18 else "cause number %02d in batch" % i 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, "--cause", cause,
"--improve", "Rule number %02d for problem" % i, "--improve", "Rule number %02d for problem" % i,
"--term", "evidence", "--problem", "problem item %02d" % i)[0], 0) "--term", "evidence", "--problem", "problem item %02d" % i)[0], 0)
@@ -115,8 +119,9 @@ class OrganizeEvidence(unittest.TestCase):
self.assertIn("copied as it is", brief) self.assertIn("copied as it is", brief)
shape = brief.split("Answer with exactly this shape")[1].split("===")[0] shape = brief.split("Answer with exactly this shape")[1].split("===")[0]
self.assertLess(shape.index("## project"), shape.index("## drops")) self.assertLess(shape.index("## project"), shape.index("## drops"))
self.assertLess(shape.index("## drops"), shape.index("## flags")) self.assertLess(shape.index("## drops"), shape.index("## same problems"))
self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 35) self.assertLess(shape.index("## same problems"), shape.index("## flags"))
self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 42)
proj_line = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] proj_line = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
ans = self.write(os.path.join(self.tmp, "ans.md"), ans = self.write(os.path.join(self.tmp, "ans.md"),
"## user\n## project\n- Kept project rule [retro 2026-11-26]\n" "## 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): 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.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) 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] own = self.read(self.data, "rules", "user.md").splitlines()[0]
ret = self.read(self.proj, ".sisi", "rules.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): 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.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) 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] own = self.read(self.data, "rules", "user.md").splitlines()[0]
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
+196 -5
View File
@@ -13,10 +13,11 @@ import unittest
from unittest import mock from unittest import mock
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REAL_HOME = os.path.expanduser("~")
sys.path.insert(0, REPO) 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", 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(): def tree():
@@ -32,11 +33,15 @@ class Problems(unittest.TestCase):
def setUp(self): def setUp(self):
before = tree() before = tree()
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product 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.tmp = tempfile.mkdtemp(prefix="sisi-prob-")
self.addCleanup(shutil.rmtree, self.tmp, True) self.addCleanup(shutil.rmtree, self.tmp, True)
self.data = os.path.join(self.tmp, "data") self.data = os.path.join(self.tmp, "data")
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.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"): for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"):
self.env.pop(name, None) self.env.pop(name, None)
self.proj = os.path.join(self.tmp, "alpha") 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"]): 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) 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=""): def sisi(self, *args, cwd=None, sid=None, stdin=""):
env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env
out_f = os.path.join(self.tmp, "stdout.tmp") out_f = os.path.join(self.tmp, "stdout.tmp")
@@ -55,6 +71,10 @@ class Problems(unittest.TestCase):
fe.seek(0) fe.seek(0)
return r.returncode, fo.read(), fe.read() 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): def records(self):
p = os.path.join(self.data, "retro.jsonl") p = os.path.join(self.data, "retro.jsonl")
if not os.path.exists(p): if not os.path.exists(p):
@@ -87,7 +107,7 @@ class Problems(unittest.TestCase):
self.assertNotIn("has come back", out) self.assertNotIn("has come back", out)
# Open problem #2 by words # 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", "--cause", "clean step was skipped on incremental runs",
"--improve", "Always clean output directory before packaging release", "--improve", "Always clean output directory before packaging release",
"--term", "value", "--problem", "stale build artifacts") "--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 # 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", 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) "--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", "--cause", "incremental cache kept old binary",
"--improve", "Hash inputs before reusing build artifacts", "--improve", "Hash inputs before reusing build artifacts",
"--term", "value", "--problem", "2") "--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("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) 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__": if __name__ == "__main__":
unittest.main() unittest.main()