Compare commits
28
Commits
94178e9b04
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25b5e90c6b | ||
|
|
68b6226aa6 | ||
|
|
6edfa6d860 | ||
|
|
2e3a114c8e | ||
|
|
9f167f8f50 | ||
|
|
4b0326ba7c | ||
|
|
0660ee13d6 | ||
|
|
1e1f26616e | ||
|
|
2a68ead05f | ||
|
|
064cd6f5ca | ||
|
|
058d6e3e56 | ||
|
|
c07ce2176b | ||
|
|
bbf21ef178 | ||
|
|
64b748b32e | ||
|
|
d4e11600cb | ||
|
|
6632a82f77 | ||
|
|
33ca3d3c4d | ||
|
|
4e549dedde | ||
|
|
2083bbbd78 | ||
|
|
5e39baaa30 | ||
|
|
d65ee6e547 | ||
|
|
2055d4bb48 | ||
|
|
6e73cca4a1 | ||
|
|
c91d5ed8a5 | ||
|
|
62e494de8e | ||
|
|
6292f5c45e | ||
|
|
6477f22933 | ||
|
|
4c32469a58 |
No files matched your search
+17
-13
@@ -3,18 +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]
|
||||
- Use no external dependencies and no cron jobs; run periodic upkeep from a counter or chance check during a normal turn, so the system improves just by being used. [owner 2026-11-23]
|
||||
- The real objective function is the one in SPEC.md; sisi always optimizes it by mechanisms (hooks, checks), never by good intentions, and never hard-codes a model or a harness. [owner 2026-11-23]
|
||||
- Measure size budgets in the unit actually paid for (characters loaded per session), and say plainly whether loaded text grew or shrank after a change. [retro 2026-11-23]
|
||||
- For classifier, matcher or lookup changes, have a different worker write the labelled set and report only held-out accuracy, prototype on a blind set, give three real rows and three real inputs from the live data as test cases, and name every flag the matcher takes — a tuner scoring its own labels or a made-up row overstates accuracy. [retro 2026-11-23] [retro 2026-11-24]
|
||||
- Detached background workers must start with python3 -B (no bytecode in shared state) and print no user-facing output whose only reader is a log; in tests send output to temp files, not pipes, and pass stdin explicitly (input or DEVNULL) — open pipes or inherited stdin hang under some shells. [retro 2026-11-23]
|
||||
- Add a test-base guard that fails any test modifying files under the repo product tree, and run hook-imported modules under python3 -X importtime, keeping the added import time under 20 ms — stray writes and slow hooks go unnoticed. [retro 2026-11-23]
|
||||
- Test config-file-editing code against hostile pre-existing state: symlinks, read-only files, commented or trailing-comma JSON, duplicate entries, edits between install and uninstall — it fails on real user files otherwise. [retro 2026-11-23]
|
||||
- When a check fails, store and show the lines that identify the failure (FAIL and ERROR blocks, else first and last 40 lines) before the tail — the cause is often far above the end of the output. [retro 2026-11-23]
|
||||
- Scoring a piece of work: it can ALWAYS be done better, so every retro names a concrete way it could have scored better even when nothing went wrong; and scores are kept in the terms the objective lists (value, verified evidence, elapsed time, compute and tool cost, attention, getting better), never in terms of its own. [owner 2026-11-23]
|
||||
- For a brief with a numeric acceptance value or check-skipping limit, compute the number from the formula and put the worked figure in the brief, name the event the count starts from, and require a test where that event happens twice. [retro 2026-11-24]
|
||||
- Never pass --help or any probe argument to a command that changes things until its usage is known from the source or the README; read the usage there first. [retro 2026-11-24]
|
||||
- A project's rules and learning live inside that project, in .sisi/ at the project root, never in a subfolder; whether .sisi/ is git-ignored is the user's choice, and sisi must work either way (owner: 'Personally I'd want this checked in and permanent'). [owner 2026-11-24]
|
||||
- In this repo, finished work that passed its checks goes to main and to both remotes (origin and github) in the same step as the final report; the report names the commit and the GitHub test run [retro 2026-11-24]
|
||||
- In this repo a new piece that arrives while a worker is busy goes at once to another worker in its own checkout and branch; a brief asks for one full test run per commit, the one inside 'sisi release', and only the tests for the change before that [retro 2026-11-25]
|
||||
- In this repo, a change to the product is designed, briefed and asked about from an unknown user with other providers and plans: nothing tied to this owner's workers, harnesses, resellers or plans goes into canon/, and per-user choices (which model to use, what it costs them) are left to each user's sisi, never asked of the owner [retro 2026-11-25]
|
||||
- In this repo, count loaded text as canon plus every header rules.py prints into a session, and check the budget against the diff before each merge, not only at the end [retro 2026-11-25]
|
||||
- In this repo, any trial of sisi against a throwaway store also sets HOME to a temp folder (as the tests do), since a rules write re-points every agent tool's rulebook at the store in use; the brief says so and ends by showing ~/.claude/CLAUDE.md unchanged [retro 2026-11-26]
|
||||
- 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, 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]
|
||||
@@ -7,19 +7,20 @@ the objective, names the gap and its cause, and states the instruction that woul
|
||||
instruction becomes a rule at once, and the next session reads it. Now and then a cheap worker audits and
|
||||
organizes the rules.
|
||||
|
||||
**Delegation.** The lead agent is told to delegate everything, and is stopped when it does the work itself.
|
||||
**Delegation.** The lead agent is told to delegate everything, and is reminded when it does the work itself.
|
||||
It routes by a models table: which workers you have, what each is good at, what it costs. A research worker
|
||||
rebuilds that table when it gets old, and every judged delegation feeds the next research. The lead does not
|
||||
choose the worker: `sisi pick CLASS` spins a wheel over the workers of that class (a capability tier: each model is
|
||||
in exactly one class, so the wheel never mixes tiers; weighted by table order and by the square of the speed ratio),
|
||||
and a delegation to a worker the wheel did not give is refused. One pick, one delegation. A worker that failed for a
|
||||
in exactly one class, so the wheel never mixes tiers; weighted by table order and by the cube of the speed ratio),
|
||||
and a delegation to a worker the wheel did not give gets a note. Recent `bad` verdicts over a worker's last 10
|
||||
good/bad jobs also scale its weight down (never to zero), while workers with no bad runs keep their full weight. One pick, one delegation. A worker that failed for a
|
||||
limit is judged `out` with the provider's message: it is off the wheel for 6 hours, then the wheel tries it again (at most
|
||||
4 times a day), and the pick that hands it out says it is a retry. A host that names its models
|
||||
shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker
|
||||
by its full model id (`claude-sonnet-5-5`); anywhere else the name must match whole.
|
||||
|
||||
**Done.** Nothing starts before `sisi done` has recorded the goal, the checks that decide success and what the
|
||||
person will need next: delegating or editing is refused until then. Every check needs a verdict
|
||||
person will need next: delegating or editing gets a note until then. Every check needs a verdict
|
||||
(`sisi done --pass N` or `--fail N`) before the turn ends; a turn that changed things, or failed a check,
|
||||
is sent to the retro, and any other closes itself, as does work that took under `retro_minutes`, passed every check and delegated nothing. While a delegated job is open and not late, a stop is not held up for checks without a verdict. Each record in `retro.jsonl` carries `session_id`, `retro_seconds` (when demanded),
|
||||
the numbers (minutes, messages, tool calls, delegations, checks), the `term` it fell short on (`value`, `evidence`, `time`, `cost`,
|
||||
@@ -87,11 +88,12 @@ its limits are.
|
||||
| `sisi fault "<what is wrong>"` / `--started\|--blocked\|--fixed N "…"` | Record an open fault in this project, start a fix, name a blocker, or close it; `sisi fault` alone lists them |
|
||||
| `sisi pick routine\|ordinary\|hard [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker; a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) |
|
||||
| `sisi retro` | Print what happened in this piece of work and known problems, to set against the objective |
|
||||
| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" [--scope user]` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault |
|
||||
| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" --level core\|user\|project` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault |
|
||||
| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) |
|
||||
| `sisi retro --later …` | The work is not finished yet |
|
||||
| `sisi learn [--project] "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it |
|
||||
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
|
||||
| `sisi learn --level core\|user\|project "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it |
|
||||
| `sisi rules move "<start of a rule>" core\|user\|project\|canon [--project PATH]` | Move one rule line, verbatim, to another level, and print the command that moves it back: `sisi rules revert` does not undo a move (core is a queue for the product, in force as a user rule until it is added to canon/core.md, then `canon` takes it out of the queue); a level is always named, `project` needs a git repo, and organize also audits placement every `audit_after` (12) retros |
|
||||
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; after `sisi rules move`, or an `organize` that moved lines between levels, it changes nothing and prints the command(s) that move them back, which that command also printed; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
|
||||
| `sisi 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 |
|
||||
@@ -132,6 +134,6 @@ Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `dir
|
||||
`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `worker_minutes` (90: a delegation is late after this many minutes, or its own `--limit`),
|
||||
`shell_workers` (false), `retro_minutes` (5: work that passed every check, delegated nothing and took less than this many minutes from `sisi done` closes without a retro),
|
||||
`disk_free_percent` (20), `disk_drop_percent` (5), `checkouts` (8; setting any of these three to 0 turns that tripwire off). Workers are started with the host's own delegation tool, so by default a shell command
|
||||
that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) is
|
||||
refused. Set `"shell_workers": true` to allow it: it is then free on the meter, and needs a pick like any
|
||||
that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) gets a
|
||||
note. Set `"shell_workers": true` to allow it: it is then free on the meter, and needs a pick like any
|
||||
delegation, and `sisi pick` prints the command line.
|
||||
+3
-3
@@ -112,11 +112,11 @@ tests, evidence and completion.
|
||||
|
||||
When work ends, the lead runs `sisi retro` to see what happened and known problems. Set it against
|
||||
the objective by term: where did work fall short, why, and what instruction prevents it? Record
|
||||
`sisi retro --gap … --cause … --improve … --term T --problem N|"<name>"` (`--problem` is required with `--gap` or refused: cite `N` or name a new one; each citation after opening is a miss; at the 2nd miss a fault opens). The improvement becomes a rule at
|
||||
once: product (every user, in the product), user (how this person works across projects, in their store), or project (`.sisi/rules.md` at root, in git its main checkout's, which may be checked in). Name the root cause, not general
|
||||
`sisi retro --gap … --cause … --improve … --term T --problem N|"<name>" --level L` (`--problem` is required with `--gap` or refused: cite `N` or name a new one; each citation after opening is a miss; at the 2nd miss a fault opens). The improvement becomes a rule at
|
||||
once, at the --level you name: core (every sisi user; queued), user (how this person works across projects), or project (`.sisi/rules.md` at root, in git its main checkout's). Name the root cause, not general
|
||||
advice. Prefer a rule that makes next work do more by itself over a caution; a caution says what stays allowed
|
||||
without asking. Work can always be done better: when nothing fell short, name the one thing that would have scored better (`--no-gap … --term T --better …`).
|
||||
When the person states a lasting preference, record their words at once with `sisi learn`. When session start says
|
||||
Record a stated lasting preference in the person's words at once: `sisi learn --level L`. When session start says
|
||||
rules need organizing, have a cheap worker do it in the background.
|
||||
|
||||
## 9. Fix what you see
|
||||
|
||||
+7
-4
@@ -12,16 +12,19 @@ Before and after the work
|
||||
|
||||
The learning loop
|
||||
sisi retro what happened in this piece of work, to set against the objective
|
||||
sisi retro --gap G --cause C --improve I --term T --problem N|"..." [--scope user]
|
||||
sisi retro --gap G --cause C --improve I --term T --problem N|"..." --level core|user|project
|
||||
record the gap and problem; the improvement is a rule at once
|
||||
sisi retro --no-gap TEXT --term T --better B | --later TEXT
|
||||
nothing fell short; or the work is not finished yet
|
||||
sisi learn [--project] TEXT the person's own words become a rule at once
|
||||
sisi learn --level core|user|project TEXT [--means HOW]
|
||||
the person's own words become a rule at once
|
||||
sisi rules the learned rules in force here
|
||||
sisi rules organize [--record FILE]
|
||||
the brief for a cheap worker to audit and organize them; record its answer
|
||||
sisi rules revert undo the last rule change made with learn, a retro or organize (user or project;
|
||||
not the move of old rules; a second re-applies it); declines if the project file changed
|
||||
sisi rules move "<start>" core|user|project|canon [--project PATH]
|
||||
move one rule to another level (canon: out of the queue once in canon/core.md)
|
||||
sisi rules revert undo the last learn, retro or organize (a second re-applies it); declines if the
|
||||
project file changed since; a move is not undone: both print the command back
|
||||
|
||||
Delegation
|
||||
sisi models the workers you have: what each is good at and what it costs
|
||||
|
||||
+3
-3
@@ -12,7 +12,7 @@ DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call
|
||||
|
||||
METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your workers and `sisi pick routine|ordinary|hard` "
|
||||
"chooses one; if doing this yourself costs less than briefing it, say why with `sisi direct \"<reason>\"` (%d more).")
|
||||
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"<gap>\" --cause \"<cause>\" --improve \"<rule>\" --term <term> --problem N|\"<name>\"` "
|
||||
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"<gap>\" --cause \"<cause>\" --improve \"<rule>\" --term <term> --problem N|\"<name>\" --level core|user|project` "
|
||||
"or `sisi retro --no-gap \"<evidence>\" --term <term> --better \"<what would score better>\"` (or pause: `sisi retro --later \"<what it waits for>\"`).")
|
||||
NODONE = "sisi: no done is recorded yet. Define what the person wants and what comes next now: `sisi done --goal \"<their goal>\" --check \"<a check that can fail>\" [--check ...] --next \"<what comes next and what you do about it>\"`."
|
||||
NOPICK = ("sisi: this delegation went to a worker the wheel did not give you (recorded so `sisi judge` still works). Use `sisi pick routine|ordinary|hard` next time "
|
||||
@@ -21,7 +21,7 @@ NOLOOK = ("sisi: this brief asks for something the person will look at but state
|
||||
"Choose it with the person from previews and put it in the brief, or add a line 'Look: <the existing design it follows>'.")
|
||||
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."
|
||||
FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term> --problem N|\"<name>\"` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term> --problem N|\"<name>\" --level core|user|project` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
OPEN = "sisi: these checks have no verdict yet: %s. Give each one: `sisi done --pass N \"<evidence>\"` or `sisi done --fail N \"<why>\"` (or pause: `sisi retro --later \"<what it waits for>\"`)."
|
||||
LATE = "%s was started %s and has not reported. Check it: if still running, let it finish (this reminder is shown once); if dead or unwanted, cancel it and run `sisi judge WORKER bad \"<why>\"`; if it reported, run `sisi judge WORKER good|bad \"<why>\"`."
|
||||
|
||||
@@ -119,7 +119,7 @@ def tick(p):
|
||||
store.append(env, "export SISI_SESSION_ID=%s" % sid, once=True) # so `sisi retro` knows its session
|
||||
if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")):
|
||||
rules.build_rulebook()
|
||||
(text := "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text)
|
||||
(text := "\n".join(x for x in (rules.project_text(cwd), rules.core_note(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
+28
-30
@@ -88,20 +88,16 @@ def sync_shared(cwd=None):
|
||||
|
||||
|
||||
def age_days():
|
||||
try:
|
||||
return (time.time() - os.path.getmtime(table())) / 86400.0
|
||||
except OSError:
|
||||
return None
|
||||
try: return (time.time() - os.path.getmtime(table())) / 86400.0
|
||||
except OSError: return None
|
||||
|
||||
|
||||
def stale(mark=None):
|
||||
"""One line when the table is missing, old, or missed a worker, else ""."""
|
||||
who = re.sub(r"[^\w./:+-]", "", str(store.read(store.data("models.stale")) if mark is None else mark), flags=re.A)[:80]
|
||||
if mark is not None and who:
|
||||
try:
|
||||
store.write(store.data("models.stale"), who + "\n")
|
||||
except Exception: # best effort: a refusal never depends on it
|
||||
pass
|
||||
try: store.write(store.data("models.stale"), who + "\n")
|
||||
except Exception: pass # best effort: a refusal never depends on it
|
||||
age = age_days()
|
||||
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
|
||||
@@ -250,26 +246,34 @@ def speeds():
|
||||
return {w: v[-10:] for w, v in out.items()}
|
||||
|
||||
|
||||
def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None):
|
||||
def qualities():
|
||||
"""Each worker's quality factor over its last 10 good/bad outcomes: ((good+1)/(n+2))/((n+1)/(n+2)) = (good+1)/(n+1)."""
|
||||
out = {}
|
||||
for o in store.records("outcomes.jsonl"):
|
||||
w = o["model"] if isinstance(o.get("model"), str) and o["model"].strip() else (o["worker"] if isinstance(o.get("worker"), str) else "")
|
||||
if o.get("verdict") in ("good", "bad") and w.strip(): out.setdefault(short(w), []).append(o["verdict"] == "good")
|
||||
return {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in out.items()}
|
||||
|
||||
|
||||
def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None, quality=None):
|
||||
"""One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1)
|
||||
times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs).
|
||||
times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs),
|
||||
times its quality factor over its last 10 good/bad outcomes ((good+1)/(n+1), so no bad runs keeps weight 1).
|
||||
A worker last said out less than OUT seconds ago (`gone`, from `outs`) is not on the wheel."""
|
||||
table_rows, gone, now = rows(text), gone or {}, now or time.time()
|
||||
bad = next((maker(r) for r in table_rows if short(r[0]) == short(review)), None) if review else None
|
||||
left = [r for r in table_rows if r[2].strip().lower() == cls and not out(r, skip, bad, gone, now)]
|
||||
if not left:
|
||||
return None
|
||||
if not left: return None
|
||||
if rand is None:
|
||||
import random
|
||||
rand = random.random
|
||||
med = {short(r[0]): median(speed[short(r[0])]) for r in left if (speed or {}).get(short(r[0]))}
|
||||
fast = min(med.values(), default=1)
|
||||
weights = [w * max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else w for w, r in zip(range(len(left), 0, -1), left)]
|
||||
fast, qual = min(med.values(), default=1), quality or {}
|
||||
weights = [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)
|
||||
for weight, r in zip(weights, left):
|
||||
x -= weight
|
||||
if x < 0:
|
||||
return r
|
||||
if (x := x - weight) < 0: return r
|
||||
return left[-1]
|
||||
|
||||
|
||||
@@ -294,8 +298,8 @@ def pick(args, cwd=None, rand=None):
|
||||
if review is not None and not any(short(r[0]) == short(review) for r in rows(text)):
|
||||
print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review)
|
||||
return 1
|
||||
speed, gone, now = speeds(), away(), time.time()
|
||||
r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now)
|
||||
speed, gone, qual, now = speeds(), away(), qualities(), time.time()
|
||||
r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual)
|
||||
if not r:
|
||||
bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None)
|
||||
again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard."}.get(cls, "")
|
||||
@@ -422,12 +426,9 @@ def judge(args, cwd=None):
|
||||
rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1],
|
||||
"why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)),
|
||||
"project_key": store.project_key(cwd)}
|
||||
if sid:
|
||||
rec["session_id"] = sid
|
||||
if began is not None:
|
||||
rec["started"] = iso(began)
|
||||
if minutes:
|
||||
rec["minutes"] = minutes
|
||||
if sid: rec["session_id"] = sid
|
||||
if began is not None: rec["started"] = iso(began)
|
||||
if minutes: rec["minutes"] = minutes
|
||||
log = store.data("outcomes.jsonl")
|
||||
store.append(log, json.dumps(rec, sort_keys=True))
|
||||
ok = store.commit("delegation judged", log)
|
||||
@@ -444,11 +445,8 @@ def run(args, cwd=None):
|
||||
gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)}
|
||||
if sitting := sorted((t, w) for w, (t, _) in gone.items() if w in listed and now - t < OUT):
|
||||
print("\nOff the wheel now:\n" + "\n".join("%s: %s" % (w, SINCE % (clock(t), clock(t + OUT))) for t, w in sitting))
|
||||
recent = outcomes(15)
|
||||
if recent:
|
||||
print("\nHow recent delegations went:\n" + "\n".join(recent))
|
||||
if stale():
|
||||
print("\n" + stale())
|
||||
if recent := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent))
|
||||
if stale(): print("\n" + stale())
|
||||
return 0
|
||||
if args == ["research"]:
|
||||
return print(research_brief()) or 0
|
||||
|
||||
+60
-20
@@ -1,12 +1,12 @@
|
||||
"""The retro: what happened, set against the objective; the gap, its cause, and the instruction that would have
|
||||
prevented it. That instruction becomes a learned rule at once."""
|
||||
import json, math, os, re, time
|
||||
import hashlib, json, math, os, re, time
|
||||
from . import rules, store
|
||||
|
||||
DONE_USAGE = """usage: sisi done --goal "<the goal in their words, 5+ words>" --check "<a check that can fail, 4+ words>" [--check ...] \\
|
||||
--next "<what they will need next and what you do about it: now, room, follow-up or drop; 4+ words>"
|
||||
sisi done --pass N "<evidence>" | --fail N "<why>" sisi done: show it"""
|
||||
FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--term", "--better", "--problem")
|
||||
FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--level", "--term", "--better", "--problem")
|
||||
TERMS = {"value": "what the person wanted", "evidence": "verified by checks that fit the risk", "time": "elapsed time",
|
||||
"cost": "compute and tool cost", "attention": "the person's attention", "learning": "getting better at the next piece of work"}
|
||||
TERM_HELP = "--term is one of: %s." % ", ".join(TERMS)
|
||||
@@ -14,8 +14,8 @@ clean = store.clean
|
||||
USAGE = """Record one of these:
|
||||
sisi retro --gap "<where the work fell short of the objective, with the evidence>" \\
|
||||
--cause "<the root cause>" \\
|
||||
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." [--scope user]
|
||||
Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: in this project, or with --scope user in all your work.
|
||||
--improve "<the instruction that would have prevented it, worded as a rule>" --term TERM --problem N|"..." --level core|user|project
|
||||
Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: --level project: this git repo only; user: all your work; core: queued for the sisi product (a user rule until it is in the product). --scope works as --level.
|
||||
sisi retro --no-gap "<what shows the work met the objective>" --term TERM \\
|
||||
--better "<one concrete thing that would have scored better on that term, 5+ words>"
|
||||
TERM is where the work fell short, or could most have scored better: %s.
|
||||
@@ -78,23 +78,47 @@ def trend():
|
||||
return ["measured (pieces of work with numbers):"] + out if len(units) >= 2 else []
|
||||
|
||||
|
||||
def _alias_root(amap, n, seen=()):
|
||||
while n in amap and n not in seen:
|
||||
seen, n = (*seen, n), amap[n]
|
||||
return n
|
||||
|
||||
|
||||
def _aliases():
|
||||
why, raw = store.regular(store.data(rules.PROBLEMS), True)
|
||||
try:
|
||||
doc = json.loads(raw.decode("utf-8", "replace")) if not why and raw else {}
|
||||
except ValueError:
|
||||
doc = {}
|
||||
amap = {int(k): v for k, v in doc.items() if str(k).isascii() and str(k).isdigit() and type(v) is int and int(k) >= 1 and v >= 1 and int(k) != v} if isinstance(doc, dict) else {}
|
||||
return {k: r for k in amap if (r := _alias_root(amap, k)) != k}
|
||||
|
||||
|
||||
def _problems(recs=None):
|
||||
"""Known problems derived from retro.jsonl in order of first appearance (1-based number)."""
|
||||
"""Known problems derived from retro.jsonl in order of first appearance (1-based number), folding merged aliases."""
|
||||
by_key, out = {}, []
|
||||
for idx, r in enumerate(store.records("retro.jsonl", 64000000) if recs is None else recs):
|
||||
if not (isinstance(r.get("problem"), str) and (name := clean(r["problem"]))):
|
||||
continue
|
||||
date, key = str(r.get("ts") or "")[:10] or "?", name.lower()
|
||||
p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": []})
|
||||
p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": [], "merged": []})
|
||||
p not in out and out.append(p)
|
||||
p["attempts"].append({"date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")})
|
||||
p["attempts"].append({"idx": idx, "date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")})
|
||||
p["last"], p["last_idx"] = date, idx
|
||||
for m, n in (_aliases() if recs is None else {}).items():
|
||||
if m <= len(out) and n <= len(out):
|
||||
src, dst = out[m - 1], out[n - 1]
|
||||
src["into"] = n
|
||||
dst["merged"].append((m, src["name"]))
|
||||
dst["attempts"] = sorted(dst["attempts"] + src["attempts"], key=lambda a: a["idx"])
|
||||
dst["last"], dst["last_idx"] = dst["attempts"][-1]["date"], dst["attempts"][-1]["idx"]
|
||||
return out
|
||||
|
||||
|
||||
def _problem_lines(probs):
|
||||
recent = sorted(probs, key=lambda p: (-p["last_idx"], -p["num"]))[:15]
|
||||
return [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n := len(p["attempts"]), "" if n == 1 else "s", p["last"]) for p in recent]
|
||||
recent = sorted((p for p in probs if not p.get("into")), key=lambda p: (-p["last_idx"], -p["num"]))[:15]
|
||||
return [l for p in recent for n in [len(p["attempts"])]
|
||||
for l in [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n, "" if n == 1 else "s", p["last"]), *[" merged: %s (#%d)" % (name, m) for m, name in p["merged"]]]]
|
||||
|
||||
|
||||
def _resolve_problem(problem, probs):
|
||||
@@ -104,10 +128,11 @@ def _resolve_problem(problem, probs):
|
||||
return None, "sisi retro: name the problem in plain words (no secrets, tokens, or long hex/digit strings)."
|
||||
if len(norm) > 400:
|
||||
return None, "sisi retro: problem name is at most 400 characters."
|
||||
canon = lambda p: probs[p["into"] - 1] if p and p.get("into") else p
|
||||
if re.fullmatch(r"[+-]?\d+", norm):
|
||||
n = int(norm)
|
||||
return (probs[n - 1], "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm)
|
||||
return next((p for p in probs if p["name"].lower() == norm.lower()), {"num": len(probs) + 1, "name": norm, "attempts": []}), ""
|
||||
return (canon(probs[n - 1]), "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm)
|
||||
return canon(next((p for p in probs if p["name"].lower() == norm.lower()), None)) or {"num": len(probs) + 1, "name": norm, "attempts": []}, ""
|
||||
|
||||
|
||||
def report(sid, cwd):
|
||||
@@ -127,12 +152,19 @@ def report(sid, cwd):
|
||||
print("\n" + "\n".join(trend()))
|
||||
|
||||
|
||||
def rulebook(cwd):
|
||||
"""The rulebook the work ran under: hash, size and rule count of the loaded core file and the project's rules."""
|
||||
p = rules.path(rules.PROJECT, cwd)
|
||||
t = store.read(store.data("generated", "core.md")) + ((p and store.regular(p, True)[1] or b"").decode("utf-8", "replace"))
|
||||
return {"hash": hashlib.sha256(t.encode()).hexdigest()[:12], "chars": len(t), "lines": len(rules._parse(t))}
|
||||
|
||||
|
||||
def record(s, cwd, opt, sid=None):
|
||||
"""Append one record for the piece of work in this session state, and begin the next one."""
|
||||
d, now, dem = s.get("done") or {}, time.time(), s.get("retro_demanded")
|
||||
entry = dict(opt, ts=time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(now)),
|
||||
project=os.path.basename(store.project_root(cwd)), unit=counts(s, cwd),
|
||||
goal=d.get("goal", ""), workers=s.get("workers_since", []))
|
||||
goal=d.get("goal", ""), workers=s.get("workers_since", []), rules=rulebook(cwd))
|
||||
if d:
|
||||
entry["done"] = d
|
||||
if sid:
|
||||
@@ -142,7 +174,7 @@ def record(s, cwd, opt, sid=None):
|
||||
log = store.data("retro.jsonl")
|
||||
store.append(log, json.dumps(entry, sort_keys=True))
|
||||
if not store.commit("retro recorded", log):
|
||||
print("sisi: retro saved, but store git commit failed.")
|
||||
print("sisi: retro saved, but store git commit failed (%s)." % store.GIT_ERROR)
|
||||
s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now
|
||||
for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused",
|
||||
"fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began"):
|
||||
@@ -203,9 +235,12 @@ def run(args, cwd=None):
|
||||
if not args:
|
||||
return report(sid, cwd) or 0
|
||||
opt = _options(args)
|
||||
scope, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "term", "better", "problem")]
|
||||
scope = scope or rules.PROJECT
|
||||
kind = (None if not opt or scope not in (rules.USER, rules.PROJECT)
|
||||
scope, level, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "level", "term", "better", "problem")]
|
||||
if level and scope and level != scope:
|
||||
print("sisi retro: --level %s and --scope %s disagree; give one of them." % (level, scope))
|
||||
return 1
|
||||
scope = level or scope
|
||||
kind = (None if not opt or (scope is not None and scope not in (rules.CORE, rules.USER, rules.PROJECT))
|
||||
else "later" if set(opt) == {"later"} and _words(opt, "later", 3)
|
||||
else "no-gap" if set(opt) == {"no-gap"} and _words(opt, "no-gap", 5)
|
||||
else "gap" if set(opt) == {"gap", "cause", "improve"} and all(_words(opt, k, 4) for k in opt) else None)
|
||||
@@ -214,6 +249,9 @@ def run(args, cwd=None):
|
||||
print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most "
|
||||
"400 characters).\n" + USAGE)
|
||||
return 1
|
||||
if kind == "gap" and (why := rules.refuse_level(scope, cwd, "sisi retro --gap ...")):
|
||||
print("sisi retro: " + why)
|
||||
return 1
|
||||
if kind != "gap" and problem is not None:
|
||||
print("sisi retro: --problem goes only with --gap.")
|
||||
return 1
|
||||
@@ -248,7 +286,7 @@ def run(args, cwd=None):
|
||||
elif kind != "later":
|
||||
record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt)
|
||||
if kind == "gap":
|
||||
found = next((p for p in _problems() if p["name"].lower() == opt["problem"].lower()), None)
|
||||
found = next((p for p in _problems() if not p.get("into") and p["name"].lower() == opt["problem"].lower()), None)
|
||||
prior = found["attempts"][:-1] if found else prob["attempts"]
|
||||
prob, misses = found or prob, len(prior)
|
||||
if misses:
|
||||
@@ -262,9 +300,10 @@ def run(args, cwd=None):
|
||||
else:
|
||||
print("opened problem %d '%s'." % (prob["num"], prob["name"]))
|
||||
try:
|
||||
added, warn = rules.add(opt["improve"], scope, "retro", cwd)
|
||||
print(warn or "recorded. In force from the next session%s: %s" % (
|
||||
" in every project" if scope == rules.USER else " in this project", added))
|
||||
added, warn = rules.add(opt["improve"], scope, "retro", cwd, problem=prob["num"])
|
||||
print(warn or ("recorded. In force from the next session%s: %s" % (
|
||||
" in every project" if scope == rules.USER else " in this project", added) if scope != rules.CORE else "recorded, queued for the product: %s" % added))
|
||||
print(rules.filed(scope, opt["improve"], cwd))
|
||||
except OSError as e:
|
||||
print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e))
|
||||
if misses >= 2:
|
||||
@@ -279,4 +318,5 @@ def run(args, cwd=None):
|
||||
print(rules.due(cwd))
|
||||
else:
|
||||
print("recorded." if kind == "no-gap" else "noted: the retro waits until this work ends.")
|
||||
scope and print("(--level goes only with --gap; it was ignored.)")
|
||||
return 0
|
||||
+299
-107
@@ -3,10 +3,12 @@
|
||||
A rule is one line. It is in force as soon as it is added: rules for all of the person's work become the last
|
||||
section of the rulebook every session loads, and a project's rules live in `.sisi/rules.md` at its root.
|
||||
Now and then a cheap worker audits and organizes them. Store changes are committed and can be undone."""
|
||||
import contextlib, hashlib, json, os, re, time
|
||||
import contextlib, hashlib, json, os, re, shlex, time
|
||||
from . import store
|
||||
|
||||
USER, PROJECT = "user", "project"
|
||||
USER, PROJECT, CORE = "user", "project", "core"
|
||||
LEVELS = """The three levels: core = the sisi product itself, for every sisi user anywhere, nothing personal (queued for its maintainers, loaded as a user rule until then);
|
||||
user = how this person works across all projects, their machine, accounts, providers; project = this one git repo only (its .sisi/rules.md)."""
|
||||
OWNER = re.compile(r"\[owner\b[^\]]*\]")
|
||||
_owner, _retro = lambda l: bool(OWNER.search(l)), lambda ls: [l for l in ls if not _owner(l)]
|
||||
_snap = lambda u, p: hashlib.sha1(("\n".join(u) + "\0" + "\n".join(p)).encode()).hexdigest()[:16]
|
||||
@@ -14,9 +16,11 @@ _TAGS = " [owner] lines are the person's words; [agent ...] lines are an agent's
|
||||
HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them." + _TAGS + "\n"
|
||||
HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them)." + _TAGS
|
||||
SMELL = re.compile(r"(?i)\bone (?:build|test|run|worker|job)\b.{0,60}\bat a time|\bflock\b|\b(?:shared?|one)\b.{0,30}\bbuild (?:folder|dir)")
|
||||
DROPS = "rules/drops.jsonl"
|
||||
DROPS, PROBLEMS = "rules/drops.jsonl", "rules/problems.json"
|
||||
_DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$")
|
||||
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip()).lower().split())
|
||||
_NOTE = re.compile(r"(?:\s+\(p\d+: (?:came back \d+x|not seen) since(?:; p\d+: (?:came back \d+x|not seen) since)*\))+$")
|
||||
_RETRO_TAG, _DATE = re.compile(r"(?:\s*\[retro\b[^\]]*\])+$"), re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", _NOTE.sub("", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip())).lower().split())
|
||||
|
||||
ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further.
|
||||
|
||||
@@ -30,15 +34,18 @@ Rewrite both lists so they serve that objective best:
|
||||
- Merge rules that say the same thing. Drop fragments, rules that are stale or contradicted by a later one,
|
||||
and rules too specific to come up again.
|
||||
- Word each rule as a direct instruction with its reason, on one line, standing on its own.
|
||||
- A rule seen in more than one project, or about how the person wants to be worked with, belongs in the
|
||||
first list. A rule about this project's own code belongs in the second.
|
||||
- Audit where each rule is filed. %(levels)s Move a rule that sits at the wrong level, in either direction,
|
||||
with its words byte-identical: a user line about one project goes to `## project` (this one; if it names another
|
||||
project leave it and flag it); a project line that applies to all the person's work goes to `## user`; a line
|
||||
that applies to every sisi user goes under `## core` (a queue for the product's maintainers). [owner ...] lines
|
||||
may move between levels too, never reworded.
|
||||
- Lines marked [owner ...] are the person's own words: copy every one of them verbatim, unchanged by even
|
||||
one character (you may reorder them). Only the other lines ([retro ...], [agent ...]) may be merged, reworded or dropped.
|
||||
- Flag, but do not change, any [owner ...] line whose text does not read as the person's own words (a paraphrase, an
|
||||
agent's conclusion, third person), and any rule that limits builds, tests or workers to one at a time or tells
|
||||
checkouts to share one build folder. List each under a final `## flags` section with its proposed corrected or
|
||||
retagged form, for the person to accept.
|
||||
- Keep the [source date] mark at the end of every line.
|
||||
- Keep the [source date] mark (and any pN tag, including on merged rules) at the end of every line, without any trailing (pN: ...) note. A rule whose problem came back after it was written should be reworked or turned into a check.
|
||||
- A `better` that recurs across retros has earned a rule: add it, worded as an instruction, marked [retro <date>].
|
||||
- Non-owner ([retro ...]) lines in each list: at most %(lines)d lines and %(chars)d characters. Fewer is better.
|
||||
- When you drop or merge away a non-owner rule, you can list `- <old rule copied as it is> | #<N or -> | <reason>` under `## drops` (#- if no problem matches; optional: a missing line is recorded as 'none given').
|
||||
@@ -48,8 +55,12 @@ Answer with exactly this shape and nothing else:
|
||||
- ...
|
||||
## project
|
||||
- ...
|
||||
## core
|
||||
- ... (only lines moved to the product queue)
|
||||
## drops
|
||||
- <old rule> | #<N or -> | <reason> (optional; only if any non-owner rules were dropped)
|
||||
## same problems
|
||||
N = M (optional; merge duplicate problem M into older N)
|
||||
## flags
|
||||
- ... (only if there are any)
|
||||
|
||||
@@ -70,7 +81,31 @@ Answer with exactly this shape and nothing else:
|
||||
def path(scope, cwd=None):
|
||||
"""Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept."""
|
||||
top, inside = store.root(cwd) if scope == PROJECT else ("", False)
|
||||
return store.data("rules", "user.md") if scope == USER else "" if inside else os.path.join(top, ".sisi", "rules.md")
|
||||
return store.data("rules", scope + ".md") if scope in (USER, CORE) else "" if inside else os.path.join(top, ".sisi", "rules.md")
|
||||
|
||||
|
||||
def has_project(cwd=None):
|
||||
"""True inside a git repository whose root is not the home folder: the only place a project list may be written."""
|
||||
top, inside = store.root(cwd)
|
||||
return not inside and os.path.lexists(os.path.join(top, ".git")) and os.path.realpath(top) != os.path.realpath(store.HOME)
|
||||
|
||||
|
||||
def refuse_level(level, cwd, cmd):
|
||||
"""Why a rule may not be filed at this level (with the command to rerun), or ""."""
|
||||
if level not in (CORE, USER, PROJECT):
|
||||
return "name the level of this rule. %s\nRerun with --level core|user|project, e.g. `%s --level user ...`." % (LEVELS, cmd)
|
||||
return "no project here (not inside a git repository, or it is the home folder), use user: `%s --level user ...`." % cmd if level == PROJECT and not has_project(cwd) else ""
|
||||
|
||||
|
||||
def filed(level, text, cwd):
|
||||
return 'filed as %s rule in %s. Wrong level? sisi rules move "%s" core|user|project' % (level, path(level, cwd), " ".join(text.split()[:5]))
|
||||
|
||||
|
||||
def core_note(cwd):
|
||||
"""At session start in the sisi repo itself: how many rules wait in the product queue."""
|
||||
top = store.project_root(cwd)
|
||||
n = len(lines(path(CORE))) if all(os.path.isfile(os.path.join(top, *f)) for f in (("canon", "core.md"), ("sisi", "rules.py"))) else 0
|
||||
return "sisi: %d rule%s proposed for the product: add each to canon/core.md, then `sisi rules move \"<start>\" canon`; or move it elsewhere." % (n, "" if n == 1 else "s") if n else ""
|
||||
|
||||
|
||||
def _legacy(cwd=None):
|
||||
@@ -93,7 +128,7 @@ def _text(p):
|
||||
try:
|
||||
return None if raw is None else raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise OSError(".sisi/rules.md is not valid UTF-8")
|
||||
raise OSError("%s is not valid UTF-8" % p)
|
||||
|
||||
|
||||
def _append(text, new):
|
||||
@@ -103,7 +138,7 @@ def _append(text, new):
|
||||
def _check_writable(p):
|
||||
if not p:
|
||||
raise OSError("this folder is inside a git directory or a bare repository")
|
||||
for t, label, folder in ((os.path.dirname(p), ".sisi", True), (p, ".sisi/rules.md", False)):
|
||||
for t, label, folder in ((os.path.dirname(p), os.path.basename(os.path.dirname(p)), True), (p, os.path.join(*p.split(os.sep)[-2:]), False)):
|
||||
why = (("a symlink" if os.path.islink(t) else "not a directory" if os.path.lexists(t) and not os.path.isdir(t) else "") if folder
|
||||
else store.regular(t)[0]) or ("read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
|
||||
if why:
|
||||
@@ -142,9 +177,8 @@ def _move(dest, old):
|
||||
_check_writable(dest)
|
||||
before = _text(dest)
|
||||
extra = [l for l in dict.fromkeys(_parse(raw)) if l not in set(_parse(before or ""))]
|
||||
rel = os.path.relpath(old, store.DATA)
|
||||
uncommitted = not os.path.isdir(os.path.join(store.DATA, ".git")) or store.git(["status", "--porcelain", "--", rel], store.DATA)[1].strip()
|
||||
if uncommitted and not store.commit("project rules before move to .sisi/rules.md", old):
|
||||
store.history()
|
||||
if store.git(["status", "--porcelain", "--", old], store.DATA)[1].strip() and not store.commit("project rules before move to .sisi/rules.md", old):
|
||||
raise OSError("could not commit store")
|
||||
extra and store.write(dest, _append(before, extra))
|
||||
(extra or _parse(raw)) and note(dest)
|
||||
@@ -163,7 +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
|
||||
else "sisi: %s is a link, and sisi does not use a linked .sisi; its rules are not read." % d if os.path.islink(d := os.path.dirname(dest))
|
||||
else "sisi: %s is %s; its rules are not read." % (dest, why) if not os.path.isfile(old) and (why := "not a directory" if os.path.lexists(d) and not os.path.isdir(d) else store.regular(dest)[0]) else "")
|
||||
if not msg and os.path.isfile(old):
|
||||
if not msg and os.path.isfile(old) and os.path.realpath(store.project_root(cwd)) != os.path.realpath(store.HOME):
|
||||
with store.lock(dest, wait=wait) as ok:
|
||||
msg = _move(dest, old) if ok else ""
|
||||
return scope_lines(PROJECT, cwd, migrate=False), msg
|
||||
@@ -179,22 +213,54 @@ def scope_lines(scope, cwd=None, migrate=True):
|
||||
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
|
||||
|
||||
|
||||
def _commit(msg, *paths, snap=None):
|
||||
if snap:
|
||||
p = store.data("rules", "last-project.json")
|
||||
store.write(p, json.dumps(dict(zip(("path", "before", "after"), snap))))
|
||||
paths = (p,) + paths
|
||||
if not store.commit(msg, *paths):
|
||||
raise OSError("store git commit failed")
|
||||
_in_store = lambda p: p.startswith(os.path.join(store.DATA, ""))
|
||||
|
||||
|
||||
def add(text, scope, source, cwd=None, log=None, means=""):
|
||||
def _apply(msg, change, record):
|
||||
"""Write {path: (before, after)}, files outside the store first, then one store commit with `record`; a failed write or commit restores every file before reporting."""
|
||||
rp = store.data("rules", "last-project.json")
|
||||
backs = list(change.items())
|
||||
def _undo():
|
||||
for p, (b, a) in backs:
|
||||
with contextlib.suppress(OSError):
|
||||
store.write(p, b) if b is not None else os.path.lexists(p) and os.remove(p)
|
||||
try:
|
||||
backs.append((rp, (_text(rp), None)))
|
||||
[store.write(p, a) for p, (b, a) in change.items() if not _in_store(p) and a is not None and a != b]
|
||||
ok = store.commit(msg, put={**{p: a for p, (b, a) in change.items() if _in_store(p)}, rp: json.dumps(record)})
|
||||
except OSError:
|
||||
_undo()
|
||||
raise
|
||||
if not ok:
|
||||
_undo()
|
||||
return "store git commit failed (%s)" % store.GIT_ERROR
|
||||
return ""
|
||||
|
||||
|
||||
def _back(line, now, old, lv):
|
||||
"""The command that moves `line` from file `now` back to file `old`, at level `lv`."""
|
||||
here, there = [] if _in_store(now) else [os.path.dirname(os.path.dirname(now))], [os.path.dirname(os.path.dirname(old))] if lv == PROJECT else []
|
||||
return ("cd %s && " % shlex.quote(here[0]) if here and there else "") + "sisi rules move %s %s" % (shlex.quote(line[2:]), lv) + "".join(" --project " + shlex.quote(r) for r in there or here)
|
||||
|
||||
|
||||
def _locks(*keys):
|
||||
st = contextlib.ExitStack()
|
||||
[st.enter_context(store.lock(k)) for k in sorted(set(keys))]
|
||||
return st
|
||||
|
||||
|
||||
def add(text, scope, source, cwd=None, log=None, means="", raw=None, problem=None):
|
||||
"""Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written."""
|
||||
line, *more = ["- %s [%s %s]" % (" ".join(str(t).split()), src, time.strftime("%Y-%m-%d")) for t, src in ((text, source), (means, "agent reading")) if t] # one commit holds both
|
||||
if scope == PROJECT and not has_project(cwd):
|
||||
raise OSError("no project here, use user")
|
||||
d = time.strftime("%Y-%m-%d")
|
||||
line, *more = ["- %s [%s %s%s]" % (" ".join(str(t).split()), src, d, " p%d" % p if p else "") for t, src, p in ((text, source, problem), (means, "agent reading", None)) if t] # one commit holds both
|
||||
line, more = (raw, []) if raw else (line, more)
|
||||
dest = path(scope, cwd)
|
||||
scope == PROJECT and not dest and _check_writable(dest)
|
||||
store.history()
|
||||
with store.lock(dest if scope == PROJECT else "user"):
|
||||
if scope == USER:
|
||||
if scope != PROJECT:
|
||||
[store.append(dest, l) for l in [line, *more]]
|
||||
else:
|
||||
_check_writable(dest)
|
||||
@@ -206,12 +272,13 @@ def add(text, scope, source, cwd=None, log=None, means=""):
|
||||
note(dest)
|
||||
try:
|
||||
log and store.append(*log)
|
||||
extra = ([dest] if scope == USER else []) + ([log[0]] if log else [])
|
||||
_commit("rule added (%s, %s)" % (scope, source), *extra, snap=(dest, before, after) if scope == PROJECT else None)
|
||||
warn = ""
|
||||
extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else [])
|
||||
rec = {store.data("rules", "last-project.json"): json.dumps({"path": dest, "before": before, "after": after})} if scope == PROJECT else {}
|
||||
warn = "" if store.commit("rule added (%s, %s)" % (scope, source), *extra, put=rec) else "store git commit failed (%s)" % store.GIT_ERROR
|
||||
except OSError as e:
|
||||
warn = "the rule is in %s; it could not be recorded for undo: %s" % (dest, e)
|
||||
scope == USER and build_rulebook()
|
||||
warn = str(e)
|
||||
warn = warn and "the rule is in %s; it could not be recorded for undo: %s" % (dest, warn)
|
||||
scope != PROJECT and build_rulebook()
|
||||
return line, warn
|
||||
|
||||
|
||||
@@ -234,7 +301,7 @@ def delivered(p):
|
||||
def build_rulebook():
|
||||
"""Write the always-loaded instructions: the product's rulebook, then the person's learned rules."""
|
||||
text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n"
|
||||
mine = delivered(path(USER))
|
||||
mine = _fit(lines(path(USER)) + lines(path(CORE))) # a rule queued for the product is in force here until it is in canon
|
||||
if mine:
|
||||
text += "\n" + HEAD_USER + "\n" + "\n".join(mine) + "\n"
|
||||
out = store.data("generated", "core.md")
|
||||
@@ -273,12 +340,13 @@ def due(cwd, claim=False):
|
||||
"""One line when the learned rules need organizing, else ""."""
|
||||
cfg, seen, cl, now, need = store.config(), _organized(), _organized(("locks", "organize.json")), time.time(), []
|
||||
active = lambda c, k: type(c.get("claim:" + k)) in (int, float) and 0 <= now - c["claim:" + k] < 1800
|
||||
for scope in (USER, PROJECT):
|
||||
for scope in (USER, PROJECT)[:2 if has_project(cwd) else 1]:
|
||||
ls, k = _retro(scope_lines(scope, cwd, migrate=False)), _mark_key(scope, cwd)
|
||||
prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0))
|
||||
over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]
|
||||
if not active(cl, k) and (over or len(ls) - prev >= cfg["organize_after"]):
|
||||
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev))))
|
||||
audit = scope == USER and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"]
|
||||
if not active(cl, k) and (over or audit or len(ls) - prev >= cfg["organize_after"]):
|
||||
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev) if len(ls) - prev >= cfg["organize_after"] else "time to audit their levels")))
|
||||
if not need:
|
||||
return ""
|
||||
if claim:
|
||||
@@ -295,23 +363,28 @@ def due(cwd, claim=False):
|
||||
|
||||
|
||||
def drops_for(num=None):
|
||||
return [d for d in store.records(DROPS) if num is None or d.get("problem") == num]
|
||||
from . import retro
|
||||
amap = retro._aliases() if num is not None else {}
|
||||
return [d for d in store.records(DROPS) if num is None or amap.get(d.get("problem"), d.get("problem")) == num]
|
||||
|
||||
|
||||
def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
|
||||
if not probs:
|
||||
canon = [p for p in probs if not p.get("into")]
|
||||
if not canon:
|
||||
return ""
|
||||
cut = lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
|
||||
amap, cut = {p["num"]: p["into"] for p in probs if p.get("into")}, lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
|
||||
all_p = "\n\n=== Every known problem (list duplicates under ## same problems as N = M, older first) ===\n" + "\n".join(
|
||||
"#%d: %s | cause: %s" % (p["num"], cut(p["name"]), cut(next((a["cause"] for a in p["attempts"] if a["cause"]), "") or "(none)")) for p in canon)
|
||||
head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n"
|
||||
"How to use this evidence:\n"
|
||||
"- Problem has 0 misses: it has not come back yet, keep it. Has misses: the sentence did not hold, keep the latest attempt and note it in `## flags` (do not just reword).\n"
|
||||
"- When merging, keep the cause; never drop a rule as redundant while its problem keeps coming back. [owner ...] rules stay verbatim.\n")
|
||||
out, used = [head], len(head)
|
||||
for p in sorted(probs, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]:
|
||||
for p in sorted(canon, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]:
|
||||
n = len(p["attempts"])
|
||||
ls = (["#%d: %s (opened %s, %d attempt%s, %d miss%s, last %s)" % (p["num"], cut(p["name"]), p["opened"], n, "" if n == 1 else "s", n - 1, "" if n == 2 else "es", p["last"])]
|
||||
+ [" attempt [%s] cause: %s | rule: %s" % (a["date"], cut(a["cause"]), cut(a["improve"])) for a in p["attempts"]]
|
||||
+ [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if d.get("problem") == p["num"]])
|
||||
+ [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if amap.get(d.get("problem"), d.get("problem")) == p["num"]])
|
||||
blk = "\n".join(ls) + "\n"
|
||||
if used + len(blk) > cap_c:
|
||||
for l in (ls if len(out) == 1 else ()):
|
||||
@@ -319,39 +392,75 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
|
||||
out.append(l + "\n"); used += len(l) + 1
|
||||
break
|
||||
out.append(blk); used += len(blk)
|
||||
return "".join(out).rstrip("\n")
|
||||
return all_p + "".join(out).rstrip("\n")
|
||||
|
||||
|
||||
def _rule_probs(line):
|
||||
"""Return [(problem_num, rule_date), ...] from trailing [retro ...] tags, or []."""
|
||||
m = _RETRO_TAG.search(line)
|
||||
dates = _DATE.findall(m.group(0)) if m else []
|
||||
if not dates:
|
||||
return []
|
||||
cur, out = max(dates), {}
|
||||
for d, p in re.findall(r"(\d{4}-\d{2}-\d{2})|\bp(\d{1,6})\b", m.group(0)):
|
||||
if d:
|
||||
cur = d
|
||||
elif (n := int(p)) >= 1:
|
||||
out[n] = max(out.get(n, ""), cur)
|
||||
return list(out.items())
|
||||
|
||||
|
||||
def _annotate(ls, probs):
|
||||
"""Append per-rule problem recurrence notes for display in `sisi rules` and `organize_brief`."""
|
||||
out = []
|
||||
for l in ls:
|
||||
if not (ps := _rule_probs(l)):
|
||||
out.append(l)
|
||||
continue
|
||||
notes = []
|
||||
for n, d in ps:
|
||||
p = probs[n - 1] if 1 <= n <= len(probs) else None
|
||||
p = probs[p["into"] - 1] if p and p.get("into") else p
|
||||
c = sum(bool(_DATE.fullmatch(a["date"])) and a["date"] > d for a in (p["attempts"] if p else ()))
|
||||
notes.append("p%d: came back %dx since" % (n, c) if c else "p%d: not seen since" % n)
|
||||
out.append("%s (%s)" % (l, "; ".join(notes)))
|
||||
return out
|
||||
|
||||
|
||||
def organize_brief(cwd):
|
||||
from . import retro
|
||||
cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd)
|
||||
cfg, u, p, probs = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) if has_project(cwd) else [], retro._problems()
|
||||
with contextlib.suppress(OSError), store.lock("organize"):
|
||||
cl = _organized(("locks", "organize.json"))
|
||||
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
|
||||
store.write(store.data("locks", "organize.json"), json.dumps(cl))
|
||||
return ORGANIZE % {
|
||||
"name": os.path.basename(store.project_root(cwd)), "objective": objective(),
|
||||
"name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "objective": objective(),
|
||||
"lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
|
||||
"flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)",
|
||||
"user": "\n".join(u) or "(none)", "project": "\n".join(p) or "(none)",
|
||||
"user": "\n".join(_annotate(u, probs)) or "(none)",
|
||||
"project": "\n".join(_annotate(p, probs)) or "(none)" if has_project(cwd) else "(not in a git project: leave `## project` empty)",
|
||||
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)",
|
||||
"evidence": _evidence(retro._problems(), drops_for())}
|
||||
"evidence": _evidence(probs, drops_for())}
|
||||
|
||||
|
||||
def organize_record(answer_file, cwd):
|
||||
"""Replace both lists with the worker's answer. Returns why not, or None when it is done."""
|
||||
cfg = store.config()
|
||||
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project)[ \t]*|## [^\n]*)$", store.read(answer_file))
|
||||
got, flags, drops = {}, "", {}
|
||||
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops|same problems)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file))
|
||||
got, flags, drops, same_lines = {}, "", {}, []
|
||||
for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)):
|
||||
if re.fullmatch(r"## (user|project)[ \t]*", h):
|
||||
got[h[3:].strip()] = [l.rstrip() for l in chunk.splitlines() if l.startswith("- ")]
|
||||
if re.fullmatch(r"## (user|project|core)[ \t]*", h):
|
||||
got[h[3:].strip()] = [l if _owner(l) else _NOTE.sub("", l) for l in (x.rstrip() for x in chunk.splitlines() if x.startswith("- "))]
|
||||
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
|
||||
flags += chunk
|
||||
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
|
||||
for l in chunk.splitlines():
|
||||
if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]):
|
||||
drops.setdefault(rk, (m[2], why))
|
||||
elif re.match(r"(?i)#{2,3}[ \t]*same problems\b", h):
|
||||
same_lines += [x.strip() for x in chunk.splitlines() if x.strip() and x.strip().lower() not in ("none", "(none)") and not x.strip().startswith("```")]
|
||||
core = got.pop(CORE, [])
|
||||
if set(got) != {USER, PROJECT}:
|
||||
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
|
||||
for scope, ls in got.items():
|
||||
@@ -359,56 +468,69 @@ def organize_record(answer_file, cwd):
|
||||
if len(r) > cfg["rules_lines"] or sum(map(len, r)) > cfg["rules_chars"]:
|
||||
return "the %s list is over the budget of %d lines and %d characters (it has %d and %d)" % (
|
||||
scope, cfg["rules_lines"], cfg["rules_chars"], len(r), sum(map(len, r)))
|
||||
up, pp = path(USER), path(PROJECT, cwd)
|
||||
if not pp or os.path.islink(os.path.dirname(pp)):
|
||||
proj = has_project(cwd) # outside a git project only the user list is organized
|
||||
up, pp, cp = path(USER), path(PROJECT, cwd) if proj else None, path(CORE)
|
||||
if not proj and got[PROJECT]:
|
||||
return "no project here, so `## project` must be empty: put those lines under `## user`, or record it inside their git project"
|
||||
if proj and (not pp or os.path.islink(os.path.dirname(pp))):
|
||||
return _migrate(cwd)[1].removeprefix("sisi: ")
|
||||
with store.lock(pp):
|
||||
msg = _move(pp, _legacy(cwd))
|
||||
with _locks(USER, *filter(None, [pp])):
|
||||
msg = proj and _move(pp, _legacy(cwd))
|
||||
if msg:
|
||||
return msg.removeprefix("sisi: ")
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False) if proj else []}
|
||||
if (want := _organized(("locks", "organize.json")).get("snap:" + _mark_key(PROJECT, cwd))) and _snap(had[USER], had[PROJECT]) != want:
|
||||
return "the rules changed since `sisi rules organize` ran; run `sisi rules organize` again"
|
||||
for scope in (USER, PROJECT):
|
||||
if miss := [l for l in had[scope] if _owner(l) and got[scope].count(l) < had[scope].count(l)]:
|
||||
return "owner rule missing or changed (%s): %s" % (scope, miss[0])
|
||||
kept = list(got[USER]) + list(got[PROJECT])
|
||||
every = got[USER] + got[PROJECT] + core # an owner line may change level, never a word
|
||||
if miss := [l for l in had[USER] + had[PROJECT] if _owner(l) and every.count(l) < (had[USER] + had[PROJECT]).count(l)]:
|
||||
return "owner rule missing or changed: %s" % miss[0]
|
||||
kept = every[:]
|
||||
dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)]
|
||||
from . import retro
|
||||
nprobs = len(retro._problems()) if dropped else 0
|
||||
nprobs = len(retro._problems()) if dropped or same_lines else 0
|
||||
pnum = lambda s: n if s.isascii() and s.isdigit() and len(s) <= 6 and 1 <= (n := int(s)) <= nprobs else None
|
||||
recs = [(store.clean(r)[:300], pnum(h[0]), h[1]) if (h := drops.get(_DKEY(r))) else (store.clean(r)[:300], None, "none given") for r in dropped]
|
||||
no_why = sum(_DKEY(r) not in drops for r in dropped)
|
||||
if not any(got.values()) and any(had.values()):
|
||||
old_amap = retro._aliases() if same_lines else {}
|
||||
amap, bad_same = dict(old_amap), []
|
||||
for raw_l in same_lines:
|
||||
m = re.fullmatch(r"(?:[-*]\s+)?#?(\d{1,6})\s*=\s*#?(\d{1,6})(?:\s+(?:#|\(|//|-).*|\s*\|.*)?", raw_l)
|
||||
n, k = (int(m[1]), int(m[2])) if m else (0, 0)
|
||||
rn = retro._alias_root(amap, n) if m else 0
|
||||
why_bad = ("expected N = M" if not m else "unknown problem number" if not (1 <= n <= nprobs and 1 <= k <= nprobs)
|
||||
else "cycle" if rn == k else "already merged" if k in amap and retro._alias_root(amap, k) != rn else "")
|
||||
bad_same.append((raw_l, why_bad)) if why_bad else amap.__setitem__(k, rn)
|
||||
if not any(got.values()) and not core and any(had.values()):
|
||||
return "the answer holds no rules at all"
|
||||
try:
|
||||
before = _text(pp)
|
||||
after = "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None
|
||||
after is not None and _check_writable(pp)
|
||||
wrote = after is not None and after != before
|
||||
wrote and store.write(pp, after)
|
||||
except OSError as e:
|
||||
return "could not write %s (%s)" % (pp, e)
|
||||
after is not None and note(pp)
|
||||
wrote_u = False
|
||||
try:
|
||||
store.write(up, "".join(l + "\n" for l in got[USER]))
|
||||
wrote_u = True
|
||||
seen = _organized()
|
||||
seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))})
|
||||
seen, op, dp, ts = _organized(), store.data("rules", "organized.json"), store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
seen["retros"] = len(store.read(store.data("retro.jsonl")).splitlines())
|
||||
seen.update({_mark_key(USER): len(_retro(got[USER])), **({_mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))} if proj else {})})
|
||||
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
|
||||
marks = store.data("rules", "organized.json")
|
||||
store.write(marks, json.dumps(seen))
|
||||
dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
for r, pn, why in recs:
|
||||
store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True))
|
||||
_commit("rules organized", marks, up, *([dp] if recs else []), snap=(pp, before, after))
|
||||
change = {up: (_text(up), "".join(l + "\n" for l in got[USER])), op: (_text(op), json.dumps(seen))}
|
||||
if proj:
|
||||
before = _text(pp)
|
||||
change[pp] = (before, "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None)
|
||||
if core:
|
||||
change[cp] = (cb := _text(cp), "".join(l + "\n" for l in dict.fromkeys(_parse(cb or "") + core)))
|
||||
if recs:
|
||||
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:
|
||||
wrote_u and build_rulebook()
|
||||
if not wrote and not wrote_u:
|
||||
return "could not write %s (%s)" % (up, e)
|
||||
print("the organized rules are in %s; they could not be recorded for undo: %s" % (pp if wrote else up, e))
|
||||
return None
|
||||
return "could not record the organized rules (%s)" % e
|
||||
if warn: return "could not record the organized rules (%s); the files are restored, so run `sisi rules organize --record %s` again once the store is free" % (warn, answer_file)
|
||||
proj and change[pp][1] is not None and note(pp)
|
||||
with contextlib.suppress(OSError), store.lock("organize"):
|
||||
cl = {k: v for k, v in _organized(("locks", "organize.json")).items()
|
||||
if k not in ("claim:" + _mark_key(USER), "claim:" + _mark_key(PROJECT, cwd), "snap:" + _mark_key(PROJECT, cwd))}
|
||||
@@ -417,13 +539,17 @@ def organize_record(answer_file, cwd):
|
||||
for scope in (USER, PROJECT):
|
||||
print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope])))
|
||||
no_why and print("%d dropped rule%s had no reason recorded" % (no_why, "" if no_why == 1 else "s"))
|
||||
[print("skipped same problems line '%s' (%s)" % b) for b in bad_same]
|
||||
[print("the same rule was in both user and project and is now one copy in %s: %s; add it back by hand if you want it at both levels (run `sisi rules` to see the lists)" % (next(lv for lv in now if l in now[lv]), l)) for l in merged]
|
||||
[print("the same rule now sits at two levels, so `sisi rules move` cannot pick one copy: %s; remove the copy you do not want by hand (run `sisi rules` to see the lists)" % l) for l in over if l not in merged]
|
||||
flags.strip() and print("Flagged for you (not changed):" + flags.rstrip())
|
||||
back and print("Moved between levels, which `sisi rules revert` does not undo; to move them back, run:\n" + "\n".join(" " + c for c in back))
|
||||
return None
|
||||
|
||||
|
||||
def revert():
|
||||
"""Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left."""
|
||||
files = ("rules/user.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS)
|
||||
"""Undo the last learn, retro or organize (a project's list only while it holds what that change left); not a move between levels."""
|
||||
files = ("rules/user.md", "rules/core.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS, PROBLEMS)
|
||||
advice = " (edit by hand or restore with git)"
|
||||
if os.path.isdir(os.path.join(store.DATA, ".git")) and store.git(["status", "--porcelain", "--", *files], store.DATA)[1].strip():
|
||||
return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice
|
||||
@@ -432,19 +558,25 @@ def revert():
|
||||
return "there is no change to the learned rules to undo"
|
||||
(commit, _, subject), changed = out.splitlines()[0].partition(" "), out.splitlines()[1:]
|
||||
redo = len(re.match(r'(Revert ")*', subject).group(0)) // 8 % 2
|
||||
snap = {}
|
||||
if "rules/last-project.json" in changed or "(project," in subject or "organized" in subject:
|
||||
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed else ""
|
||||
try:
|
||||
snap = json.loads(raw)
|
||||
except ValueError:
|
||||
snap = None
|
||||
if (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str)
|
||||
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)
|
||||
# every change that writes a project list or moves a rule writes this record, so it is read even when its bytes did not change
|
||||
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed or re.search(r'\(project,|organized"*$|^rule moved', subject) else "{}"
|
||||
try:
|
||||
snap = json.loads(raw)
|
||||
except ValueError:
|
||||
snap = None
|
||||
if isinstance(snap, dict) and isinstance(snap.get("reverse"), list) and all(isinstance(c, str) for c in snap["reverse"]):
|
||||
print("to move them back, run:\n" + "\n".join(" " + c for c in snap["reverse"]))
|
||||
return "the last rule change, `%s`, moved rules between levels, which revert does not undo; the commands above move them back" % subject
|
||||
if isinstance(snap, dict) and snap.get("final"):
|
||||
return "the last rule change, `%s`, took the rule into canon/core.md, which is final and cannot be undone" % subject
|
||||
if snap != {} and (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str)
|
||||
or not os.path.isabs(sp) or os.path.normpath(sp) != sp or not sp.endswith("/.sisi/rules.md") or ".git" in sp.split(os.sep)
|
||||
or any(snap[k] is not None and not isinstance(snap[k], str) for k in ("before", "after"))):
|
||||
return "the undo record for `%s` is missing, corrupt or outside .sisi/rules.md, so it cannot be undone%s" % (subject, advice)
|
||||
if store.git(["rev-parse", "-q", "--verify", commit + "^"], store.DATA)[0]:
|
||||
return "there is no change to the learned rules to undo" # the first commit holds the rules from before sisi kept history
|
||||
p, (now, want) = snap.get("path"), (snap.get("before"), snap.get("after"))[::1 if redo else -1]
|
||||
with store.lock(p or "user"), store.lock("store"):
|
||||
with _locks(USER, *filter(None, [p])), store.lock("store"):
|
||||
if store.git(["log", "-1", "--format=%H", "--", *files], store.DATA)[1].strip() != commit:
|
||||
return "another rule change finished while waiting; run `sisi rules revert` again"
|
||||
try:
|
||||
@@ -468,8 +600,11 @@ def show(cwd):
|
||||
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
|
||||
proj, note = _migrate(cwd)
|
||||
note and print("\n" + note)
|
||||
for title, ls in (("Learned, all projects", lines(path(USER))), ("Learned, this project", proj)):
|
||||
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(ls) or " (none)"))
|
||||
groups = (("Learned, all projects", lines(path(USER))), ("Queued for the product (in force as user rules until then)", lines(path(CORE))), ("Learned, this project", proj))
|
||||
from . import retro
|
||||
probs = retro._problems() if any(_rule_probs(l) for _, ls in groups for l in ls) else []
|
||||
for title, ls in groups:
|
||||
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(_annotate(ls, probs)) or " (none)"))
|
||||
if due(cwd):
|
||||
print("\n" + due(cwd))
|
||||
|
||||
@@ -484,15 +619,66 @@ def run(args, cwd=None):
|
||||
return 0
|
||||
if args[0] == "organize" and len(args) == 3 and args[1] == "--record":
|
||||
why = organize_record(args[2], cwd)
|
||||
elif args[:1] == ["move"]:
|
||||
why = move(args[1:], cwd)
|
||||
elif args == ["revert"]:
|
||||
why = revert()
|
||||
else:
|
||||
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules revert"
|
||||
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules move \"<start of a rule>\" core|user|project|canon [--project PATH] | sisi rules revert"
|
||||
if why:
|
||||
print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why)
|
||||
return 1 if why else 0
|
||||
|
||||
|
||||
def move(args, cwd):
|
||||
"""`sisi rules move "<start of a rule line>" LEVEL|canon [--project PATH]`: one line, verbatim, to another level (canon: out of
|
||||
the product queue, once it is in canon/core.md); it prints the command that moves it back. Returns why not, or None."""
|
||||
top, usage = None, 'usage: sisi rules move "<start of a rule line>" core|user|project|canon [--project PATH]'
|
||||
if "--project" in args:
|
||||
i = args.index("--project")
|
||||
if i + 1 >= len(args):
|
||||
return usage
|
||||
top, args = os.path.abspath(args[i + 1]), args[:i] + args[i + 2:]
|
||||
if not has_project(top) or os.path.realpath(store.root(top)[0]) != os.path.realpath(top):
|
||||
return "--project needs the folder of a git repository (its root)"
|
||||
if len(args) != 2 or args[1] not in (CORE, USER, PROJECT, "canon"):
|
||||
return usage
|
||||
start, to, to_cwd = " ".join(args[0].split()), args[1], top or cwd
|
||||
forms = [f for f in ([start, start[2:]] if start.startswith("- ") else [start]) if f]
|
||||
homes = {path(lv, c): (lv, c) for lv, c in [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in (cwd, top) if c and has_project(c)]}
|
||||
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())
|
||||
|
||||
|
||||
@@ -507,14 +693,19 @@ def _said(words, cwd):
|
||||
|
||||
|
||||
def learn(args, cwd=None):
|
||||
"""`sisi learn [--project] "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
|
||||
"""`sisi learn --level core|user|project "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
|
||||
owner tag only when the words are found in the person's recent messages, else the agent's own tag."""
|
||||
args, scope = list(args), PROJECT if "--project" in args else None
|
||||
while (j := next((j for j, a in enumerate(args[:-1]) if a in ("--level", "--scope")), None)) is not None:
|
||||
scope, args[j:j + 2] = args[j + 1], []
|
||||
i = args.index("--means") if "--means" in args else len(args)
|
||||
args, means = list(args[:i]), " ".join(args[i + 1:])
|
||||
scope = PROJECT if "--project" in args else USER
|
||||
text = " ".join(a for a in args if a != "--project").strip()
|
||||
if len(text.split()) < 3 or (means and len(means.split()) < 3):
|
||||
print('usage: sisi learn [--project] "<what the person said, in their words>" [--means "<how I will apply it>"]')
|
||||
words, means = [a for a in args[:i] if a != "--project"], " ".join(args[i + 1:])
|
||||
text = " ".join(words).strip()
|
||||
if len(text.split()) < 3 or (i < len(args) and len(means.split()) < 3) or any(w.startswith("--") for w in words):
|
||||
print('usage: sisi learn --level core|user|project "<what the person said, in their words>" [--means "<how I will apply it>"]')
|
||||
return 1
|
||||
if why := refuse_level(scope, cwd, 'sisi learn'):
|
||||
print("sisi learn: " + why)
|
||||
return 1
|
||||
heard = _said(text, cwd)
|
||||
log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
|
||||
@@ -524,5 +715,6 @@ def learn(args, cwd=None):
|
||||
print("sisi learn: could not write %s (%s). Nothing was changed, and your words were not kept." % (path(scope, cwd) or cwd or os.getcwd(), e))
|
||||
return 1
|
||||
heard or print("sisi learn: these words were not found in the person's recent messages, so the rule carries the weaker tag [agent, attributed to owner]; a later owner statement or a measurement overrides it.")
|
||||
print(warn or "in force from the next session: %s" % line)
|
||||
print(warn or ("in force from the next session: %s" if scope != CORE else "queued for the product, in force as a user rule until then: %s") % line)
|
||||
print(filed(scope, text, cwd))
|
||||
return 0
|
||||
+22
-8
@@ -20,10 +20,11 @@ def _where(own, xdg, fallback):
|
||||
DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share"))
|
||||
STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state"))
|
||||
LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi")
|
||||
GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error
|
||||
|
||||
# Every setting there is. The person overrides one under "core" in config.json in their store.
|
||||
DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8,
|
||||
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False,
|
||||
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 7, "shell_workers": False,
|
||||
"worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8}
|
||||
|
||||
def config():
|
||||
@@ -98,24 +99,37 @@ def append(path, line, once=False):
|
||||
|
||||
def git(args, cwd, timeout=15):
|
||||
# A repository named by the caller's environment (a git hook sets GIT_DIR) must not decide which project this folder is.
|
||||
global GIT_ERROR
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")}
|
||||
env["GIT_OPTIONAL_LOCKS"] = "0" # a plain `git status` holds index.lock while it runs, and a commit started then fails on it
|
||||
try:
|
||||
r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env)
|
||||
return r.returncode, r.stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return 1, ""
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
r = subprocess.CompletedProcess(args, 1, "", str(e))
|
||||
GIT_ERROR = (r.stderr.strip().partition("\n")[0] or "git exited with %d" % r.returncode) if r.returncode else ""
|
||||
return r.returncode, r.stdout
|
||||
|
||||
|
||||
def commit(message, *paths):
|
||||
"""One commit in the person's store holding only these paths, so the change can be undone on its own."""
|
||||
def commit(message, *paths, put=None):
|
||||
"""One commit in the person's store holding only these paths, so the change can be undone on its own. `put` ({path: text})
|
||||
is written under the lock and committed too: another process's `git add` never reads a file as it is replaced."""
|
||||
history()
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA)
|
||||
rel = [os.path.relpath(p, DATA) for p in paths]
|
||||
[write(p, text) for p, text in (put or {}).items()]
|
||||
rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))]
|
||||
return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
|
||||
(git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or
|
||||
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0))
|
||||
|
||||
|
||||
def history():
|
||||
"""Start the store's git history once, holding the rules as they are, so no undo goes back past them."""
|
||||
if not os.path.isdir(os.path.join(DATA, ".git")):
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or [git(a, DATA) for a in (["init", "-q"], ["add", "-A", "--", "rules"], [
|
||||
"-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "--allow-empty", "-m", "rules before sisi kept history"])]
|
||||
|
||||
|
||||
_roots = {}
|
||||
|
||||
|
||||
|
||||
+803
-49
File diff suppressed because it is too large.
Load diff
@@ -10,8 +10,9 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
GAP = ("--gap", "the export dropped rows with empty names until the person noticed",
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence")
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project")
|
||||
|
||||
|
||||
def tree():
|
||||
@@ -27,6 +28,9 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-orgev-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
@@ -61,11 +65,11 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
return f.read()
|
||||
|
||||
def test_brief_has_problem_evidence_and_respects_caps(self):
|
||||
self.assertEqual(self.sisi("retro", "--gap", "export dropped rows with empty names in table",
|
||||
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows with empty names in table",
|
||||
"--cause", "first cause missed null guard",
|
||||
"--improve", "Check null names before exporting rows",
|
||||
"--term", "evidence", "--problem", "row count mismatch")[0], 0)
|
||||
self.assertEqual(self.sisi("retro", "--gap", "export dropped rows again on blank fields",
|
||||
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows again on blank fields",
|
||||
"--cause", "second cause forgot whitespace trim",
|
||||
"--improve", "Strip whitespace and assert total row count matches",
|
||||
"--term", "evidence", "--problem", "1")[0], 0)
|
||||
@@ -85,7 +89,7 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
long_cause = "word " * 1000
|
||||
for i in range(2, 19):
|
||||
cause = long_cause if i == 18 else "cause number %02d in batch" % i
|
||||
self.assertEqual(self.sisi("retro", "--gap", "gap number %02d failed verification check" % i,
|
||||
self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "gap number %02d failed verification check" % i,
|
||||
"--cause", cause,
|
||||
"--improve", "Rule number %02d for problem" % i,
|
||||
"--term", "evidence", "--problem", "problem item %02d" % i)[0], 0)
|
||||
@@ -115,8 +119,9 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
self.assertIn("copied as it is", brief)
|
||||
shape = brief.split("Answer with exactly this shape")[1].split("===")[0]
|
||||
self.assertLess(shape.index("## project"), shape.index("## drops"))
|
||||
self.assertLess(shape.index("## drops"), shape.index("## flags"))
|
||||
self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 35)
|
||||
self.assertLess(shape.index("## drops"), shape.index("## same problems"))
|
||||
self.assertLess(shape.index("## same problems"), shape.index("## flags"))
|
||||
self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 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"
|
||||
@@ -165,7 +170,7 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
|
||||
def test_owner_rules_stay_verbatim_with_drops_format(self):
|
||||
self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"}))
|
||||
self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Check row counts before export", "--problem", "empty names")[0], 0)
|
||||
own = self.read(self.data, "rules", "user.md").splitlines()[0]
|
||||
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
|
||||
@@ -297,7 +302,7 @@ class OrganizeEvidence(unittest.TestCase):
|
||||
|
||||
def test_drops_ignore_kept_owner_and_invented_rules(self):
|
||||
self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"}))
|
||||
self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Kept retro rule always here", "--problem", "empty names")[0], 0)
|
||||
own = self.read(self.data, "rules", "user.md").splitlines()[0]
|
||||
ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0]
|
||||
|
||||
+196
-5
@@ -13,10 +13,11 @@ import unittest
|
||||
from unittest import mock
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REAL_HOME = os.path.expanduser("~")
|
||||
sys.path.insert(0, REPO)
|
||||
from sisi import retro, store
|
||||
from sisi import retro, rules, store
|
||||
GAP = ("--gap", "the export dropped rows with empty names until the person noticed",
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence")
|
||||
"--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project")
|
||||
|
||||
|
||||
def tree():
|
||||
@@ -32,11 +33,15 @@ class Problems(unittest.TestCase):
|
||||
def setUp(self):
|
||||
before = tree()
|
||||
self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree"))
|
||||
book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md")
|
||||
mine = self.read(book) if os.path.exists(book) else None
|
||||
self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file"))
|
||||
self.tmp = tempfile.mkdtemp(prefix="sisi-prob-")
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data,
|
||||
SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"))
|
||||
SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"),
|
||||
CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
||||
for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"):
|
||||
self.env.pop(name, None)
|
||||
self.proj = os.path.join(self.tmp, "alpha")
|
||||
@@ -44,6 +49,17 @@ class Problems(unittest.TestCase):
|
||||
for args in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]):
|
||||
subprocess.run(["git"] + args, cwd=self.proj, check=True, stdin=subprocess.DEVNULL, capture_output=True)
|
||||
|
||||
def in_process(self, fn, *args):
|
||||
out, here = io.StringIO(), os.getcwd()
|
||||
os.chdir(self.tmp)
|
||||
try:
|
||||
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \
|
||||
mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \
|
||||
mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out):
|
||||
return fn(*args), out.getvalue()
|
||||
finally:
|
||||
os.chdir(here)
|
||||
|
||||
def sisi(self, *args, cwd=None, sid=None, stdin=""):
|
||||
env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env
|
||||
out_f = os.path.join(self.tmp, "stdout.tmp")
|
||||
@@ -55,6 +71,10 @@ class Problems(unittest.TestCase):
|
||||
fe.seek(0)
|
||||
return r.returncode, fo.read(), fe.read()
|
||||
|
||||
def read(self, *parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def records(self):
|
||||
p = os.path.join(self.data, "retro.jsonl")
|
||||
if not os.path.exists(p):
|
||||
@@ -87,7 +107,7 @@ class Problems(unittest.TestCase):
|
||||
self.assertNotIn("has come back", out)
|
||||
|
||||
# Open problem #2 by words
|
||||
rc, out, err = self.sisi("retro", "--gap", "build script left stale artifacts in output",
|
||||
rc, out, err = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts in output",
|
||||
"--cause", "clean step was skipped on incremental runs",
|
||||
"--improve", "Always clean output directory before packaging release",
|
||||
"--term", "value", "--problem", "stale build artifacts")
|
||||
@@ -125,7 +145,7 @@ class Problems(unittest.TestCase):
|
||||
# Add more non-problem records and cite #2; numbers stay stable
|
||||
self.assertEqual(self.sisi("retro", "--no-gap", "the build passed cleanly on first run",
|
||||
"--term", "time", "--better", "parallelize the test suite run here")[0], 0)
|
||||
rc, out, _ = self.sisi("retro", "--gap", "build script left stale artifacts again",
|
||||
rc, out, _ = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts again",
|
||||
"--cause", "incremental cache kept old binary",
|
||||
"--improve", "Hash inputs before reusing build artifacts",
|
||||
"--term", "value", "--problem", "2")
|
||||
@@ -354,6 +374,177 @@ class Problems(unittest.TestCase):
|
||||
self.assertTrue(any("alpha issue" in l for l in faults_lines), faults_lines)
|
||||
self.assertTrue(any("bravo issue" in l for l in faults_lines), faults_lines)
|
||||
|
||||
def test_organize_brief_lists_every_problem_and_same_problems_section(self):
|
||||
self.assertEqual(self.sisi("retro", "--level", "project",
|
||||
"--gap", "stated a remembered tool behaviour without running the command",
|
||||
"--cause", "stated a remembered tool behaviour without checking",
|
||||
"--improve", "Run the command before stating tool behaviour",
|
||||
"--term", "evidence",
|
||||
"--problem", "claimed tool behaviour or timing from memory in a question or fault brief")[0], 0)
|
||||
for i in range(2, 18):
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Rule number %02d for problem" % i,
|
||||
"--problem", "distinct item %02d" % i)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", "--level", "project",
|
||||
"--gap", "inferred driver behaviour from defaults without testing",
|
||||
"--cause", "Inferred driver behaviour from lpoptions defaults instead of running the filter chain",
|
||||
"--improve", "Push a known test page before claiming driver behaviour",
|
||||
"--term", "evidence",
|
||||
"--problem", "Unmeasured claims about tool behaviour")[0], 0)
|
||||
brief, _ = self.in_process(rules.organize_brief, self.proj)
|
||||
self.assertIn("## same problems", brief)
|
||||
self.assertIn("N = M", brief)
|
||||
# All 18 problems (beyond the 15-problem cap in _evidence) appear with number, name, and cause
|
||||
self.assertIn("#1:", brief)
|
||||
self.assertIn("claimed tool behaviour or timing from memory in a question or fault brief", brief)
|
||||
self.assertIn("stated a remembered tool behaviour without checking", brief)
|
||||
self.assertIn("#18:", brief)
|
||||
self.assertIn("Unmeasured claims about tool behaviour", brief)
|
||||
self.assertIn("Inferred driver behaviour from lpoptions defaults instead of running the filter chain", brief)
|
||||
self.assertIn("#2:", brief)
|
||||
self.assertIn("distinct item 02", brief)
|
||||
|
||||
def test_merge_problems_counts_misses_opens_fault_and_shows_in_report(self):
|
||||
p1_a = "claimed tool behaviour or timing from memory in a question or fault brief"
|
||||
p1_b = "Unmeasured claims about tool behaviour"
|
||||
p2_a = "push not gated on the test run's exit code"
|
||||
p2_b = "a gating command's exit status was hidden by a display filter"
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Run the command before claiming behaviour", "--problem", p1_a)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Gate every push on the test exit code", "--problem", p2_a)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Test the filter chain on a known page first", "--problem", p1_b)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Never pipe a gating command into a filter", "--problem", p2_b)[0], 0)
|
||||
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
proj_rules = [l for l in self.read(self.proj, ".sisi", "rules.md").splitlines() if l.startswith("- ")]
|
||||
ans = os.path.join(self.tmp, "merge.md")
|
||||
with open(ans, "w", encoding="utf-8") as f:
|
||||
f.write("## user\n## project\n" + "\n".join(proj_rules) + "\n## same problems\n1 = 3\n2 = 4\n")
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
|
||||
rep = self.sisi("retro")[1]
|
||||
self.assertIn("#1: " + p1_a + " (2 attempts", rep)
|
||||
self.assertIn("#2: " + p2_a + " (2 attempts", rep)
|
||||
self.assertNotIn("#3: " + p1_b, rep)
|
||||
self.assertNotIn("#4: " + p2_b, rep)
|
||||
self.assertIn(p1_b, rep)
|
||||
self.assertIn(p2_b, rep)
|
||||
self.assertLess(rep.index("#1: " + p1_a), rep.index(p1_b))
|
||||
self.assertLess(rep.index("#2: " + p2_a), rep.index(p2_b))
|
||||
|
||||
# Existing numbering stays valid: a new problem gets #5, not #3
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Separate problem rule five", "--problem", "separate fifth issue")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("opened problem 5 'separate fifth issue'", out)
|
||||
|
||||
# Citing merged number 3 counts as 2nd miss of #1 and opens its fault
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged number three", "--problem", "3")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 1 '%s' has come back: 2 misses" % p1_a, out)
|
||||
self.assertIn("opened fault #1", out)
|
||||
|
||||
# Citing merged name p2_b counts as 2nd miss of #2 and opens its fault
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged name p2_b", "--problem", p2_b)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 2 '%s' has come back: 2 misses" % p2_a, out)
|
||||
self.assertIn("opened fault #2", out)
|
||||
|
||||
# Citing merged number 4 a second time (event happens twice) counts 3 misses on #2 without opening a duplicate fault
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fifth rule via merged number four", "--problem", "4")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 2 '%s' has come back: 3 misses" % p2_a, out)
|
||||
self.assertEqual(len(self.sisi("fault")[1].strip().splitlines()), 2)
|
||||
|
||||
# Citing #5 still resolves to #5
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for fifth issue", "--problem", "5")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 5 'separate fifth issue' has come back: 1 miss", out)
|
||||
|
||||
def test_per_rule_note_counts_citations_through_alias(self):
|
||||
p3_a = "a long real-data run started without its read-only admission check"
|
||||
p3_b = "untested script left for unattended run"
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
retro_rows = [
|
||||
{"ts": "2026-11-20T10:00:00", "problem": p3_a, "cause": "no admission check", "improve": "Run read-only admission check first"},
|
||||
{"ts": "2026-11-21T10:00:00", "problem": p3_b, "cause": "never dry-ran script", "improve": "Dry-run one item end to end first"},
|
||||
]
|
||||
with open(os.path.join(self.data, "retro.jsonl"), "w", encoding="utf-8") as f:
|
||||
f.write("".join(json.dumps(r) + "\n" for r in retro_rows))
|
||||
os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True)
|
||||
with open(os.path.join(self.proj, ".sisi", "rules.md"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join([
|
||||
"- Run read-only admission check first [retro 2026-11-20 p1]",
|
||||
"- Dry-run one item end to end first [retro 2026-11-21 p2]",
|
||||
]) + "\n")
|
||||
ans = os.path.join(self.tmp, "merge3.md")
|
||||
with open(ans, "w", encoding="utf-8") as f:
|
||||
f.write("## user\n## project\n- Run read-only admission check first [retro 2026-11-20 p1]\n- Dry-run one item end to end first [retro 2026-11-21 p2]\n## same problems\n1 = 2\n")
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
|
||||
rc, retro_out, _ = self.sisi("retro", *GAP, "--improve", "Verify one sample output before batching", "--problem", "2")
|
||||
self.assertEqual(rc, 0, retro_out)
|
||||
self.assertIn("problem 1 '%s' has come back: 2 misses" % p3_a, retro_out)
|
||||
|
||||
_, listing_inproc = self.in_process(rules.show, self.proj)
|
||||
listing_cli = self.sisi("rules")[1]
|
||||
brief = self.sisi("rules", "organize")[1]
|
||||
for out_txt in (listing_inproc, listing_cli, brief):
|
||||
self.assertIn("[retro 2026-11-20 p1] (p1: came back 2x since)", out_txt)
|
||||
self.assertIn("[retro 2026-11-21 p2] (p2: came back 1x since)", out_txt)
|
||||
self.in_process(rules.build_rulebook)
|
||||
book = self.read(self.data, "generated", "core.md")
|
||||
self.assertNotIn("came back", book)
|
||||
|
||||
def test_bad_same_problems_skipped_and_revert_undoes_aliases(self):
|
||||
p_a = "a long real-data run started without its read-only admission check"
|
||||
p_b = "untested script left for unattended run"
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule before bad merge", "--problem", p_a)[0], 0)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule before bad merge", "--problem", p_b)[0], 0)
|
||||
rules_path = os.path.join(self.proj, ".sisi", "rules.md")
|
||||
before = self.read(rules_path)
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
ans = os.path.join(self.tmp, "bad_merge.md")
|
||||
with open(ans, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join([
|
||||
"## user",
|
||||
"- Kept organized user rule [retro 2026-11-26]",
|
||||
"## project",
|
||||
"- Combined organized project rule [retro 2026-11-26 p1]",
|
||||
"## same problems",
|
||||
"1 = 99",
|
||||
"0 = 1",
|
||||
"1 = 1",
|
||||
"1 = 2",
|
||||
"2 = 1",
|
||||
"not a valid pair",
|
||||
]) + "\n")
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
self.assertIn("99", out)
|
||||
self.assertIn("0 = 1", out)
|
||||
self.assertIn("1 = 1", out)
|
||||
self.assertIn("2 = 1", out)
|
||||
self.assertIn("not a valid pair", out)
|
||||
# Rest of organize recorded
|
||||
self.assertIn("Combined organized project rule", self.read(rules_path))
|
||||
self.assertIn("Kept organized user rule", self.read(self.data, "rules", "user.md"))
|
||||
# Valid 1 = 2 took effect
|
||||
rep = self.sisi("retro")[1]
|
||||
self.assertIn("#1: " + p_a + " (2 attempts", rep)
|
||||
self.assertNotIn("#2: " + p_b, rep)
|
||||
|
||||
# Revert undoes the organize AND removes the alias
|
||||
rc, rev_out, _ = self.sisi("rules", "revert")
|
||||
self.assertEqual(rc, 0, rev_out)
|
||||
self.assertEqual(self.read(rules_path), before)
|
||||
rep_after = self.sisi("retro")[1]
|
||||
self.assertIn("#1: " + p_a + " (1 attempt", rep_after)
|
||||
self.assertIn("#2: " + p_b + " (1 attempt", rep_after)
|
||||
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Post-revert citation of two", "--problem", "2")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("problem 2 '%s' has come back: 1 miss" % p_b, out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user