Compare 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
13 changed files with 1570 additions and 111 deletions

No files matched your search

-1
View File
@@ -1,4 +1,3 @@
__pycache__/ __pycache__/
*.pyc *.pyc
.agent-work/ .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 -->
+36 -16
View File
@@ -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 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. nowhere, read-only, hooks of an unexpected shape) is left alone and reported.
| Tool | Rulebook (in its folder) | Hooks | | Tool | Rulebook (in its folder) | Hooks | Project rules |
|---|---|---| |---|---|---|---|
| Claude Code | `~/.claude/CLAUDE.md` | `settings.json` | | 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`) | | 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` | | 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` | | 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, Crush, Amp | their global instructions file | none: not confirmed | | OpenCode, Antigravity (`~/.gemini`), Pi, Kiro, Copilot, Amp | their global instructions file | none: not confirmed | `AGENTS.md` note is in the file the tool reads |
| Muse, Cursor | none documented | not covered | | 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`, 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 `toolCall.name`, …), and the class of each tool call (shell, read, edit, search, web, delegate) comes from
@@ -78,20 +80,38 @@ 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 --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) |
| `sisi retro --later …` | The work is not finished yet | | `sisi retro --later …` | The work is not finished yet |
| `sisi learn [--project] "…"` | The person's own words become a rule at once | | `sisi learn [--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 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 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 | | `sisi direct "…"` | Allow more direct tool calls this turn, with the reason |
## Where things live ## Where things live
- **The product** (this repository): the code in `sisi/`, the rulebook in `canon/core.md`. The same for Rules live at three levels:
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 - **The product** (this repository): the code in `sisi/`, and the rulebook in `canon/core.md` — rules useful to everyone
was learned), `models.md` (your workers), `retro.jsonl` (each piece of work: session, `retro_seconds`, counts, goal, term) using sisi, the same for all users. `SPEC.md` is what it aims at.
and `outcomes.jsonl` (each judged delegation: session, `project_key`, `model`, `started`/`ended`, minutes, verdict, why). All plain - **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md`
text you can read and edit. (how you like to work, across all your projects), `models.md` (your workers), `retro.jsonl` (each piece of work: session,
- **The rulebook every session loads** is generated from the two: `canon/core.md`, then your learned rules. `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`. - **Scratch** (session state, bytecode): `$SISI_STATE`, else `$XDG_STATE_HOME/sisi`, else `~/.local/state/sisi`.
Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`. Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`.
+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 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 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 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 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 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. 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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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."} {"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 the learned rules in force here
sisi rules organize [--record FILE] sisi rules organize [--record FILE]
the brief for a cheap worker to audit and organize them; record its answer the brief for a cheap worker to audit and organize them; record its answer
sisi rules revert undo the last 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 Delegation
sisi models the workers you have: what each is good at and what it costs sisi models the workers you have: what each is good at and what it costs
@@ -39,9 +40,10 @@ Setting up
Hooks (the agent tool calls these): sisi tick | prompt | watch | gate 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, 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): def main(argv):
+4 -5
View File
@@ -142,9 +142,7 @@ def _rulebook(h, d, book, mode):
_save(target, block + text) _save(target, block + text)
found = True found = True
elif found and mode != "check": elif found and mode != "check":
new = BLOCK.sub(lambda m: block, text, count=1) (new := BLOCK.sub(lambda m: block, text, count=1)) != text and _save(target, new)
if new != text:
_save(target, new)
if not found: if not found:
return "MISSING (run `sisi install`)" return "MISSING (run `sisi install`)"
return "imported" if h.get("import") else "in a marked block" 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("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("your store: %s" % store.DATA)
print("rulebook: %d lines, %d characters" % (len(book.splitlines()), len(book))) print("rulebook: %d lines, %d characters" % (len(book.splitlines()), len(book)))
print("learned rules: %d for all projects, %d for this one" % ( proj_n = len(rules.scope_lines(rules.PROJECT, cwd, migrate=False))
len(rules.lines(rules.path(rules.USER))), len(rules.lines(rules.path(rules.PROJECT, cwd))))) 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("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)")) print("sisi on PATH: %s" % (shutil.which("sisi") or "no: add ~/.local/bin to PATH (`sisi install` links it there)"))
for h in _table(): for h in _table():
+4 -4
View File
@@ -262,8 +262,8 @@ def research_record(answer_file):
return "the answer is too long (at most 40 rows and 12,000 characters)" return "the answer is too long (at most 40 rows and 12,000 characters)"
store.write(table(), text + "\n") store.write(table(), text + "\n")
os.path.isfile(store.data("models.stale")) and os.remove(store.data("models.stale")) os.path.isfile(store.data("models.stale")) and os.remove(store.data("models.stale"))
store.commit("models table researched", table()) ok = store.commit("models table researched", table())
print("models table recorded: %d workers." % (len(lines) - 2)) print("models table recorded: %d workers.%s" % (len(lines) - 2, "" if ok else " (store commit failed)"))
return None return None
@@ -304,8 +304,8 @@ def judge(args, cwd=None):
rec["minutes"] = minutes rec["minutes"] = minutes
log = store.data("outcomes.jsonl") log = store.data("outcomes.jsonl")
store.append(log, json.dumps(rec, sort_keys=True)) store.append(log, json.dumps(rec, sort_keys=True))
store.commit("delegation judged", log) ok = store.commit("delegation judged", log)
print("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.") print("%s%s" % ("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.", "" if ok else " (store commit failed)"))
return 0 return 0
+8 -3
View File
@@ -109,7 +109,8 @@ def record(s, cwd, opt, sid=None):
entry["retro_seconds"] = max(0, int(round(now - dem))) entry["retro_seconds"] = max(0, int(round(now - dem)))
log = store.data("retro.jsonl") log = store.data("retro.jsonl")
store.append(log, json.dumps(entry, sort_keys=True)) store.append(log, json.dumps(entry, sort_keys=True))
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 s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now
for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused", for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused",
"fails_since", "picked", "starts", "retro_demanded", "began"): "fails_since", "picked", "starts", "retro_demanded", "began"):
@@ -202,8 +203,12 @@ def run(args, cwd=None):
elif kind != "later": elif kind != "later":
record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt) record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt)
if kind == "gap": if kind == "gap":
print("recorded. In force from the next session%s: %s" % ( try:
" in every project" if scope == rules.USER else " in this project", rules.add(opt["improve"], scope, "retro", cwd))) 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): if rules.due(cwd):
print(rules.due(cwd)) print(rules.due(cwd))
else: else:
+241 -49
View File
@@ -1,8 +1,8 @@
"""Learned rules: what retros and the person add to the instructions. """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 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. 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. Every change is one commit and can be undone.""" Now and then a cheap worker audits and organizes them. Store changes are committed and can be undone."""
import json, os, re, time import json, os, re, time
from . import store from . import store
@@ -48,30 +48,156 @@ Answer with exactly this shape and nothing else:
def path(scope, cwd=None): def path(scope, cwd=None):
if scope == USER: """Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept."""
return store.data("rules", "user.md") top, inside = store.root(cwd) if scope == PROJECT else ("", False)
return store.data("rules", "projects", store.project_key(cwd) + ".md") 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): 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): def _text(p):
"""Put one rule in force. `source` is "owner" for the person's own words, "retro" for a retro's finding.""" """What a regular file holds now, None when absent; OSError when unusable or not UTF-8."""
p = path(scope, cwd) why, raw = store.regular(p, True)
line = "- %s [%s %s]" % (" ".join(str(text).split()), source, time.strftime("%Y-%m-%d")) if why:
store.append(p, line) raise OSError("%s is %s" % (p, why))
store.commit("rule added (%s, %s)" % (scope, source), 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")
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: if scope == USER:
build_rulebook() return lines(path(USER))
return line 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): def _commit(msg, *paths, snap=None):
"""The newest rules that fit the budget, oldest first. The rest wait for organizing.""" 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 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"]: if len(out) >= cfg["rules_lines"] or chars + len(line) > cfg["rules_chars"]:
break break
out.append(line) out.append(line)
@@ -79,6 +205,11 @@ def delivered(p):
return out[::-1] 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(): def build_rulebook():
"""Write the always-loaded instructions: the product's rulebook, then the person's learned rules.""" """Write the always-loaded instructions: the product's rulebook, then the person's learned rules."""
text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n" text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n"
@@ -96,8 +227,9 @@ def build_rulebook():
def project_text(cwd): def project_text(cwd):
mine = delivered(path(PROJECT, cwd)) ls, note = _migrate(cwd, wait=False)
return HEAD_PROJECT + "\n" + "\n".join(mine) if mine else "" mine = _fit(ls)
return "\n".join(x for x in (note, HEAD_PROJECT + "\n" + "\n".join(mine) if mine else "") if x)
def objective(): def objective():
@@ -112,14 +244,18 @@ def _organized():
return {} return {}
def _mark_key(scope, cwd=None):
return "rules/user.md" if scope == USER else os.path.realpath(path(PROJECT, cwd))
def due(cwd): def due(cwd):
"""One line when the learned rules need organizing, else "".""" """One line when the learned rules need organizing, else ""."""
cfg, seen, why = store.config(), _organized(), [] cfg, seen, why = store.config(), _organized(), []
for scope in (USER, PROJECT): for scope in (USER, PROJECT):
p = path(scope, cwd) ls, k = scope_lines(scope, cwd, migrate=False), _mark_key(scope, cwd)
ls = lines(p) prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0))
over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"] over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]
added = len(ls) - int(seen.get(os.path.relpath(p, store.DATA), 0)) added = len(ls) - prev
if over or added >= cfg["organize_after"]: 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)) why.append("%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % added))
if not why: if not why:
@@ -135,7 +271,7 @@ def organize_brief(cwd):
"name": os.path.basename(store.project_root(cwd)), "objective": objective(), "name": os.path.basename(store.project_root(cwd)), "objective": objective(),
"lines": cfg["rules_lines"], "chars": cfg["rules_chars"], "lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
"user": "\n".join(lines(path(USER))) or "(none)", "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)"} "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)} for i in range(1, len(parts) - 1, 2)}
if set(got) != {USER, PROJECT}: if set(got) != {USER, PROJECT}:
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines" return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
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(): for scope, ls in got.items():
if len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]: 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)" % ( 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))) scope, cfg["rules_lines"], cfg["rules_chars"], len(ls), sum(map(len, ls)))
seen, changed = _organized(), [] up, pp = path(USER), path(PROJECT, cwd)
for scope, ls in got.items(): if not pp or os.path.islink(os.path.dirname(pp)):
p = path(scope, cwd) return _migrate(cwd)[1].removeprefix("sisi: ")
store.write(p, "".join(l + "\n" for l in ls)) with store.lock(pp):
seen[os.path.relpath(p, store.DATA)] = len(ls) msg = _move(pp, _legacy(cwd))
changed.append(p) if msg:
print("%s rules: %d lines (were %d)" % (scope, len(ls), len(had[scope]))) return msg.removeprefix("sisi: ")
marks = store.data("rules", "organized.json") had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
store.write(marks, json.dumps(seen)) if not any(got.values()) and any(had.values()):
store.commit("rules organized", marks, *changed) 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() build_rulebook()
for scope in (USER, PROJECT):
print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope])))
return None return None
def revert(): def revert():
"""Undo the last change to the learned rules. Returns why not, or None when it is done.""" """Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left."""
rc, out = store.git(["log", "-1", "--format=%H %s", "--", "rules"], store.DATA) 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(): if rc != 0 or not out.strip():
return "there is no change to the learned rules to undo" return "there is no change to the learned rules to undo"
commit, _, subject = out.strip().partition(" ") (commit, _, subject), changed = out.splitlines()[0].partition(" "), out.splitlines()[1:]
rc, _ = store.git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "revert", "--no-edit", commit], store.DATA) redo = len(re.match(r'(Revert ")*', subject).group(0)) // 8 % 2
if rc != 0: snap = {}
store.git(["revert", "--abort"], store.DATA) if "rules/last-project.json" in changed or "(project," in subject or "organized" in subject:
return "could not undo `%s`" % 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() build_rulebook()
print("undone: %s" % subject) print("undone: %s" % subject)
return None return None
@@ -185,8 +373,9 @@ def revert():
def show(cwd): def show(cwd):
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md")) print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
for scope, title in ((USER, "Learned, all projects"), (PROJECT, "Learned, this project")): proj, note = _migrate(cwd)
ls = lines(path(scope, 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)")) print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(ls) or " (none)"))
if due(cwd): if due(cwd):
print("\n" + due(cwd)) print("\n" + due(cwd))
@@ -218,8 +407,11 @@ def learn(args, cwd=None):
if len(text.split()) < 3: if len(text.split()) < 3:
print('usage: sisi learn [--project] "<what the person said, in their words>"') print('usage: sisi learn [--project] "<what the person said, in their words>"')
return 1 return 1
log = store.data("rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
store.append(log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split()))) try:
store.commit("the person's words", log) line, warn = add(text, scope, "owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split()))))
print("in force from the next session: %s" % add(text, scope, "owner", cwd)) 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 return 0
+83 -19
View File
@@ -2,10 +2,12 @@
Three places: the product (this copy, never written at run time), the person's store (learned rules, the 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).""" 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__))) ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
HOME = os.path.expanduser("~") 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): def _where(own, xdg, fallback):
"""The folder in the environment variable `own`, else `xdg`/sisi, else the default under the home.""" """The folder in the environment variable `own`, else `xdg`/sisi, else the default under the home."""
base = os.environ.get(xdg) base = os.environ.get(xdg)
@@ -61,13 +63,16 @@ def records(name):
def write(path, text): def write(path, text):
os.makedirs(os.path.dirname(path), exist_ok=True) os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = "%s.%d.tmp" % (path, os.getpid()) tmp = "%s.%d.tmp" % (path, os.getpid())
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
try: try:
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode)) # a rewritten file keeps its permissions with open(tmp, "w", encoding="utf-8", newline="") as f:
except OSError: f.write(text)
pass with contextlib.suppress(OSError):
os.replace(tmp, path) 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): def append(path, line):
@@ -87,18 +92,36 @@ def git(args, cwd, timeout=15):
def commit(message, *paths): def commit(message, *paths):
"""One commit in the person's store holding only these paths, so the change can be undone on its own.""" """One commit in the person's store holding only these paths, so the change can be undone on its own."""
if not os.path.isdir(os.path.join(DATA, ".git")): with lock("store"):
git(["init", "-q"], DATA) os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA)
rel = [os.path.relpath(p, DATA) for p in paths] rel = [os.path.relpath(p, DATA) for p in paths]
git(["add", "--"] + rel, DATA) return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA) (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): def project_root(cwd=None):
"""The project a folder belongs to. Every checkout of one repository is the same project.""" """The project a folder belongs to. Every checkout of one repository is the same project."""
cwd = cwd or os.getcwd() return root(cwd)[0]
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)
def project_key(cwd=None): 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]) 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): def snapshot(cwd):
"""A fingerprint of the working tree: the commit, what is uncommitted, what is untracked. "" outside git.""" """A fingerprint of the working tree: the commit, what is uncommitted, what is untracked. "" outside git."""
rc, status = git(["status", "--porcelain"], cwd) rc, out = git(["rev-parse", "--path-format=absolute", "--show-toplevel", "HEAD"], cwd)
if rc != 0: top = (out.splitlines() or [""])[0]
if not top:
return "" return ""
head, diff = git(["rev-parse", "HEAD"], cwd)[1], git(["diff", "HEAD"], cwd)[1] real, rel, _ = agents_target(top)
return hashlib.sha1((head + status + diff).encode()).hexdigest()[:16] 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): def _session_path(sid):
@@ -134,6 +186,18 @@ def session(sid):
write(path, json.dumps(state)) 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): def current_session(cwd=None):
"""The session a command typed by an agent belongs to: the id session start exported, else the most """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).""" recently active lead (not worker) session of this project. None when there is none (a person at a terminal)."""
+1166 -6
View File
File diff suppressed because it is too large. Load diff