Compare commits

...
14 Commits
Author SHA1 Message Date
swaitsandClaude Fable 5.2 1e3b14aa88 Check in sisi's own project rules and the AGENTS.md note
ci / test (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 21:47:10 -07:00
swaits 2bec0823f3 Fix hostile project files, non-blocking tick lock, store commit lock, and revert checks 2026-11-24 21:15:24 -07:00
swaits e969aa2bd4 Simplify project rules locking, migration, undo validation, and commit checks 2026-11-24 20:40:20 -07:00
swaitsandClaude Opus 5.5 b588cec7a8 Project rules: one list per repository, claimed migration, undo that checks the file
- In git the project root is always the main checkout's, from any subfolder or worktree; the
  git check-ignore branch and the non-git ancestor walk are gone. When git cannot answer, the
  nearest folder holding .git; inside a git directory or bare repository nothing is written.
- The root is looked up once per process: session start runs 4 git processes (was 10).
- Every write of a project's list (learn, retro, organize, move) records path/before/after in
  rules/last-project.json and commits it, so `sisi rules revert` undoes the last change of any
  kind; it restores only while the file holds exactly what the change left, else declines.
- The move from the store is claimed by an atomic rename; the store copy is removed only after
  the store commit succeeds; a claim left by a crash is picked up later; BOM and non-UTF-8 safe.
- A linked .sisi is named in one line; the note closes the file it opens; learn into a folder
  that cannot be written says so in one line and keeps nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:58:19 -07:00
swaits a540bd45ff Fix AGENTS.md note handling, snapshot cost/false-alarm, and read-only doctor 2026-11-24 19:12:25 -07:00
swaits c1cd6d7ee3 Keep a marked .sisi/rules.md note in project root AGENTS.md 2026-11-24 18:49:27 -07:00
swaits de58a13e82 Store project rules in <project root>/.sisi/rules.md with safe migration and revert 2026-11-24 18:38:31 -07:00
swaits aa6c268f58 Review fixes: the agent marker counts only at the very start of the first request; quick work is timed from its first request, and a failed check or a backwards clock still sends it to the retro
ci / test (push) Canceled after 0s
2026-11-24 13:41:03 -07:00
swaits dacfc84594 Merge the delegation and retro cost record 2026-11-24 13:39:05 -07:00
swaits 058b7a80cf Record lead session id, timestamps, model id, and retro_seconds in outcomes.jsonl and retro.jsonl 2026-11-24 13:36:02 -07:00
swaitsandClaude Sonnet 5.5 927eb1bb0b Work that took under retro_minutes (5) from sisi done, passed every check and delegated nothing closes without a retro
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 13:34:01 -07:00
swaitsandClaude Sonnet 5.5 6a5ed356a2 A lead waiting on a delegation that is open and not late is not stopped for checks without a verdict
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 13:32:13 -07:00
swaitsandClaude Sonnet 5.5 85b9f1489d A session whose first request says an agent, not the user, sent it is a worker, so the direct-call limit no longer kills a delegated worker
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 13:31:46 -07:00
swaitsandClaude Fable 5.2 abd48cba8f A delegation to a worker the models table does not list says the table is out of date and marks it for every session
The refusal used to say to pick from the wheel, which can never give an
unlisted worker. Now it says to rebuild the table, and a marker makes
session start in every session say the same until a table that lists the
worker is recorded. A worker in the table, a shell-started worker and an
empty model keep the plain no-pick refusal. The marker is best effort and
its text is cleaned before it is stored or printed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 10:42:09 -07:00
14 changed files with 1966 additions and 172 deletions

No files matched your search

-1
View File
@@ -1,4 +1,3 @@
__pycache__/
*.pyc
.agent-work/
.sisi/
+15
View File
@@ -0,0 +1,15 @@
- This repo is sisi itself: a learned rule that applies to every sisi user on every system goes into the product (canon/core.md) and is then deleted from the learned lists, so the sisi people download is effective at once; only rules about this owner or this machine stay in the learned lists. [owner 2026-11-23]
- sisi is a self-improvement loop (forced retros, each improvement a rule at once, rules organized) and nothing more — keep it simple and small, never over-build; anything beyond costs the person attention. [owner 2026-11-23]
- sisi must work globally, for any agent in any harness (T3 Code or otherwise): rules, hooks and the loops are installed and enforced in every agent tool on the machine, not only Claude Code. [owner 2026-11-23]
- Use no external dependencies and no cron jobs; run periodic upkeep from a counter or chance check during a normal turn, so the system improves just by being used. [owner 2026-11-23]
- The real objective function is the one in SPEC.md; sisi always optimizes it by mechanisms (hooks, checks), never by good intentions, and never hard-codes a model or a harness. [owner 2026-11-23]
- Measure size budgets in the unit actually paid for (characters loaded per session), and say plainly whether loaded text grew or shrank after a change. [retro 2026-11-23]
- When a brief asks for a classifier, matcher or lookup change, have a different worker write the labelled set and report only held-out accuracy, prototype first on a blind set, give three real rows and three real inputs copied from the live data as required test cases, and name every flag the existing 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 (never write bytecode into shared state) and print no user-facing output whose only reader is a log; in tests, send their 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 code that edits another program's config files against hostile pre-existing state: symlinks, read-only files, commented or trailing-comma JSON, duplicate entries, edits between install and uninstall — such code fails on real user files. [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 a check-skipping time or count 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 in which 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]
+3
View File
@@ -0,0 +1,3 @@
<!-- sisi:begin -->
This project's learned rules are in `.sisi/rules.md`. Read that file before any work here and follow it.
<!-- sisi:end -->
+40 -19
View File
@@ -19,8 +19,8 @@ by its full model id (`claude-sonnet-5-5`); anywhere else the name must match wh
**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
(`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. Each record in `retro.jsonl` carries the numbers
(minutes, messages, tool calls, delegations, checks) and the `term` it fell short on (`value`, `evidence`, `time`, `cost`,
is sent to the retro, and any other closes itself, as does work that took under `retro_minutes`, passed every check and delegated nothing. While a delegated job is open and not late, a stop is not held up for checks without a verdict. Each record in `retro.jsonl` carries `session_id`, `retro_seconds` (when demanded),
the numbers (minutes, messages, tool calls, delegations, checks) and the `term` it fell short on (`value`, `evidence`, `time`, `cost`,
`attention` or `learning`: the terms of the objective), and `sisi retro` lays the facts out under those terms and shows their trend.
## Install
@@ -52,14 +52,16 @@ not installed (its folder is absent) gets nothing created. For a tool that is in
everything else in the file is kept. A file sisi cannot edit safely (comments, a trailing comma, a symlink to
nowhere, read-only, hooks of an unexpected shape) is left alone and reported.
| Tool | Rulebook (in its folder) | Hooks |
|---|---|---|
| Claude Code | `~/.claude/CLAUDE.md` | `settings.json` |
| Codex | `~/.codex/AGENTS.md` | `hooks.json` (the person trusts them once in Codex's `/hooks`) |
| Qwen Code | `~/.qwen/QWEN.md` | `settings.json` |
| Grok | `~/.grok/AGENTS.md` | none: Grok runs the hooks in `~/.claude/settings.json` |
| OpenCode, Antigravity (`~/.gemini`), Pi, Kiro, Copilot, Crush, Amp | their global instructions file | none: not confirmed |
| Muse, Cursor | none documented | not covered |
| Tool | Rulebook (in its folder) | Hooks | Project rules |
|---|---|---|---|
| Claude Code | `~/.claude/CLAUDE.md` | `settings.json` | session-start print (reads `AGENTS.md` only without `CLAUDE.md`) |
| Codex | `~/.codex/AGENTS.md` | `hooks.json` (the person trusts them once in Codex's `/hooks`) | session-start print; `AGENTS.md` note is in the file it reads |
| Qwen Code | `~/.qwen/QWEN.md` | `settings.json` | session-start print; `AGENTS.md` note is in the file it reads |
| Grok | `~/.grok/AGENTS.md` | none: Grok runs the hooks in `~/.claude/settings.json` | `AGENTS.md` note is in the file it reads |
| OpenCode, Antigravity (`~/.gemini`), Pi, Kiro, Copilot, Amp | their global instructions file | none: not confirmed | `AGENTS.md` note is in the file the tool reads |
| Crush | `~/.config/crush/CRUSH.md` | none: not confirmed | `AGENTS.md` note is read only when started at project root |
| Cursor | none documented | not covered | `AGENTS.md` note is in the file Cursor CLI reads |
| Muse | none documented | not covered | unconfirmed |
Hooks read a tool's input under whichever field names it uses (`session_id`, `sessionId`, `conversationId`,
`toolCall.name`, …), and the class of each tool call (shell, read, edit, search, web, delegate) comes from
@@ -78,25 +80,44 @@ its limits are.
| `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] "…"` | The person's own words become a rule at once |
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them; undo the last change |
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them; undo the last rule change made with `learn`, a retro or `organize`, in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
| `sisi models` / `sisi models research [--record FILE]` | The workers table; have a worker rebuild it |
| `sisi judge WORKER good\|bad "…" [--minutes N] [--newest]` | How a delegation went; the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest |
| `sisi direct "…"` | Allow more direct tool calls this turn, with the reason |
## Where things live
- **The product** (this repository): the code in `sisi/`, the rulebook in `canon/core.md`. The same for
everyone. `SPEC.md` is what it aims at.
- **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md` and `rules/projects/*.md` (what
was learned), `models.md` (your workers), `retro.jsonl` and `outcomes.jsonl` (what happened). All plain
text you can read and edit.
- **The rulebook every session loads** is generated from the two: `canon/core.md`, then your learned rules.
Rules live at three levels:
- **The product** (this repository): the code in `sisi/`, and the rulebook in `canon/core.md` — rules useful to everyone
using sisi, the same for all users. `SPEC.md` is what it aims at.
- **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md`
(how you like to work, across all your projects), `models.md` (your workers), `retro.jsonl` (each piece of work: session,
`retro_seconds`, counts, goal, term) and `outcomes.jsonl` (each judged delegation: session, `project_key`, `model`,
`started`/`ended`, minutes, verdict, why). All plain text you can read and edit.
- **Each project** (`.sisi/rules.md` in the project's folder: in a git repository, the root of its main checkout, shared by
all its worktrees; outside git, the folder sisi is run in): rules specific to one project. In a bare repository with
worktrees or a repository made with `--separate-git-dir`, each worktree (or the main checkout and linked worktree)
has its own list, and `GIT_DIR` in the environment is followed. A worktree's own checked-in
copy of `.sisi/rules.md` is the committed version; new rules are written in the main checkout, for you to commit. You choose
whether to check `.sisi/` into git or ignore it (sisi works either way, and never commits or stages it for you). When
sisi adds to, organizes or moves old rules into `.sisi/rules.md`, it also puts a marked note (`<!-- sisi:begin -->` ... `<!-- sisi:end -->`) in the project
root's `AGENTS.md` pointing to `.sisi/rules.md`, so the note is in the file those tools read; `revert` does not add or remove the note; after undoing a project's only rule, the empty `.sisi/` folder and the note remain. It is skipped with a
one-line reason when `AGENTS.md` is read-only, a folder, not UTF-8, a link that is broken or points outside the project
or into `.git` or `.sisi`, or if writing fails. Deleting the block removes it only until the next rule is written, when
sisi puts it back. If `AGENTS.md` is checked in, git shows it as modified until you commit it (sisi never commits it),
and if `.sisi/` is git-ignored, people who clone the project get a note pointing at a file they do not have. A
hard-linked `AGENTS.md` is replaced by a separate file. Old project rules moved from your store are not undone by
`revert`; the old list stays in your store's git history (`git -C ~/.local/share/sisi log -p -- rules/projects`).
- **The rulebook every session loads** (`generated/core.md`) is built from the product (`canon/core.md`) and your user
rules (`rules/user.md`). Project rules are not in the generated rulebook; they are printed at session start by the `tick`
hook (for tools whose session-start output reaches the agent), pointed to by the `AGENTS.md` note, and shown by `sisi rules`.
- **Scratch** (session state, bytecode): `$SISI_STATE`, else `$XDG_STATE_HOME/sisi`, else `~/.local/state/sisi`.
Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`.
Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8),
`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7),
`shell_workers` (false). Workers are started with the host's own delegation tool, so by default a shell command
`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `worker_minutes` (15),
`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). 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
delegation, and `sisi pick` prints the command line.
+1 -1
View File
@@ -107,7 +107,7 @@ tests, evidence and completion.
When a piece of work ends, the lead runs `sisi retro`, which prints what happened. Set it against
the objective, term by term: where did the work fall short, why, and what instruction would have
prevented it? Record that (`sisi retro --gap … --cause … --improve …`). The improvement becomes a rule at
once, in this project or in all your work. Name the root cause; general advice is not an
once: product (useful to every sisi user, in the product), user (how this person works across projects, in their store), or project (one project, in `.sisi/rules.md` at its root, in git its main checkout's, which may be checked in). Name the root cause; general advice is not an
improvement. Work can always be done better: when nothing fell short, name the one thing that would have scored better (`--no-gap … --better …`). Name the term of the objective each time (`--term`). When the person states a lasting
preference, record their words at once with `sisi learn`. When session start says the learned
rules need organizing, have a cheap worker do it in the background.
+4 -4
View File
@@ -2,14 +2,14 @@
{"name": "claude", "detect": "~/.claude", "env": "CLAUDE_CONFIG_DIR", "rules": "CLAUDE.md", "import": true, "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "The built-in Explore and Plan subagents do not load CLAUDE.md."},
{"name": "codex", "detect": "~/.codex", "env": "CODEX_HOME", "rules": "AGENTS.md", "hooks": {"file": "hooks.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "Hooks run only after the person trusts them once in Codex's /hooks; AGENTS.override.md shadows the rulebook; hosted web search is not metered."},
{"name": "qwen", "detect": "~/.qwen", "rules": "QWEN.md", "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "A tool Qwen names differently from canon/tools.json is not metered."},
{"name": "grok", "detect": "~/.grok", "rules": "AGENTS.md", "limits": "Grok already runs the hooks in ~/.claude/settings.json; its session-start and prompt output is discarded, so project rules do not reach it at session start."},
{"name": "grok", "detect": "~/.grok", "rules": "AGENTS.md", "limits": "Grok already runs the hooks in ~/.claude/settings.json; its session-start and prompt output is discarded, though it reads the project's AGENTS.md note."},
{"name": "opencode", "detect": "~/.config/opencode", "rules": "AGENTS.md", "clean": ["plugins/sisi.js"], "limits": "Its plugin hooks are unverified, so none are wired."},
{"name": "antigravity", "detect": "~/.gemini", "rules": "GEMINI.md", "clean": ["settings.json"], "limits": "Its global hooks file location is unconfirmed, so none are wired."},
{"name": "pi", "detect": "~/.pi", "rules": "agent/AGENTS.md", "clean": ["agent/extensions/sisi.ts"], "limits": "Its extension hooks are unverified, so none are wired."},
{"name": "kiro", "detect": "~/.kiro", "rules": "steering/AGENTS.md", "limits": "Hook support is unconfirmed, so none are wired."},
{"name": "copilot", "detect": "~/.copilot", "rules": "copilot-instructions.md", "limits": "Hook support is unconfirmed, so none are wired."},
{"name": "crush", "detect": "~/.config/crush", "rules": "CRUSH.md", "limits": "Hook support is unconfirmed, so none are wired."},
{"name": "crush", "detect": "~/.config/crush", "rules": "CRUSH.md", "limits": "Hook support is unconfirmed, so none are wired; it reads project AGENTS.md only from the folder it is started in, not from a subfolder."},
{"name": "amp", "detect": "~/.config/amp", "rules": "AGENTS.md", "limits": "Hook support is unconfirmed, so none are wired."},
{"name": "muse", "detect": "~/.config/muse", "limits": "No documented global instructions file."},
{"name": "cursor", "detect": "~/.cursor", "limits": "No global instructions file, and CLI hook support is unconfirmed."}
{"name": "muse", "detect": "~/.config/muse", "limits": "No documented global instructions file; whether it reads project AGENTS.md is unconfirmed."},
{"name": "cursor", "detect": "~/.cursor", "limits": "No global instructions file, and CLI hook support is unconfirmed; Cursor CLI reads project AGENTS.md."}
]
+5 -3
View File
@@ -19,7 +19,8 @@ The learning loop
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 change to the learned rules
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
Delegation
sisi models the workers you have: what each is good at and what it costs
@@ -39,9 +40,10 @@ Setting up
Hooks (the agent tool calls these): sisi tick | prompt | watch | gate
Your rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository. Settings: "core" in
Your own rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository;
a project's rules live in its .sisi/rules.md. Settings: "core" in
its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after,
research_days, shell_workers, worker_minutes)."""
research_days, shell_workers, worker_minutes, retro_minutes)."""
def main(argv):
+25 -22
View File
@@ -5,30 +5,26 @@ should be delegating. The end-of-turn hook forces the retro when work was done."
import json, os, re, sys, time
from . import models, rules, store
# A delegated session says so in the first lines of its first request (the brief).
WORKER = re.compile(r"(?im)^\W*(you are a (worker|subagent|sub-agent|delegate)\b|do this task yourself|do not delegate)")
# A delegated session says so in the first lines of its first request (the brief), or a host's bracketed line
# at the start of a line says an agent, not the user, sent it.
WORKER = re.compile(r"(?im)^\W*(you are a (worker|subagent|sub-agent|delegate)\b|do this task yourself|do not delegate)|\A\s*\[[^\]\n]{0,200}\bsent this message, not the user\.?\]")
DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call the meter counts
METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your "
"workers; brief one and judge what comes back. If doing this yourself really costs less than briefing "
"it, say why first: `sisi direct \"<reason>\"` allows %d more.\n")
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro`: it prints what "
"happened. Set that against the objective and record the gap and the improvement, or that there was "
"none. If the work is not finished and you are only pausing (for the person, for background work), say "
"so instead: `sisi retro --later \"<what it waits for>\"`.")
GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro`: it prints what happened. Set that against the objective and record the gap and the improvement, or that there was none. "
"If the work is not finished and you are only pausing (for the person, for background work), say so instead: `sisi retro --later \"<what it waits for>\"`.")
NODONE = ("sisi: nothing starts before done is recorded. Work out what the person wants and what they will need "
"next, then: sisi done --goal \"<their goal>\" --check \"<a check that can fail>\" [--check ...] "
"--next \"<what comes next and what you do about it>\"\n")
NOPICK = ("sisi: this delegation goes to a worker the wheel did not give you. sisi pick routine|ordinary|hard gives "
"you one for this task (--review-of WORKER for a review, --not WORKER if one is out); one pick, one "
"delegation.\n")
NOPICK = ("sisi: this delegation goes to a worker the wheel did not give you. sisi pick routine|ordinary|hard gives you one for this task "
"(--review-of WORKER for a review, --not WORKER if one is out); one pick, one delegation.\n")
UNKNOWN = "sisi: the worker you named is not in the models table, so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), then run `sisi pick`.\n"
NOSHELL = "sisi: do not shell out to a worker; start it with the host's delegation tool.\n"
FAILED = ("sisi: check %s failed. A failed check is a gap: record it with `sisi retro --gap \"<where it fell "
"short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term>`.")
OPEN = ("sisi: these checks have no verdict yet: %s. Give each one: sisi done --pass N \"<evidence>\" or --fail N "
"\"<why>\". If the work is only pausing: sisi retro --later \"<what it waits for>\".")
LATE = ("%s was started %s and has not reported. Check it now: if it is dead or no longer wanted, cancel it with the "
"host's tool and record `sisi judge WORKER bad \"<why>\"`; if it reported, judge it.")
FAILED = "sisi: check %s failed. A failed check is a gap: record it with `sisi retro --gap \"<where it fell short>\" --cause \"<the root cause>\" --improve \"<the rule that prevents it>\" --term <term>`."
OPEN = "sisi: these checks have no verdict yet: %s. Give each one: sisi done --pass N \"<evidence>\" or --fail N \"<why>\". If the work is only pausing: sisi retro --later \"<what it waits for>\"."
LATE = "%s was started %s and has not reported. Check it now: if it is dead or no longer wanted, cancel it with the host's tool and record `sisi judge WORKER bad \"<why>\"`; if it reported, judge it."
# The names each host gives a hook's fields; the first one present (and of the right type) wins.
FIELDS = (("session_id", str, ("session_id", "sessionId", "conversation_id", "conversationId")),
@@ -129,6 +125,7 @@ def prompt(p):
if not s.get("prompts") and WORKER.search(p["prompt"][:2000]):
s["worker"] = True
s["prompts"] = s.get("prompts", 0) + 1
s.get("prompts_since") or s.update(began=time.time()) # the first request of a piece of work
s["prompts_since"] = s.get("prompts_since", 0) + 1
s["direct"], s["extra"], s["blocks"] = 0, 0, 0
return 0
@@ -156,9 +153,12 @@ def watch(p):
if kind == "delegate" or shell:
target = ti.get("target") if isinstance(ti.get("target"), dict) else {}
names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent"))
text = command if shell else str(next((n for n in names if n), "")) # tool_input.model may be a short name: a segment
if tool != "workflow" and models.usable(store.read(models.table())) and not models.claim(s, text, not shell and bool(names[0])):
sys.stderr.write(say(NOPICK))
text = command if shell else next((n for n in names if n and isinstance(n, str)), "") # tool_input.model may be a short name: a segment
table_text = store.read(models.table())
if tool != "workflow" and models.usable(table_text) and not models.claim(s, text, not shell and bool(names[0])):
unknown = not shell and text.strip() and not models.known(table_text, text)
unknown and models.stale(text)
sys.stderr.write(say(UNKNOWN if unknown else NOPICK))
return 2
s["delegations_since"] = s.get("delegations_since", 0) + 1
s.pop("paused", None)
@@ -199,19 +199,22 @@ def gate(p, for_subagent=False):
_begin(s, cwd)
if s.get("worker"):
return 0
reason = " ".join("sisi: " + LATE % (w, time.strftime("%H:%M", time.localtime(t))) for w, t in models.overdue(s))
reason, demand = " ".join("sisi: " + LATE % (w, time.strftime("%H:%M", time.localtime(t))) for w, t in models.overdue(s)), False
if not reason and not s.get("paused"):
checks = (s.get("done") or {}).get("checks") or []
unsaid = ["%d. %s" % (i, c["text"]) for i, c in enumerate(checks, 1) if not c["verdict"]]
failed = [str(i) for i, c in enumerate(checks, 1) if c["verdict"] == "fail"]
worked = s.get("changed") or store.snapshot(cwd) != s.get("snapshot")
if checks and not unsaid and not failed and not worked:
quick = 0 <= time.time() - s.get("began", 0) < 60 * store.config()["retro_minutes"] and not s.get("delegations_since") and not s.get("fails_since")
if checks and not unsaid and not failed and (not worked or quick):
from . import retro
retro.record(s, cwd, {}) # every check passed and nothing changed: the work closes itself
retro.record(s, cwd, {}, sid) # every check passed and nothing changed, or it was quick and alone: the work closes itself
return 0
reason = OPEN % "; ".join(unsaid) if unsaid else GATE if worked else FAILED % ", ".join(failed) if failed else ""
reason = "" if unsaid and models.waiting(s) else OPEN % "; ".join(unsaid) if unsaid else GATE if worked else FAILED % ", ".join(failed) if failed else ""
demand = bool(reason and not unsaid)
if not reason or s.get("blocks", 0) >= 2:
return 0
s["blocks"] = s.get("blocks", 0) + 1
demand and s.setdefault("retro_demanded", time.time())
print(json.dumps({"decision": "block", "reason": say(reason)}))
return 0
+4 -5
View File
@@ -142,9 +142,7 @@ def _rulebook(h, d, book, mode):
_save(target, block + text)
found = True
elif found and mode != "check":
new = BLOCK.sub(lambda m: block, text, count=1)
if new != text:
_save(target, new)
(new := BLOCK.sub(lambda m: block, text, count=1)) != text and _save(target, new)
if not found:
return "MISSING (run `sisi install`)"
return "imported" if h.get("import") else "in a marked block"
@@ -308,8 +306,9 @@ def doctor(cwd=None):
print("release in use: %s" % (os.path.realpath(_current()) if os.path.lexists(_current()) else "none: run `sisi release`"))
print("your store: %s" % store.DATA)
print("rulebook: %d lines, %d characters" % (len(book.splitlines()), len(book)))
print("learned rules: %d for all projects, %d for this one" % (
len(rules.lines(rules.path(rules.USER))), len(rules.lines(rules.path(rules.PROJECT, cwd)))))
proj_n = len(rules.scope_lines(rules.PROJECT, cwd, migrate=False))
print("learned rules: %d for all projects, %d for this one%s" % (len(rules.lines(rules.path(rules.USER))), proj_n, " (waiting to be moved from store)" if os.path.isfile(rules._legacy(cwd)) else ""))
proj_n and print("project note: %s" % rules.note(cwd, write=False))
print("models table: %s" % ("none yet" if age is None else "%d days old" % age))
print("sisi on PATH: %s" % (shutil.which("sisi") or "no: add ~/.local/bin to PATH (`sisi install` links it there)"))
for h in _table():
+50 -32
View File
@@ -47,8 +47,7 @@ ASK = ("In the background, give the output of `sisi models research` to a resear
"answer with `sisi models research --record FILE`.")
def table():
return store.data("models.md")
def table(): return store.data("models.md")
def age_days():
@@ -58,12 +57,18 @@ def age_days():
return None
def stale():
"""One line when the table is missing or old, else ""."""
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
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
return ""
return ("sisi: a delegation named `%s`, which the models table does not list. " % who + ASK) if who and not known(store.read(table()), who) else ""
KEYS = ("worker", "how", "use", "cost", "good", "notes", "maker") # a column is known by its header's first word
@@ -83,13 +88,10 @@ def rows(text):
return out
def usable(text):
return any(re.search(r"routine|ordinary|hard", r[2].lower()) for r in rows(text))
def usable(text): return any(re.search(r"routine|ordinary|hard", r[2].lower()) for r in rows(text))
def short(cell):
w = str(cell).split()
return w[0].lower() if w else ""
def short(cell): return (str(cell).split() or [""])[0].lower()
def maker(r):
@@ -99,9 +101,7 @@ def maker(r):
return r[6].lower() or (m.group() if "/" in name and m else r[1].lower().replace(name, "") or name)
def command(row):
"""A row that is called by a shell command line (it has <brief> in it, and is not a host subagent)."""
return "<brief>" in row[1] and "host subagent" not in row[1].lower()
def command(row): return "<brief>" in row[1] and "host subagent" not in row[1].lower()
def is_call(command_line):
@@ -116,12 +116,15 @@ def is_call(command_line):
return False
def known(table_text, text): return claim({"picked": [short(r[0]) for r in rows(table_text)]}, text, True)
def claim(s, text, segment=False):
"""Spend the pick that this delegation's model text names; False when none of the picks fits. With `segment` (the
host names its models shortly: `fast` for `maker-fast-2`) one whole `-` segment of a picked id's last `/` part that has a letter fits."""
for name in s.get("picked") or []:
if any(re.search(r"(?<![a-z0-9.-])%s(?![a-z0-9.-])" % re.escape(n), text.lower()) for n in (name, name.rsplit("/", 1)[-1])) or (
segment and re.search("[a-z]", text) and text.lower() in name.rsplit("/", 1)[-1].split("-")):
segment and re.search("[a-z]", text.lower()) and text.lower() in name.rsplit("/", 1)[-1].split("-")):
s["picked"].remove(name)
starts = s["starts"] if isinstance(s.get("starts"), dict) else {}
starts[name] = (starts[name] if isinstance(starts.get(name), list) else []) + [time.time()]
@@ -138,6 +141,11 @@ def overdue(s):
return [(w, min(old(v))) for w, v in (starts.items() if isinstance(starts, dict) and type(mins) in (int, float) else []) if old(v)]
def waiting(s):
"""A delegation of this piece of work is open: started and not yet judged."""
return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values())
def out(r, skip, bad, today):
"""Why this worker is off the wheel, "" when it is on."""
until = [d for d in re.findall(r"out until (\d{4}-\d{2}-\d{2})", " ".join(r).lower()) if d > today]
@@ -155,7 +163,7 @@ def speeds():
out = {}
for o in store.records("outcomes.jsonl"):
if o.get("verdict") == "good" and type(o.get("minutes")) is int and 0 < o["minutes"] <= 10000 and isinstance(o.get("worker"), str):
out.setdefault(short(o["worker"]), []).append(o["minutes"])
out.setdefault(short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), []).append(o["minutes"])
return {w: v[-10:] for w, v in out.items()}
@@ -253,8 +261,9 @@ def research_record(answer_file):
if len(lines) > 42 or len(text) > 12000:
return "the answer is too long (at most 40 rows and 12,000 characters)"
store.write(table(), text + "\n")
store.commit("models table researched", table())
print("models table recorded: %d workers." % (len(lines) - 2))
os.path.isfile(store.data("models.stale")) and os.remove(store.data("models.stale"))
ok = store.commit("models table researched", table())
print("models table recorded: %d workers.%s" % (len(lines) - 2, "" if ok else " (store commit failed)"))
return None
@@ -270,21 +279,33 @@ def judge(args, cwd=None):
if len(args) != 3 or not args[0].strip() or args[1] not in ("good", "bad") or len(args[2].split()) < 3 or minutes == 0:
print('usage: sisi judge WORKER good|bad "<what it did well or badly, in a sentence>" [--minutes N] [--newest]')
return 1
sid = store.current_session(cwd)
trows = rows(store.read(table()))
hits = [r for r in trows if short(r[0]) == short(args[0])] or [r for r in trows if claim({"picked": [short(r[0])]}, args[0], True)]
model = (hits[0][0].split() or [""])[0] if len(hits) == 1 else args[0]
sid, now, began = store.current_session(cwd), time.time(), None
if sid:
with store.session(sid) as s:
starts = s["starts"].get(short(args[0])) if isinstance(s.get("starts"), dict) else None
starts = s["starts"].get(short(model)) if isinstance(s.get("starts"), dict) else None
if isinstance(starts, list) and starts:
began = starts.pop(-1 if newest else 0) # one start per open job, oldest first
if type(began) in (int, float) and math.isfinite(began) and began <= time.time(): # else dropped, times nothing
minutes = minutes or max(1, int((time.time() - began) / 60))
cand = starts.pop(-1 if newest else 0) # one start per open job, oldest first
if type(cand) in (int, float) and math.isfinite(cand) and cand <= now: # else dropped, times nothing
began = cand
minutes = minutes or max(1, int((now - began) / 60))
note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(starts))
iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t))
rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1],
"why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)),
"project_key": store.project_key(cwd)}
if sid:
rec["session_id"] = sid
if began is not None:
rec["started"] = iso(began)
if minutes:
rec["minutes"] = minutes
log = store.data("outcomes.jsonl")
store.append(log, json.dumps(dict({"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "worker": args[0], "verdict": args[1],
"why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd))},
**{"minutes": minutes} if minutes else {}), sort_keys=True))
store.commit("delegation judged", log)
print("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.")
store.append(log, json.dumps(rec, sort_keys=True))
ok = store.commit("delegation judged", log)
print("%s%s" % ("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.", "" if ok else " (store commit failed)"))
return 0
@@ -301,12 +322,9 @@ def run(args, cwd=None):
print("\n" + stale())
return 0
if args == ["research"]:
print(research_brief())
return 0
return print(research_brief()) or 0
if len(args) == 3 and args[:2] == ["research", "--record"]:
why = research_record(args[2])
if why:
print("sisi models: %s. Nothing was changed." % why)
return 1 if why else 0
return (print("sisi models: %s. Nothing was changed." % why) or 1) if why else 0
print("usage: sisi models | sisi models research [--record FILE]")
return 1
+20 -10
View File
@@ -1,6 +1,6 @@
"""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, os, re, time
import 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 ...] \\
@@ -95,19 +95,25 @@ def report(sid, cwd):
print("\n" + "\n".join(trend()))
def record(s, cwd, opt):
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 = s.get("done") or {}, time.time()
entry = dict(opt, ts=time.strftime("%Y-%m-%dT%H:%M:%S"), project=os.path.basename(store.project_root(cwd)),
unit=counts(s, cwd), goal=d.get("goal", ""), workers=s.get("workers_since", []))
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", []))
if d:
entry["done"] = d
if sid:
entry["session_id"] = sid
if type(dem) in (int, float) and math.isfinite(dem) and dem <= now:
entry["retro_seconds"] = max(0, int(round(now - dem)))
log = store.data("retro.jsonl")
store.append(log, json.dumps(entry, sort_keys=True))
store.commit("retro recorded", log)
if not store.commit("retro recorded", log):
print("sisi: retro saved, but store git commit failed.")
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"):
"fails_since", "picked", "starts", "retro_demanded", "began"):
s.pop(key, None)
@@ -193,12 +199,16 @@ def run(args, cwd=None):
if kind == "later":
s["paused"] = True
else:
record(s, cwd, opt)
record(s, cwd, opt, sid)
elif kind != "later":
record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt)
if kind == "gap":
print("recorded. In force from the next session%s: %s" % (
" in every project" if scope == rules.USER else " in this project", rules.add(opt["improve"], scope, "retro", cwd)))
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))
except OSError as e:
print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e))
if rules.due(cwd):
print(rules.due(cwd))
else:
+241 -49
View File
@@ -1,8 +1,8 @@
"""Learned rules: what retros and the person add to the instructions.
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 are printed when a session starts there.
Now and then a cheap worker audits and organizes them. Every change is one commit and can be undone."""
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 json, os, re, time
from . import store
@@ -48,30 +48,156 @@ Answer with exactly this shape and nothing else:
def path(scope, cwd=None):
if scope == USER:
return store.data("rules", "user.md")
return store.data("rules", "projects", store.project_key(cwd) + ".md")
"""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")
def _legacy(cwd=None):
return os.path.join(store.DATA, "rules", "projects", store.project_key(cwd) + ".md")
def _parse(text):
return [l.rstrip() for l in text.lstrip("\ufeff").splitlines() if l.startswith("- ")]
def lines(p):
return [l.rstrip() for l in store.read(p).splitlines() if l.startswith("- ")]
return _parse(store.read(p))
def add(text, scope, source, cwd=None):
"""Put one rule in force. `source` is "owner" for the person's own words, "retro" for a retro's finding."""
p = path(scope, cwd)
line = "- %s [%s %s]" % (" ".join(str(text).split()), source, time.strftime("%Y-%m-%d"))
store.append(p, line)
store.commit("rule added (%s, %s)" % (scope, source), p)
def _text(p):
"""What a regular file holds now, None when absent; OSError when unusable or not UTF-8."""
why, raw = store.regular(p, True)
if why:
raise OSError("%s is %s" % (p, why))
try:
return None if raw is None else raw.decode("utf-8")
except UnicodeDecodeError:
raise OSError(".sisi/rules.md is not valid UTF-8")
def _append(text, new):
return (text or "") + ("\n" if text and not text.endswith("\n") else "") + "".join(l + "\n" for l in new)
def _check_writable(p):
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)):
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:
raise OSError("%s is %s" % (label, why))
if not os.path.exists(os.path.dirname(p)) and not os.access(os.path.dirname(os.path.dirname(p)), os.W_OK):
raise OSError("the project folder cannot be written")
def note(where, write=True):
"""Keep one marked note in `AGENTS.md` (write=True), or report whether it is there (write=False)."""
root = os.path.dirname(os.path.dirname(where if write else path(PROJECT, where))) or where
target, _, why = store.agents_target(root)
try:
if not target:
raise OSError(why)
if write and os.path.exists(target) and not (os.stat(target).st_mode & 0o200):
raise OSError("it is read-only")
text = _text(target) or ""
if not write:
return "in AGENTS.md" if store.NOTE_RE.search(text) else "missing from AGENTS.md"
if not store.NOTE_RE.search(text):
nl = "\r\n" if "\r\n" in text else "\n"
sep = "" if not text or text.endswith(nl * 2) else nl if text.endswith(nl) else nl * 2
store.write(target, "%s%s<!-- sisi:begin -->%s%s%s<!-- sisi:end -->%s" % (text, sep, nl, store.NOTE, nl, nl))
except OSError as e:
why = "it is not valid UTF-8" if "UTF-8" in str(e) else str(e)
return print("sisi: could not add the rules note to %s (%s)." % (os.path.join(root, "AGENTS.md"), why)) if write else "missing (%s)" % why
def _move(dest, old):
"""Move the store's old file into `.sisi/rules.md` under the project lock. Returns a warning, or ""."""
if not os.path.isfile(old):
return ""
raw = store.read(old)
try:
_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):
raise OSError("could not commit store")
extra and store.write(dest, _append(before, extra))
(extra or _parse(raw)) and note(dest)
os.remove(old)
if not store.commit("project rules moved to .sisi/rules.md", old):
raise OSError("could not commit store")
except OSError as e:
not os.path.exists(old) and store.write(old, raw)
return "sisi: could not move this project's rules to %s (%s); keeping the copy in your store." % (dest, e)
return ""
def _migrate(cwd=None, wait=True):
"""Move this project's rules out of the store if an old file exists. Returns (rules, warning)."""
dest, old = path(PROJECT, cwd), _legacy(cwd)
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):
with store.lock(dest, wait=wait) as ok:
msg = _move(dest, old) if ok else ""
return scope_lines(PROJECT, cwd, migrate=False), msg
def scope_lines(scope, cwd=None, migrate=True):
if scope == USER:
build_rulebook()
return line
return lines(path(USER))
if migrate:
return _migrate(cwd)[0]
dest, old = path(PROJECT, cwd), _legacy(cwd)
raw = store.regular(dest, True)[1] if dest and not os.path.islink(os.path.dirname(dest)) else None
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
def delivered(p):
"""The newest rules that fit the budget, oldest first. The rest wait for organizing."""
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")
def add(text, scope, source, cwd=None, log=None):
"""Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written."""
line = "- %s [%s %s]" % (" ".join(str(text).split()), source, time.strftime("%Y-%m-%d"))
dest = path(scope, cwd)
scope == PROJECT and not dest and _check_writable(dest)
with store.lock(dest if scope == PROJECT else "user"):
if scope == USER:
store.append(dest, line)
else:
_check_writable(dest)
msg = _move(dest, _legacy(cwd))
msg and print(msg)
before = _text(dest)
after = _append(before, [line])
store.write(dest, after)
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 = ""
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()
return line, warn
def _fit(ls):
cfg, out, chars = store.config(), [], 0
for line in reversed(lines(p)):
for line in reversed(ls):
if len(out) >= cfg["rules_lines"] or chars + len(line) > cfg["rules_chars"]:
break
out.append(line)
@@ -79,6 +205,11 @@ def delivered(p):
return out[::-1]
def delivered(p):
"""The newest rules that fit the budget, oldest first. The rest wait for organizing."""
return _fit(lines(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"
@@ -96,8 +227,9 @@ def build_rulebook():
def project_text(cwd):
mine = delivered(path(PROJECT, cwd))
return HEAD_PROJECT + "\n" + "\n".join(mine) if mine else ""
ls, note = _migrate(cwd, wait=False)
mine = _fit(ls)
return "\n".join(x for x in (note, HEAD_PROJECT + "\n" + "\n".join(mine) if mine else "") if x)
def objective():
@@ -112,14 +244,18 @@ def _organized():
return {}
def _mark_key(scope, cwd=None):
return "rules/user.md" if scope == USER else os.path.realpath(path(PROJECT, cwd))
def due(cwd):
"""One line when the learned rules need organizing, else ""."""
cfg, seen, why = store.config(), _organized(), []
for scope in (USER, PROJECT):
p = path(scope, cwd)
ls = lines(p)
ls, k = 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"]
added = len(ls) - int(seen.get(os.path.relpath(p, store.DATA), 0))
added = len(ls) - prev
if over or added >= cfg["organize_after"]:
why.append("%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % added))
if not why:
@@ -135,7 +271,7 @@ def organize_brief(cwd):
"name": os.path.basename(store.project_root(cwd)), "objective": objective(),
"lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
"user": "\n".join(lines(path(USER))) or "(none)",
"project": "\n".join(lines(path(PROJECT, cwd))) or "(none)",
"project": "\n".join(scope_lines(PROJECT, cwd)) or "(none)",
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)"}
@@ -147,37 +283,89 @@ def organize_record(answer_file, cwd):
for i in range(1, len(parts) - 1, 2)}
if set(got) != {USER, PROJECT}:
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
had = {scope: lines(path(scope, cwd)) for scope in got}
if not any(got.values()) and any(had.values()):
return "the answer holds no rules at all"
for scope, ls in got.items():
if len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > 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(ls), sum(map(len, ls)))
seen, changed = _organized(), []
for scope, ls in got.items():
p = path(scope, cwd)
store.write(p, "".join(l + "\n" for l in ls))
seen[os.path.relpath(p, store.DATA)] = len(ls)
changed.append(p)
print("%s rules: %d lines (were %d)" % (scope, len(ls), len(had[scope])))
marks = store.data("rules", "organized.json")
store.write(marks, json.dumps(seen))
store.commit("rules organized", marks, *changed)
up, pp = path(USER), path(PROJECT, cwd)
if 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))
if msg:
return msg.removeprefix("sisi: ")
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
if not any(got.values()) 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(got[USER]), _mark_key(PROJECT, cwd): len(got[PROJECT])})
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
marks = store.data("rules", "organized.json")
store.write(marks, json.dumps(seen))
_commit("rules organized", marks, up, snap=(pp, before, after))
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
build_rulebook()
for scope in (USER, PROJECT):
print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope])))
return None
def revert():
"""Undo the last change to the learned rules. Returns why not, or None when it is done."""
rc, out = store.git(["log", "-1", "--format=%H %s", "--", "rules"], store.DATA)
"""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")
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
rc, out = store.git(["log", "-1", "--format=%H %s", "--name-only", "--", *files], store.DATA)
if rc != 0 or not out.strip():
return "there is no change to the learned rules to undo"
commit, _, subject = out.strip().partition(" ")
rc, _ = store.git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "revert", "--no-edit", commit], store.DATA)
if rc != 0:
store.git(["revert", "--abort"], store.DATA)
return "could not undo `%s`" % subject
(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)
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"):
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:
cur = p and _text(p)
if p and (cur != now or not os.path.isdir(os.path.dirname(os.path.dirname(p)))):
return "%s has changed since `%s`, or its folder moved or is gone, so that change cannot be undone%s" % (p, subject, advice)
p and _check_writable(p)
p and (os.remove(p) if want is None and cur is not None else want != cur and store.write(p, want))
except OSError as e:
return "could not restore %s (%s)%s" % (p, e, advice)
if store.git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "revert", "--no-edit", commit], store.DATA)[0]:
store.git(["revert", "--abort"], store.DATA)
p and want != cur and (store.write(p, cur) if cur is not None else os.path.lexists(p) and os.remove(p))
return "could not undo `%s`%s" % (subject, advice)
build_rulebook()
print("undone: %s" % subject)
return None
@@ -185,8 +373,9 @@ def revert():
def show(cwd):
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
for scope, title in ((USER, "Learned, all projects"), (PROJECT, "Learned, this project")):
ls = lines(path(scope, cwd))
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)"))
if due(cwd):
print("\n" + due(cwd))
@@ -218,8 +407,11 @@ def learn(args, cwd=None):
if len(text.split()) < 3:
print('usage: sisi learn [--project] "<what the person said, in their words>"')
return 1
log = store.data("rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
store.append(log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split())))
store.commit("the person's words", log)
print("in force from the next session: %s" % add(text, scope, "owner", cwd))
log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
try:
line, warn = add(text, scope, "owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split()))))
except OSError as e:
print("sisi learn: could not write %s (%s). Nothing was changed, and your words were not kept." % (path(scope, cwd) or cwd or os.getcwd(), e))
return 1
print(warn or "in force from the next session: %s" % line)
return 0
+84 -20
View File
@@ -2,10 +2,12 @@
Three places: the product (this copy, never written at run time), the person's store (learned rules, the
models table, the retro log; a git repository, so every change can be undone), and scratch (session state)."""
import contextlib, fcntl, hashlib, json, os, stat, subprocess
import contextlib, fcntl, hashlib, json, os, re, stat, subprocess
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
HOME = os.path.expanduser("~")
NOTE = "This project's learned rules are in `.sisi/rules.md`. Read that file before any work here and follow it."
NOTE_RE = re.compile(r"^<!-- sisi:begin -->\r?\n" + re.escape(NOTE) + r"\r?\n<!-- sisi:end -->(?:\r?\n|$)", re.M)
def _where(own, xdg, fallback):
"""The folder in the environment variable `own`, else `xdg`/sisi, else the default under the home."""
base = os.environ.get(xdg)
@@ -19,7 +21,7 @@ LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi")
# Every setting there is. The person overrides one under "core" in config.json in their store.
DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8,
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False,
"worker_minutes": 15}
"worker_minutes": 15, "retro_minutes": 5}
def config():
@@ -61,13 +63,16 @@ def records(name):
def write(path, text):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = "%s.%d.tmp" % (path, os.getpid())
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
try:
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode)) # a rewritten file keeps its permissions
except OSError:
pass
os.replace(tmp, path)
with open(tmp, "w", encoding="utf-8", newline="") as f:
f.write(text)
with contextlib.suppress(OSError):
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode)) # a rewritten file keeps its permissions
os.replace(tmp, path)
except BaseException:
with contextlib.suppress(OSError):
os.remove(tmp)
raise
def append(path, line):
@@ -87,18 +92,36 @@ def git(args, cwd, timeout=15):
def commit(message, *paths):
"""One commit in the person's store holding only these paths, so the change can be undone on its own."""
if not os.path.isdir(os.path.join(DATA, ".git")):
git(["init", "-q"], DATA)
rel = [os.path.relpath(p, DATA) for p in paths]
git(["add", "--"] + rel, DATA)
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)
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]
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))
_roots = {}
def root(cwd=None):
"""(project root, inside a git directory or bare repository). In git the root is the main checkout's, shared by
its worktrees; when git cannot answer, the nearest folder holding `.git`; outside git, the folder itself."""
cwd = os.path.abspath(cwd or os.getcwd())
if cwd not in _roots:
rc, out = git(["rev-parse", "--path-format=absolute", "--is-inside-git-dir", "--git-common-dir", "--show-toplevel"], cwd)
inside, common, top = (out.splitlines() + ["", "", ""])[:3]
cur = cwd
while rc and inside != "true" and not os.path.lexists(os.path.join(cur, ".git")) and cur != os.path.dirname(cur):
bare = os.path.basename(cur) == ".git" or all(os.path.exists(os.path.join(cur, n)) for n in ("HEAD", "objects", "refs"))
inside, cur = ("true", cur) if bare else ("", os.path.dirname(cur))
top = os.path.dirname(common) if os.path.basename(common) == ".git" else top if rc == 0 else cur if os.path.lexists(os.path.join(cur, ".git")) else cwd
_roots[cwd] = (cwd, True) if inside == "true" else (top, False)
return _roots[cwd]
def project_root(cwd=None):
"""The project a folder belongs to. Every checkout of one repository is the same project."""
cwd = cwd or os.getcwd()
rc, out = git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
return os.path.dirname(out.strip()) if rc == 0 and os.path.basename(out.strip()) == ".git" else os.path.abspath(cwd)
return root(cwd)[0]
def project_key(cwd=None):
@@ -106,13 +129,42 @@ def project_key(cwd=None):
return "%s-%s" % (os.path.basename(root) or "root", hashlib.sha1(root.encode()).hexdigest()[:8])
def regular(path, load=False):
"""("", bytes|None) if `path` is absent or a regular non-link file within 64,000 bytes, else (reason, None)."""
try:
st = os.lstat(path)
why = "a symlink" if stat.S_ISLNK(st.st_mode) else "not a regular file" if not stat.S_ISREG(st.st_mode) else "over 64,000 bytes" if st.st_size > 64000 else ""
if why or not load:
return why, None
with open(path, "rb") as f:
return ("", raw) if len(raw := f.read(64001)) <= 64000 else ("over 64,000 bytes", None)
except (FileNotFoundError, NotADirectoryError):
return "", None
def agents_target(root):
"""(real_path, rel_path, "") for `root/AGENTS.md` when safe, else (None, "", reason)."""
agents, real_root = os.path.join(root, "AGENTS.md"), os.path.realpath(root)
real, link = os.path.realpath(agents) if os.path.islink(agents) else os.path.join(real_root, "AGENTS.md"), os.path.islink(agents)
rel = os.path.relpath(real, real_root) if link else "AGENTS.md"
why = ("it is a dangling symlink" if link and not os.path.exists(agents) else "it is a directory" if os.path.isdir(agents)
else "it is a symlink outside the project" if link and os.path.commonpath([real_root, real]) != real_root
else "it is a symlink into " + rel.split(os.sep)[0] if link and rel.split(os.sep)[0] in (".git", ".sisi")
else "it is " + issue if (issue := regular(real if link else agents)[0]) else "")
return (None, "", why) if why else (real, rel, "")
def snapshot(cwd):
"""A fingerprint of the working tree: the commit, what is uncommitted, what is untracked. "" outside git."""
rc, status = git(["status", "--porcelain"], cwd)
if rc != 0:
rc, out = git(["rev-parse", "--path-format=absolute", "--show-toplevel", "HEAD"], cwd)
top = (out.splitlines() or [""])[0]
if not top:
return ""
head, diff = git(["rev-parse", "HEAD"], cwd)[1], git(["diff", "HEAD"], cwd)[1]
return hashlib.sha1((head + status + diff).encode()).hexdigest()[:16]
real, rel, _ = agents_target(top)
spec = ["--", ":(top)", ":(top,exclude).sisi"] + ([":(top,exclude)" + rel] if rel else [])
head, status, diff = (out if rc == 0 else ""), git(["status", "--porcelain"] + spec, cwd)[1], git(["diff", "HEAD"] + spec, cwd)[1]
body = NOTE_RE.sub("", (regular(real, True)[1] or b"").decode("utf-8", "replace") if real else "").rstrip("\r\n")
return hashlib.sha1((head + status + diff + "\0" + body).encode()).hexdigest()[:16]
def _session_path(sid):
@@ -134,6 +186,18 @@ def session(sid):
write(path, json.dumps(state))
@contextlib.contextmanager
def lock(key, wait=True):
"""Exclusive lock in the store for one project (or user); with wait=False, yields False if busy."""
p, ok = data("locks", "%s-%s.lock" % (os.path.basename(key) or "root", hashlib.sha1(key.encode()).hexdigest()[:8])), True
with open(p, "a") as f:
try:
fcntl.flock(f, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
except BlockingIOError:
ok = False
yield ok
def current_session(cwd=None):
"""The session a command typed by an agent belongs to: the id session start exported, else the most
recently active lead (not worker) session of this project. None when there is none (a person at a terminal)."""
+1474 -6
View File
File diff suppressed because it is too large. Load diff