65 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
swaitsandClaude Fable 5.2 6e73cca4a1 Merge: store files are written under the store lock with their commit; tests cannot write the person's rules file
ci / test (push) Canceled after 0s
Fixes the CI failure in run 46195092165 (short read while indexing rules/last-project.json).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 16:39:10 -07:00
swaitsandClaude Fable 5.2 c91d5ed8a5 Project rule: probe a worker reported as not confirmed before accepting the table
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 16:39:10 -07:00
swaitsandClaude Fable 5.2 62e494de8e Tests: no background git upkeep in test projects
The setup commit started a detached git gc that pruned the tripwires test's fake .git/worktrees folders later under load (7 of 16 runs failed with four loops at once; 0 of 40 after).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 16:39:10 -07:00
swaitsandClaude Fable 5.2 6292f5c45e Store commit fix: fit the size budget (put paths are committed without being named twice)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 16:09:59 -07:00
swaitsandClaude Fable 5.2 6477f22933 Tests: in-process helper uses the temp home; guard fails any test that writes the person's own rules file
The new organize test rebuilt the rulebook in-process with the real home folder and re-pointed ~/.claude/CLAUDE.md at a deleted temp store.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 15:55:47 -07:00
swaits 4c32469a58 Store commits: write the files they stage under the store lock; reads take no optional lock
A commit under the store lock read a store file as another process replaced it
outside that lock. git: "short read while indexing rules/last-project.json"
(CI run 46195092165), then "rules/user.md" from rules organize. The undo
snapshot and organize's two store files are now written inside store.commit,
under the lock. sisi's own unlocked `git status` also held index.lock against
those commits ("Unable to create index.lock: File exists"): git calls take no
optional lock. The first line of git's stderr stays in the message.
2026-11-28 15:53:39 -07:00
swaits 94178e9b04 Merge: note at delegation when a brief for something the person will look at states no look
ci / test (push) Canceled after 0s
2026-11-28 15:02:38 -07:00
swaits 7c44dc2b68 Screen-look check, tuning round: name screens, windows, PDFs, print and footers as screen work
Every term is now matched as a whole word (the boundaries used to bind only the first
and last term), so 'build' no longer counts as 'ui'. Eight terms are added for screens,
windows, UI, onboarding, PDFs, printable matter, footers and terminals; write, generate
and produce count as making. The four look groups are one compiled expression. Train
0.95 (38 of 40), held 0.96 (22 of 23), every real row right.
2026-11-28 15:01:01 -07:00
swaits 74afc795a2 Merge labelled briefs for the screen-look check 2026-11-28 14:49:32 -07:00
swaits 58ee83fa38 Note a delegation whose brief asks for something the person will look at but states no look
Rule 5 gains one sentence: the brief states the look, chosen with the person from previews.
The delegation hook adds a note (never a block) when the brief makes something, names two
or more screen terms and states no look (no Look:/Design system: line, fewer than three of
the four groups). Five lines are merged elsewhere in hooks.py; the labelled-set test skips
while tests/data/screen_briefs.jsonl is absent.
2026-11-28 14:48:15 -07:00
swaitsandClaude Sonnet 5.5 6f8cc60890 Add labelled screen-brief examples for the look-note check
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 14:37:06 -07:00
swaitsandClaude Sonnet 5.5 8e2654892e Review fixes for out-retry: ignore clocks far ahead, refuse out for an unknown worker, name only a usable return time
ci / test (push) Canceled after 0s
A verdict (or table) dated 6 h or more ahead of now took a worker out until that date, so a wrong clock could do it for good: such times now say nothing.
`sisi judge X out` for a name that is not one worker of the table was recorded and changed nothing: now refused.
The all-out message named the return of a worker that would still be excluded: it now names only workers pick could hand out.
The refusal for `out until` in a table told a research worker to judge the worker, which would record a made-up verdict: it now says to delete the note.
The wheel test raced its own clock (failed on c5fd556 too); it now uses one fixed time. Code size guard 2265 to 2267.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:58:48 -07:00
swaits c5fd556196 Track worker availability from judged out verdicts, not table notes
A worker judged `out` (with the provider's message) is off the wheel for 6 hours,
then tried again: at most 24 h / 6 h = 4 tries a day. A later good or bad verdict
puts it back at once. `sisi pick` says when a pick is a retry and names when the
first out worker of a class is back; `sisi models` lists who is out and until when.

Why: `out until DATE` notes were typed by an agent as a guess, a rebuild copied
them across, a good verdict never cleared them, and a date of today did not count,
so working workers stayed off the wheel for days. A new table may no longer carry
the note (the research brief says so, and recording one is refused); an old table
is still read: its note dates from the table's own time and spends itself in 6 hours.
2026-11-27 17:29:37 -07:00
swaitsandClaude Fable 5.2 a3f769a840 Project rule: sisi trials redirect HOME as well as the store
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 22:57:34 -07:00
swaits b300a8fa09 Make organize drop reasons lenient, bounded, and non-blocking
ci / test (push) Canceled after 0s
2026-11-26 22:50:09 -07:00
swaitsandClaude Fable 5.2 cf1298a726 Merge feat/organize-evidence: problem evidence in the organize brief, recorded drop reasons
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 22:35:20 -07:00
swaits 58f23df148 Fix retro problem race, 2MB read bound, wording, redaction check, and docs
ci / test (push) Canceled after 0s
2026-11-26 22:31:14 -07:00
swaits 4b9a59b23b Include problem evidence and drop reasons in rules organize 2026-11-26 22:29:06 -07:00
swaitsandClaude Fable 5.2 37b85251a6 Rule 8: keep 'name the one thing that would have scored better'
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 22:18:19 -07:00
swaits 8362f69c16 Track recurring problems in retro and escalate repeats to faults 2026-11-26 22:17:39 -07:00
swaitsandClaude Fable 5.2 4d6b2caa8b Project rules: two learned rules from the 11-25 retros
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 22:07:22 -07:00
sisi a5882e3cfd Review fixes: late faults per session, one-commit learn --means, FIFO pending, extend targets late job, said guards, flags header, README
ci / test (push) Canceled after 0s
2026-11-25 22:54:07 -07:00
swaitsandClaude Opus 5.5 a63134ee6e Size guard: room for the GIT_DIR fix
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:37:18 -07:00
swaits 60e7dea44f Merge branch 'fix/tripwire-linked' into fix/parallel-incident 2026-11-25 22:37:10 -07:00
swaitsandClaude Opus 5.5 2485fbf352 Size guards: product 2090 lines, rulebook 136 lines / 10530 chars after the incident fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:30:02 -07:00
swaits 4810a03fde Merge branch 'fix/long-workers' into fix/parallel-incident
# Conflicts:
#	tests/test_core.py
2026-11-25 22:28:24 -07:00
swaits ed189976f8 Workers: 90m default, per-job --limit/--branch, extend, prompt status, 2x fault gate 2026-11-25 22:27:46 -07:00
swaitsandClaude Haiku 5.5 8f679dbba0 Git: a repository named by the caller's environment (GIT_DIR and friends) no longer decides which project a folder is
A git hook sets GIT_DIR, so sisi's git calls resolved every checkout to that outer repository; the tripwire test failed with inherited GIT_DIR.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-25 22:23:01 -07:00
t 9f442c4ddc start 2026-11-25 22:22:19 -07:00
t 0ed7df1155 start 2026-11-25 22:22:19 -07:00
t 6f5b1aa3ca start 2026-11-25 22:22:18 -07:00
t 73434306c8 start 2026-11-25 22:22:17 -07:00
t 6d77c91b5b start 2026-11-25 22:22:17 -07:00
t d7c0b40197 start 2026-11-25 22:22:17 -07:00
t 055810f20f start 2026-11-25 22:22:16 -07:00
t acdfa210cb start 2026-11-25 22:22:16 -07:00
t 6b0602ad17 start 2026-11-25 22:22:13 -07:00
t 54d122961f start 2026-11-25 22:20:36 -07:00
t 54312e6154 start 2026-11-25 22:20:31 -07:00
swaits 5b28ba1a8c Merge branch 'fix/owner-tag' into fix/parallel-incident 2026-11-25 22:17:53 -07:00
swaitsandClaude Opus 5.5 72262a83d7 Rulebook: drop the duplicate parallel-build sentence in rule 4, reflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:17:53 -07:00
sisi 848560a975 learn: owner tag only for words found in the person's recent messages; agent-attributed tag otherwise; --means line; organize flags concurrency smells and doubtful owner lines 2026-11-25 22:16:18 -07:00
swaitsandClaude Opus 5.5 bf6f67f0ff Rulebook: own checkout and build folder per worker, measured concurrency, resource fixes keep parallelism, time limit in every brief
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:01:09 -07:00
14 changed files with 3095 additions and 366 deletions

No files matched your search

+17 -10
View File
@@ -3,15 +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]
- Detached background workers must start with python3 -B and print no user-facing output whose only reader is a log; in tests send output to temp files, not pipes, and pass stdin explicitly. [retro 2026-11-23]
- Add a test-base guard that fails any test modifying files under the repo product tree, and run hook-imported modules under python3 -X importtime, keeping added import time under 20 ms. [retro 2026-11-23]
- 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 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]
+24 -18
View File
@@ -7,21 +7,24 @@ 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 host that names its models and a delegation to a worker the wheel did not give gets a note. Recent `bad` verdicts over a worker's last 10
good/bad jobs also scale its weight down (never to zero), while workers with no bad runs keep their full weight. One pick, one delegation. A worker that failed for a
limit is judged `out` with the provider's message: it is off the wheel for 6 hours, then the wheel tries it again (at most
4 times a day), and the pick that hands it out says it is a retry. A host that names its models
shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker 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) and 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`,
`attention` or `learning`: the terms of the objective), and `sisi retro` lays the facts out under those terms and shows their trend. `attention` or `learning`: the terms of the objective), and (for gap retros) the `problem` name. `sisi retro` lays the facts out under those terms, lists known problems (most recently cited first), and shows their trend. Citing the same problem a third time (2nd miss) and after opens a fault requiring a hook or automatic check rather than another rule. Problems are shared across all projects in your store while the fault opens in the project where the problem was cited, and a reworded name opens a new problem (matching is by the same words, ignoring case and spacing), so cite by number.
**Faults.** Record any fault you see with `sisi fault "<what is wrong>"` (kept per project across sessions). **Faults.** Record any fault you see with `sisi fault "<what is wrong>"` (kept per project across sessions).
Where the tool has hooks, session start and every request show the faults still not fixed, and with the gate Where the tool has hooks, session start and every request show the faults still not fixed, and with the gate
@@ -83,15 +86,17 @@ its limits are.
| `sisi done --goal … --check … [--check …] --next …` | Record what done means and what comes next; nothing starts before | | `sisi done --goal … --check … [--check …] --next …` | Record what done means and what comes next; nothing starts before |
| `sisi done --pass N "…"` / `--fail N "…"` | Give a check its verdict and evidence; `sisi done` alone shows it | | `sisi done --pass N "…"` / `--fail N "…"` | Give a check its verdict and evidence; `sisi done` alone shows it |
| `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]` | The wheel gives one worker; a review goes to a different maker | | `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, 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 [--scope user]` | Record the gap and the term of the objective it fell short on; the improvement is a rule at once | | `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] "…"` | The person's own words become a rule at once | | `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; undo the last rule change made with `learn`, a retro or `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 models` / `sisi models research [--record FILE]` | The workers table (the shared baseline table ships with sisi in `canon/models.md`); have a worker rebuild 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; 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 judge WORKER good\|bad "…" [--minutes N] [--newest]` | How a delegation went; 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 models` / `sisi models research [--record FILE]` | The workers table (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it |
| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest |
| `sisi judge WORKER extend MINUTES "<reason>" [--newest]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest) gets MINUTES more from now, and its late fault clears |
| `sisi direct "…"` | Allow more direct tool calls this turn, with the reason | | `sisi direct "…"` | Allow more direct tool calls this turn, with the reason |
## Where things live ## Where things live
@@ -101,8 +106,9 @@ Rules live at three levels:
- **The product** (this repository): the code in `sisi/`, and the rulebook in `canon/core.md` — rules useful to everyone - **The product** (this repository): the code in `sisi/`, and the rulebook in `canon/core.md` — rules useful to everyone
using sisi, the same for all users. `SPEC.md` is what it aims at. using sisi, the same for all users. `SPEC.md` is what it aims at.
- **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md` - **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md`
(how you like to work, across all your projects), `models.md` (your workers), `retro.jsonl` (each piece of work: session, (how you like to work, across all your projects), `rules/drops.jsonl` (rules dropped or merged away during `organize`,
`retro_seconds`, counts, goal, term) and `outcomes.jsonl` (each judged delegation: session, `project_key`, `model`, with date, matching problem number, and reason), `models.md` (your workers), `retro.jsonl` (each piece of work: session,
`retro_seconds`, counts, goal, term, problem; problem tracking reads the last 64,000,000 bytes) and `outcomes.jsonl` (each judged delegation: session, `project_key`, `model`,
`started`/`ended`, minutes, verdict, why). All plain text you can read and edit. `started`/`ended`, minutes, verdict, why). All plain text you can read and edit.
- **Each project** (`.sisi/rules.md` in the project's folder: in a git repository, the root of its main checkout, shared by - **Each project** (`.sisi/rules.md` in the project's folder: in a git repository, the root of its main checkout, shared by
all its worktrees; outside git, the folder sisi is run in): rules specific to one project. In a bare repository with all its worktrees; outside git, the folder sisi is run in): rules specific to one project. In a bare repository with
@@ -125,9 +131,9 @@ Rules live at three levels:
Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`. Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`.
Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8), Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8),
`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `worker_minutes` (15), `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.
+52 -45
View File
@@ -56,35 +56,39 @@ something that did not run read as passed.
## 4. Deliver fast ## 4. Deliver fast
Time to a first useful result and time to a verified finish are both part of success. Work in Time to a first useful result and time to a verified finish are both part of success. Work in parallel,
parallel, run the quickest check first and slow ones in the background, and hand over a useful run the quickest check first and slow ones in the background, and hand over a useful part as soon as it
part as soon as it stands on its own. Release each piece the moment its checks pass, with a way stands on its own. Release each piece the moment its checks pass, with a way back; reviews and later
back; reviews and later builds run beside or after a release, never in front of it. Make the smallest piece that can be released on its own the first check in `sisi done`, and release it before any other build or review starts. Do not chain builds run beside or after a release, never in front of it. Make the smallest piece that can be released
single workers one after another. Long builds running at once each get their own checkout and on its own the first check in `sisi done`, and release it before any other build or review starts. Do
branch, merged as each passes. When something has taken out of proportion to its not chain single workers one after another; merge each branch as it passes. When something has taken out
progress, stop and change approach: narrow it, use another worker, or ask. Never buy speed with of proportion to its progress, stop and change approach: narrow it, use another worker, or ask. Never
a weaker check. buy speed with a weaker check.
## 5. Delegate everything (lead only) ## 5. Delegate everything (lead only)
You own the outcome; workers do the work. Delegate reading, searching, building, testing, You own the outcome; workers do the work. Delegate reading, searching, building, testing, research and
research and first reviews, and keep your own context for intent, design, judgement and the first reviews, and keep your own context for intent, design, judgement and the final call. Do something
final call. Do something yourself only when briefing it would cost more than doing it. yourself only when briefing it would cost more than doing it. `sisi models` lists the workers you have.
`sisi models` lists the workers you have. Decide the class of the task (routine, ordinary, hard), Decide the class of the task (routine, ordinary, hard), counting rework as cost, then `sisi pick CLASS`
counting rework as cost, then `sisi pick CLASS` spins the wheel over the workers of that class and spins the wheel over the workers of that class and gives you one: use it. A class holds models of like
gives you one: use it. A class holds models of like strength from different makers; the wheel never mixes classes. A review always goes to a different maker than the author: strength from different makers; the wheel never mixes classes. A review always goes to a different maker
`sisi pick CLASS --review-of WORKER`. Start the worker with the host's own delegation tool; do not than the author: `sisi pick CLASS --review-of WORKER`. Start the worker with the host's own delegation
shell out to a worker's command line. Run tool; do not shell out to a worker's command line. Run independent work in parallel. Brief a worker as a
independent work in parallel. Brief a worker as a peer who starts cold: the outcome, what is peer who starts cold: the outcome, what is known and ruled out, what done looks like, the files it may
known and ruled out, what done looks like, the files it may change, what it may create. Decide change, what it may create, and a time limit (`sisi pick CLASS --limit MINUTES [--branch NAME]`). At the
the central mechanism in the brief, set against the person's standing rules on its subject, and say what a failed or limit it stops and reports as it stands: what is proven, what failed, what did not run. Extending is the
gamed job does to each number it optimizes. For a reported fault, the report's exact inputs are an acceptance test. For a lead's call, made once, with a reason (`sisi judge WORKER extend MINUTES "<reason>"`). Decide the
replacement, list each behaviour of the old thing as keep, change or drop, with a check for every central mechanism in the brief, set against the person's standing rules on its subject, and say what a
keep. Always use the newest version of a model within its maker and class. Its report is evidence for failed or gamed job does to each number it optimizes. For anything the person will look at, the brief
you to judge, not a fact to pass on; record how it went with `sisi judge`. When a worker fails states the look (type, colours, spacing, layout at each width), chosen with the person from previews.
for a limit, a login or a connection, give the same brief to the next one at once: do not ask For a reported fault, the report's exact inputs are an acceptance test. For a replacement, list each
the person and do not report it. When session start says the models table is old, start a behaviour of the old thing as keep, change or drop, with a check for every keep. Always use the newest
research worker in the background to rebuild it. version of a model within its maker and class. Its report is evidence for you to judge, not a fact to
pass on; record how it went with `sisi judge`. When a worker fails for a limit, a login or a connection,
judge it `out` with the provider's message (sisi retries it by itself) and give the same brief to the
next one at once: do not ask the person and do not report it. Rebuild the models table in the background
when session start says it is old.
## 6. Report plainly ## 6. Report plainly
@@ -106,26 +110,29 @@ tests, evidence and completion.
## 8. Close with a retro ## 8. Close with a retro
When a piece of work ends, the lead runs `sisi retro`, which prints what happened. Set it against When work ends, the lead runs `sisi retro` to see what happened and known problems. Set it against
the objective, term by term: where did the work fall short, why, and what instruction would have the objective by term: where did work fall short, why, and what instruction prevents it? Record
prevented it? Record that (`sisi retro --gap … --cause … --improve …`). 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 (useful to every sisi user, in the product), user (how this person works across projects, in their store), or project (one project, in `.sisi/rules.md` at its root, in git its main checkout's, which may be checked in). Name the root cause; general advice is not an 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
improvement. Prefer an improvement that makes the next work do more by itself over one that adds advice. Prefer a rule that makes next work do more by itself over a caution; a caution says what stays allowed
a caution; a new 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 … --better …`). Name the term of the objective each time (`--term`). When the person states a lasting 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 …`).
preference, record their words at once with `sisi learn`. When session start says the learned 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
A fault you see is yours, whether or not the request covers it: a crash, a failed run, a full A fault you see is yours, whether or not the request covers it: a crash, a failed run, a full disk, a
disk, a slow build, a wrong result, a mess. In the turn you see it, start its fix, or name what slow build, a wrong result, a mess. In the turn you see it, start its fix, or name what blocks the fix
blocks the fix and what would unblock it. Noting it, reporting it or working around it is not a and what would unblock it. Noting it, reporting it or working around it is not a fix. Fix the cause, not
fix. Fix the cause, not the symptom: ask why it happened, what else the same cause breaks, and the symptom: ask why it happened, what else the same cause breaks, and whether your own work fed it.
whether your own work fed it. What your work makes is yours to clear once no running job uses What your work makes is yours to clear once no running job uses it: copies, checkouts, branches, build
it: copies, checkouts, branches, build output, background jobs. Before work that makes copies, output, background jobs. Each worker that builds gets its own checkout and build folder, and workers
checkouts or builds, know how much room they take, share one build folder between checkouts where build at the same time: never make them take turns on one lock or share a build folder unless the build
the tool allows, and never start more than the machine has room for. A brief names what its tool is known to be safe with that. Measure what each piece needs and what the machine has free (CPU,
worker may create; remove it when the piece merges, without asking. Record it with `sisi fault memory, disk per checkout and build folder) and set how many build at once from that: never one unless a
"<what is wrong>"`. Where the tool has hooks, sisi shows open faults at every request and sends measurement says so. A brief names what its worker may create; remove it when the piece merges or is
you back twice before a turn ends on one with no fix started and no blocker named. A worker fixes dropped, without asking. Cleaning up is the answer to disk use, not fewer workers. Record a fault with
what its brief covers and reports the rest. Never wait to be told. `sisi fault "<what is wrong>"`; for a resource fault name the measured cause there first, and never cut
parallelism unless a measurement shows parallelism caused it. Where the tool has hooks, sisi shows open
faults at every request and sends you back twice before a turn ends on one with no fix started and no
blocker named. A worker fixes what its brief covers and reports the rest. Never wait to be told.
+12 -7
View File
@@ -12,24 +12,29 @@ 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 [--scope user] sisi retro --gap G --cause C --improve I --term T --problem N|"..." --level core|user|project
record the gap; the improvement becomes 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
sisi models research [--record FILE] sisi models research [--record FILE]
the brief for a research worker to rebuild that table; record its answer the brief for a research worker to rebuild that table; record its answer
sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]
the wheel gives you one worker of that class; one pick, one delegation the wheel gives you one worker of that class; one pick, one delegation
sisi judge WORKER good|bad WHY how a delegation went sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest]
how a delegation went (`out` with the provider's own message when it hit a
limit: sisi tries it again by itself), or give a running job more time
sisi direct REASON allow yourself more direct tool calls this turn, with the reason sisi direct REASON allow yourself more direct tool calls this turn, with the reason
Setting up Setting up
+15 -5
View File
@@ -8,7 +8,8 @@ BLOCK = 'sisi: open fault(s) with no fix started and no blocker named: %s. Start
_path = lambda cwd=None: os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json") _path = lambda cwd=None: os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")
_gb = lambda b: "%d GB" % round(b / 1e9) if b >= 1e9 else "%.1f GB" % (b / 1e9) _gb = lambda b: "%d GB" % round(b / 1e9) if b >= 1e9 else "%.1f GB" % (b / 1e9)
_safe = lambda s: str(s).encode("utf-8", "replace").decode("utf-8") _safe = lambda s: str(s).encode("utf-8", "replace").decode("utf-8")
lines = lambda cwd=None: [_fmt(f) for f in _load(_path(cwd))[0]["items"]] _mine = lambda f, sid: not f.get("kind", "").startswith("late:") or bool(sid) and f["kind"].startswith("late:%s:" % sid[:8]) # a late fault belongs to the session that started the job
lines = lambda cwd=None, sid="": [_fmt(f) for f in _load(_path(cwd))[0]["items"] if _mine(f, sid)]
def _load(p): def _load(p):
empty = {"next": 1, "items": []} empty = {"next": 1, "items": []}
@@ -30,8 +31,8 @@ def _fmt(f):
age = "%ds" % s if s < 60 else "%dm" % (s // 60) if s < 3600 else "%dh" % (s // 3600) if s < 86400 else "%dd" % (s // 86400) age = "%ds" % s if s < 60 else "%dm" % (s // 60) if s < 3600 else "%dh" % (s // 3600) if s < 86400 else "%dd" % (s // 86400)
return "#%d [%s, %s] %s%s" % (f["id"], f["state"], age, _safe(f["text"]), " — " + _safe(f["note"]) if f.get("note") else "") return "#%d [%s, %s] %s%s" % (f["id"], f["state"], age, _safe(f["text"]), " — " + _safe(f["note"]) if f.get("note") else "")
def gate(cwd=None): def gate(cwd=None, sid=""):
opened = [f for f in _load(_path(cwd))[0]["items"] if f["state"] == "open"] opened = [f for f in _load(_path(cwd))[0]["items"] if f["state"] == "open" and _mine(f, sid)]
return BLOCK % "; ".join("#%d %s" % (f["id"], _safe(f["text"])) for f in opened) if opened else "" return BLOCK % "; ".join("#%d %s" % (f["id"], _safe(f["text"])) for f in opened) if opened else ""
def add(cwd, text, kind="", flag="", fid=0): def add(cwd, text, kind="", flag="", fid=0):
@@ -44,6 +45,8 @@ def add(cwd, text, kind="", flag="", fid=0):
hit = next((f for f in doc["items"] if f["id"] == fid), None) hit = next((f for f in doc["items"] if f["id"] == fid), None)
if not hit: if not hit:
return None return None
if hit.get("kind", "").startswith("late:") and (flag != "--fixed" or hit["kind"].startswith("late:%s:" % (store.current_session(cwd) or "")[:8])):
raise OSError('#%d is a late worker fault; run `sisi judge WORKER good|bad|out "<why>"` or `sisi judge WORKER extend MINUTES "<reason>"`.' % fid)
doc["items"] = [f for f in doc["items"] if f["id"] != fid] if flag == "--fixed" else doc["items"] doc["items"] = [f for f in doc["items"] if f["id"] != fid] if flag == "--fixed" else doc["items"]
hit.update(state=flag[2:], note=text) hit.update(state=flag[2:], note=text)
elif kind and any(f.get("kind") == kind for f in doc["items"]): elif kind and any(f.get("kind") == kind for f in doc["items"]):
@@ -58,6 +61,13 @@ def add(cwd, text, kind="", flag="", fid=0):
store.write(p, out) store.write(p, out)
return hit return hit
def clear(cwd, prefix, keep=()):
if os.path.lexists(p := _path(cwd)):
with store.lock(p):
doc, err = _load(p)
if not err and len(items := [f for f in doc["items"] if not (f.get("kind", "").startswith(prefix) and f.get("kind") not in keep)]) != len(doc["items"]):
store.write(p, json.dumps({"next": doc["next"], "items": items}))
def _checkouts(cwd): def _checkouts(cwd):
try: try:
cur = os.path.abspath(cwd) cur = os.path.abspath(cwd)
@@ -73,7 +83,7 @@ def _checkouts(cwd):
except OSError: except OSError:
return 0 return 0
def check(cwd, start_free=None): def check(cwd, start_free=None, sid=""):
cfg, hits, pos = store.config(), [], lambda k: type(cfg[k]) in (int, float) and cfg[k] > 0 cfg, hits, pos = store.config(), [], lambda k: type(cfg[k]) in (int, float) and cfg[k] > 0
try: try:
st = os.statvfs(cwd) if pos("disk_free_percent") or (pos("disk_drop_percent") and type(start_free) in (int, float)) else None st = os.statvfs(cwd) if pos("disk_free_percent") or (pos("disk_drop_percent") and type(start_free) in (int, float)) else None
@@ -93,7 +103,7 @@ def check(cwd, start_free=None):
add(cwd, text, kind) add(cwd, text, kind)
except OSError: except OSError:
unsaved.append("[open] " + text) unsaved.append("[open] " + text)
ls = ([] if err else lines(cwd)) + unsaved ls = ([] if err else lines(cwd, sid)) + unsaved
return "\n".join(([err] if err else []) + ([HEAD] + ls[:10] + (["and %d more: sisi fault" % (len(ls) - 10)] if len(ls) > 10 else []) if ls else [])) return "\n".join(([err] if err else []) + ([HEAD] + ls[:10] + (["and %d more: sisi fault" % (len(ls) - 10)] if len(ls) > 10 else []) if ls else []))
def run(args, cwd=None): def run(args, cwd=None):
+44 -17
View File
@@ -12,14 +12,16 @@ DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call
METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your workers and `sisi pick routine|ordinary|hard` " 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>` " 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 "
"(--review-of WORKER for a review, --not WORKER if one is out); one pick, one delegation.") "(--review-of WORKER for a review, --not WORKER if one is out); one pick, one delegation.")
NOLOOK = ("sisi: this brief asks for something the person will look at but states no look (typefaces, sizes, colours, spacing, layout at each width). "
"Choose it with the person from previews and put it in the brief, or add a line 'Look: <the existing design it follows>'.")
UNKNOWN = "sisi: the worker you named is not in the models table (recorded so `sisi judge` still works), so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), and use `sisi pick` next time." UNKNOWN = "sisi: the worker you named is not in the models table (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>` (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>\"`."
@@ -68,8 +70,7 @@ def tool_class(tool):
_classes = {n: c for c, names in raw.items() for n in names} _classes = {n: c for c, names in raw.items() for n in names}
except (ValueError, AttributeError, TypeError): except (ValueError, AttributeError, TypeError):
_classes = {} # a missing or broken table meters nothing rather than breaking the session _classes = {} # a missing or broken table meters nothing rather than breaking the session
tool = tool.lower() return _classes.get(t := tool.lower()) or ("delegate" if t.endswith("delegate_task") else "")
return _classes.get(tool) or ("delegate" if tool.endswith("delegate_task") else "")
def own(command): def own(command):
@@ -99,11 +100,11 @@ def _begin(state, cwd):
pass pass
def _faults(cwd, gate=False, free=None): def _faults(cwd, gate=False, free=None, sid=""):
if gate and not os.path.lexists(os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")): if gate and not os.path.lexists(os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")):
return "" return ""
from . import faults from . import faults
return faults.gate(cwd) if gate else faults.check(cwd, free) return faults.gate(cwd, sid) if gate else faults.check(cwd, free, sid)
def tick(p): def tick(p):
@@ -118,29 +119,54 @@ 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)) if x) (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)
if text:
print(text)
return 0 return 0
def _late_lines(late1, cwd):
now, cfg_m = time.time(), store.config()["worker_minutes"]
def prog(branch, ext):
rc, out = store.git(["log", "-1", "--format=%ct", branch], cwd, timeout=2) if branch else (1, "")
return "commit %dm ago on %s" % (max(0, int((now - int(out.strip())) / 60)), branch) if rc == 0 and out.strip().isdigit() else "extended %dm ago" % max(0, int((now - ext) / 60)) if ext is not None else "no report since it started"
return ["sisi: worker %s has run %dm (limit %gm); last progress: %s" % (w, int((now - t) / 60), lim if lim is not None else cfg_m, prog(b, e)) for w, t, lim, b, e in late1]
def prompt(p): def prompt(p):
"""Each request: a new turn begins. The first request tells a delegated worker from a lead.""" """Each request: a new turn begins. The first request tells a delegated worker from a lead."""
sid, cwd, worker, free = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"], None sid, cwd, worker, free, late1 = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"], None, []
if sid: if sid:
with store.session(sid) as s: with store.session(sid) as s:
_begin(s, cwd) _begin(s, cwd)
if not s.get("prompts") and WORKER.search(p["prompt"][:2000]): if not s.get("prompts") and WORKER.search(p["prompt"][:2000]):
s["worker"] = True s["worker"] = True
worker, free = worker or bool(s.get("worker")), s.get("free_bytes") worker, free = worker or bool(s.get("worker")), s.get("free_bytes")
worker or not p["prompt"].strip() or WORKER.search(p["prompt"][:2000]) or s.update(said=((s["said"] if isinstance(s.get("said"), list) else []) + [" ".join(p["prompt"].split())[:8000]])[-20:]) # the person's own words
s["prompts"] = s.get("prompts", 0) + 1 s["prompts"] = s.get("prompts", 0) + 1
s.get("prompts_since") or s.update(began=time.time()) # the first request of a piece of work s.get("prompts_since") or s.update(began=time.time()) # the first request of a piece of work
s["prompts_since"] = s.get("prompts_since", 0) + 1 s["prompts_since"] = s.get("prompts_since", 0) + 1
s["direct"], s["extra"], s["blocks"] = 0, 0, 0 s["direct"], s["extra"], s["blocks"] = 0, 0, 0
not worker and (text := _faults(cwd, False, free)) and print(text) not worker and (models.sync_late(s, cwd, sid), late1 := models.late(s, 1))
not worker and (text := "\n".join(x for x in [_faults(cwd, False, free, sid)] + _late_lines(late1, cwd) if x)) and print(text)
return 0 return 0
# A brief states no look when it makes something (MAKING), names two or more of SCREEN and has neither a `Look:` / `Design system:` line nor three
# of the four GROUPS (type, colour, spacing, grid). Each entry is a regular expression, tried against the lowercase brief.
SCREEN = ("layouts?", "screens?", "screenshots?", "windows?", "viewports?", "phone[- ]widths?", "responsive", "stylesheets?", "css", "dark mode", "light and dark",
"typefaces?", "toolbars?", "sidebars?", "modals?", "dialog box(?:es)?", "cards?", "panels?", "charts?", "buttons?", "headlines?", "wraps", "scroll\\w*",
"ui", "onboarding", "pdfs?", r"print(?:able|er|ing|ed)", "footer", "terminal")
_SCREEN = re.compile(r"\b(?:(" + r")|(".join(SCREEN) + r"))\b")
MAKING = re.compile(r"\b(?:build\w*|creat\w*|mak(?:e|es|ing)\b|(?:re)?design\w*|restyle\w*|adds?\b|adding\b|lay(?:s|ing)? out|implement\w*|writ(?:e|es|ing)\b|generat(?:e|es|ing)\b|produc(?:e|es|ing)\b)")
GROUPS = re.compile(r"((?:fonts?|typefaces?|typography|type scale|helvetica|arial|roboto|georgia|garamond|times new roman|system-ui|sans-serif|segoe ui|sf pro|\binter\b))|((?:#[0-9a-f]{3,8}\b|palettes?|colou?r schemes?))|((?:padding|margins?|\bgaps?\b|spacing|radius))|((?:\bgrids?\b|columns?|breakpoints?))")
LOOK_LINE = re.compile(r"(?im)^\W{0,6}(?:look|design system)\s*:")
def screen_brief_without_look(text):
"""True when a brief asks for something the person will look at and states no look for it. Anything that is not text is False."""
t = text.lower() if isinstance(text, str) else ""
return bool(MAKING.search(t)) and len({m.lastindex for m in _SCREEN.finditer(t)}) >= 2 and not LOOK_LINE.search(t) and len({m.lastindex for m in GROUPS.finditer(t)}) < 3
def watch(p): def watch(p):
"""Before a tool call by the lead: count it, record delegations, and remind when off-course (never blocking).""" """Before a tool call by the lead: count it, record delegations, and remind when off-course (never blocking)."""
sid, tool, ti = p["session_id"], p["tool_name"].lower(), p["tool_input"] sid, tool, ti = p["session_id"], p["tool_name"].lower(), p["tool_input"]
@@ -157,13 +183,14 @@ def watch(p):
shell and not cfg["shell_workers"] and notes.append(NOSHELL) shell and not cfg["shell_workers"] and notes.append(NOSHELL)
(kind in ("delegate", "edit") or shell) and not s.get("done") and notes.append(NODONE) (kind in ("delegate", "edit") or shell) and not s.get("done") and notes.append(NODONE)
if kind == "delegate" or shell: if kind == "delegate" or shell:
brief = command if shell else " ".join(v for k in ("prompt", "task", "message", "instructions", "description", "content", "text") if isinstance(v := ti.get(k), str))
screen_brief_without_look(brief) and notes.append(NOLOOK)
target = ti.get("target") if isinstance(ti.get("target"), dict) else {} target = ti.get("target") if isinstance(ti.get("target"), dict) else {}
names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent")) names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent"))
text = command if shell else next((n for n in names if n and isinstance(n, str)), "") text = command if shell else next((n for n in names if n and isinstance(n, str)), "")
table_text = store.read(models.table()) table_text = store.read(models.table())
if tool != "workflow" and not models.claim(s, text, not shell and bool(names[0])): if tool != "workflow" and not models.claim(s, text, not shell and bool(names[0])):
probe = {"picked": [models.short(r[0]) for r in models.rows(table_text)]} known = models.claim(probe := {"picked": [models.short(r[0]) for r in models.rows(table_text)]}, text, True)
known = models.claim(probe, text, True)
if models.usable(table_text): if models.usable(table_text):
not shell and text.strip() and not known and models.stale(text) not shell and text.strip() and not known and models.stale(text)
notes.append(UNKNOWN if not shell and text.strip() and not known else NOPICK) notes.append(UNKNOWN if not shell and text.strip() and not known else NOPICK)
@@ -180,8 +207,7 @@ def watch(p):
s["changed"] = True s["changed"] = True
s.pop("paused", None) s.pop("paused", None)
s["direct"], s["direct_since"] = s.get("direct", 0) + 1, s.get("direct_since", 0) + 1 s["direct"], s["direct_since"] = s.get("direct", 0) + 1, s.get("direct_since", 0) + 1
if notes: notes and print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": say("\n".join(notes))}}))
print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": say("\n".join(notes))}}))
return 0 return 0
@@ -207,10 +233,11 @@ def gate(p, for_subagent=False):
_begin(s, cwd) _begin(s, cwd)
if s.get("worker"): if s.get("worker"):
return 0 return 0
open_f, starts = _faults(cwd, True), s["starts"] if isinstance(s.get("starts"), dict) else {} models.sync_late(s, cwd, sid)
open_f, starts = _faults(cwd, True, None, sid), s["starts"] if isinstance(s.get("starts"), dict) else {}
seen = [x for x in (s["reminded"] if isinstance(s.get("reminded"), list) else []) seen = [x for x in (s["reminded"] if isinstance(s.get("reminded"), list) else [])
if isinstance(x, list) and len(x) == 2 and x[1] in (starts.get(x[0]) if isinstance(starts.get(x[0]), list) else ())] if isinstance(x, list) and len(x) == 2 and x[1] in (starts.get(x[0]) if isinstance(starts.get(x[0]), list) else ())]
late = models.overdue({"starts": {w: [t for t in v if [w, t] not in seen] for w, v in starts.items() if isinstance(v, list)}}) late = models.overdue({"starts": {w: [t for t in v if [w, t] not in seen] for w, v in starts.items() if isinstance(v, list)}, "meta": s.get("meta")})
reason, demand = " ".join("sisi: " + LATE % (w, time.strftime("%H:%M", time.localtime(t))) for w, t in late), False reason, demand = " ".join("sisi: " + LATE % (w, time.strftime("%H:%M", time.localtime(t))) for w, t in late), False
if not reason and not s.get("paused"): if not reason and not s.get("paused"):
checks = (s.get("done") or {}).get("checks") or [] checks = (s.get("done") or {}).get("checks") or []
+150 -71
View File
@@ -13,7 +13,7 @@ ASK_STALE = ("which AI models this machine can delegate work to, what each is go
"Only the newest version of each model belongs in the table. A smaller or faster variant is a different model.") "Only the newest version of each model belongs in the table. A smaller or faster variant is a different model.")
EXTRA_SHARED = ("\nThen a second, separately marked section starting on its own line with `=== Shared models ===`, followed by `researched YYYY-MM-DD` on its first line and a baseline ranking table " EXTRA_SHARED = ("\nThen a second, separately marked section starting on its own line with `=== Shared models ===`, followed by `researched YYYY-MM-DD` on its first line and a baseline ranking table "
"(`| model | maker | class | score | released | list price | benchmarks | good at, bad at |`) with one row per model (keyed by model id, never provider route), sorted by class then score descending, " "(`| model | maker | class | score | released | list price | benchmarks | good at, bad at |`) with one row per model (keyed by model id, never provider route), sorted by class then score descending, "
"holding only shared public facts (no plans, allowances, `out until` dates, judged records, or personal notes).\n") "holding only shared public facts (no plans, allowances, availability, judged records, or personal notes).\n")
RESEARCH = """You are a worker. Do this task yourself; do not delegate it further. RESEARCH = """You are a worker. Do this task yourself; do not delegate it further.
@@ -38,8 +38,9 @@ other makers (benchmarks and the maker's own positioning), so that every class h
several makers. A model that seems to fit two classes goes in the lower one only if it truly performs at that several makers. A model that seems to fit two classes goes in the lower one only if it truly performs at that
level, never in both. "how to call it" is exact: the host delegation tool's provider and model id (T3 Code's level, never in both. "how to call it" is exact: the host delegation tool's provider and model id (T3 Code's
delegate_task); the host's subagent model name where it has subagents; the full command line with <brief> where delegate_task); the host's subagent model name where it has subagents; the full command line with <brief> where
the brief goes only for a worker the host's tool cannot reach. A worker that is unavailable carries exactly the brief goes only for a worker the host's tool cannot reach. Do not say in the notes whether a worker is
`out until YYYY-MM-DD` in its notes. available: `sisi judge WORKER out "<message>"` takes a worker that hit a limit off the wheel for a while, and
sisi tries it again by itself.
Then one line starting "Fallback order:" that says who takes over when a worker is out, level by level. Then one line starting "Fallback order:" that says who takes over when a worker is out, level by level.
%(extra)s %(extra)s
=== Shipped baseline table === === Shipped baseline table ===
@@ -87,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
@@ -162,19 +159,36 @@ def claim(s, text, segment=False):
if any(re.search(r"(?<![a-z0-9.-])%s(?![a-z0-9.-])" % re.escape(n), text.lower()) for n in (name, name.rsplit("/", 1)[-1])) or ( if any(re.search(r"(?<![a-z0-9.-])%s(?![a-z0-9.-])" % re.escape(n), text.lower()) for n in (name, name.rsplit("/", 1)[-1])) or (
segment and re.search("[a-z]", text.lower()) and text.lower() in name.rsplit("/", 1)[-1].split("-")): segment and re.search("[a-z]", text.lower()) and text.lower() in name.rsplit("/", 1)[-1].split("-")):
s["picked"].remove(name) s["picked"].remove(name)
starts = s["starts"] if isinstance(s.get("starts"), dict) else {} t, starts = time.time(), (s["starts"] if isinstance(s.get("starts"), dict) else {})
starts[name] = (starts[name] if isinstance(starts.get(name), list) else []) + [time.time()] starts[name] = (starts[name] if isinstance(starts.get(name), list) else []) + [t]
s["starts"] = starts # `sisi judge` times the job from here s["starts"] = starts # `sisi judge` times the job from here
if isinstance(s.get("pending"), dict) and isinstance(q := s["pending"].get(name), list) and q and isinstance(meta := q.pop(0), dict):
s["meta"] = {**(s["meta"] if isinstance(s.get("meta"), dict) else {}), "%s %r" % (name, t): meta}
s.setdefault("workers_since", []).append(name) s.setdefault("workers_since", []).append(name)
return True return True
return False return False
def late(s, factor=1):
"""Open jobs whose age >= factor * threshold: [(worker, start, limit, branch, extended)]."""
now, default_m, starts, meta, out = time.time(), store.config()["worker_minutes"], s.get("starts"), s.get("meta"), []
num = lambda x: type(x) in (int, float) and math.isfinite(x)
for w, v in (starts.items() if isinstance(starts, dict) else ()):
for t in (v if isinstance(v, list) else ()):
m = meta.get("%s %r" % (w, t)) if num(t) and t <= now and isinstance(meta, dict) else {}
m = m if isinstance(m, dict) else {}
lim = m.get("limit") if num(m.get("limit")) and m["limit"] > 0 else None
th = lim if lim is not None else default_m
if num(t) and t <= now and num(th) and now - t >= 60 * factor * th:
out.append((w, t, lim, m.get("branch") if isinstance(m.get("branch"), str) and m["branch"] else None, m.get("extended") if num(m.get("extended")) else None))
return out
def overdue(s): def overdue(s):
"""Open delegations older than `worker_minutes`: [(worker, its oldest such start)]. A bad or future start is none.""" """Open delegations older than their threshold: [(worker, its oldest such start)]."""
mins, starts = store.config()["worker_minutes"], s.get("starts") by_w, l = {}, late(s, 1)
old = lambda v: [t for t in v if type(t) in (int, float) and math.isfinite(t) and t <= time.time() - 60 * mins] if isinstance(v, list) else [] [by_w.setdefault(w, min(t for w2, t, *_ in l if w2 == w)) for w, *_ in l]
return [(w, min(old(v))) for w, v in (starts.items() if isinstance(starts, dict) and type(mins) in (int, float) else []) if old(v)] return list(by_w.items())
def waiting(s): def waiting(s):
@@ -182,11 +196,40 @@ def waiting(s):
return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values()) return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values())
def out(r, skip, bad, today): OUT = 6 * 3600 # a worker judged `out` sits out this long, then the wheel tries it again: 24 h / 6 h = at most 4 tries a day
"""Why this worker is off the wheel, "" when it is on.""" clock = lambda t: time.strftime("%m-%d %H:%M", time.localtime(t))
until = [d for d in re.findall(r"out until (\d{4}-\d{2}-\d{2})", " ".join(r).lower()) if d > today] SINCE = "out since %s, back on the wheel at %s"
def outs(text, log, written, today=None, now=None):
"""{worker: (since, why)}: each worker last said to be out, and when. An `out` verdict in the log says it, and any
later verdict takes it back. A table from before `out` verdicts says it with a note, `out until DATE` (DATE today or
later), unless the log holds a verdict for that worker newer than the table (`written`); the note dates from the table. A time OUT or more ahead of `now` is a wrong clock and says nothing."""
last, today, now = {}, today or time.strftime("%Y-%m-%d"), now or time.time()
for o in log:
try:
t = time.mktime(time.strptime(o["ts"], "%Y-%m-%dT%H:%M:%S"))
t - now < OUT and last.__setitem__(short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), (t, o.get("verdict"), str(o.get("why") or "")))
except (KeyError, TypeError, ValueError):
pass # a damaged line is no verdict
gone = {w: (t, why) for w, (t, verdict, why) in last.items() if verdict == "out"}
for r in rows(text):
w, until = short(r[0]), [d for d in re.findall(r"out until (\d{4}-\d{2}-\d{2})", " ".join(r).lower()) if d >= today]
if until and written is not None and written - now < OUT and not (w in last and last[w][0] >= int(written)): # the log keeps whole seconds
gone[w] = (written, "out until " + until[0])
return gone
def away():
"""`outs` for the table and the log as they are now."""
return outs(store.read(table()), store.records("outcomes.jsonl"), os.path.getmtime(table()) if os.path.exists(table()) else None, now=time.time())
def out(r, skip, bad, gone, now):
"""Why this worker is off the wheel, "" when it is on: excluded, the maker of the work under review, or out."""
since = gone.get(short(r[0]))
return ("excluded" if short(r[0]) in skip else "same maker as the work under review" if maker(r) == bad return ("excluded" if short(r[0]) in skip else "same maker as the work under review" if maker(r) == bad
else "out until " + until[0] if until else "") else SINCE % (clock(since[0]), clock(since[0] + OUT)) if since and now - since[0] < OUT else "")
def median(v): def median(v):
@@ -203,41 +246,49 @@ 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, today=None, speed=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),
table_rows, today = rows(text), today or time.strftime("%Y-%m-%d") 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."""
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, today)] 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]
def pick(args, cwd=None, rand=None): def pick(args, cwd=None, rand=None):
"""`sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...]`: the wheel gives one worker.""" """`sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]`: the wheel gives one worker."""
cls, skip, review, i = (args[0] if args and args[0] in ("routine", "ordinary", "hard") else None), set(), None, 1 cls, skip, review, limit, branch, i = (args[0] if args and args[0] in ("routine", "ordinary", "hard") else None), set(), None, None, None, 1
while cls and i < len(args): while cls and i < len(args):
if args[i] == "--not" and i + 1 < len(args): if args[i] == "--not" and i + 1 < len(args): skip.add(short(args[i + 1]))
skip.add(short(args[i + 1])) elif args[i] == "--review-of" and i + 1 < len(args): review = args[i + 1]
elif args[i] == "--review-of" and i + 1 < len(args): elif args[i] == "--limit" and i + 1 < len(args) and re.fullmatch(r"[1-9]\d{0,3}|10000", args[i + 1]): limit = int(args[i + 1])
review = args[i + 1] elif args[i] == "--branch" and i + 1 < len(args) and re.fullmatch(r"[A-Za-z0-9._/-]{1,100}", args[i + 1]) and not args[i + 1].startswith("-"): branch = args[i + 1]
else: else: cls = None
cls = None
i += 2 i += 2
if not cls: if not cls:
print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...]") print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]")
return 1 return 1
text = store.read(table()) text = store.read(table())
mine = [r for r in rows(text) if r[2].strip().lower() == cls] mine = [r for r in rows(text) if r[2].strip().lower() == cls]
@@ -247,25 +298,32 @@ 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 = speeds() speed, gone, qual, now = speeds(), away(), qualities(), time.time()
r = choose(text, cls, skip, review, rand, speed=speed) 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, "")
first = min((gone[short(x[0])][0] + OUT for x in mine if out(x, skip, bad, gone, now).startswith("out since")), default=None)
print(("sisi pick: every worker of class %s is out or excluded: %s." % (cls, "; ".join( print(("sisi pick: every worker of class %s is out or excluded: %s." % (cls, "; ".join(
"%s (%s)" % (x[0], out(x, skip, bad, time.strftime("%Y-%m-%d"))) for x in mine)) if mine "%s (%s)" % (x[0], out(x, skip, bad, gone, now)) for x in mine)) if mine
else "sisi pick: the models table has no worker of class %s." % cls) + again) else "sisi pick: the models table has no worker of class %s." % cls)
+ (" The first is back on the wheel at %s." % clock(first) if first is not None else "") + again)
return 1 return 1
sid = store.current_session(cwd) sid = store.current_session(cwd)
if sid: if sid:
with store.session(sid) as s: with store.session(sid) as s:
s.setdefault("picked", []).append(short(r[0])) s.setdefault("picked", []).append(w := short(r[0]))
q = s["pending"] if isinstance(s.get("pending"), dict) else {}
s["pending"] = {**q, w: (q[w] if isinstance(q.get(w), list) else []) + [{"limit": limit, "branch": branch}]} # one entry per pick, claimed in order
print("worker: %s (model id: %s)\nstart it with the host's delegation tool; one pick buys one delegation" % (r[0], short(r[0]))) print("worker: %s (model id: %s)\nstart it with the host's delegation tool; one pick buys one delegation" % (r[0], short(r[0])))
if store.config()["shell_workers"] or not command(r): if store.config()["shell_workers"] or not command(r):
print("how to call it: " + r[1]) print("how to call it: " + r[1])
print("good at, bad at: %s\nnotes: %s" % (r[4], r[5])) print("good at, bad at: %s\nnotes: %s" % (r[4], r[5]))
t = speed.get(short(r[0])) t = speed.get(short(r[0]))
print("speed: median %g min over %d timed jobs" % (median(t), len(t)) if t else "speed: no timed jobs yet") print("speed: median %g min over %d timed jobs" % (median(t), len(t)) if t else "speed: no timed jobs yet")
if g := gone.get(short(r[0])): # its last verdict was `out`: a retry, so a quick failure is expected and cheap
print("retry: this worker hit a limit at %s: %s; if it fails for the limit again, judge it out again and pick another" % (
clock(g[0]), g[1][:160] + ("…" if len(g[1]) > 160 else "")))
return 0 return 0
@@ -298,8 +356,8 @@ def research_record(answer_file):
for r in rows(text): for r in rows(text):
if len(re.findall(r"routine|ordinary|hard", r[2].lower())) != 1: if len(re.findall(r"routine|ordinary|hard", r[2].lower())) != 1:
return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6]) return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6])
if re.search(r"out (?!until \d{4}-\d{2}-\d{2}(?!\d))(until|till)\b", r[5].lower()): if re.search(r"\bout (?:until|till)\b", " ".join(r), re.I): # what the wheel would read as a legacy note
return "a worker that is out needs exactly `out until YYYY-MM-DD` in its notes: | %s |" % " | ".join(r[:6]) return "a row may not say who is out: delete the `out until` note from it (the agent that delegates judges a worker that hit a limit: `sisi judge WORKER out \"<the provider's message>\"`): | %s |" % " | ".join(r[:6])
if len(lines) > 42 or len(text) > 12000: if len(lines) > 42 or len(text) > 12000:
return "the answer is too long (at most 40 rows and 12,000 characters)" return "the answer is too long (at most 40 rows and 12,000 characters)"
if shared and ("|" not in shared or not _shared_date(shared)[0]): if shared and ("|" not in shared or not _shared_date(shared)[0]):
@@ -315,41 +373,62 @@ def research_record(answer_file):
return None return None
def sync_late(s, cwd, sid, add=True):
if not (late2 := late(s, 2)) and not os.path.lexists(os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")): return
from . import faults
prefix, now, cfg_m = "late:%s:" % sid[:8], time.time(), store.config()["worker_minutes"]
want = {"%s%s@%d" % (prefix, w, int(t)): 'worker %s has run %dm (past 2x %gm limit). Judge it (`sisi judge %s good|bad|out "<why>"`) or extend (`sisi judge %s extend MINUTES "<reason>"`).' % (
w, int((now - t) / 60), lim if lim is not None else cfg_m, w, w) for w, t, lim, *_ in late2}
try:
faults.clear(cwd, prefix, set(want)); add and [faults.add(cwd, text, kind=k) for k, text in want.items()]
except OSError: pass
def judge(args, cwd=None): def judge(args, cwd=None):
"""`sisi judge WORKER good|bad "<why>" [--minutes N] [--newest]`: how a delegation went, and how long the job took: """`sisi judge WORKER good|bad|out "<why>" [--minutes N] [--newest] | extend MINUTES "<why>" [--newest]`."""
from the oldest start of this worker's open jobs (the newest with --newest) unless --minutes says."""
from . import retro # not at the top: hooks import this module and must stay quick from . import retro # not at the top: hooks import this module and must stay quick
args, newest, minutes, note = [a for a in args if a != "--newest"], "--newest" in args, None, "" args, newest, minutes, note = [a for a in args if a != "--newest"], "--newest" in args, None, ""
if "--minutes" in args: if "--minutes" in args:
i = args.index("--minutes") i = args.index("--minutes")
v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:]
minutes = int(v) if re.fullmatch(r"[1-9]\d{0,3}|10000", v) else 0 minutes = int(v) if re.fullmatch(r"[1-9]\d{0,3}|10000", v) else 0
if len(args) != 3 or not args[0].strip() or args[1] not in ("good", "bad") or len(args[2].split()) < 3 or minutes == 0: ext = len(args) == 4 and args[1] == "extend" and minutes is None and re.fullmatch(r"[1-9]\d{0,3}|10000", args[2])
print('usage: sisi judge WORKER good|bad "<what it did well or badly, in a sentence>" [--minutes N] [--newest]') if not args or not args[0].strip() or not (ext or (len(args) == 3 and args[1] in ("good", "bad", "out") and minutes != 0)) or len(args[-1].split()) < 3:
print('usage: sisi judge WORKER good|bad|out "<what it did well or badly, or the provider\'s message when it hit a limit, in a sentence>" [--minutes N] [--newest] | extend MINUTES "<reason, 3+ words>" [--newest]')
return 1 return 1
trows = rows(store.read(table())) trows = rows(store.read(table()))
hits = [r for r in trows if short(r[0]) == short(args[0])] or [r for r in trows if claim({"picked": [short(r[0])]}, args[0], True)] hits = [r for r in trows if short(r[0]) == short(args[0])] or [r for r in trows if claim({"picked": [short(r[0])]}, args[0], True)]
if args[1] == "out" and len(hits) != 1: # a verdict that names no one worker would change nothing
return print("sisi judge: %r is not one worker of the models table; name it as the table does." % args[0]) or 1
model = (hits[0][0].split() or [""])[0] if len(hits) == 1 else args[0] model = (hits[0][0].split() or [""])[0] if len(hits) == 1 else args[0]
sid, now, began = store.current_session(cwd), time.time(), None wkey, sid, now, began = short(model), store.current_session(cwd), time.time(), None
if sid: if sid:
with store.session(sid) as s: with store.session(sid) as s:
starts = s["starts"].get(short(model)) if isinstance(s.get("starts"), dict) else None starts = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None
if isinstance(starts, list) and starts: cand = (starts.pop(-1 if newest else 0) if not ext else starts[-1 if newest else 0]) if isinstance(starts, list) and starts else None
cand = starts.pop(-1 if newest else 0) # one start per open job, oldest first if ext and not newest: # the job that is late, not just the oldest open one
if type(cand) in (int, float) and math.isfinite(cand) and cand <= now: # else dropped, times nothing cand = next((min(t for w, t, *_ in l if w == wkey) for l in (late(s, 2), late(s, 1)) if any(w == wkey for w, *_ in l)), cand)
began = cand ok_t = type(cand) in (int, float) and math.isfinite(cand) and cand <= now
minutes = minutes or max(1, int((now - began) / 60)) if ext:
note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(starts)) if not ok_t: return print("sisi judge: no open job for %s." % args[0]) or 1
lim, m, k = max(0, int((now - cand) / 60)) + int(args[2]), (s["meta"] if isinstance(s.get("meta"), dict) else {}), "%s %r" % (wkey, cand)
m[k], s["meta"] = {**(m[k] if isinstance(m.get(k), dict) else {}), "limit": lim, "extended": now, "reason": retro.clean(args[3])}, m
isinstance(s.get("reminded"), list) and s.__setitem__("reminded", [x for x in s["reminded"] if x != [wkey, cand]])
return sync_late(s, cwd, sid, False) or print("extended %s limit to %d min." % (wkey, lim)) or 0
isinstance(s.get("meta"), dict) and s["meta"].pop("%s %r" % (wkey, cand), None)
if ok_t:
began = cand
minutes = minutes or max(1, int((now - began) / 60))
note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(starts))
sync_late(s, cwd, sid, False)
elif ext: return print("sisi judge: no open job for %s." % args[0]) or 1
iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t)) iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t))
rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1], 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)
@@ -363,11 +442,11 @@ def run(args, cwd=None):
print(text or stale()) print(text or stale())
if text: if text:
print("\n(researched %d days ago)" % age_days()) print("\n(researched %d days ago)" % age_days())
recent = outcomes(15) gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)}
if recent: if sitting := sorted((t, w) for w, (t, _) in gone.items() if w in listed and now - t < OUT):
print("\nHow recent delegations went:\n" + "\n".join(recent)) print("\nOff the wheel now:\n" + "\n".join("%s: %s" % (w, SINCE % (clock(t), clock(t + OUT))) for t, w in sitting))
if stale(): if recent := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent))
print("\n" + stale()) 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
+125 -17
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") 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 [--scope user] --improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." --level core|user|project
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.
@@ -45,7 +45,7 @@ def facts(state, cwd):
"evidence (measured): %d check(s) passed, %d failed" % (n["checks_pass"], n["checks_fail"])] + d[1:-1] "evidence (measured): %d check(s) passed, %d failed" % (n["checks_pass"], n["checks_fail"])] + d[1:-1]
out += ["value (judged): did the person get what they wanted? changed: %d commit(s), %d file(s) uncommitted" % (n["commits"], len(dirty))] out += ["value (judged): did the person get what they wanted? changed: %d commit(s), %d file(s) uncommitted" % (n["commits"], len(dirty))]
from . import faults from . import faults
fs = faults.lines(cwd) fs = faults.lines(cwd, store.current_session(cwd))
return out + d[:1] + d[1:][-1:] + (["open faults (%d):" % len(fs)] + [" " + l for l in fs] if fs else []) + ["learning (measured): last 10 pieces of work named: %s" % (named or "none yet")] return out + d[:1] + d[1:][-1:] + (["open faults (%d):" % len(fs)] + [" " + l for l in fs] if fs else []) + ["learning (measured): last 10 pieces of work named: %s" % (named or "none yet")]
@@ -78,6 +78,63 @@ 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):
"""Known problems derived from retro.jsonl in order of first appearance (1-based number), folding merged aliases."""
by_key, out = {}, []
for idx, r in enumerate(store.records("retro.jsonl", 64000000) if recs is None else recs):
if not (isinstance(r.get("problem"), str) and (name := clean(r["problem"]))):
continue
date, key = str(r.get("ts") or "")[:10] or "?", name.lower()
p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": [], "merged": []})
p not in out and out.append(p)
p["attempts"].append({"idx": idx, "date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")})
p["last"], p["last_idx"] = date, idx
for m, n in (_aliases() if recs is None else {}).items():
if m <= len(out) and n <= len(out):
src, dst = out[m - 1], out[n - 1]
src["into"] = n
dst["merged"].append((m, src["name"]))
dst["attempts"] = sorted(dst["attempts"] + src["attempts"], key=lambda a: a["idx"])
dst["last"], dst["last_idx"] = dst["attempts"][-1]["date"], dst["attempts"][-1]["idx"]
return out
def _problem_lines(probs):
recent = sorted((p for p in probs if not p.get("into")), key=lambda p: (-p["last_idx"], -p["num"]))[:15]
return [l for p in recent for n in [len(p["attempts"])]
for l in [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n, "" if n == 1 else "s", p["last"]), *[" merged: %s (#%d)" % (name, m) for m, name in p["merged"]]]]
def _resolve_problem(problem, probs):
if not problem or not (norm := " ".join(problem.split())):
return None, 'sisi retro: every --gap retro names a problem (--problem N to cite, or --problem "<name>" to open one).'
if clean(problem) != norm:
return None, "sisi retro: name the problem in plain words (no secrets, tokens, or long hex/digit strings)."
if len(norm) > 400:
return None, "sisi retro: problem name is at most 400 characters."
canon = lambda p: probs[p["into"] - 1] if p and p.get("into") else p
if re.fullmatch(r"[+-]?\d+", norm):
n = int(norm)
return (canon(probs[n - 1]), "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm)
return canon(next((p for p in probs if p["name"].lower() == norm.lower()), None)) or {"num": len(probs) + 1, "name": norm, "attempts": []}, ""
def report(sid, cwd): def report(sid, cwd):
state = {} state = {}
if sid: if sid:
@@ -86,6 +143,8 @@ def report(sid, cwd):
print("sisi retro: what happened in this piece of work, by term of the objective.") print("sisi retro: what happened in this piece of work, by term of the objective.")
print("\n".join(facts(state, cwd))) print("\n".join(facts(state, cwd)))
print("\nThe objective: %s" % rules.objective()) print("\nThe objective: %s" % rules.objective())
if (plines := _problem_lines(_problems())):
print("\nknown problems (most recent first):\n" + "\n".join(plines))
print("\nSet what happened against the objective, term by term. Where did the work fall short, why, and what " print("\nSet what happened against the objective, term by term. Where did the work fall short, why, and what "
"instruction would have prevented it? Name the root cause; general advice is not an improvement.\n") "instruction would have prevented it? Name the root cause; general advice is not an improvement.\n")
print(USAGE) print(USAGE)
@@ -93,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:
@@ -108,10 +174,10 @@ def record(s, cwd, opt, sid=None):
log = store.data("retro.jsonl") log = store.data("retro.jsonl")
store.append(log, json.dumps(entry, sort_keys=True)) store.append(log, json.dumps(entry, sort_keys=True))
if not store.commit("retro recorded", log): if not store.commit("retro recorded", log):
print("sisi: retro saved, but store git commit failed.") print("sisi: retro saved, but store git commit failed (%s)." % store.GIT_ERROR)
s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now
for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused", for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused",
"fails_since", "picked", "starts", "retro_demanded", "began"): "fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began"):
s.pop(key, None) s.pop(key, None)
@@ -152,7 +218,7 @@ def _options(args):
opt, i = {}, 0 opt, i = {}, 0
while i < len(args): while i < len(args):
if args[i] in FLAGS and i + 1 < len(args) and args[i][2:] not in opt: if args[i] in FLAGS and i + 1 < len(args) and args[i][2:] not in opt:
opt[args[i][2:]] = clean(args[i + 1]) opt[args[i][2:]] = args[i + 1] if args[i] == "--problem" else clean(args[i + 1])
i += 2 i += 2
else: else:
return None return None
@@ -169,16 +235,26 @@ 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 = [(opt or {}).pop(k, None) for k in ("scope", "term", "better")] 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)
if kind is None or len(opt.get("improve", "")) > 400 or len(better or "") > 400 or (kind == "later" and (term or better)) or (kind != "no-gap" and better): if (kind is None or len(opt.get("improve", "")) > 400 or len(better or "") > 400 or (kind == "later" and (term or better))
or (kind != "no-gap" and better)):
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:
print("sisi retro: --problem goes only with --gap.")
return 1
if kind != "later" and term not in TERMS: if kind != "later" and term not in TERMS:
print("sisi retro: name the term of the objective where the work fell short, or could most have scored better. " + TERM_HELP) print("sisi retro: name the term of the objective where the work fell short, or could most have scored better. " + TERM_HELP)
return 1 return 1
@@ -186,7 +262,16 @@ def run(args, cwd=None):
print("sisi retro: a piece of work can always be done better. Add --better \"<one concrete thing that would have " print("sisi retro: a piece of work can always be done better. Add --better \"<one concrete thing that would have "
"scored better on %s, 5+ words>\"; it is recorded, and becomes a rule only if it recurs." % term) "scored better on %s, 5+ words>\"; it is recorded, and becomes a rule only if it recurs." % term)
return 1 return 1
opt.update({"term": term} if kind == "gap" else {"term": term, "better": clean(better)} if kind == "no-gap" else {}) prob = None
if kind == "gap":
probs = _problems()
prob, why = _resolve_problem(problem, probs)
if not prob:
plines = _problem_lines(probs)
print(why + ("\nknown problems (most recent first):\n" + "\n".join(plines) + "\nRe-run with --problem N (one of the numbers above) or --problem \"<new problem name>\"."
if plines else "\nknown problems: none yet.\nRe-run with --problem \"<new problem name>\"."))
return 1
opt.update({"term": term, "problem": prob["name"]} if kind == "gap" else {"term": term, "better": clean(better)} if kind == "no-gap" else {})
if sid: if sid:
with store.session(sid) as s: with store.session(sid) as s:
if kind == "no-gap" and any(c["verdict"] == "fail" for c in (s.get("done") or {}).get("checks", [])): if kind == "no-gap" and any(c["verdict"] == "fail" for c in (s.get("done") or {}).get("checks", [])):
@@ -201,14 +286,37 @@ 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 not p.get("into") and p["name"].lower() == opt["problem"].lower()), None)
prior = found["attempts"][:-1] if found else prob["attempts"]
prob, misses = found or prob, len(prior)
if misses:
print("problem %d '%s' has come back: %d miss%s" % (prob["num"], prob["name"], misses, "" if misses == 1 else "es"))
for a in prior:
print(" - [%s] %s" % (a["date"], a["improve"] or a["cause"] or "(no improvement recorded)"))
ds, cut = rules.drops_for(prob["num"]), lambda s: s if len(s) <= 180 else s[:177] + "..."
for d in reversed(ds[-5:]):
print(" - dropped [%s] %s (%s)" % (str(d.get("ts") or "")[:10] or "?", cut(str(d.get("rule") or "")), cut(str(d.get("reason") or ""))))
len(ds) > 5 and print(" and %d more" % (len(ds) - 5))
else:
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:
from . import faults
msg = "Problem '%s' came back: written rules failed %d times. Fix it with a hook or an automatic check, not another sentence." % (prob["name"][:170], misses)
try:
if (hit := faults.add(cwd, msg, kind="problem:%d" % prob["num"])):
print("sisi: opened fault #%d: %s" % (hit["id"], hit["text"]))
except OSError as e:
print("sisi: could not open fault for problem %d (%s)." % (prob["num"], e))
if rules.due(cwd): if rules.due(cwd):
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
+377 -99
View File
@@ -3,15 +3,24 @@
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]
HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them.\n" _TAGS = " [owner] lines are the person's words; [agent ...] lines are an agent's reading, which a later owner statement or a measurement overrides."
HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them):" HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them." + _TAGS + "\n"
HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them)." + _TAGS
SMELL = re.compile(r"(?i)\bone (?:build|test|run|worker|job)\b.{0,60}\bat a time|\bflock\b|\b(?:shared?|one)\b.{0,30}\bbuild (?:folder|dir)")
DROPS, PROBLEMS = "rules/drops.jsonl", "rules/problems.json"
_DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$")
_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.
@@ -25,19 +34,35 @@ 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 [retro ...] lines may be merged, reworded or dropped. one character (you may reorder them). Only the other lines ([retro ...], [agent ...]) may be merged, reworded or dropped.
- Keep the [source date] mark at the end of every line. - Flag, but do not change, any [owner ...] line whose text does not read as the person's own words (a paraphrase, an
agent's conclusion, third person), and any rule that limits builds, tests or workers to one at a time or tells
checkouts to share one build folder. List each under a final `## flags` section with its proposed corrected or
retagged form, for the person to accept.
- Keep the [source date] mark (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').
Answer with exactly this shape and nothing else: Answer with exactly this shape and nothing else:
## user ## user
- ... - ...
## project ## project
- ... - ...
## core
- ... (only lines moved to the product queue)
## drops
- <old rule> | #<N or -> | <reason> (optional; only if any non-owner rules were dropped)
## same problems
N = M (optional; merge duplicate problem M into older N)
## flags
- ... (only if there are any)
=== The first list now (all projects) === === The first list now (all projects) ===
%(user)s %(user)s
@@ -45,15 +70,42 @@ Answer with exactly this shape and nothing else:
=== The second list now (project "%(name)s") === === The second list now (project "%(name)s") ===
%(project)s %(project)s
=== Flagged for the person (likely wrong; propose a fix) ===
%(flagged)s
=== What recent retros found, newest last (context only) === === What recent retros found, newest last (context only) ===
%(retros)s %(retros)s%(evidence)s
""" """
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):
@@ -76,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):
@@ -86,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:
@@ -125,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)
@@ -146,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
@@ -162,39 +213,72 @@ 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): _in_store = lambda p: p.startswith(os.path.join(store.DATA, ""))
if snap:
p = store.data("rules", "last-project.json")
store.write(p, json.dumps(dict(zip(("path", "before", "after"), snap))))
paths = (p,) + paths
if not store.commit(msg, *paths):
raise OSError("store git commit failed")
def add(text, scope, source, cwd=None, log=None): 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 = "- %s [%s %s]" % (" ".join(str(text).split()), source, time.strftime("%Y-%m-%d")) 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, line) [store.append(dest, l) for l in [line, *more]]
else: else:
_check_writable(dest) _check_writable(dest)
msg = _move(dest, _legacy(cwd)) msg = _move(dest, _legacy(cwd))
msg and print(msg) msg and print(msg)
before = _text(dest) before = _text(dest)
after = _append(before, [line]) after = _append(before, [line, *more])
store.write(dest, after) store.write(dest, after)
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
@@ -217,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")
@@ -256,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:
@@ -277,25 +362,105 @@ def due(cwd, claim=False):
% "; ".join(m for _, m in need)) % "; ".join(m for _, m in need))
def drops_for(num=None):
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):
canon = [p for p in probs if not p.get("into")]
if not canon:
return ""
amap, cut = {p["num"]: p["into"] for p in probs if p.get("into")}, lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
all_p = "\n\n=== Every known problem (list duplicates under ## same problems as N = M, older first) ===\n" + "\n".join(
"#%d: %s | cause: %s" % (p["num"], cut(p["name"]), cut(next((a["cause"] for a in p["attempts"] if a["cause"]), "") or "(none)")) for p in canon)
head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n"
"How to use this evidence:\n"
"- Problem has 0 misses: it has not come back yet, keep it. Has misses: the sentence did not hold, keep the latest attempt and note it in `## flags` (do not just reword).\n"
"- When merging, keep the cause; never drop a rule as redundant while its problem keeps coming back. [owner ...] rules stay verbatim.\n")
out, used = [head], len(head)
for p in sorted(canon, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]:
n = len(p["attempts"])
ls = (["#%d: %s (opened %s, %d attempt%s, %d miss%s, last %s)" % (p["num"], cut(p["name"]), p["opened"], n, "" if n == 1 else "s", n - 1, "" if n == 2 else "es", p["last"])]
+ [" attempt [%s] cause: %s | rule: %s" % (a["date"], cut(a["cause"]), cut(a["improve"])) for a in p["attempts"]]
+ [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if amap.get(d.get("problem"), d.get("problem")) == p["num"]])
blk = "\n".join(ls) + "\n"
if used + len(blk) > cap_c:
for l in (ls if len(out) == 1 else ()):
if used + len(l) + 1 <= cap_c:
out.append(l + "\n"); used += len(l) + 1
break
out.append(blk); used += len(blk)
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):
cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) from . import retro
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"],
"user": "\n".join(u) or "(none)", "project": "\n".join(p) or "(none)", "flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)",
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)"} "user": "\n".join(_annotate(u, probs)) or "(none)",
"project": "\n".join(_annotate(p, probs)) or "(none)" if has_project(cwd) else "(not in a git project: leave `## project` empty)",
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)",
"evidence": _evidence(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()
parts = re.split(r"(?m)^## (user|project)[ \t]*$", 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 = {parts[i]: [l.rstrip() for l in parts[i + 1].splitlines() if l.startswith("- ")] got, flags, drops, same_lines = {}, "", {}, []
for i in range(1, len(parts) - 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|core)[ \t]*", h):
got[h[3:].strip()] = [l if _owner(l) else _NOTE.sub("", l) for l in (x.rstrip() for x in chunk.splitlines() if x.startswith("- "))]
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
flags += chunk
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
for l in chunk.splitlines():
if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]):
drops.setdefault(rk, (m[2], why))
elif re.match(r"(?i)#{2,3}[ \t]*same problems\b", h):
same_lines += [x.strip() for x in chunk.splitlines() if x.strip() and x.strip().lower() not in ("none", "(none)") and not x.strip().startswith("```")]
core = got.pop(CORE, [])
if set(got) != {USER, PROJECT}: 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():
@@ -303,46 +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]
if not any(got.values()) and any(had.values()): kept = every[:]
dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)]
from . import retro
nprobs = len(retro._problems()) if dropped or same_lines else 0
pnum = lambda s: n if s.isascii() and s.isdigit() and len(s) <= 6 and 1 <= (n := int(s)) <= nprobs else None
recs = [(store.clean(r)[:300], pnum(h[0]), h[1]) if (h := drops.get(_DKEY(r))) else (store.clean(r)[:300], None, "none given") for r in dropped]
no_why = sum(_DKEY(r) not in drops for r in dropped)
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)
wrote_u = False
try:
store.write(up, "".join(l + "\n" for l in got[USER]))
wrote_u = True
seen = _organized()
seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))})
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
marks = store.data("rules", "organized.json") change = {up: (_text(up), "".join(l + "\n" for l in got[USER])), op: (_text(op), json.dumps(seen))}
store.write(marks, json.dumps(seen)) if proj:
_commit("rules organized", marks, up, snap=(pp, before, after)) before = _text(pp)
change[pp] = (before, "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None)
if core:
change[cp] = (cb := _text(cp), "".join(l + "\n" for l in dict.fromkeys(_parse(cb or "") + core)))
if recs:
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 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))}
@@ -350,12 +538,18 @@ def organize_record(answer_file, cwd):
build_rulebook() build_rulebook()
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"))
[print("skipped same problems line '%s' (%s)" % b) for b in bad_same]
[print("the same rule was in both user and project and is now one copy in %s: %s; add it back by hand if you want it at both levels (run `sisi rules` to see the lists)" % (next(lv for lv in now if l in now[lv]), l)) for l in merged]
[print("the same rule now sits at two levels, so `sisi rules move` cannot pick one copy: %s; remove the copy you do not want by hand (run `sisi rules` to see the lists)" % l) for l in over if l not in merged]
flags.strip() and print("Flagged for you (not changed):" + flags.rstrip())
back and print("Moved between levels, which `sisi rules revert` does not undo; to move them back, run:\n" + "\n".join(" " + c for c in back))
return None 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") 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
@@ -364,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:
@@ -400,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))
@@ -416,27 +619,102 @@ 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())
def _said(words, cwd):
"""True when the words are a quotation of one of the person's recent messages in this session."""
try:
sid = store.current_session(cwd)
said = json.loads(store.read(store._session_path(sid)) or "{}").get("said") if sid else None
except (OSError, ValueError, AttributeError):
return False
return isinstance(said, list) and any(" %s " % _norm(words) in " %s " % _norm(m) for m in said if isinstance(m, str))
def learn(args, cwd=None): def learn(args, cwd=None):
"""`sisi learn [--project] TEXT`: the person's own words become a rule at once.""" """`sisi learn --level core|user|project "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
scope = PROJECT if "--project" in args else USER owner tag only when the words are found in the person's recent messages, else the agent's own tag."""
text = " ".join(a for a in args if a != "--project").strip() args, scope = list(args), PROJECT if "--project" in args else None
if len(text.split()) < 3: while (j := next((j for j, a in enumerate(args[:-1]) if a in ("--level", "--scope")), None)) is not None:
print('usage: sisi learn [--project] "<what the person said, in their words>"') scope, args[j:j + 2] = args[j + 1], []
i = args.index("--means") if "--means" in args else len(args)
words, means = [a for a in args[:i] if a != "--project"], " ".join(args[i + 1:])
text = " ".join(words).strip()
if len(text.split()) < 3 or (i < len(args) and len(means.split()) < 3) or any(w.startswith("--") for w in words):
print('usage: sisi learn --level core|user|project "<what the person said, in their words>" [--means "<how I will apply it>"]')
return 1 return 1
if why := refuse_level(scope, cwd, 'sisi learn'):
print("sisi learn: " + why)
return 1
heard = _said(text, cwd)
log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
try: try:
line, warn = add(text, scope, "owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split())))) line, warn = add(text, scope, "owner" if heard else "agent, attributed to owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split()))), means)
except OSError as e: except OSError as 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)) 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
print(warn or "in force from the next session: %s" % line) 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" 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
+39 -13
View File
@@ -20,11 +20,12 @@ def _where(own, xdg, fallback):
DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share")) DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share"))
STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state")) STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state"))
LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi") LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi")
GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error
# Every setting there is. The person overrides one under "core" in config.json in their store. # 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": 15, "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():
cfg = dict(DEFAULTS) cfg = dict(DEFAULTS)
@@ -50,10 +51,20 @@ def read(path, default=""):
return default return default
def records(name): def records(name, limit=2000000):
"""The JSON objects in a data file, one per line; a damaged or non-object line is skipped.""" """The JSON objects in a data file, one per line; a damaged or non-object line is skipped."""
out = [] p, out = data(name), []
for line in read(data(name)).splitlines(): try:
with open(p, "rb", opener=lambda q, f: os.open(q, f | os.O_NOFOLLOW)) as f:
if not stat.S_ISREG(os.fstat(f.fileno()).st_mode):
return out
raw = f.read(limit + 1)
if len(raw) > limit:
f.seek(-limit, 2)
raw = f.read(limit).split(b"\n", 1)[-1]
except OSError:
return out
for line in raw.decode("utf-8", "replace").splitlines():
try: try:
o = json.loads(line) o = json.loads(line)
except (ValueError, RecursionError): except (ValueError, RecursionError):
@@ -87,23 +98,38 @@ def append(path, line, once=False):
def git(args, cwd, timeout=15): def git(args, cwd, timeout=15):
# A repository named by the caller's environment (a git hook sets GIT_DIR) must not decide which project this folder is.
global GIT_ERROR
env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")}
env["GIT_OPTIONAL_LOCKS"] = "0" # a plain `git status` holds index.lock while it runs, and a commit started then fails on it
try: try:
r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout) r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env)
return r.returncode, r.stdout except (OSError, subprocess.SubprocessError) as e:
except (OSError, subprocess.SubprocessError): r = subprocess.CompletedProcess(args, 1, "", str(e))
return 1, "" GIT_ERROR = (r.stderr.strip().partition("\n")[0] or "git exited with %d" % r.returncode) if r.returncode else ""
return r.returncode, r.stdout
def commit(message, *paths): 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.""" """One commit in the person's store holding only these paths, so the change can be undone on its own. `put` ({path: text})
is written under the lock and committed too: another process's `git add` never reads a file as it is replaced."""
history()
with lock("store"): 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()]
rel = [os.path.relpath(p, DATA) for p in paths] 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
(git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or (git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0)) 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 = {}
+63
View File
@@ -0,0 +1,63 @@
{"split": "held", "label": "quiet", "real": false, "text": "Write the architecture overview for new engineers: docs/architecture.md, 800-1200 words, plus one diagram as Mermaid source in the same file. Read the repository and trace one request from the load balancer through the gateway, the auth service and the order service to the database and back, and describe each hop: what it is called, which directory holds it, how to run it locally, and what to read first. Name three places where the code and the old wiki disagree (the wiki is at docs/legacy/) and say which you trust and why. Every file path you write must exist; check them with a script and show the result. No code changes. Stop at 25 minutes and report as it stands."}
{"split": "held", "label": "quiet", "real": false, "text": "Deduplicate the customer export: data/customers_2026-11.csv has about 1.2 million rows and roughly 4% are the same person entered twice (typos in names, differing phone formats, the same email in different case). Write tools/dedupe.py that produces customers_clean.csv and a merges.csv listing which rows were merged and why. Matching rules: same lower-cased email; otherwise same normalised phone plus a name similarity above 0.9. Keep the most recently updated row's fields, but fill empty fields from the older ones. Never merge two rows that have different non-empty emails and the same phone; list them in review.csv instead. Run on the 10,000-row sample first and show the three counts; then the full file. Stop at 30 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Fix a caching bug in the Node/Express server (server/static.js, server/pages.js): after a deploy, browsers keep showing the old HTML page for up to a day because the server sends Cache-Control: max-age=86400 on the server-rendered pages as well as on the hashed assets. Pages should be revalidated every time (no-cache with ETag) while files under /assets/ with a content hash in the name keep a one-year immutable lifetime. Check the other headers too (Vary, Content-Type). No change to what the pages contain. Done means: supertest tests assert the headers for a page, a hashed asset, an unhashed asset and a 404, and curl -I against a local run shows them; conditional requests with If-None-Match get 304. 20 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Create the three-step onboarding flow for the iOS app in Sources/Onboarding/ (SwiftUI, iOS 17). Step 1 asks for the name, step 2 asks which sports to follow (multi-select, at least one required before Next enables), step 3 asks for notification permission and then lands on Home. Back swipes must keep the answers entered so far. Progress is shown as three dots. Store results through the existing ProfileStore; do not touch it otherwise. Handle Dynamic Type at the largest size without clipping and VoiceOver reading the dots as 'step 2 of 3'. Done means: the unit tests for the step state machine pass, the app builds for the simulator, and you have screenshots of each step on iPhone SE and iPhone 15 Pro Max, each viewed. Allow 40 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Build a home-screen widget for the Android app showing today's top three tasks (Glance / Jetpack, module widget/). It shows task titles, a tick that marks one done from the widget without opening the app, and a '+' that opens the add-task screen. It refreshes when tasks change and at least every 30 minutes, and handles the empty case ('Nothing due today') and being resized from 2x2 to 4x2 cells. Reads from TaskRepository through the existing content provider; do not alter the provider. Done means: instrumented tests for the tick action and refresh pass on an emulator, the module builds in release mode, and screenshots of the widget at 2x2 and 4x2, with three tasks and with none, were each looked at. Stop at 40 minutes and report what stands."}
{"split": "train", "label": "note", "real": false, "text": "Add a Preferences dialog to the Qt 6 (QWidgets, C++) desktop editor: src/ui/preferences_dialog.{h,cpp} and a hook in MainWindow's Edit menu (Ctrl+,). Tabs: General (autosave interval, restore session), Editor (tab width, wrap lines, show whitespace), Keys (read-only list of shortcuts for now). OK/Apply/Cancel behave the standard way; Apply writes to QSettings under the keys in docs/settings-keys.md; Cancel discards. Changing tab width updates open editors live after Apply. Done means: the unit tests for the settings round trip pass, the app builds with cmake, and screenshots of each tab under the default Fusion style and at 150% scaling have been looked at. Limit: 40 minutes. Don't touch other dialogs."}
{"split": "train", "label": "quiet", "real": false, "text": "Add rate limiting to the public API in the Go service (internal/api/ratelimit.go, middleware wiring in internal/api/router.go, tests). Policy: 100 requests per minute per API key, 20 per minute for unauthenticated clients by IP, using a token bucket held in the existing Redis (use the redis client already in go.mod). Respond 429 with a Retry-After header and the JSON error shape used elsewhere. Redis down must fail open with a logged warning, not take the API down. Add X-RateLimit-Remaining to every response. Done means: tests with miniredis cover limit hit, refill, fail-open and per-key isolation; go vet and the full test suite pass; a quick load run of 1000 requests with hey shows the 101st request in a minute gets 429. 30 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Design and build the 404 and 500 error pages for our Rails app: app/views/errors/not_found.html.erb, server_error.html.erb, a small stylesheet, and the routes wiring in config/routes.rb (exceptions_app). They should be friendly, say what happened in one sentence, offer a search box on the 404 and a 'Try again' link plus the status page link on the 500, and never depend on the database or any asset pipeline step that could itself fail while the app is down, so inline the CSS. Done means: request specs confirm status codes and that the 500 page renders with the database connection stubbed to raise; screenshots of both pages at desktop and phone widths are looked at. 25 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Produce the monthly sales report as a single self-contained HTML file from the data in data/sales_2026_10.csv, generated by reports/monthly.py (new; use matplotlib for charts embedded as inline SVG). Contents: a one-paragraph summary with the month's total and change on last month; a line chart of daily revenue; a bar chart of revenue by region; a table of the top ten products; a note listing any days with missing data. Someone will open it from an email on a laptop and may print it. Done means: the script runs from a clean checkout with python reports/monthly.py, totals in the report equal the sums computed independently from the CSV, and you have opened the output, scrolled it end to end and checked the print preview. 30 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Build the Users admin page in the Vue 3 app (src/views/AdminUsers.vue and its composable). A table of users with name, email, role, last seen; search box filtering as you type with a 250 ms debounce; sort by clicking a header; role filter; pagination of 25 rows backed by GET /api/admin/users?page=&q=&role=&sort=. A row's Disable button asks for confirmation and then calls POST /api/admin/users/:id/disable. Show a skeleton while loading, an empty state, and an error banner with retry. Only users with the admin flag may see the route; others are redirected to /. Done means: component tests cover search, sort, pagination and disable; and a screenshot of the populated, empty and error states each looked at. Time limit 30 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "Containerise the image-resizing service so it can run as a non-root user with a read-only root filesystem: edit Dockerfile, docker-compose.yml and k8s/deployment.yaml only. Multi-stage build; final image on a slim base with only the runtime libraries libvips needs; user 10001; writable tmp via an emptyDir mounted at /tmp; healthcheck calling /healthz. Report the image size before and after and confirm the container passes the integration test script scripts/it.sh when started with --read-only and --cap-drop ALL. Do not change application code; if it writes outside /tmp, report the path. Stop at 30 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "Add a 'prune' subcommand to the backup tool (backup/cli.py, backup/retention.py, tests). It deletes old snapshots from a repository directory by a policy given as --keep-daily N --keep-weekly N --keep-monthly N, keeping the newest snapshot in each bucket, and never the last remaining snapshot. --dry-run prints exactly what would be deleted and kept, one line each, and is the default unless --yes is given. Snapshot names are timestamps in UTC as in docs/format.md. Output is plain text for logs. Deletion must be crash-safe: rename to a trash directory first, remove after. Done means: tests with a generated year of snapshots check that each policy keeps the expected set, including week and month boundaries; a dry run on a copy of the sample repo in tests/fixtures is quoted in your report. Stop at 25 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Write a small command-line tool, crates/pkgdiff, that compares two lockfiles (Cargo.lock format) and prints what changed: packages added, removed, and upgraded or downgraded with old and new versions, one per line, sorted by name, in plain text suitable for pasting into a pull request. Flags: --format plain|markdown, --only added|removed|changed, and -q to print nothing but set the exit code (0 no difference, 1 differences, 2 error such as an unreadable file). Read both files with the existing lockfile parser in crates/lock; do not add dependencies. Done means: unit tests over three fixture pairs, including a duplicated crate at two versions and a yanked entry; clippy and fmt clean; output of a real diff between the last two release tags quoted in your report. 25 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Build a 'Team members' page for the admin app: admin/src/pages/Team.vue and a test. List members with avatar, name, role and a Remove button with confirmation; an Invite form (email, role) at the top; pending invites in a second list with Resend and Revoke. Wire to the existing /api/team endpoints (see docs/team-api.md); no backend changes.\nLook: follows the existing admin theme. Reuse the Card, DataTable and Button components from admin/src/components and the tokens in admin/src/theme.css; add no new colours, fonts or spacing values.\nDone means: component tests pass, lint is clean, and one screenshot at laptop width and one at phone width are viewed to confirm it matches the neighbouring Billing page. 30 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Build the sending worker for outgoing email, in services/mailer/ (Python, asyncio). It reads messages from the Postgres table outbox (columns in docs/outbox.md), renders them with the existing render_template(name, context) function, which you call but do not modify, and delivers over SMTP with STARTTLS to the relay in MAIL_HOST. Retry transient failures (4xx, timeouts) with backoff up to 8 times, mark permanent failures (5xx) as failed with the server's message, and make sure two worker processes never send the same row (use SELECT ... FOR UPDATE SKIP LOCKED). Done means: tests with a local aiosmtpd server cover success, transient retry, permanent failure and the two-worker case; the worker shuts down cleanly on SIGTERM without losing a claimed row. 35 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "You are building the data service behind our 'Fleet' dashboard: the dashboard page itself is another worker's job in the web/ directory and you must not touch it. Your part is the Go server in cmd/fleetd and internal/api. It serves JSON the page fetches from the browser: GET /api/fleet/summary (counts per status), GET /api/fleet/vehicles?status=&page= (paginated), and GET /api/fleet/vehicles/{id}/history (last 500 positions). It also serves the built page files from web/dist with correct content types and a SPA fallback so any unknown path returns index.html, but returns 404 for /api/ paths that do not exist. CORS stays closed; the browser talks to the same origin. Done means: go test passes with a fake store, a curl run against a local instance shows each endpoint's payload matches the schema in docs/api.md, and the 404 behaviour is covered by a test. 30 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Lay out the new 'Projects' overview page in the Angular app (projects/web/src/app/overview/: component, template, scss, spec). It shows project cards: name, owner, status badge and a progress bar from the API's percentComplete field. Card spacing: 20 px gaps between cards, 24 px padding inside, 12 px corner radius. Grid: four columns from 1280 px, three from 960, two from 600, one below that. Cards link to /projects/:id. Sorting by name or last updated through a dropdown, remembered in the URL query string. Done means: ng test passes for sorting and the URL state, ng build is clean, and screenshots at 1440, 800 and 375 wide are viewed. Time limit: 30 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Review PR #318 (queue worker retries) as a second pair of eyes; read-only, change nothing and push nothing. The author's claim is that failed jobs are retried with exponential backoff, at most five times, and never run twice at the same time. Check that claim against the code in worker/ and the tests: look for retry counters that reset, clock use that breaks under daylight-saving changes, a lock that can be held forever when a worker dies, and jobs that are retried after a permanent error. Run the tests and also write and run one extra test of your own that tries to run a job twice concurrently (keep it out of the branch). Report findings by severity with file and line, say which you reproduced and which are only suspicion. 25 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Write the HTML email for 'Your weekly summary' in mailer/templates/weekly.html with a plain-text twin weekly.txt (Jinja2; the variables are in mailer/context.py, which you must not change). Content: greeting with first name, three headline numbers (visits, signups, revenue), a list of the top five pages with their counts, and a footer with the unsubscribe link and postal address. It must hold up in Outlook and in Gmail's mobile app, so tables for structure and inline styles, no scripts. Show a sensible fallback when a number is missing. Done means: both templates render from the sample context in tests/fixtures without errors, a rendered copy of each sent through the preview script is looked at, and the plain text reads cleanly. 25 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "A goroutine leak shows up in the metrics service (memory grows by about 40 MB a day). Find the leak and fix it in internal/collector/ (and tests there). Start from a heap and goroutine profile: run the service locally with the load generator in bench/gen.go for ten minutes, capture pprof goroutine dumps at the start and the end, and tell me which stack is accumulating. Then fix it, add a regression test using goleak, and repeat the ten-minute run to show the goroutine count stays flat. Quote counts before and after. If the cause is outside internal/collector, stop and report instead of editing elsewhere. Stop at 40 minutes and report as it stands."}
{"split": "train", "label": "note", "real": false, "text": "The checkout page (templates/checkout.html and static/checkout.css) looks dated and customers complain it feels untrustworthy. Restyle it so it feels modern and calm, while keeping every form field name, id and the JavaScript hooks (data-js-* attributes) exactly as they are, because payment scripts bind to them. Work only in those two files. The order summary must stay visible while the customer fills the form on a laptop, and fold above the form on a phone. Done means: the existing Playwright checkout test still passes unmodified, and before and after screenshots at laptop and phone widths are placed side by side in notes/checkout-restyle.md and you have looked at each. Limit 30 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Create the HTML template for our monthly newsletter, newsletter/monthly.mjml, compiled with the mjml CLI into newsletter/dist/monthly.html. Blocks: masthead with the logo from assets/logo.png, a lead story with image, headline, two paragraphs and a button, a row of three short items, an events list with date, title and place, and a footer with unsubscribe and address. Fill the sample content from newsletter/sample.json and keep every block optional, so an issue without events still looks right. It must degrade gracefully with images blocked. Done means: the mjml build is warning-free, the full and the minimal sample both compile, and you have rendered both and viewed them at desktop and phone width. Stop at 30 minutes and report as it stands."}
{"split": "held", "label": "quiet", "real": false, "text": "Review the mobile checkout screen as it exists today in the beta build and report problems; make no changes. Use the debug APK in artifacts/beta.apk on the Pixel 7 emulator and walk through: add to cart, enter an address, pick delivery, pay with the test card, and also the failure paths (declined card, address with a typo, losing network at the last step). Note where the layout shifts, which buttons stay tappable when they should not, where the keyboard covers a field, whether the back button loses entered data, and anything that confuses you. Give each finding steps to reproduce and a screenshot. Separate bugs from opinions. Stop at 30 minutes and report what you covered."}
{"split": "held", "label": "quiet", "real": false, "text": "Write the live-updates gateway for the status page: a Node service in services/live/ that browsers connect to over WebSocket at /live and that streams events from the Redis stream status:events. The status page itself (static, in public/) already exists and is not yours; the page expects JSON messages of the form in docs/live-protocol.md and reconnects by itself, sending the last event id it saw, so you must replay missed events from the stream. Support 5,000 simultaneous browser connections on one process, send a ping every 25 seconds and drop silent clients, and reject Origins other than the page's own. Done means: a load script opens 5,000 sockets and reports memory and the 99th percentile delivery delay; tests cover replay after reconnect and the origin check. Stop at 40 minutes with what you have."}
{"split": "held", "label": "quiet", "real": true, "text": "You are building the server half of a dashboard program: one binary that polls a local compiler cache every 10 seconds, records history in SQLite and serves a dashboard page on 127.0.0.1. Another worker is building the page at the same time. HTTP: GET /api/view, GET /api/export as a download, POST /api/zero refused for a foreign Origin, plus the page's static files embedded in the binary with correct content types. Command line: serve and open the browser unless --no-open; install writes a systemd user unit. Done means: tests pass on fixtures for range totals, a counter reset, pruning; clippy clean; a live read-only run whose totals match the cache's own numbers."}
{"split": "train", "label": "quiet", "real": false, "text": "Write a migration that splits the single 'events' table into 'events' and 'event_payloads' in our SQLite store (migrations/0042_split_payloads.sql and the Python runner changes in store/migrate.py). The payload column is large JSON and is slowing every list query. Requirements: it runs inside one transaction, is re-runnable without harm if interrupted, keeps all rows (count and a checksum of ids before and after must match), and has a down migration. Existing code reading events.payload must keep working through a view of the same name until the callers move, so provide that view. Test on a copy of tests/fixtures/events_big.db (2 million rows) and report the migration's time and the size of the file before and after. Never run against the live db file. Time limit 35 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Research, no code: which charting library should the web team adopt for the analytics app: Chart.js, ECharts, Recharts, Plot or uPlot? Our needs: time series with up to 200,000 points per chart, zoom and pan, stacked bars, a bundle under 150 KB gzipped for the common case, TypeScript types, a licence that allows closed-source use. For each, get facts from the project's docs or repository with URLs and exact source words, and measure the bundle size yourself by building a one-chart sample with Vite. Time the render of 200,000 points in each in headless Chromium and report the median of five. Unverified claims must be labelled so. End with a recommendation and what would change it. Write to notes/charting-choice.md. Limit 40 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "Find out how other open-source projects handle schema versioning for JSON config files that users edit by hand, and recommend one approach for ours. Look at at least six real projects (for example Cargo, VS Code settings, Home Assistant, Kubernetes, Terraform, ESLint flat config) and for each record, with the URL and the exact words from their documentation: where the version number lives, what happens when a newer file meets an older program and the reverse, and how migration is done. Don't summarise from memory. Mark anything you could not find. Then compare with our config loader in src/config/load.py (read only) and recommend the smallest change that gives us safe upgrades. Report goes in notes/config-versioning.md. Stop at 30 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Add PDF output for invoices using reportlab: invoices/pdf.py exposes render_invoice(invoice) -> bytes, plus tests. A customer prints it on A4 or Letter, so it must fit both. It carries the seller block, the customer block, an invoice number and dates, a line-item table that continues cleanly onto a second page with the header row repeated, then subtotal, tax and total at the bottom right, and a footer line with payment details. Currency amounts right-aligned. Long item descriptions wrap rather than overflow. Done means: tests render a 1-line, a 12-line and a 70-line invoice; page count is 1, 1 and 2; you have rasterised the three PDFs and looked at them. Don't change the invoice model. Time limit 35 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Generate printable shipping labels: tools/labels.py takes orders.json and writes labels.pdf, one 4x6 inch label per page for a thermal printer. Each label: ship-to address, ship-from in smaller text, service name, weight, a Code 128 barcode of the tracking number, and the order number. Addresses can be up to six lines; names with accents must print correctly. If an address does not fit, shrink the text down to a floor and flag the order in a separate warnings.txt instead of clipping. Done means: tests cover the long-address and accent cases, the barcode of a sample label decodes back to its tracking number (use zbar), and you have rasterised the sample output at printer resolution and looked at three pages. 30 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Restyle the documentation site's article pages (docs/theme/article.css and docs/theme/article.html only). Type: body in Newsreader 18 px with 1.6 line height, headings in Inter semibold, code in JetBrains Mono 15 px. Colour, light: text #1b1f24, background #fdfdfb, links #0b5fff, code background #f2f2ee; dark: text #e8e8e3, background #14161a, links #7aa7ff. Spacing: article column 70 characters wide, 24 px between paragraphs, code blocks with 16 px padding and 6 px radius. Layout: a left nav 260 px wide appearing from 960 px up, collapsing to a menu button below that. Done means: the site builds with mkdocs build --strict and screenshots of one long article at 1440, 800 and 390 wide, light and dark, are each viewed top to bottom. Time limit 30 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Write 'diskwatch', a command-line tool in Python (tools/diskwatch.py, tests), that reports the ten largest directories under a path, one per line as ' 4.2G /var/lib/docker', sorted by size descending, plain text only, no colour, no interactive mode, so it can be piped to mail. Options: --depth N (default 2), --min-size 500M, --exclude PATTERN (repeatable), --json for machine-readable output. Do not follow symlinks; count a file once even if hard-linked; unreadable directories are listed on stderr and do not stop the run. Exit 0 on success, 2 on bad arguments. Done means: tests on a generated tree cover hard links, symlink loops and a permission error; the output on /usr matches du -x within 1%; run and show it. 25 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Write unit tests for the existing React component src/components/DatePicker.tsx using Testing Library and vitest; make no production code changes except exports needed for testing, and list any you make. Cover: selecting a date, keyboard navigation with arrows and Enter, min and max bounds (disabled days cannot be chosen), month rollover across year end, leap-year February, locale week start (Monday for de, Sunday for en-US), and controlled versus uncontrolled use. Aim for the behaviour, not the markup, so the tests survive a restyle. If you find a bug, write the failing test, mark it test.fails with a comment, and report it. Done means: the suite passes, the coverage of DatePicker.tsx is quoted, and you have made one deliberate break to see that a test fails. 25 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Write a job that reads the gzipped nginx access logs in /srv/logs/2026-11/ (about 40 GB) and produces a CSV of the 200 slowest request paths by 95th percentile response time, with request counts, for paths seen at least 500 times. Normalise paths first: replace numeric ids and UUIDs with :id so /orders/1042 and /orders/77 count together. Stream, do not load the files whole, use at most 2 GB of memory, and write progress to stderr every million lines. Put the code in tools/slowpaths.py with tests on a hand-made 1000-line sample. Before the full run, run it on one day's file and show me the timing and the first twenty output lines; extrapolate the total time. Then run all of it in the background. 30 minutes for the code and sample run."}
{"split": "held", "label": "note", "real": true, "text": "You are building the page half of a dashboard, an egui app compiled to wasm with trunk. The server sends one View; the page only draws it. Top row: range buttons, refresh control, light/dark switch, Copy summary, Export JSON, Zero stats with confirmation. Headline figures: hit rate large, coloured green at 70% or more, yellow 40-70%, red below 40%; time saved; problem count. Then six compact cards, then sections: Problems, Where compiles went (one stacked bar with a legend), Over time (two charts with a language filter), Speed (horizontal bars), Raw counters. Works at phone width (390 px): rows wrap or stack, no horizontal scrolling, nothing clipped. Content height must not jump on refresh: give charts and cards fixed heights. Done means: release build succeeds; screenshots at 1280 and 390 wide in light and dark, each looked at; clicking a range button changes the request."}
{"split": "held", "label": "quiet", "real": true, "text": "Redesign the look and layout of an existing dashboard page. Type: embed Inter for text and JetBrains Mono for numbers; panel title 11 px uppercase, body 13 px, headline number 40 px. Colour, dark: page #0e1116, panel #161a22, border #232936, text #e6e9ef; state colours good #3fb950, warn #d29922, bad #f85149. Panels: 8 px radius, 16 px padding, 12 px gaps. Grid: three columns at 1100 px and wider, two from 700, one below. Tables live inside their panel, numbers right-aligned in mono. Done means: screenshots at 1440, 900 and 390 wide, each viewed top to bottom; no table wider than its panel."}
{"split": "train", "label": "quiet", "real": false, "text": "Speed up the GitHub Actions workflow .github/workflows/ci.yml, which takes 19 minutes on a typical pull request. Goal: under 8 minutes median without dropping any check. Likely levers: caching of the cargo registry and target dir keyed on Cargo.lock, running the three test shards in parallel as a matrix, building the Docker image only when the Dockerfile or its inputs change, and moving lints off the critical path. Measure first: pull the last 20 successful runs with gh run list and tabulate time per job. After the change, push to a branch and report the timings of at least three runs, plus a list of every check that still runs so I can compare with before. Do not touch the release workflow. Limit 40 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Build a terminal UI for our job queue, in a new crate crates/qtop (Rust, ratatui + crossterm; add dependencies only to that crate). It shows the queue live: one row per job with id, state, age and worker, refreshed every second from the existing GET /v1/jobs endpoint. Keys: j/k or arrows move the selection, Enter opens a detail pane with the job's last 50 log lines, r retries a failed job, c cancels a running one after a y/n confirmation, q quits and restores the terminal even on panic. Handle a terminal resized to 80x24 and to 200x60. Done means: cargo test passes (state handling tested without a tty), clippy clean, and captured frames of both sizes that you have read. 30 minutes; run builds under prlimit --core=1:1 --."}
{"split": "train", "label": "quiet", "real": false, "text": "Write the 'Getting started with Harbor' guide in docs/guide/getting-started.md for people using the web app for the first time. Walk through signing in, creating a project, inviting a teammate and reading the activity feed; run the app locally (docker compose up) and take real screenshots of each existing screen you mention into docs/guide/img/, with descriptive file names and alt text. Describe only what the app does today; if a step in the product spec does not work, leave it out and list it in your report. Plain, friendly language, short paragraphs, no more than 1200 words. Do not change app code or styles. Done means: following the guide on a fresh install works end to end, every image shown exists, and the link checker passes. Time limit 30 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "One slow report query is timing out in production: the one in reports/queries/cohort_retention.sql, which now takes about 90 seconds on the replica. Find out why and fix it in SQL or with an index, in the migration folder only (no application code changes). First reproduce on the restored snapshot in the postgres-test container (it holds last Tuesday's data), save EXPLAIN (ANALYZE, BUFFERS) before and after, and report the time before and after. Any index you propose must be created concurrently and come with the size it adds and the effect on write speed of the table, measured with pgbench using the script in bench/. Don't touch the live database. Stop at 35 minutes and report as things stand."}
{"split": "train", "label": "quiet", "real": false, "text": "Review the new account-settings screen on branch feat/settings-v2; do not change any code. Read the diff in src/ui/settings/ and tell me what is wrong, not what is nice. Look at the layout logic (does it break at narrow widths, does anything overlap or clip when the translated strings are twice as long), the buttons (disabled states, double-submit, focus after a click, keyboard activation), and the form handling (validation messages, what happens on a failed save). Run the existing Playwright tests and write down which pass. Report as a list ordered by severity with file and line for each, and say separately what you could not check. Do not comment on taste, colours or visual style; this is a correctness review. 25 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Find out why the product page is slow, without changing it. Use the Chrome trace and Lighthouse against the local build (npm run build && npm run preview) for /products/42, five runs each, throttled to a mid-range phone. Report median Largest Contentful Paint, total blocking time, and the transfer size by type (script, css, image, font), and name the three biggest contributors with the evidence (which request, which long task, which file). Say which fixes you think would give the largest drop and an estimate, but make none. Save the raw traces to artifacts/perf/ (small ones only) and the report to notes/perf-product.md. Be exact about what you measured and what you only suspect. 25 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Write the Compose screen for the Android app's 'Create reminder' flow: app/src/main/java/.../reminder/CreateReminderScreen.kt and its ViewModel. Fields: title (required), date and time pickers, repeat (none/daily/weekly/custom days), and an optional note. Save is disabled until valid; saving calls ReminderRepository.create and then pops back with a snackbar saying 'Reminder set for <when>'. Handle process death with SavedStateHandle. Past times are rejected with an inline message. Talkback must announce each field's error. Done means: ViewModel unit tests and a Compose UI test for the happy path and the past-time error pass; ./gradlew assembleDebug is clean; screenshots on a small and a large phone emulator were viewed. 40 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Build the 'Order history' screen for the React Native app (src/screens/OrderHistory.tsx plus tests). Sectioned list by month, each row showing order number, date, status chip and total; tap opens OrderDetail (exists); pull to refresh; infinite scroll with 20 per page from GET /v1/orders?cursor=; empty and error states.\nDesign system: the app's own, in src/design/ (tokens.ts, Text, Chip, Row). Use only those; no raw hex values, font names or pixel sizes in the screen file, and a lint rule enforces this.\nDone means: jest tests for paging and the empty and error states pass, tsc and lint are clean, and screenshots on iOS and Android simulators are viewed. 35 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Create a terminal interface for browsing our release history, in cmd/relbrowse (Go, bubbletea and bubbles; add nothing else to go.mod). It reads releases from the local file ~/.cache/rel/index.json and shows a scrollable list of version, date and one-line summary; typing '/' starts a filter, Enter on a release opens its notes in a pager view, Esc goes back, and 'o' opens the release URL through xdg-open. It should cope with a 60-column terminal and a huge one, with no flicker on resize, and leave the screen clean when it exits, including on Ctrl-C. Done means: go test passes (model updates tested by feeding messages, no terminal needed), go vet is clean, and you have captured the program's output at 60x20 and 160x50 using a pseudo-terminal and read both captures. Stop at 30 minutes and report as it stands."}
{"split": "held", "label": "quiet", "real": false, "text": "Measure and report only: how big is our front-end, and where does it come from? Build the production bundle of the storefront (pnpm build) and use source-map-explorer and vite-bundle-visualizer to produce the breakdown of JavaScript and CSS by package and by our own folder, gzipped and raw. List the twenty largest contributors, flag duplicates (the same package at two versions), and note which code is loaded on the first page view versus lazily. Compare with the bundle at tag v3.2.0 built the same way and say what grew most. Do not change any source. Put the tables in notes/bundle-report.md and keep the visualizer's html output under artifacts/. Stop at 25 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Rewrite README.md and docs/quickstart.md for the 'tallyho' CLI so a new user can go from install to first successful run in under five minutes. Keep what is correct, cut what is stale (the Python 2 notes, the old Homebrew tap), and verify every command you document by running it in a clean container, pasting the real output where it is shown. Add a short 'Troubleshooting' section covering the three most frequent errors in the issue tracker (use gh issue list --label bug to find them). Do not change any code or the CLI's help text; if you find the help text wrong, list it in your report instead. Done means: a fresh container follows the quickstart verbatim without a failure; links check clean with lychee. Limit 20 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Make the public documentation site feel less like a default template: restyle docs/theme (style.css and base.html only; leave the content, the search script and the navigation markup as they are). Visitors are developers reading reference pages for long stretches, so reading comfort matters most; code samples and tables must stay easy to scan, and the sidebar should always show where the reader is. Try something distinctive but not loud. Done means: mkdocs build --strict passes, the search still works in a local serve, and screenshots of the home page, one long reference page and one table-heavy page, at desktop and phone width, are viewed before and after. Stop at 30 minutes and report as it stands."}
{"split": "train", "label": "note", "real": false, "text": "Create the main window for the GTK4 (Python, PyGObject) 'Seedling' garden planner: seedling/window.py and seedling/window.ui as plain XML. Left: a list of beds; right: the selected bed's plants with sow date and expected harvest; a header bar with Add bed, Add plant and a search toggle. Selecting a bed updates the right side; double-clicking a plant opens the existing PlantDialog. The window remembers its size and the selected bed between runs. Empty states for no beds and no plants. Done means: pytest (headless via xvfb) passes the selection and persistence tests; you launch it under xvfb, take screenshots of the empty, one-bed and many-bed cases, and look at them. 35 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Make a new pricing page for the marketing site (site/pricing.html and site/pricing.css only; plain HTML and CSS, no framework). Three plans: Free, Team, Business, with a monthly/yearly toggle that changes the shown prices without a reload and remembers the choice in localStorage. Use Source Serif 4 for headings and Inter for body text. Brand colours are #1F3A5F for headings and buttons and #F4F1EA for the page background; the recommended plan gets an accent #E07A1F. Each plan has a button linking to /signup?plan=NAME. Done means: toggle works with scripting on and degrades to yearly prices with scripting off; screenshots at 1200 and 390 pixels wide, both looked at. Limit 25 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Produce the quarterly board report as a PDF straight from our metrics database: reports/board_q.py (WeasyPrint, from an HTML template in reports/templates/board.html.j2). Sections: executive summary text pulled from a markdown file passed with --summary; revenue and churn charts for the last eight quarters; a table of the top twenty customers by revenue; headcount by team; a page of definitions at the end. Page numbers and the report title run in the header or footer. A table that crosses a page must repeat its header row. Output must open in any reader and print cleanly on A4. Done means: running against tests/fixtures/metrics.sqlite produces the PDF, the numbers in it agree with direct queries (show the check), and you looked at every page as an image. Stop at 40 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "The mobile app's offline sync needs a server endpoint; build only the server side, in api/sync/ (Python FastAPI). POST /sync accepts a list of changes the phone made while offline (create, update, delete for notes, each with a client timestamp and a client-generated id) and returns the changes made elsewhere since the cursor it sent, plus a new cursor. Conflicts: last write wins by server receive time, but a delete beats an update unless the update is newer than the delete. The app screens are another team's work; the response shapes are fixed in docs/sync-schema.json and must validate. Done means: pytest passes, including property-style tests that apply random change lists in different orders and end in the same state; the schema validates sample responses. Time limit 40 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Research task, no code changes: choose a library for generating PDFs from Python for our invoicing service. Candidates to compare: reportlab, WeasyPrint, fpdf2, and generating via headless Chromium. For each, find out from the project's own documentation or repository (give the URL for every claim): licence, maintenance state (last release, open issues trend), system dependencies and container image size impact, speed for a 3-page document measured by you with the same sample data, and support for right-to-left text and embedded fonts. Quote the exact source words for each fact; mark anything you could not confirm. Finish with a recommendation of one and a sentence on what would change your mind. Write it to notes/pdf-choice.md. 30 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Test, do not change: take screenshots of the existing app (npm run dev, port 5173) at 1440, 1024, 768 and 390 pixels wide for these routes: /, /orders, /orders/1042, /settings, in light and dark mode, using the Playwright script in tools/shots.mjs (extend it if needed; that file only). Save to artifacts/shots/ named route-width-mode.png. Then look at every image and report anything that looks broken: overflow, clipped text, overlapping elements, unreadable contrast, console errors during the load. Do not fix anything; list each problem with the route, width and mode where you saw it, and attach the file name. If the app does not start, report the exact error. 20 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Replace the hand-written Makefile build of the C library libfoo with CMake. Files you may change: CMakeLists.txt (new), cmake/ (new), Makefile (reduce to a thin wrapper calling cmake, keeping 'make', 'make test' and 'make install' working), and .github/workflows/build.yml. The behaviours to keep: shared and static builds selectable with -DBUILD_SHARED_LIBS, the generated foo_version.h, 'make test' running the 14 unit tests, install layout including the pkg-config file. Drop: the old 'make dist' target (the release script does that now). Done means: an out-of-tree build on Linux passes all 14 tests; installed headers and libraries are identical in name and location to the old install (diff the two file lists); CI passes. Time limit 40 minutes. Use prlimit --core=1:1 -- for runs."}
{"split": "held", "label": "note", "real": false, "text": "Build the order tracking page for the Next.js 14 app (app router): app/track/[orderId]/page.tsx and its client component. Behaviour: on load it fetches /api/orders/{id}/status and shows the current step out of Placed, Packed, Shipped, Out for delivery, Delivered; while the order is not delivered it polls every 20 seconds and stops polling when the tab is hidden. Shipped and later states show the carrier name, a tracking number that copies on click with a 'Copied' confirmation lasting two seconds, and an estimated delivery date. Unknown order id shows 'We can't find that order' with a link to /help. It has to hold up at phone width, 360 px, with nothing clipped or scrolling sideways. Done means: tests for polling, copy and the not-found state pass, and you have viewed screenshots at 1280 and 360 wide of every state. Stop at 35 minutes and report where things stand."}
{"split": "train", "label": "note", "real": false, "text": "Build the Settings page for our React 18 + Vite web app (src/pages/Settings.tsx and a test file; nothing else). Sections: Profile (display name, email read-only), Notifications (three toggles: email, push, weekly digest), Danger zone (Delete account with a typed-confirmation dialog). Saving is optimistic: toggles call PATCH /api/me/prefs immediately, roll back and show an inline error if the call fails. The page must work on a phone: stack everything, keep the Delete button reachable without sideways scrolling. Keyboard: Tab order follows reading order, Esc closes the dialog. Done means: vitest passes for the toggle rollback and the typed confirmation; npm run build is clean; screenshots at 1280 and 375 pixels wide, each looked at. Time limit 30 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Implement the 'Trip detail' screen in the Flutter app (lib/screens/trip_detail.dart, plus a widget test). It shows the trip name and dates, a list of stops in order with arrival times, a map placeholder widget (the real map comes later; use the existing MapStub), and an Edit and a Share action in the app bar. Pull-to-refresh reloads from TripRepository. Empty trip: show a message and an Add stop button. Loading and error states needed, the error with Retry. Must work in portrait and landscape and on a 5-inch phone without overflow errors. Done means: flutter test passes, flutter analyze is clean, and screenshots from the emulator in portrait and landscape are viewed. 40 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "Build the 'Audit log' screen for the macOS app (SwiftUI): Sources/Audit/AuditLogView.swift and tests. A table of entries (time, actor, action, target) with search, a date range control and an Export CSV button that saves through NSSavePanel; selecting a row shows full JSON in a side inspector. Data comes from AuditStore, which exists. Keep 10,000 rows scrolling smoothly by using the lazy table APIs.\nLook: native macOS, matching the existing Preferences window and the other lists in the app. Use the app's DesignKit components and the system's semantic colours and fonts; introduce no custom ones.\nDone means: unit tests for filtering and CSV output pass, the target builds, and a screenshot in light and dark appearance is viewed. Stop at 35 minutes."}
{"split": "held", "label": "quiet", "real": false, "text": "Create the 'Receipt' view in the Kotlin Multiplatform app's shared Compose UI (shared/ui/receipt/ReceiptView.kt, with a preview and a screenshot test). Show merchant, date, itemised lines with quantity and price, tax, tip, total and a 'Share' button. Type: Roboto Mono 13 sp for amounts, Roboto Medium 16 sp for merchant, Roboto Regular 14 sp otherwise. Colour: surface #FFFFFF, text #1C1B1F, dividers #E0E0E6, total highlight #0A6E4F; dark variants #1C1B1F, #E6E1E5, #38363A, #5FD3A8. Spacing: 16 dp screen padding, 8 dp between lines, 24 dp above the total, 8 dp radius on the share button. Done means: the screenshot tests pass in light and dark for 1, 12 and 60 lines, and you have looked at each. Stop at 35 minutes."}
{"split": "held", "label": "note", "real": false, "text": "Implement the 'Import wizard' in the WPF desktop app (Importer.Wpf/Wizard/): four pages, namely choose file, map columns, preview and result. Choose file accepts drag and drop and a Browse button for .csv and .xlsx; map columns shows the file's headers beside the target fields with a dropdown per field and guesses matches by name; preview shows the first 50 rows as they will be imported with invalid cells marked; result reports counts imported and skipped with a button to save the skipped rows. Back and Next keep the user's choices; Cancel asks before discarding. Use the existing ImportService; no changes to it. Done means: view-model tests for the mapping guess and the page flow pass, the solution builds in Release, and screenshots of all four pages at 100% and 200% display scaling were viewed. Stop at 45 minutes."}
{"split": "train", "label": "note", "real": false, "text": "Build the landing page for 'Tidepool' in the SvelteKit app, route src/routes/+page.svelte with components under src/lib/landing/. Sections: hero with headline, one-line pitch and a 'Get started' button; three feature blurbs with icons from lucide; a testimonial strip rotating every six seconds and pausing on hover or focus; a closing call to action and footer links. Copy is in docs/landing-copy.md, use it verbatim. It must score at least 95 on Lighthouse performance and accessibility on a throttled mobile run. Done means: npm run check and the build pass, Lighthouse numbers are quoted, and screenshots at laptop and phone width are looked at. Time limit 35 minutes."}
{"split": "train", "label": "quiet", "real": false, "text": "Measure only: audit the contrast and keyboard behaviour of the staging site (read-only; do not submit forms). For the five pages in docs/audit-pages.txt, run axe-core through Playwright and list every contrast failure with the selector, the measured ratio and the required one. Then tab through each page and note any control you cannot reach or cannot see focus on. Output a table to notes/a11y-staging.md, count of failures per page first. Do not propose redesigns or change any files in src/; this is the measurement the designer will use. If a page needs a login, use the test account named in the env var STAGING_USER; do not write its password anywhere. 25 minutes."}
+1230 -64
View File
File diff suppressed because it is too large. Load diff
+397
View File
@@ -0,0 +1,397 @@
"""Tests for organize evidence, drop reasons, and revert consistency."""
import glob
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REAL_HOME = os.path.expanduser("~")
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", "--level", "project")
def tree():
out = hashlib.sha1()
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
if os.path.isfile(p):
with open(p, "rb") as f:
out.update(p.encode() + f.read())
return out.hexdigest()
class OrganizeEvidence(unittest.TestCase):
def setUp(self):
before = tree()
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
mine = self.read(book) if os.path.exists(book) else None
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
self.tmp = tempfile.mkdtemp(prefix="sisi-orgev-")
self.addCleanup(shutil.rmtree, self.tmp, True)
self.data = os.path.join(self.tmp, "data")
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"))
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"):
self.env.pop(name, None)
self.proj = os.path.join(self.tmp, "alpha")
os.makedirs(self.proj)
for args in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]):
subprocess.run(["git"] + args, cwd=self.proj, check=True, stdin=subprocess.DEVNULL, capture_output=True)
def sisi(self, *args, cwd=None, sid=None, stdin=""):
env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env
out_f = os.path.join(self.tmp, "stdout.tmp")
err_f = os.path.join(self.tmp, "stderr.tmp")
with open(out_f, "w+", encoding="utf-8") as fo, open(err_f, "w+", encoding="utf-8") as fe:
r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args),
cwd=cwd or self.proj, env=env, input=stdin, stdout=fo, stderr=fe, text=True)
fo.seek(0)
fe.seek(0)
return r.returncode, fo.read(), fe.read()
def write(self, path, text):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(text)
return path
def read(self, *parts):
with open(os.path.join(*parts), encoding="utf-8") as f:
return f.read()
def test_brief_has_problem_evidence_and_respects_caps(self):
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows with empty names in table",
"--cause", "first cause missed null guard",
"--improve", "Check null names before exporting rows",
"--term", "evidence", "--problem", "row count mismatch")[0], 0)
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows again on blank fields",
"--cause", "second cause forgot whitespace trim",
"--improve", "Strip whitespace and assert total row count matches",
"--term", "evidence", "--problem", "1")[0], 0)
rc, brief, err = self.sisi("rules", "organize")
self.assertEqual((rc, err), (0, ""), brief)
self.assertIn("row count mismatch", brief)
self.assertIn("2 attempts", brief)
self.assertIn("1 miss", brief)
self.assertIn("first cause missed null guard", brief)
self.assertIn("Check null names before exporting rows", brief)
self.assertIn("second cause forgot whitespace trim", brief)
self.assertIn("Strip whitespace and assert total row count matches", brief)
self.assertIn("keep the latest attempt", brief)
self.assertIn("keep the cause", brief)
# Add 17 more problems (18 total > 15 cap) and a 5000-char cause on problem 18
long_cause = "word " * 1000
for i in range(2, 19):
cause = long_cause if i == 18 else "cause number %02d in batch" % i
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "gap number %02d failed verification check" % i,
"--cause", cause,
"--improve", "Rule number %02d for problem" % i,
"--term", "evidence", "--problem", "problem item %02d" % i)[0], 0)
# Re-cite problem 1 so it is most recently cited
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Latest rule for row count mismatch",
"--problem", "1")[0], 0)
rc, brief2, _ = self.sisi("rules", "organize")
self.assertEqual(rc, 0)
ev = brief2.split("=== Known problems")[1]
self.assertLessEqual(len(ev), 5050)
self.assertIn("row count mismatch", ev)
self.assertIn("problem item 18", ev)
self.assertNotIn(long_cause, ev)
self.assertNotIn("problem item 02", ev)
self.assertNotIn("problem item 03", ev)
self.assertNotIn("problem item 04", ev)
def test_no_problems_brief_is_minimal_and_organize_works(self):
self.assertEqual(self.sisi("learn", "--project", "Keep project outputs deterministic always")[0], 0)
self.assertEqual(self.sisi("retro", "--no-gap", "the run passed every check cleanly",
"--term", "time", "--better", "start the verification step much earlier")[0], 0)
rc, brief, _ = self.sisi("rules", "organize")
self.assertEqual(rc, 0)
self.assertNotIn("=== Known problems", brief)
self.assertIn("## drops", brief)
self.assertIn("a missing line is recorded as 'none given'", brief)
self.assertIn("copied as it is", brief)
shape = brief.split("Answer with exactly this shape")[1].split("===")[0]
self.assertLess(shape.index("## project"), shape.index("## drops"))
self.assertLess(shape.index("## drops"), shape.index("## same problems"))
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]
ans = self.write(os.path.join(self.tmp, "ans.md"),
"## user\n## project\n- Kept project rule [retro 2026-11-26]\n"
"## drops\n- %s | #- | reworded for clarity\n" % proj_line[2:])
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (0, ""), out)
recs = [json.loads(l) for l in self.read(self.data, "rules", "drops.jsonl").splitlines() if l.strip()]
self.assertEqual(len(recs), 1)
self.assertIsNone(recs[0]["problem"])
self.assertEqual(recs[0]["reason"], "reworded for clarity")
def test_missing_and_unparseable_drops_accepted_with_none_given(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule for empty names",
"--problem", "empty names")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule for empty names",
"--problem", "1")[0], 0)
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
r1, r2 = self.read(rules_path).splitlines()
self.assertEqual(self.sisi("rules", "organize")[0], 0)
ans = os.path.join(self.tmp, "ans.md")
for body in (
"## user\n## project\n%s\n" % r2,
"## user\n## project\n%s\n## drops\n- %s | #1 | \n" % (r2, r1[2:]),
"## user\n## project\n%s\n## drops\n- %s\n" % (r2, r1[2:]),
):
rc, out, err = self.sisi("rules", "organize", "--record", self.write(ans, body))
self.assertEqual((rc, err), (0, ""), (body, out))
self.assertIn("1 dropped rule had no reason recorded", out)
recs = [json.loads(l) for l in self.read(self.data, "rules", "drops.jsonl").splitlines() if l.strip()]
self.assertEqual(recs[-1]["rule"], r1)
self.assertEqual(recs[-1]["reason"], "none given")
self.assertIsNone(recs[-1]["problem"])
self.assertEqual(self.sisi("rules", "revert")[0], 0)
self.assertEqual(self.sisi("rules", "organize")[0], 0)
good = "## user\n## project\n%s\n## drops\n- %s | #1 | superseded by second rule\n" % (r2, r1[2:])
rc, out, err = self.sisi("rules", "organize", "--record", self.write(ans, good))
self.assertEqual((rc, err), (0, ""), out)
self.assertNotIn("no reason recorded", out)
self.assertEqual(self.read(rules_path), r2 + "\n")
recs = [json.loads(l) for l in self.read(self.data, "rules", "drops.jsonl").splitlines() if l.strip()]
self.assertEqual(recs[-1]["problem"], 1)
self.assertEqual(recs[-1]["rule"], r1)
self.assertEqual(recs[-1]["reason"], "superseded by second rule")
def test_owner_rules_stay_verbatim_with_drops_format(self):
self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"}))
self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Check row counts before export", "--problem", "empty names")[0], 0)
own = self.read(self.data, "rules", "user.md").splitlines()[0]
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
self.assertEqual(self.sisi("rules", "organize")[0], 0)
ans = os.path.join(self.tmp, "ans.md")
# Dropping an owner rule even with a ## drops entry is refused
bad_drop = "## user\n## project\n%s\n## drops\n- %s | #- | tried to drop owner\n" % (ret, own[2:])
rc, out, _ = self.sisi("rules", "organize", "--record", self.write(ans, bad_drop))
self.assertEqual(rc, 1, out)
self.assertIn("owner rule missing or changed", out)
self.assertIn(own, self.read(self.data, "rules", "user.md"))
# Rewording an owner rule is still refused
bad_edit = "## user\n- Keep owner rule [owner 2026-11-26]\n## project\n%s\n" % ret
rc, out, _ = self.sisi("rules", "organize", "--record", self.write(ans, bad_edit))
self.assertEqual(rc, 1, out)
self.assertIn("owner rule missing or changed", out)
# Keeping owner verbatim while dropping retro rule with reason succeeds
good = "## user\n%s\n## project\n- Export verifies row counts [retro 2026-11-26]\n## drops\n- %s | #1 | replaced with stronger rule\n" % (own, ret[2:])
rc, out, err = self.sisi("rules", "organize", "--record", self.write(ans, good))
self.assertEqual((rc, err), (0, ""), out)
self.assertIn(own, self.read(self.data, "rules", "user.md"))
def test_recorded_drop_appears_in_next_brief_and_retro_has_come_back(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "First attempt rule to drop", "--problem", "empty names")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second attempt rule to keep", "--problem", "1")[0], 0)
r1, r2 = self.read(self.proj, ".sisi", "rules.md").splitlines()
self.assertEqual(self.sisi("rules", "organize")[0], 0)
ans = self.write(os.path.join(self.tmp, "ans.md"),
"## user\n## project\n%s\n## drops\n- %s | #1 | too vague to prevent bug\n" % (r2, r1[2:]))
self.assertEqual(self.sisi("rules", "organize", "--record", ans)[0], 0)
rc, brief, _ = self.sisi("rules", "organize")
self.assertEqual(rc, 0)
self.assertIn("earlier dropped:", brief)
self.assertIn("has not come back yet", brief)
self.assertIn("note it in `## flags`", brief)
self.assertIn(r1, brief)
self.assertIn("too vague to prevent bug", brief)
rc, retro_out, _ = self.sisi("retro", *GAP, "--improve", "Third attempt rule after drop", "--problem", "1")
self.assertEqual(rc, 0, retro_out)
self.assertIn("problem 1 'empty names' has come back: 2 misses", retro_out)
self.assertIn("dropped [", retro_out)
self.assertIn(r1, retro_out)
self.assertIn("too vague to prevent bug", retro_out)
def test_revert_after_organize_undoes_and_redoes_drop_reasons(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule before organize", "--problem", "empty names")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule before organize", "--problem", "1")[0], 0)
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
before = self.read(rules_path)
r1, r2 = before.splitlines()
self.assertEqual(self.sisi("rules", "organize")[0], 0)
ans = self.write(os.path.join(self.tmp, "ans.md"),
"## user\n## project\n%s\n## drops\n- %s | #1 | dropped during organize\n" % (r2, r1[2:]))
self.assertEqual(self.sisi("rules", "organize", "--record", ans)[0], 0)
self.assertIn("dropped during organize", self.read(self.data, "rules", "drops.jsonl"))
rc, out, _ = self.sisi("rules", "revert")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(rules_path), before)
drops_path = os.path.join(self.data, "rules", "drops.jsonl")
self.assertFalse(os.path.exists(drops_path) and "dropped during organize" in self.read(drops_path))
self.assertNotIn("dropped during organize", self.sisi("rules", "organize")[1])
# Second revert re-applies both the organized rules and the drop reason
rc, out, _ = self.sisi("rules", "revert")
self.assertEqual(rc, 0, out)
self.assertEqual(self.read(rules_path), r2 + "\n")
self.assertIn("dropped during organize", self.read(drops_path))
self.assertIn("dropped during organize", self.sisi("rules", "organize")[1])
def test_lenient_drops_variants_all_accepted(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Check row counts before export", "--problem", "empty names")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Trim whitespace before export", "--problem", "1")[0], 0)
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
r1, r2 = self.read(rules_path).splitlines()
r1_notags = r1[2:].rsplit(" [retro ", 1)[0]
ans = os.path.join(self.tmp, "ans.md")
drops_path = os.path.join(self.data, "rules", "drops.jsonl")
# 1. No brief printed first + reworded rule + no drops section + plural message
rc, out, err = self.sisi("rules", "organize", "--record", self.write(
ans, "## user\n## project\n- Reworded export check [retro 2026-11-26]\n"))
self.assertEqual((rc, err), (0, ""), out)
self.assertIn("2 dropped rules had no reason recorded", out)
recs = [json.loads(l) for l in self.read(drops_path).splitlines()]
self.assertEqual([(x["rule"], x["reason"], x["problem"]) for x in recs],
[(r1, "none given", None), (r2, "none given", None)])
self.assertEqual(self.sisi("rules", "revert")[0], 0)
cases = [
("backticks", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\n- `%s` | #1 | reason one\n- `%s` | #1 | reason two\n" % (r1, r2[2:]),
[(r1, "reason one", 1), (r2, "reason two", 1)], False),
("no_date_tag", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\n- %s | #1 | no tag reason\n- %s | #- | second reason\n" % (r1_notags, r2[2:].rsplit(" [", 1)[0]),
[(r1, "no tag reason", 1), (r2, "second reason", None)], False),
("one_of_two_merged", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\n- %s | #1 | merged into one\n" % r1[2:],
[(r1, "merged into one", 1), (r2, "none given", None)], "1 dropped rule had no reason recorded"),
("pipe_in_reason", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\n- %s | #1 | replaced A | B | C\n- %s | #- | x | y\n" % (r1[2:], r2[2:]),
[(r1, "replaced A | B | C", 1), (r2, "x | y", None)], False),
("none_under_drops", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\nnone\n",
[(r1, "none given", None), (r2, "none given", None)], "2 dropped rules had no reason recorded"),
("closing_fence", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\n- %s | #1 | kept reason\n- %s | #- | also kept\n```\n" % (r1[2:], r2[2:]),
[(r1, "kept reason", 1), (r2, "also kept", None)], False),
("star_and_indented", "## user\n## project\n- Merged [retro 2026-11-26]\n## drops\n * %s | #1 | star reason\n 1. %s | #- | num reason\n" % (r1[2:], r2[2:]),
[(r1, "star reason", 1), (r2, "num reason", None)], False),
("drops_between_user_and_project", "## user\n## drops:\n- %s | #1 | middle drops\n- %s | #- | middle two\n## project\n- Kept project [retro 2026-11-26]\n" % (r1[2:], r2[2:]),
[(r1, "middle drops", 1), (r2, "middle two", None)], False),
("heading_h3_Drops", "## user\n## project\n- Kept project [retro 2026-11-26]\n### Drops\n- %s | #1 | h3 reason\n- %s | #- | h3 two\n## notes\n- %s | #1 | ignored after next heading\n" % (r1[2:], r2[2:], r1[2:]),
[(r1, "h3 reason", 1), (r2, "h3 two", None)], False),
("drops_before_flags", "## user\n## project\n- Kept project [retro 2026-11-26]\n## drops\n- %s | #1 | before flags\n- %s | #- | two\n## flags\n- flag item\n" % (r1[2:], r2[2:]),
[(r1, "before flags", 1), (r2, "two", None)], False),
]
for name, text, expected, notice in cases:
self.assertEqual(self.sisi("rules", "organize")[0], 0, name)
rc, out, err = self.sisi("rules", "organize", "--record", self.write(ans, text))
self.assertEqual((rc, err), (0, ""), (name, out))
self.assertIn("Kept project" if "Kept project" in text else "Merged", self.read(rules_path), name)
if notice:
self.assertIn(notice, out, name)
else:
self.assertNotIn("no reason recorded", out, name)
recs = [json.loads(l) for l in self.read(drops_path).splitlines()]
self.assertEqual([(x["rule"], x["reason"], x["problem"]) for x in recs[-2:]], expected, name)
self.assertEqual(self.sisi("rules", "revert")[0], 0, name)
def test_drops_ignore_kept_owner_and_invented_rules(self):
self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"}))
self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Kept retro rule always here", "--problem", "empty names")[0], 0)
own = self.read(self.data, "rules", "user.md").splitlines()[0]
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
ans = self.write(os.path.join(self.tmp, "ans.md"),
"## user\n%s\n## project\n%s\n## drops\n"
"- %s | #- | named kept rule\n"
"- %s | #- | named owner rule\n"
"- Invented rule never existed | #1 | invented\n" % (own, ret, ret[2:], own[2:]))
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (0, ""), out)
self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "drops.jsonl")))
def test_drops_bounded_redacted_and_invalid_problem_numbers_safe(self):
long_rule = "Very long rule text " + ("x" * 350)
self.assertEqual(self.sisi("retro", *GAP, "--improve", long_rule, "--problem", "empty names")[0], 0)
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
r1 = self.read(rules_path).splitlines()[0]
for i in range(3):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Extra rule number %d here" % i, "--problem", "1")[0], 0)
rs = self.read(rules_path).splitlines()
big_num = "9" * 5000
long_reason = "api_key=sk-abcdefghijklmnopqrstuvwx " + ("y" * 350)
ans = self.write(os.path.join(self.tmp, "ans.md"),
"## user\n## project\n- Remaining [retro 2026-11-26]\n## drops\n"
"- %s | #999 | %s\n"
"- %s | #0 | zero prob\n"
"- %s | #%s | five thousand digits\n"
"- %s | #\uff11 | fullwidth digit\n"
% (rs[0][2:], long_reason, rs[1][2:], rs[2][2:], big_num, rs[3][2:]))
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (0, ""), out)
recs = [json.loads(l) for l in self.read(self.data, "rules", "drops.jsonl").splitlines()]
self.assertEqual(len(recs), 4)
for rec in recs:
self.assertIsNone(rec["problem"])
self.assertLessEqual(len(rec["rule"]), 300)
self.assertLessEqual(len(rec["reason"]), 300)
self.assertNotIn("sk-abcdefghijklmnop", recs[0]["reason"])
self.assertIn("<redacted>", recs[0]["reason"])
def test_retro_caps_drops_at_five_with_more_and_evidence_is_newest_first(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Seed rule for problem one", "--problem", "empty names")[0], 0)
long_r = "Long dropped rule " + ("a" * 220)
long_why = "Long drop reason " + ("b" * 220)
dp = os.path.join(self.data, "rules", "drops.jsonl")
os.makedirs(os.path.dirname(dp), exist_ok=True)
with open(dp, "w", encoding="utf-8") as f:
for i in range(1, 8):
rule_s = long_r if i == 7 else "- Dropped rule %02d [retro 2026-11-26]" % i
why_s = long_why if i == 7 else "drop reason %02d" % i
f.write(json.dumps({"ts": "2026-11-26T00:00:%02d" % i, "rule": rule_s, "problem": 1, "reason": why_s}) + "\n")
rc, brief, _ = self.sisi("rules", "organize")
self.assertEqual(rc, 0)
ev = brief.split("=== Known problems")[1]
self.assertLess(ev.index("Long dropped rule"), ev.index("drop reason 01"))
rc, retro_out, err = self.sisi("retro", *GAP, "--improve", "Next rule after seven drops", "--problem", "1")
self.assertEqual((rc, err), (0, ""), retro_out)
drop_lines = [l for l in retro_out.splitlines() if l.strip().startswith("- dropped [")]
self.assertEqual(len(drop_lines), 5, retro_out)
self.assertIn("and 2 more", retro_out)
self.assertNotIn("drop reason 01", retro_out)
self.assertNotIn("drop reason 02", retro_out)
self.assertIn("drop reason 03", retro_out)
for dl in drop_lines:
self.assertLessEqual(len(dl), 390)
self.assertNotIn("a" * 170, retro_out)
self.assertNotIn("b" * 170, retro_out)
def test_evidence_cap_counts_header_and_truncates_single_large_problem(self):
# One problem with 70 attempts of ~90 chars each -> >6000 chars total, exceeding 5000.
# Fails if: (1) cap is raised, (2) truncation branch is removed, (3) header is not counted.
os.makedirs(self.data, exist_ok=True)
with open(os.path.join(self.data, "retro.jsonl"), "w", encoding="utf-8") as f:
for i in range(70):
f.write(json.dumps({
"ts": "2026-11-26T00:00:00",
"problem": "single huge problem",
"cause": "cause_%02d_%s" % (i, "c" * 30),
"improve": "rule_%02d_%s" % (i, "r" * 20),
}) + "\n")
rc, brief, err = self.sisi("rules", "organize")
self.assertEqual((rc, err), (0, ""))
ev_raw = ("\n\n=== Known problems" + brief.split("=== Known problems")[1]).rstrip("\n")
self.assertLessEqual(len(ev_raw), 5000)
self.assertIn("#1: single huge problem", ev_raw)
self.assertIn("attempt [", ev_raw)
self.assertNotIn("rule_69_", ev_raw)
if __name__ == "__main__":
unittest.main()
+550
View File
@@ -0,0 +1,550 @@
"""Tests for retro problem tracking and repeat-miss fault escalation."""
import contextlib
import glob
import hashlib
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REAL_HOME = os.path.expanduser("~")
sys.path.insert(0, REPO)
from sisi import retro, rules, store
GAP = ("--gap", "the export dropped rows with empty names until the person noticed",
"--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project")
def tree():
out = hashlib.sha1()
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
if os.path.isfile(p):
with open(p, "rb") as f:
out.update(p.encode() + f.read())
return out.hexdigest()
class Problems(unittest.TestCase):
def setUp(self):
before = tree()
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
mine = self.read(book) if os.path.exists(book) else None
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
self.tmp = tempfile.mkdtemp(prefix="sisi-prob-")
self.addCleanup(shutil.rmtree, self.tmp, True)
self.data = os.path.join(self.tmp, "data")
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data,
SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"),
CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"):
self.env.pop(name, None)
self.proj = os.path.join(self.tmp, "alpha")
os.makedirs(self.proj)
for args in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]):
subprocess.run(["git"] + args, cwd=self.proj, check=True, stdin=subprocess.DEVNULL, capture_output=True)
def in_process(self, fn, *args):
out, here = io.StringIO(), os.getcwd()
os.chdir(self.tmp)
try:
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \
mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \
mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out):
return fn(*args), out.getvalue()
finally:
os.chdir(here)
def sisi(self, *args, cwd=None, sid=None, stdin=""):
env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env
out_f = os.path.join(self.tmp, "stdout.tmp")
err_f = os.path.join(self.tmp, "stderr.tmp")
with open(out_f, "w+", encoding="utf-8") as fo, open(err_f, "w+", encoding="utf-8") as fe:
r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args),
cwd=cwd or self.proj, env=env, input=stdin, stdout=fo, stderr=fe, text=True)
fo.seek(0)
fe.seek(0)
return r.returncode, fo.read(), fe.read()
def read(self, *parts):
with open(os.path.join(*parts), encoding="utf-8") as f:
return f.read()
def records(self):
p = os.path.join(self.data, "retro.jsonl")
if not os.path.exists(p):
return []
with open(p, encoding="utf-8") as f:
return [json.loads(l) for l in f.read().splitlines() if l.strip()]
def test_open_cite_missing_unknown_old_records_and_stable_numbers(self):
# Seed old records without 'problem' field and ensure they stay valid and belong to no problem
os.makedirs(self.data, exist_ok=True)
log = os.path.join(self.data, "retro.jsonl")
with open(log, "w", encoding="utf-8") as f:
f.write(json.dumps({"ts": "2026-11-20T10:00:00", "gap": "old gap without problem",
"cause": "old cause", "improve": "Old rule without problem", "term": "evidence"}) + "\n")
f.write(json.dumps({"ts": "2026-11-21T10:00:00", "no-gap": "all good",
"better": "do something better next time", "term": "time"}) + "\n")
# Missing --problem on --gap is refused with nothing written
rc, out, err = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export")
self.assertNotEqual(rc, 0, out)
self.assertEqual(len(self.records()), 2)
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "rules.md")))
self.assertIn("--problem", out)
# Open problem #1 by words
rc, out, err = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export",
"--problem", "export drops empty names")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.records()[-1]["problem"], "export drops empty names")
self.assertNotIn("has come back", out)
# Open problem #2 by words
rc, out, err = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts in output",
"--cause", "clean step was skipped on incremental runs",
"--improve", "Always clean output directory before packaging release",
"--term", "value", "--problem", "stale build artifacts")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.records()[-1]["problem"], "stale build artifacts")
# Unknown problem numbers refused with nothing written, listing known problems and re-run syntax
for bad_num in ("0", "-1", "3", "99"):
before_count = len(self.records())
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not be recorded at all", "--problem", bad_num)
self.assertNotEqual(rc, 0, bad_num)
self.assertEqual(len(self.records()), before_count, bad_num)
self.assertIn("export drops empty names", out)
self.assertIn("stale build artifacts", out)
self.assertIn("--problem", out)
# --no-gap and --later unchanged and refuse --problem
self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row cleanly",
"--term", "time", "--better", "start the first build sooner than before")[0], 0)
self.assertNotIn("problem", self.records()[-1])
self.assertNotEqual(self.sisi("retro", "--no-gap", "the export kept every row cleanly",
"--term", "time", "--better", "start the first build sooner than before",
"--problem", "1")[0], 0)
self.assertNotEqual(self.sisi("retro", "--later", "waiting for the owner to reply", "--problem", "1")[0], 0)
# Cite problem #1 by number: numbers remain stable (#1 is still export drops empty names)
rc, out, err = self.sisi("retro", *GAP, "--improve", "Add an automated row-count assertion to export tests",
"--problem", "1")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.records()[-1]["problem"], "export drops empty names")
self.assertIn("problem 1 'export drops empty names' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertIn("Compare row counts before and after every export", out)
# Add more non-problem records and cite #2; numbers stay stable
self.assertEqual(self.sisi("retro", "--no-gap", "the build passed cleanly on first run",
"--term", "time", "--better", "parallelize the test suite run here")[0], 0)
rc, out, _ = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts again",
"--cause", "incremental cache kept old binary",
"--improve", "Hash inputs before reusing build artifacts",
"--term", "value", "--problem", "2")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 'stale build artifacts' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertIn("Always clean output directory before packaging release", out)
def test_misses_and_fault_escalation_lifecycle(self):
# 1st attempt: 0 misses, no fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "First rule attempt for empty names",
"--problem", "empty name export bug")
self.assertEqual(rc, 0, out)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
# 2nd attempt: 1 miss, no fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule attempt for empty names",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertIn("First rule attempt for empty names", out)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
# 3rd attempt (2nd miss): opens a fault, records retro and rule
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Third rule attempt for empty names",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 2 misses", out)
self.assertIn("First rule attempt for empty names", out)
self.assertIn("Second rule attempt for empty names", out)
self.assertEqual(len(self.records()), 3)
with open(os.path.join(self.proj, ".sisi", "rules.md"), encoding="utf-8") as f:
self.assertIn("Third rule attempt for empty names", f.read())
faults_out = self.sisi("fault")[1]
self.assertEqual(len(faults_out.strip().splitlines()), 1, faults_out)
self.assertIn("empty name export bug", faults_out)
self.assertIn("2 times", faults_out)
self.assertIn("hook or an automatic check", faults_out)
# 4th attempt while fault is still open (or started): opens NO duplicate fault
self.assertEqual(self.sisi("fault", "--started", "1", "building automatic export test hook")[0], 0)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule attempt while fault open",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 3 misses", out)
self.assertEqual(len(self.sisi("fault")[1].strip().splitlines()), 1)
# Fix the fault, then another attempt opens a new fault
self.assertEqual(self.sisi("fault", "--fixed", "1", "added export hook to CI check")[0], 0)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fifth rule attempt after fix",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 4 misses", out)
faults_after = self.sisi("fault")[1]
self.assertEqual(len(faults_after.strip().splitlines()), 1, faults_after)
self.assertIn("4 times", faults_after)
def test_no_arg_retro_lists_problems_most_recent_first_capped_at_15(self):
for i in range(1, 18):
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Rule number %02d for problem" % i,
"--problem", "problem item %02d" % i)
self.assertEqual(rc, 0, out)
# Re-cite problem 1 so it becomes the most recently cited
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for problem 01", "--problem", "1")
self.assertEqual(rc, 0, out)
rep = self.sisi("retro")[1]
lines = [l for l in rep.splitlines() if "problem item " in l]
self.assertEqual(len(lines), 15, "\n".join(lines))
# Most recently cited (#1 with 2 attempts) is first, followed by #17 .. #4; #2 and #3 drop off the 15-line cap
self.assertIn("#1:", lines[0])
self.assertIn("problem item 01", lines[0])
self.assertIn("2 attempts", lines[0])
self.assertIn("#17:", lines[1])
self.assertIn("problem item 17", lines[1])
self.assertIn("1 attempt", lines[1])
self.assertNotIn("problem item 02", rep)
self.assertNotIn("problem item 03", rep)
def test_race_derives_number_and_misses_after_append(self):
real_append = store.append
log_path = os.path.join(self.data, "retro.jsonl")
def racing_append(extra_records):
injected = False
def wrapper(path, line, once=False):
nonlocal injected
if not injected and path == log_path:
injected = True
for rec in extra_records:
real_append(path, json.dumps(rec))
return real_append(path, line, once=once)
return wrapper
base_args = list(GAP) + ["--improve", "Always verify export row count in CI checks", "--problem"]
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")):
# Between pre-check (empty log) and append, another session opens a different problem and the same problem
extra = [
{"ts": "2026-11-26T10:00:00", "gap": "other gap", "cause": "other cause",
"improve": "Other rule first", "term": "time", "problem": "other race problem"},
{"ts": "2026-11-26T10:00:01", "gap": "same gap", "cause": "same cause",
"improve": "Earlier racing rule for shared problem", "term": "evidence", "problem": "shared race problem"},
]
out1 = io.StringIO()
with mock.patch.object(store, "append", side_effect=racing_append(extra)), contextlib.redirect_stdout(out1):
rc1 = retro.run(base_args + ["shared race problem"], cwd=self.proj)
self.assertEqual(rc1, 0, out1.getvalue())
self.assertIn("problem 2 'shared race problem' has come back: 1 miss", out1.getvalue())
self.assertNotIn("opened problem 1", out1.getvalue())
rep1 = self.sisi("retro")[1]
self.assertIn("#1: other race problem (1 attempt", rep1)
self.assertIn("#2: shared race problem (2 attempts", rep1)
# Second race: pre-check sees #2 with 2 attempts (1 miss); racing session adds 3rd attempt before append
extra2 = [
{"ts": "2026-11-26T10:05:00", "gap": "third gap", "cause": "third cause",
"improve": "Third racing rule for shared problem", "term": "evidence", "problem": "shared race problem"},
]
out2 = io.StringIO()
with mock.patch.object(store, "append", side_effect=racing_append(extra2)), contextlib.redirect_stdout(out2):
rc2 = retro.run(base_args + ["2"], cwd=self.proj)
self.assertEqual(rc2, 0, out2.getvalue())
self.assertIn("problem 2 'shared race problem' has come back: 3 misses", out2.getvalue())
self.assertIn("opened fault #1", out2.getvalue())
rep2 = self.sisi("retro")[1]
self.assertIn("#2: shared race problem (4 attempts", rep2)
def test_large_log_past_2mb_keeps_problem_numbers_and_attempts(self):
os.makedirs(self.data, exist_ok=True)
log = os.path.join(self.data, "retro.jsonl")
first = json.dumps({"ts": "2026-01-01T10:00:00", "gap": "early gap", "cause": "early cause",
"improve": "Early rule for problem one", "term": "evidence", "problem": "early problem"}) + "\n"
pad_line = json.dumps({"ts": "2026-06-01T10:00:00", "no-gap": "all checks passed cleanly today " + ("x" * 120),
"better": "start the build earlier next time around", "term": "time"}) + "\n"
last = json.dumps({"ts": "2026-11-26T10:00:00", "gap": "late gap", "cause": "late cause",
"improve": "Late rule for problem two", "term": "value", "problem": "late problem"}) + "\n"
repeat_count = (2_100_000 // len(pad_line)) + 1
with open(log, "w", encoding="utf-8") as f:
f.write(first + (pad_line * repeat_count) + last)
self.assertGreater(os.path.getsize(log), 2_000_000)
rep = self.sisi("retro")[1]
self.assertIn("#1: early problem (1 attempt", rep)
self.assertIn("#2: late problem (1 attempt", rep)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for early problem", "--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'early problem' has come back: 1 miss", out)
rep2 = self.sisi("retro")[1]
self.assertIn("#1: early problem (2 attempts", rep2)
self.assertIn("#2: late problem (1 attempt", rep2)
def test_wording_refusals_and_miss_singular(self):
# With no problems yet, refusals must not say "numbers above"
for p_args in ((), ("--problem", "1")):
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not be written anywhere", *p_args)
self.assertNotEqual(rc, 0)
self.assertIn("none yet", out)
self.assertNotIn("numbers above", out)
self.assertEqual(self.records(), [])
# Problem name over 400 characters is refused with a message mentioning the 400-character limit
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not be written anywhere", "--problem", "p" * 401)
self.assertNotEqual(rc, 0)
self.assertIn("400", out)
self.assertEqual(self.records(), [])
# --no-gap with --problem says --problem goes only with --gap
rc, out, _ = self.sisi("retro", "--no-gap", "the export kept every row cleanly",
"--term", "time", "--better", "start the first build sooner than before",
"--problem", "1")
self.assertNotEqual(rc, 0)
self.assertIn("--problem", out)
self.assertIn("--gap", out)
self.assertNotIn("that is not a retro yet", out)
self.assertEqual(self.records(), [])
def test_redacted_problem_names_refused(self):
bad_names = (
"sk-abcdefghijklmnopqrstuvwx",
"0123456789abcdef0123456789abcdef01234567",
"1234567890" * 4,
"api_key=supersecret999 broken",
)
for bad in bad_names:
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not record secret problem name", "--problem", bad)
self.assertNotEqual(rc, 0, bad)
self.assertIn("plain words", out)
self.assertNotIn(bad, out)
self.assertEqual(self.records(), [])
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "rules.md")))
def test_two_problems_each_open_own_fault_and_case_spacing_joins(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Alpha rule one for export", "--problem", "alpha issue")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Bravo rule one for export", "--problem", "bravo issue")[0], 0)
# Citing by name with different case and spacing joins the same problem
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Alpha rule two by name", "--problem", " ALPHA issue ")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'alpha issue' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
# 2nd miss on problem 1 opens its fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Alpha rule three opens fault", "--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'alpha issue' has come back: 2 misses", out)
# Same-length second problem joins via case/spacing then reaches 2 misses and opens its own fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Bravo rule two by name", "--problem", " bravo ISSUE ")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 'bravo issue' has come back: 1 miss", out)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Bravo rule three opens fault", "--problem", "2")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 'bravo issue' has come back: 2 misses", out)
faults_lines = self.sisi("fault")[1].strip().splitlines()
self.assertEqual(len(faults_lines), 2, 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)
def test_organize_brief_lists_every_problem_and_same_problems_section(self):
self.assertEqual(self.sisi("retro", "--level", "project",
"--gap", "stated a remembered tool behaviour without running the command",
"--cause", "stated a remembered tool behaviour without checking",
"--improve", "Run the command before stating tool behaviour",
"--term", "evidence",
"--problem", "claimed tool behaviour or timing from memory in a question or fault brief")[0], 0)
for i in range(2, 18):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Rule number %02d for problem" % i,
"--problem", "distinct item %02d" % i)[0], 0)
self.assertEqual(self.sisi("retro", "--level", "project",
"--gap", "inferred driver behaviour from defaults without testing",
"--cause", "Inferred driver behaviour from lpoptions defaults instead of running the filter chain",
"--improve", "Push a known test page before claiming driver behaviour",
"--term", "evidence",
"--problem", "Unmeasured claims about tool behaviour")[0], 0)
brief, _ = self.in_process(rules.organize_brief, self.proj)
self.assertIn("## same problems", brief)
self.assertIn("N = M", brief)
# All 18 problems (beyond the 15-problem cap in _evidence) appear with number, name, and cause
self.assertIn("#1:", brief)
self.assertIn("claimed tool behaviour or timing from memory in a question or fault brief", brief)
self.assertIn("stated a remembered tool behaviour without checking", brief)
self.assertIn("#18:", brief)
self.assertIn("Unmeasured claims about tool behaviour", brief)
self.assertIn("Inferred driver behaviour from lpoptions defaults instead of running the filter chain", brief)
self.assertIn("#2:", brief)
self.assertIn("distinct item 02", brief)
def test_merge_problems_counts_misses_opens_fault_and_shows_in_report(self):
p1_a = "claimed tool behaviour or timing from memory in a question or fault brief"
p1_b = "Unmeasured claims about tool behaviour"
p2_a = "push not gated on the test run's exit code"
p2_b = "a gating command's exit status was hidden by a display filter"
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Run the command before claiming behaviour", "--problem", p1_a)[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Gate every push on the test exit code", "--problem", p2_a)[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Test the filter chain on a known page first", "--problem", p1_b)[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Never pipe a gating command into a filter", "--problem", p2_b)[0], 0)
self.in_process(rules.organize_brief, self.proj)
proj_rules = [l for l in self.read(self.proj, ".sisi", "rules.md").splitlines() if l.startswith("- ")]
ans = os.path.join(self.tmp, "merge.md")
with open(ans, "w", encoding="utf-8") as f:
f.write("## user\n## project\n" + "\n".join(proj_rules) + "\n## same problems\n1 = 3\n2 = 4\n")
why, out = self.in_process(rules.organize_record, ans, self.proj)
self.assertIsNone(why, out)
rep = self.sisi("retro")[1]
self.assertIn("#1: " + p1_a + " (2 attempts", rep)
self.assertIn("#2: " + p2_a + " (2 attempts", rep)
self.assertNotIn("#3: " + p1_b, rep)
self.assertNotIn("#4: " + p2_b, rep)
self.assertIn(p1_b, rep)
self.assertIn(p2_b, rep)
self.assertLess(rep.index("#1: " + p1_a), rep.index(p1_b))
self.assertLess(rep.index("#2: " + p2_a), rep.index(p2_b))
# Existing numbering stays valid: a new problem gets #5, not #3
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Separate problem rule five", "--problem", "separate fifth issue")
self.assertEqual(rc, 0, out)
self.assertIn("opened problem 5 'separate fifth issue'", out)
# Citing merged number 3 counts as 2nd miss of #1 and opens its fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged number three", "--problem", "3")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 '%s' has come back: 2 misses" % p1_a, out)
self.assertIn("opened fault #1", out)
# Citing merged name p2_b counts as 2nd miss of #2 and opens its fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged name p2_b", "--problem", p2_b)
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 '%s' has come back: 2 misses" % p2_a, out)
self.assertIn("opened fault #2", out)
# Citing merged number 4 a second time (event happens twice) counts 3 misses on #2 without opening a duplicate fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fifth rule via merged number four", "--problem", "4")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 '%s' has come back: 3 misses" % p2_a, out)
self.assertEqual(len(self.sisi("fault")[1].strip().splitlines()), 2)
# Citing #5 still resolves to #5
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for fifth issue", "--problem", "5")
self.assertEqual(rc, 0, out)
self.assertIn("problem 5 'separate fifth issue' has come back: 1 miss", out)
def test_per_rule_note_counts_citations_through_alias(self):
p3_a = "a long real-data run started without its read-only admission check"
p3_b = "untested script left for unattended run"
os.makedirs(self.data, exist_ok=True)
retro_rows = [
{"ts": "2026-11-20T10:00:00", "problem": p3_a, "cause": "no admission check", "improve": "Run read-only admission check first"},
{"ts": "2026-11-21T10:00:00", "problem": p3_b, "cause": "never dry-ran script", "improve": "Dry-run one item end to end first"},
]
with open(os.path.join(self.data, "retro.jsonl"), "w", encoding="utf-8") as f:
f.write("".join(json.dumps(r) + "\n" for r in retro_rows))
os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True)
with open(os.path.join(self.proj, ".sisi", "rules.md"), "w", encoding="utf-8") as f:
f.write("\n".join([
"- Run read-only admission check first [retro 2026-11-20 p1]",
"- Dry-run one item end to end first [retro 2026-11-21 p2]",
]) + "\n")
ans = os.path.join(self.tmp, "merge3.md")
with open(ans, "w", encoding="utf-8") as f:
f.write("## user\n## project\n- Run read-only admission check first [retro 2026-11-20 p1]\n- Dry-run one item end to end first [retro 2026-11-21 p2]\n## same problems\n1 = 2\n")
self.in_process(rules.organize_brief, self.proj)
why, out = self.in_process(rules.organize_record, ans, self.proj)
self.assertIsNone(why, out)
rc, retro_out, _ = self.sisi("retro", *GAP, "--improve", "Verify one sample output before batching", "--problem", "2")
self.assertEqual(rc, 0, retro_out)
self.assertIn("problem 1 '%s' has come back: 2 misses" % p3_a, retro_out)
_, listing_inproc = self.in_process(rules.show, self.proj)
listing_cli = self.sisi("rules")[1]
brief = self.sisi("rules", "organize")[1]
for out_txt in (listing_inproc, listing_cli, brief):
self.assertIn("[retro 2026-11-20 p1] (p1: came back 2x since)", out_txt)
self.assertIn("[retro 2026-11-21 p2] (p2: came back 1x since)", out_txt)
self.in_process(rules.build_rulebook)
book = self.read(self.data, "generated", "core.md")
self.assertNotIn("came back", book)
def test_bad_same_problems_skipped_and_revert_undoes_aliases(self):
p_a = "a long real-data run started without its read-only admission check"
p_b = "untested script left for unattended run"
self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule before bad merge", "--problem", p_a)[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule before bad merge", "--problem", p_b)[0], 0)
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
before = self.read(rules_path)
self.in_process(rules.organize_brief, self.proj)
ans = os.path.join(self.tmp, "bad_merge.md")
with open(ans, "w", encoding="utf-8") as f:
f.write("\n".join([
"## user",
"- Kept organized user rule [retro 2026-11-26]",
"## project",
"- Combined organized project rule [retro 2026-11-26 p1]",
"## same problems",
"1 = 99",
"0 = 1",
"1 = 1",
"1 = 2",
"2 = 1",
"not a valid pair",
]) + "\n")
why, out = self.in_process(rules.organize_record, ans, self.proj)
self.assertIsNone(why, out)
self.assertIn("99", out)
self.assertIn("0 = 1", out)
self.assertIn("1 = 1", out)
self.assertIn("2 = 1", out)
self.assertIn("not a valid pair", out)
# Rest of organize recorded
self.assertIn("Combined organized project rule", self.read(rules_path))
self.assertIn("Kept organized user rule", self.read(self.data, "rules", "user.md"))
# Valid 1 = 2 took effect
rep = self.sisi("retro")[1]
self.assertIn("#1: " + p_a + " (2 attempts", rep)
self.assertNotIn("#2: " + p_b, rep)
# Revert undoes the organize AND removes the alias
rc, rev_out, _ = self.sisi("rules", "revert")
self.assertEqual(rc, 0, rev_out)
self.assertEqual(self.read(rules_path), before)
rep_after = self.sisi("retro")[1]
self.assertIn("#1: " + p_a + " (1 attempt", rep_after)
self.assertIn("#2: " + p_b + " (1 attempt", rep_after)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Post-revert citation of two", "--problem", "2")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 '%s' has come back: 1 miss" % p_b, out)
if __name__ == "__main__":
unittest.main()