Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b6eb37252 | |||
| b9fe2e2bf5 | |||
| c8eeeadd24 | |||
| 66670f4e3d | |||
| 0cc242ac1b | |||
| 60a1f5c385 | |||
| b4b84a4280 | |||
| bc066943f6 | |||
| 7b59056c3d | |||
| 333ebe58b8 | |||
| effe6393c0 | |||
| a55ecc0be6 | |||
| 023e121e1b | |||
| a08da8b266 | |||
| 6520628fef | |||
| 3a3631609c | |||
| e758bf1a91 | |||
| db88211599 |
@@ -1,5 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
|
||||
- To keep Mattermost DMs, move the keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, and name it in the project's config as `env-file`; `mattermost-dm` and loop-claude's DMs no longer read `~/.claude/.env`, and a project with no `env-file` gets none. A failure names each missing key and holds no token.
|
||||
|
||||
## 0.10.0
|
||||
|
||||
- The loop commits each change it makes to a file in the config's folder, such as a plan kept there, in that folder's git repo, titled as it titles its commits in the checkout. rule-hook ranks the plan on such a commit; before, it refused the commit.
|
||||
|
||||
@@ -73,7 +73,7 @@ Then pick a model with `/model`.
|
||||
|
||||
Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt.
|
||||
|
||||
To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude/.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, and run `chmod 600 ~/.claude/.env`. Without that file, loop-claude sends no DM.
|
||||
To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` to the project's config, as Install → "Set up a project" describes. Without that setting, loop-claude sends no DM for the project; `~/.claude/.env` is no longer read.
|
||||
|
||||
### Set up a project
|
||||
|
||||
@@ -94,6 +94,8 @@ goals-and-audience = "checkout:README.md"
|
||||
principles = "~/.claude/principles"
|
||||
```
|
||||
|
||||
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
|
||||
|
||||
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
|
||||
|
||||
```sh
|
||||
@@ -140,14 +142,14 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how.
|
||||
- `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; `~/.claude/.env` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one.
|
||||
- `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; the project's `env-file` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one.
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
|
||||
- `project-config [<setting>]` prints the paths a project's config sets, or the one asked for, and fails naming each setting the config leaves out; Install → "Set up a project" shows a config.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`, by default the one its config names; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, Grep, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
|
||||
- `run-tests [<pytest args>...]` runs this repo's test suite, as Test says.
|
||||
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report.
|
||||
|
||||
@@ -36,7 +36,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
raise
|
||||
if stop.reason:
|
||||
say(stop.reason, effects, stdout=not stop.code)
|
||||
# Every stop but the human's own Ctrl-C and the help is DMed, so a loop left overnight never ends unseen. A loop given no task prints the help.
|
||||
# Every stop but the human's own Ctrl-C and the help is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help.
|
||||
if stop.code != 130 and stop.reason != HELP:
|
||||
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
|
||||
return stop.code
|
||||
|
||||
@@ -34,9 +34,9 @@ interrupts of every loop on the machine. The first answer counts, from either pl
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
Where ~/.claude/.env exists, loop-claude also sends the human each question, each release ready
|
||||
to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are left out:
|
||||
Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
|
||||
Where the project's config sets env-file, loop-claude also sends the human each question, each
|
||||
release ready to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are
|
||||
left out: Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
|
||||
|
||||
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
||||
as bin/loop_state/running_loops.py describes.
|
||||
|
||||
@@ -756,6 +756,23 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
|
||||
def test_sends_the_dm_through_the_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self):
|
||||
checkout = Checkout(self)
|
||||
token = "tok-3f9a1c7e-sentinel"
|
||||
env_file = checkout.home / ".claude-projects" / "proj.env"
|
||||
env_file.write_text(f"MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN={token}\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
env_file.chmod(0o600)
|
||||
with (checkout.home / ".claude-projects" / "proj" / "config.toml").open("a") as config:
|
||||
config.write('env-file = "~/.claude-projects/proj.env"\n')
|
||||
run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")])
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
self.assertIn("could not DM you on Mattermost: cannot reach https://127.0.0.1:1", run.stderr)
|
||||
held = [run.raw_stdout, run.raw_stderr, json.dumps(run.calls), json.dumps(run.starts)]
|
||||
held += [file.read_text(errors="replace") for file in checkout.home.rglob("*") if file.is_file() and file != env_file and not file.is_symlink()]
|
||||
self.assertGreater(len(held), 8, "the walk reached the archive, the state and the transcripts")
|
||||
for text in held:
|
||||
self.assertNotIn(token, text)
|
||||
|
||||
def test_resumes_the_worker_headless_with_the_answer_typed_at_its_terminal_not_with_keys_typed_before_it(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
|
||||
@@ -47,7 +47,7 @@ class Effects:
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
# Sends the human a direct message on Mattermost, as `mattermost-dm` does; a Failure where it could not.
|
||||
# Sends the human a direct message on Mattermost, as `mattermost-dm` does, for the project whose checkout holds the current directory; a Failure where it could not.
|
||||
dm: typing.Callable[[str], Failure | None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: git_repo.Git
|
||||
@@ -85,7 +85,7 @@ def system_effects() -> Effects:
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
dm=lambda text: dm(text, pathlib.Path.home(), http_json),
|
||||
dm=lambda text: dm(text, None, pathlib.Path.home(), http_json),
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
input=input,
|
||||
|
||||
@@ -58,7 +58,6 @@ class Said(unittest.TestCase):
|
||||
self.assertEqual(flushes, [f"{STAMP} hello\n"])
|
||||
|
||||
|
||||
|
||||
class LocalTime(unittest.TestCase):
|
||||
def test_renders_seconds_in_the_machines_zone(self):
|
||||
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from mattermost_dm import dm, main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: dm.read_config(dm.env_file(pathlib.Path.home())), dm.http_json, sys.stderr))
|
||||
sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: dm.config_of(None, pathlib.Path.home()), dm.http_json, sys.stderr))
|
||||
|
||||
+18
-9
@@ -9,6 +9,7 @@ import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
|
||||
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
|
||||
@@ -35,10 +36,6 @@ class Config:
|
||||
recipient: str
|
||||
|
||||
|
||||
def env_file(home: pathlib.Path) -> pathlib.Path:
|
||||
return home / ".claude" / ".env"
|
||||
|
||||
|
||||
def read_config(path: pathlib.Path) -> Config | Failure:
|
||||
"""The server, bot token and recipient that path's KEY=value lines hold."""
|
||||
try:
|
||||
@@ -126,10 +123,22 @@ def error_message(failure: urllib.error.HTTPError) -> str:
|
||||
return message if isinstance(message, str) else ""
|
||||
|
||||
|
||||
def dm(text: str, home: pathlib.Path, http: Http) -> Failure | None:
|
||||
"""Sends text as home's .claude/.env configures it. A machine without that file hasn't asked for DMs, so there the DM is skipped."""
|
||||
path = env_file(home)
|
||||
if not path.exists():
|
||||
def dm(text: str, directory: str | None, home: pathlib.Path, http: Http) -> Failure | None:
|
||||
"""Sends text to the recipient that the project's env file names. The project is the one whose checkout holds directory, and its config names the file.
|
||||
|
||||
The DM is skipped where the config sets no env-file, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no file to read the recipient from."""
|
||||
project = located(directory, home)
|
||||
if isinstance(project, Failure) or project.env_file is None:
|
||||
return None
|
||||
config = read_config(path)
|
||||
config = read_config(project.env_file)
|
||||
return config if isinstance(config, Failure) else send(config, text, http)
|
||||
|
||||
|
||||
def config_of(directory: str | None, home: pathlib.Path) -> Config | Failure:
|
||||
"""The server, token and recipient in the env file that the config of the project holding directory names."""
|
||||
project = located(directory, home)
|
||||
if isinstance(project, Failure):
|
||||
return project
|
||||
if project.env_file is None:
|
||||
return Failure(f"{project.folder / 'config.toml'} sets no `env-file`; set it to the file that holds {', '.join(KEYS[:-1])} and {KEYS[-1]}")
|
||||
return read_config(project.env_file)
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
usage: mattermost-dm [<message>]
|
||||
|
||||
Sends <message>, or else stdin, from the bot to the recipient that ~/.claude/.env names. That file
|
||||
holds three KEY=value lines, and only its owner may read it, since it holds the bot's token:
|
||||
Sends <message>, or else stdin, from the bot to the recipient that a project's env file names. Run it
|
||||
inside the project's checkout, or a worktree of it. The project's config,
|
||||
~/.claude-projects/<key>/config.toml, names the env file in `env-file`, a path outside the checkout
|
||||
and the config's folder, such as "~/.claude-projects/<key>.env". The file holds three KEY=value lines,
|
||||
and only its owner may read it, since it holds the bot's token:
|
||||
|
||||
MATTERMOST_URL=https://chat.example
|
||||
MATTERMOST_TOKEN=<the bot's access token>
|
||||
@@ -11,8 +14,9 @@ holds three KEY=value lines, and only its owner may read it, since it holds the
|
||||
|
||||
Exit 0 once the message is sent.
|
||||
Exit 1, saying why, when Mattermost cannot be reached or refuses the message.
|
||||
Exit 2, saying why, on misuse: bad arguments, an empty message, or a ~/.claude/.env that is
|
||||
missing or unreadable, lacks a key, names a server off https, or that others may read.
|
||||
Exit 2, saying why, on misuse: bad arguments, an empty message, a directory with no project config,
|
||||
a config that sets no `env-file`, or an env file that is missing or unreadable, lacks a key, names a
|
||||
server off https, or that others may read. None of these messages holds the token.
|
||||
"""
|
||||
import typing
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import contextlib
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
@@ -12,16 +13,18 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.test_project_config import configured
|
||||
from mattermost_dm import dm, main
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from loop_effects.effects import system_effects
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mattermost-dm"
|
||||
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
|
||||
|
||||
|
||||
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
|
||||
path = pathlib.Path(folder) / ".env"
|
||||
def env_file(folder: str, text: str, mode: int = 0o600, name: str = ".env") -> pathlib.Path:
|
||||
path = pathlib.Path(folder) / name
|
||||
path.write_text(text)
|
||||
path.chmod(mode)
|
||||
return path
|
||||
@@ -201,32 +204,80 @@ class HttpJson(unittest.TestCase):
|
||||
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
|
||||
|
||||
|
||||
class Dm(unittest.TestCase):
|
||||
def home_with(self, home: str, text: str) -> pathlib.Path:
|
||||
folder = pathlib.Path(home, ".claude")
|
||||
folder.mkdir()
|
||||
return env_file(str(folder), text)
|
||||
class Project(unittest.TestCase):
|
||||
"""A home with a git checkout that a config names; `folder` is the config's folder."""
|
||||
|
||||
def test_sends_through_the_env_file_under_home(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
self.home_with(home, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
|
||||
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
|
||||
def setUp(self) -> None:
|
||||
made = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(made.cleanup)
|
||||
self.home = pathlib.Path(made.name).resolve()
|
||||
self.checkout = self.home / "code" / "proj"
|
||||
self.checkout.mkdir(parents=True)
|
||||
self.folder = configured(self, self.checkout, home=self.home)
|
||||
|
||||
def test_skips_the_dm_on_a_machine_without_the_env_file(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
|
||||
self.assertEqual(server.requests, [])
|
||||
def name_env_file(self, text: str | None = None) -> pathlib.Path:
|
||||
"""Makes the config name ~/.claude-projects/proj.env, holding text where that is not None."""
|
||||
with (self.folder / "config.toml").open("a") as config:
|
||||
config.write('env-file = "~/.claude-projects/proj.env"\n')
|
||||
path = self.home / ".claude-projects" / "proj.env"
|
||||
return path if text is None else env_file(str(path.parent), text, name=path.name)
|
||||
|
||||
|
||||
class Dm(Project):
|
||||
def test_sends_through_the_env_file_the_config_names(self):
|
||||
self.name_env_file("MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", str(self.checkout), self.home, server))
|
||||
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
|
||||
|
||||
def test_loop_claudes_dm_posts_the_text_for_the_project_holding_the_current_directory(self):
|
||||
self.name_env_file("MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
server = mattermost()
|
||||
with unittest.mock.patch("loop_effects.effects.http_json", server), contextlib.chdir(self.checkout):
|
||||
self.assertIsNone(system_effects().dm("Which one?"))
|
||||
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
|
||||
|
||||
def test_skips_the_dm_for_a_project_whose_config_names_no_env_file_even_where_the_old_shared_file_exists(self):
|
||||
(self.home / ".claude").mkdir()
|
||||
env_file(str(self.home / ".claude"), "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=other-projects-token\nMATTERMOST_RECIPIENT=lilleman\n", name=".env")
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", str(self.checkout), self.home, server))
|
||||
self.assertEqual(server.requests, [])
|
||||
|
||||
def test_fails_naming_the_file_where_the_config_names_one_that_is_not_there(self):
|
||||
path = self.name_env_file()
|
||||
self.assertEqual(dm.dm("Which one?", str(self.checkout), self.home, mattermost()), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
||||
|
||||
def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = self.home_with(home, "MATTERMOST_URL=https://chat.example\n")
|
||||
self.assertEqual(dm.dm("Which one?", pathlib.Path(home), mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
||||
path = self.name_env_file("MATTERMOST_URL=https://chat.example\n")
|
||||
self.assertEqual(dm.dm("Which one?", str(self.checkout), self.home, mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
||||
|
||||
def test_skips_the_dm_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self):
|
||||
other = self.home / "code" / "other"
|
||||
other.mkdir()
|
||||
subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env())
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", str(other), self.home, server))
|
||||
self.assertEqual(server.requests, [])
|
||||
|
||||
def test_config_of_names_the_setting_to_add_where_the_config_names_no_env_file(self):
|
||||
failed = dm.config_of(str(self.checkout), self.home)
|
||||
assert isinstance(failed, Failure), failed
|
||||
self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `env-file`; set it to the file that holds MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")
|
||||
|
||||
def test_config_of_reads_the_env_file_the_config_names(self):
|
||||
self.name_env_file("MATTERMOST_URL=https://chat.example/\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
self.assertEqual(dm.config_of(str(self.checkout), self.home), CONFIG)
|
||||
|
||||
def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self):
|
||||
self.name_env_file("MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
failed = dm.dm("Which one?", str(self.checkout), self.home, dm.http_json)
|
||||
assert isinstance(failed, Failure), failed
|
||||
self.assertIn("cannot reach https://127.0.0.1:1", failed.reason)
|
||||
self.assertNotIn("secret-token", failed.reason)
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
class Main(Project):
|
||||
def run_main(self, argv: list[str], stdin: str = "", config: object = CONFIG, server: object = None) -> tuple[int, str]:
|
||||
stderr = io.StringIO()
|
||||
sent = server or mattermost()
|
||||
@@ -255,13 +306,13 @@ class Main(unittest.TestCase):
|
||||
server.answers[("GET", "/api/v4/users/me")] = Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")
|
||||
self.assertEqual(self.run_main(["hi"], server=server), (1, "mattermost-dm: GET /api/v4/users/me answered 401: Invalid or expired session, please login again.\n"))
|
||||
|
||||
def test_the_launcher_prints_help_and_reads_the_env_file_under_home(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
env = {**isolated_env(), "HOME": home}
|
||||
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env)
|
||||
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
|
||||
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env)
|
||||
self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {home}/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n"))
|
||||
def test_the_launcher_prints_help_and_reads_the_env_file_the_projects_config_names(self):
|
||||
env = {**isolated_env(), "HOME": str(self.home)}
|
||||
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env, cwd=self.checkout)
|
||||
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
|
||||
path = self.name_env_file()
|
||||
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env, cwd=self.checkout)
|
||||
self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -21,29 +21,39 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil
|
||||
goals-and-audience = "folder:goals.md"
|
||||
principles = "folder:principles"
|
||||
|
||||
`env-file` is the one optional setting: the file of KEY=value credentials the project's tools read,
|
||||
a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as
|
||||
"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and
|
||||
a tool that needs one fails naming the setting. It is printed with the others only where it is set.
|
||||
|
||||
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
|
||||
setting, names an unknown one or misspells a path. No setting has a default.
|
||||
setting, names an unknown one or misspells a path, and where `env-file` is asked for and not set.
|
||||
No setting has a default.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from project_config.settings import CONFIG, ENV_FILE, load, ProjectConfig, SETTINGS
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git
|
||||
from project_config.settings import load, ProjectConfig, SETTINGS
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) > 1 or (argv and argv[0] not in SETTINGS):
|
||||
print(f"usage: project-config [<setting>], where <setting> is one of {', '.join(SETTINGS)}", file=sys.stderr)
|
||||
if len(argv) > 1 or (argv and argv[0] not in (*SETTINGS, ENV_FILE)):
|
||||
print(f"usage: project-config [<setting>], where <setting> is one of {', '.join((*SETTINGS, ENV_FILE))}", file=sys.stderr)
|
||||
return 1
|
||||
config = located(None, pathlib.Path.home())
|
||||
if isinstance(config, Failure):
|
||||
print(config.reason, file=sys.stderr)
|
||||
return 1
|
||||
print(config.paths[argv[0]] if argv else "\n".join(f"{name}: {config.paths[name]}" for name in SETTINGS))
|
||||
paths = {**config.paths, **({ENV_FILE: config.env_file} if config.env_file else {})}
|
||||
if argv and argv[0] not in paths:
|
||||
print(f"{config.folder / CONFIG} sets no `{ENV_FILE}`", file=sys.stderr)
|
||||
return 1
|
||||
print(paths[argv[0]] if argv else "\n".join(f"{name}: {path}" for name, path in paths.items()))
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ CONFIG = "config.toml"
|
||||
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles")
|
||||
# They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default.
|
||||
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
|
||||
# The one setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
|
||||
ENV_FILE = "env-file"
|
||||
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
|
||||
|
||||
# Where a project keeps a file, for a tool that reads it at a commit: a path from the checkout's top, as git names it; or, outside the checkout, the file itself, which the tool reads as it stands, since the checkout's commits hold no version of it.
|
||||
Place = str | pathlib.Path
|
||||
@@ -25,6 +28,8 @@ class ProjectConfig:
|
||||
folder: pathlib.Path
|
||||
top: pathlib.Path
|
||||
paths: dict[str, pathlib.Path]
|
||||
# The config's `env-file`, or None where it sets none.
|
||||
env_file: pathlib.Path | None = None
|
||||
|
||||
def tracked(self, setting: str) -> str | None:
|
||||
"""setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, whose commits hold no version of it."""
|
||||
@@ -54,14 +59,22 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
return Failure(f"{' and '.join(str(file) for file, _ in named)} each name the checkout {main}; only one config may")
|
||||
file, values = named[0]
|
||||
paths = {name: placed(values[name], top, file.parent, home) for name in SETTINGS if name in values}
|
||||
env_file = anywhere(values.get(ENV_FILE), home)
|
||||
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
|
||||
faults = [
|
||||
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
|
||||
*(f"`{name}` is not a setting" for name in values if name not in SETTINGS),
|
||||
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, ENV_FILE)),
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None),
|
||||
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
|
||||
]
|
||||
if faults:
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}.")
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path})
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {ENV_FILE}.")
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file)
|
||||
|
||||
|
||||
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
|
||||
"""Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names."""
|
||||
return any(path.resolve().is_relative_to(place.resolve()) for place in places)
|
||||
|
||||
|
||||
def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure | None:
|
||||
@@ -74,6 +87,12 @@ def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure |
|
||||
return config if isinstance(config, Failure) else load(config[0], config[0], home)
|
||||
|
||||
|
||||
def env_files(home: pathlib.Path) -> list[pathlib.Path]:
|
||||
"""Every config's env-file, read without the checks load makes, so a config that fails them still keeps its credentials guarded; a config that cannot be read names none."""
|
||||
configs = [read(file, home) for file in sorted((home / PROJECTS).glob(f"*/{CONFIG}"))]
|
||||
return [path for config in configs if not isinstance(config, Failure) and (path := anywhere(config[1].get(ENV_FILE), home))]
|
||||
|
||||
|
||||
def read(file: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, dict[str, object]] | Failure:
|
||||
"""The checkout a config names, as an absolute path, and its other values."""
|
||||
try:
|
||||
|
||||
@@ -8,8 +8,8 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import env_files, held, load, OUTSIDE, ProjectConfig, SETTINGS
|
||||
from failure import Failure
|
||||
from project_config.settings import held, load, ProjectConfig, SETTINGS
|
||||
from test_env import isolated_env
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config"
|
||||
@@ -149,6 +149,50 @@ class LoadTest(ConfigCase):
|
||||
self.assertIn(named, reason)
|
||||
self.assertIn("`decisions`", reason)
|
||||
|
||||
def test_env_file_is_the_one_optional_setting_and_names_a_file_outside_the_checkout_and_the_configs_folder(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, ProjectConfig), found
|
||||
self.assertIsNone(found.env_file, "a project that sets none has asked for no credentials, and never falls back to another project's")
|
||||
for case, spelled in {"~/": '"~/.claude-projects/acme.env"', "absolute": f'"{self.home}/.claude-projects/acme.env"'}.items():
|
||||
with self.subTest(case=case):
|
||||
self.write(f"acme-{case[0]}", CLIENT.replace("acme-billing", f"acme-{case[0]}") + f"env-file = {spelled}\n")
|
||||
named = load(self.home / "code" / f"acme-{case[0]}", self.home / "code" / f"acme-{case[0]}", self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual(named.env_file, self.home / ".claude-projects" / "acme.env")
|
||||
|
||||
def test_an_env_file_in_the_checkout_or_the_configs_folder_or_spelt_loosely_fails_naming_it(self) -> None:
|
||||
cases = {
|
||||
"a checkout: path": lambda home: '"checkout:.env"',
|
||||
"a folder: path": lambda home: '"folder:acme.env"',
|
||||
"no prefix": lambda home: '".env"',
|
||||
"a path in the checkout": lambda home: f'"{home}/code/acme-billing/.env"',
|
||||
"a path in the config's folder": lambda home: f'"{home}/.claude-projects/acme/acme.env"',
|
||||
"not text": lambda home: "3",
|
||||
}
|
||||
for case, spelled in cases.items():
|
||||
with self.subTest(case=case), tempfile.TemporaryDirectory() as made:
|
||||
self.home = pathlib.Path(made).resolve()
|
||||
self.checkout = self.home / "code" / "acme-billing"
|
||||
self.write("acme", CLIENT + f"env-file = {spelled(self.home)}\n")
|
||||
reason = self.failure()
|
||||
self.assertIn("`env-file`", reason)
|
||||
self.assertNotIn("is not a setting", reason)
|
||||
|
||||
def test_a_worktree_refuses_an_env_file_in_the_main_checkout_as_well_as_one_in_its_own_files(self) -> None:
|
||||
for case, folder in {"the main checkout": "acme-billing", "the worktree": "acme-billing-item-3"}.items():
|
||||
with self.subTest(case=case), tempfile.TemporaryDirectory() as made:
|
||||
self.home = pathlib.Path(made).resolve()
|
||||
self.checkout = self.home / "code" / "acme-billing"
|
||||
self.write("acme", CLIENT + f'env-file = "{self.home}/code/{folder}/.env"\n')
|
||||
found = load(self.home / "code" / "acme-billing-item-3", self.checkout, self.home)
|
||||
assert isinstance(found, Failure), found
|
||||
self.assertIn("`env-file`", found.reason)
|
||||
|
||||
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
|
||||
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally env-file.")
|
||||
|
||||
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
self.write("acme-copy", CLIENT)
|
||||
@@ -194,6 +238,15 @@ class HeldTest(ConfigCase):
|
||||
self.assertIsInstance(held(target, self.home), ProjectConfig, "git names the folder by its resolved path")
|
||||
|
||||
|
||||
class EnvFilesTest(ConfigCase):
|
||||
def test_lists_each_readable_configs_env_file_even_one_load_refuses(self) -> None:
|
||||
self.write("acme", CLIENT + 'env-file = "~/acme.env"\n')
|
||||
self.write("misplaced", 'checkout = "~/code/other"\nenv-file = "/srv/other.env"\n')
|
||||
self.write("broken", "checkout = ")
|
||||
self.write("none", CLIENT)
|
||||
self.assertEqual(env_files(self.home), [self.home / "acme.env", pathlib.Path("/srv/other.env")])
|
||||
|
||||
|
||||
class ToolTest(ConfigCase):
|
||||
def run_tool(self, *args: str, cwd: pathlib.Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], cwd=cwd or self.checkout, env={**isolated_env(), "HOME": str(self.home)}, capture_output=True, text=True)
|
||||
@@ -212,6 +265,16 @@ class ToolTest(ConfigCase):
|
||||
one = self.run_tool("changelog", cwd=self.checkout / "src")
|
||||
self.assertEqual((one.returncode, one.stdout), (0, f"{self.checkout}/CHANGELOG.md\n"))
|
||||
|
||||
def test_prints_the_env_file_where_the_config_sets_one_and_fails_asking_for_it_where_it_does_not(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
unset = self.run_tool("env-file")
|
||||
self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `env-file`\n"))
|
||||
self.assertNotIn("env-file", self.run_tool().stdout)
|
||||
(folder / "config.toml").write_text(CLIENT + 'env-file = "~/.claude-projects/acme.env"\n')
|
||||
one = self.run_tool("env-file")
|
||||
self.assertEqual((one.returncode, one.stdout), (0, f"{self.home}/.claude-projects/acme.env\n"))
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-1], f"env-file: {self.home}/.claude-projects/acme.env")
|
||||
|
||||
def test_fails_on_stderr(self) -> None:
|
||||
cases = {"no config": ((), "no config names the checkout"), "an unknown setting": (("readme",), "usage:"), "two arguments": (("plan", "changelog"), "usage:")}
|
||||
for case, (args, said) in cases.items():
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Whether a Read or a Grep reads a credentials file, or a Bash command names one, for the `env-file-read` rule.
|
||||
|
||||
The files are `~/.claude/.env` and every config's `env-file`, not only the calling project's: a worker in one client's project must not read another client's credentials either, and listing every config's file needs no git call, as finding the calling project's would.
|
||||
A Bash command names one where its text spells the file's path, or one of its words, a redirect's target included, leads to the file from the directory `cd` left the command in. Whether the command reads the file is not judged, so one that only mentions the path is refused too.
|
||||
This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob, a variable of its own or a recursive search of a folder that holds it; todo.md item 370 covers the recursive Bash searches."""
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import Call, text
|
||||
from project_config.settings import env_files
|
||||
from failure import Failure
|
||||
from rule_hook.git import guarded_git
|
||||
from command_lines.shell_command import lexed, OPERATOR, resolved
|
||||
|
||||
# What a Grep's glob holds beyond literals, `*`, `?` and `/`: forms globbed() does not translate.
|
||||
UNMATCHED = re.compile(r"[{}\[\]\\,\s]|/$")
|
||||
|
||||
|
||||
def env_file_breaches(call: Call, home: str) -> list[Breach]:
|
||||
guarded: dict[str, pathlib.Path] = {}
|
||||
for path in (pathlib.Path(home, ".claude", ".env"), *env_files(pathlib.Path(home))):
|
||||
if path.is_file():
|
||||
# Several configs may name one file: it is checked, and reported, once.
|
||||
guarded.setdefault(os.path.realpath(path), path)
|
||||
# A command may name the file without reading it, so the detail claims no read of it.
|
||||
found = "the command names {}, a file of credentials that must stay out of the transcript" if call.tool == "Bash" else "the call reads {}, whose credentials would land in the transcript"
|
||||
return [Breach("env-file-read", found.format(path), call.cwd) for path in guarded.values() if reached(call, path, home)]
|
||||
|
||||
|
||||
def reached(call: Call, path: pathlib.Path, home: str) -> bool:
|
||||
"""Whether a Read or a Grep reads path, or a Bash command names it."""
|
||||
if call.tool == "Read":
|
||||
return names(resolved(call.cwd, text(call.given, "file_path"), home), path)
|
||||
if call.tool == "Grep":
|
||||
searched = resolved(call.cwd, text(call.given, "path") or ".", home)
|
||||
# ripgrep's --glob overrides its ignore files, so an ignored file is skipped unless a glob matches it.
|
||||
return names(searched, path) or holds(searched, path) and (globbed(text(call.given, "glob"), searched, path) or not ignored(path))
|
||||
command = text(call.given, "command")
|
||||
relative = os.path.relpath(path, home)
|
||||
spellings = "|".join(re.escape(spelling) for spelling in (str(path), *(f"{prefix}/{relative}" for prefix in ("~", "$HOME", "${HOME}"))))
|
||||
# Bounded on both sides, so a longer path that holds a spelling, such as ~/.claude/.envrc, is another file.
|
||||
spelt = re.search(rf"(?<![\w./~-])(?:{spellings})(?![\w.-])", command)
|
||||
return spelt is not None or any(names(word, path) for word in paths(command, call.cwd, home))
|
||||
|
||||
|
||||
def paths(command: str, cwd: str, home: str) -> typing.Iterator[str]:
|
||||
"""Each word of the command as a path from the directory `cd` left it in. Unlike simple_commands, it keeps a redirect's target, which a command reads as it reads an operand."""
|
||||
tokens = lexed(command)
|
||||
if tokens is None:
|
||||
# One unbalanced quote should not hide the other lines.
|
||||
tokens = [token for line in command.splitlines() for token in (lexed(line) or []) + ["\n"]]
|
||||
directory = cwd
|
||||
words: list[str] = []
|
||||
for token in [*tokens, "\n"]:
|
||||
if token and set(token) <= OPERATOR:
|
||||
if len(words) == 2 and words[0] == "cd":
|
||||
directory = resolved(directory, words[1], home)
|
||||
words = []
|
||||
else:
|
||||
# The lexer has joined a quoted "$HOME" to the rest of its word.
|
||||
word = re.sub(r"^\$(HOME|\{HOME\})(?=/|$)", "~", token)
|
||||
words.append(word)
|
||||
yield resolved(directory, word, home)
|
||||
|
||||
|
||||
def globbed(glob: str, searched: str, path: pathlib.Path) -> bool:
|
||||
"""Whether a Grep's glob can match path, as ripgrep matches it: one without a `/` against the file's name, one with a `/` against the path from the searched folder. A glob holding a form this does not translate, such as `{a,b}`, counts as matching."""
|
||||
if not glob:
|
||||
return False
|
||||
if UNMATCHED.search(glob):
|
||||
return True
|
||||
if glob.startswith("!"):
|
||||
# It only excludes files.
|
||||
return False
|
||||
anchored = glob.lstrip("/") if "/" in glob else f"**/{glob}"
|
||||
# A `**` that is not a whole folder name matches as `*` in ripgrep; crossing folders there only refuses more.
|
||||
translated = {"**/": "(?:.*/)?", "**": ".*", "*": "[^/]*", "?": "[^/]"}
|
||||
pattern = "".join(translated.get(piece, re.escape(piece)) for piece in re.split(r"(\*\*/|\*\*|\*|\?)", anchored))
|
||||
return re.fullmatch(pattern, os.path.relpath(os.path.realpath(path), os.path.realpath(searched))) is not None
|
||||
|
||||
|
||||
def names(given: str, path: pathlib.Path) -> bool:
|
||||
"""Whether given leads to path, through any symlink."""
|
||||
try:
|
||||
return os.path.realpath(given) == os.path.realpath(path)
|
||||
except ValueError:
|
||||
# A word holding a NUL byte names no file.
|
||||
return False
|
||||
|
||||
|
||||
def holds(folder: str, path: pathlib.Path) -> bool:
|
||||
try:
|
||||
return pathlib.Path(os.path.realpath(path)).is_relative_to(os.path.realpath(folder))
|
||||
except ValueError:
|
||||
# A folder whose path holds a NUL byte holds no file.
|
||||
return False
|
||||
|
||||
|
||||
def ignored(path: pathlib.Path) -> bool:
|
||||
"""Whether the checkout holding path ignores it: Grep runs ripgrep, which skips such a file in a folder it searches unless a glob matches it."""
|
||||
return not isinstance(guarded_git(str(path.parent), "check-ignore", "--quiet", path.name), Failure)
|
||||
@@ -3,7 +3,7 @@
|
||||
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
|
||||
rule-hook overrides (prints this chunk's overrides)
|
||||
|
||||
settings.json runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, in every session and
|
||||
settings.json runs it before each Agent, Bash, Edit, Grep, MultiEdit, Read, Skill and Write call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
@@ -44,6 +44,7 @@ from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
|
||||
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
|
||||
from git_cli.git_command import commits
|
||||
from rule_hook.committed_files import committed_file_breaches
|
||||
from rule_hook.env_file import env_file_breaches
|
||||
from failure import Failure
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from rule_hook.file_text import read
|
||||
@@ -86,9 +87,12 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
|
||||
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ)
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home)
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home) + env_file_breaches(call, home)
|
||||
if call.tool == "Read":
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home)
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home)
|
||||
if call.tool == "Grep":
|
||||
# Only env-file-read checks a Grep, and it takes no override, so no marker or log line concerns the call.
|
||||
return "", "", env_file_breaches(call, home)
|
||||
path = text(call.given, "file_path")
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
|
||||
@@ -11,7 +11,7 @@ from command_lines.shell_command import launched, Simple
|
||||
from review_rules.review_folder import REPORTS
|
||||
from command_lines.docker_command import unlimited
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "env-file-read", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -35,6 +35,12 @@ RULES: dict[RuleName, Rule] = {
|
||||
"a container made with docker run or docker create has a memory limit and a swap limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so a runaway container fails alone instead of starving the machine; a swap limit equal to the memory limit keeps it out of swap",
|
||||
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. One under run-heavy passes, as run-heavy's docker adds the limits on Linux, unless it names docker by its path, or changes or clears PATH, as env -i, sudo or doas do. A container a script or docker compose starts is not checked",
|
||||
),
|
||||
# A marker would let the credentials into the transcript all the same, so no marker waives it.
|
||||
"env-file-read": Rule(
|
||||
"an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which loop-claude archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `~/.claude/bin/project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title",
|
||||
"against ~/.claude/.env and the env-file of every config under ~/.claude-projects: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it",
|
||||
overridable=False,
|
||||
),
|
||||
"ignorefile-sorted": Rule(
|
||||
"each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
|
||||
"a .*ignore file; a block already unsorted before the edit is left alone",
|
||||
|
||||
@@ -18,7 +18,7 @@ from rule_hook.rules import blocks, Breach, check, command_breaches, file_breach
|
||||
from rule_hook.main import breaches_of
|
||||
from rule_hook.call import Call, parsed_call
|
||||
from git_cli.git_command import commit_message, CommitCall, commits
|
||||
from project_config.test_project_config import configured
|
||||
from project_config.test_project_config import configured, write_config
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from rule_hook.git import guarded_git
|
||||
from test_env import isolated_env
|
||||
@@ -360,6 +360,112 @@ class ReviewerRung(unittest.TestCase):
|
||||
self.assertTrue(any("Skill" in tools for tools in matchers))
|
||||
|
||||
|
||||
class EnvFileRead(unittest.TestCase):
|
||||
"""A home with ~/.claude/.env and a config whose env-file lies outside any checkout."""
|
||||
def setUp(self) -> None:
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / ".env").write_text("TOKEN=x\n")
|
||||
write_config(self.home, self.home / "code" / "acme")
|
||||
config = self.home / ".claude-projects" / "acme" / "config.toml"
|
||||
config.write_text(config.read_text() + 'env-file = "~/secrets/acme.env"\n')
|
||||
(self.home / "secrets").mkdir()
|
||||
(self.home / "secrets" / "acme.env").write_text("TOKEN=y\n")
|
||||
|
||||
def breached(self, tool: str, given: dict[str, typing.Any], cwd: str = "/r") -> list[str]:
|
||||
found = breaches_of(Call(tool, given, cwd), str(self.home), {})
|
||||
return sorted({rule for rule in rules(found[2]) if rule == "env-file-read"}) if found else []
|
||||
|
||||
def test_a_read_of_claude_s_env_or_a_config_s_env_file_is_refused(self):
|
||||
self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/.claude/.env"}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Read", {"file_path": "acme.env"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
|
||||
def test_a_read_spelt_from_home_is_refused_naming_the_file(self):
|
||||
found = breaches_of(Call("Read", {"file_path": "~/.claude/.env"}, "/r"), str(self.home), {})
|
||||
self.assertEqual([breach.detail for breach in found[2]], [f"the call reads {self.home}/.claude/.env, whose credentials would land in the transcript"])
|
||||
|
||||
def test_the_log_names_a_read_by_its_file_and_a_command_by_its_first_line(self):
|
||||
self.assertEqual(breaches_of(Call("Read", {"file_path": "a.txt"}, "/r"), str(self.home), {})[1], "a.txt")
|
||||
self.assertEqual(breaches_of(Call("Bash", {"command": "ls -l\nls -a\nls"}, "/r"), str(self.home), {})[1], "ls -l")
|
||||
|
||||
def test_a_read_through_a_symlink_is_refused(self):
|
||||
(self.home / "link").symlink_to(self.home / "secrets" / "acme.env")
|
||||
self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/link"}), ["env-file-read"])
|
||||
|
||||
def test_a_read_of_another_file_passes(self):
|
||||
self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/.claude/settings.json"}), [])
|
||||
|
||||
def test_a_grep_of_the_file_or_of_a_folder_holding_it_is_refused(self):
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/secrets/acme.env"}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": str(self.home)}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": "~/secrets"}), ["env-file-read"])
|
||||
|
||||
def test_a_grep_of_a_folder_whose_checkout_ignores_the_file_or_of_another_folder_passes(self):
|
||||
subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env())
|
||||
(self.home / ".claude" / ".gitignore").write_text(".env\n")
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude"}), [])
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/code"}), [])
|
||||
|
||||
def test_a_command_naming_the_file_is_refused(self):
|
||||
for command in ("cat ~/.claude/.env", "sh -c 'cat ~/.claude/.env'", f"sh -c 'cat {self.home}/secrets/acme.env'", f"grep TOKEN {self.home}/secrets/acme.env", "source $HOME/secrets/acme.env", "wc < ${HOME}/.claude/.env", "cd ~/secrets && cat acme.env"):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), ["env-file-read"])
|
||||
|
||||
def test_a_command_naming_another_file_passes(self):
|
||||
self.assertEqual(self.breached("Bash", {"command": f"cat ~/.claude/.envrc /backup{self.home}/.claude/.env .env"}, "/r"), [])
|
||||
self.assertEqual(self.breached("Bash", {"command": "cat 'a\0b'"}, f"{self.home}/.claude"), [])
|
||||
|
||||
def test_a_command_s_refusal_says_it_names_the_file_not_that_it_reads_it(self):
|
||||
found = breaches_of(Call("Bash", {"command": "ls -l ~/.claude/.env"}, "/r"), str(self.home), {})
|
||||
details = [breach.detail for breach in found[2] if breach.rule == "env-file-read"]
|
||||
self.assertEqual(len(details), 1)
|
||||
self.assertTrue(details[0].startswith(f"the command names {self.home}/.claude/.env"), details[0])
|
||||
self.assertNotIn("reads", details[0])
|
||||
|
||||
def test_the_rule_names_the_way_on_for_a_command_that_only_mentions_the_path(self):
|
||||
holds = RULES["env-file-read"].holds
|
||||
self.assertIn('"the .env in ~/.claude"', holds)
|
||||
self.assertIn("`~/.claude/bin/project-config env-file`", holds)
|
||||
self.assertNotIn(". ", holds, "one sentence")
|
||||
|
||||
def test_a_command_redirecting_from_the_file_is_refused(self):
|
||||
self.assertEqual(self.breached("Bash", {"command": "cd ~/secrets && wc < acme.env"}), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Bash", {"command": "wc < acme.env"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Bash", {"command": "while read l; do echo $l; done < .env"}, f"{self.home}/.claude"), ["env-file-read"])
|
||||
|
||||
def test_a_command_naming_the_file_through_a_quoted_home_is_refused(self):
|
||||
for command in ('cat "$HOME"/.claude/.env', 'cat "${HOME}"/.claude/.env'):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), ["env-file-read"])
|
||||
|
||||
def test_a_grep_s_glob_is_refused_only_where_it_can_match_the_ignored_file(self):
|
||||
subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env())
|
||||
(self.home / ".claude" / ".gitignore").write_text(".env\n")
|
||||
for glob, expected in (("**/*.md", []), ("rules/*.md", []), ("*.py", []), ("!.env", []), ("*", ["env-file-read"]), (".env*", ["env-file-read"]), ("{*.md,.env}", ["env-file-read"])):
|
||||
with self.subTest(glob):
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude", "glob": glob}), expected)
|
||||
|
||||
def test_a_grep_s_glob_with_a_slash_is_matched_against_the_path_from_the_searched_folder(self):
|
||||
subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env())
|
||||
(self.home / ".claude" / ".gitignore").write_text(".env\n")
|
||||
# ~/secrets/acme.env is in no checkout, so only the ignored file's breach tells the globs apart.
|
||||
for glob, refused in ((".claude/*", True), ("**/.env", True), ("/.claude/.env", True), (".claude/**", True), ("secrets/*", False), ("*/*.md", False), (".env/*", False)):
|
||||
with self.subTest(glob):
|
||||
found = breaches_of(Call("Grep", {"pattern": "TOKEN", "path": str(self.home), "glob": glob}, "/r"), str(self.home), {})
|
||||
self.assertEqual(any(breach.detail.startswith(f"the call reads {self.home}/.claude/.env,") for breach in found[2]), refused)
|
||||
|
||||
def test_a_file_several_configs_name_is_reported_once(self):
|
||||
write_config(self.home, self.home / "code" / "other")
|
||||
config = self.home / ".claude-projects" / "other" / "config.toml"
|
||||
config.write_text(config.read_text() + 'env-file = "~/secrets/../secrets/acme.env"\n')
|
||||
found = breaches_of(Call("Read", {"file_path": "~/secrets/acme.env"}, "/r"), str(self.home), {})
|
||||
self.assertEqual(len([breach for breach in found[2] if breach.rule == "env-file-read"]), 1)
|
||||
|
||||
def test_a_grep_of_a_path_holding_a_nul_byte_passes(self):
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": "a\0b"}), [])
|
||||
|
||||
|
||||
class ReviewerReport(unittest.TestCase):
|
||||
def breached(self, tool: str, path: str, agent: str = "prose-reviewer", cwd: str = "/r") -> list[str]:
|
||||
given = {"file_path": path, "content": "BLOCK\n"} if tool == "Write" else {"file_path": path, "old_string": "a", "new_string": "b"}
|
||||
|
||||
@@ -1907,3 +1907,28 @@ Read most (opens and searches):
|
||||
- `bin/rule_hook/rules.py` 2
|
||||
- `docs/decisions.md` 2
|
||||
- `todo.md` 2
|
||||
|
||||
## Reading cost, chunk 9fcf2541d7c8, finished 2026-11-13T19:06:07Z
|
||||
|
||||
37154 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `skills/larv-review/SKILL.md` 7
|
||||
|
||||
## Reading cost, chunk ea61fbec00f3, finished 2026-11-13T19:51:50Z
|
||||
|
||||
160159 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/loop_claude/test_black_box.py` 11
|
||||
- `README.md` 6
|
||||
- `bin/mattermost_dm/test_mattermost_dm.py` 4
|
||||
- `settings.json` 4
|
||||
- `bin/project_config/settings.py` 3
|
||||
- `bin/project_config/test_project_config.py` 3
|
||||
- `CHANGELOG.md` 2
|
||||
- `bin/loop_effects/effects.py` 2
|
||||
- `bin/mattermost_dm/dm.py` 2
|
||||
- `bin/project_config/main.py` 2
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@
|
||||
"type": "command"
|
||||
}
|
||||
],
|
||||
"matcher": "Agent|Bash|Edit|MultiEdit|Read|Skill|Write"
|
||||
"matcher": "Agent|Bash|Edit|Grep|MultiEdit|Read|Skill|Write"
|
||||
}
|
||||
],
|
||||
"SubagentStart": [
|
||||
|
||||
@@ -6,29 +6,33 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 369`
|
||||
`Next ID = 376`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 348 | 0.11.0 | | | **Read each project's credentials from the env file its config names, fail naming each missing key, and keep every value out of prompts, transcripts, logs and the archive.** | 2 | 2 | 4 | 6 | 3 | 1.6 by 2, 4 by 5 | 6.9 |
|
||||
| 370 | 0.11.0 | | security | **Refuse a Bash command that recursively searches a folder holding an env-file, as `grep -r` or `rg` do, so no credential reaches a transcript.** | 2 | 2 | 4 | 6 | 2 | 4 by 3 | 4.2 |
|
||||
| 371 | 0.11.0 | | owner | **Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only.** | 3 | 2 | 3 | 6 | 5 | code health by 3 | 2.9 |
|
||||
| 354 | 0.11.0 | | | **Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 4, code health by 1 | 1.2 |
|
||||
| 364 | 0.11.0 | 354 | | **Read a client repo's own `CLAUDE.md` and `AGENTS.md`, propose to its team each change that aligns them with this setup, and record each conflict left as a decision in the project's records.** | 2 | 2 | 2 | 4 | 2 | 1.6 by 4, 1.2 by 2 | 2.2 |
|
||||
| 360 | 0.11.0 | | | **Make `chunk-pr merge` wait for the human approvals a project's config requires, as part of the gate, before it merges.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 5 | 1.6 |
|
||||
| 357 | 0.11.0 | | | **Write prose in the language a project's config names, and title its commits, pull requests and branches by the templates it names.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 5 | 1.4 |
|
||||
| 350 | 0.11.0 | | | **Route every read and write of the plan, by tools and by agents, through one plan-store interface and `todo-item`, with the markdown file as one backend.** | 4 | 2 | 3 | 7 | 7 | 1.6 by 4, code health by 2 | 1.1 |
|
||||
| 349 | 0.11.0 | | | **Convert markdown to ADF and back with `@larvit/adf-codec`'s portable calls, through a pinned Node shim run in a container with a memory limit.** | 2 | 1 | 2 | 3 | 2 | 1.6 by 3 | 1.1 |
|
||||
| 351 | 0.11.0 | 348, 349, 350 | | **Read a project's plan from the child issues of a Jira Cloud epic its config names, ranked in Jira's backlog order.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 351 | 0.11.0 | 349, 350 | | **Read a project's plan from the child issues of a Jira Cloud epic its config names, ranked in Jira's backlog order.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 353 | 0.11.0 | 351 | | **Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
|
||||
| 358 | 0.11.0 | | | **Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
|
||||
| 362 | 0.11.0 | 348 | | **Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 3 | 1.0 |
|
||||
| 362 | 0.11.0 | | | **Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 3 | 1.0 |
|
||||
| 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 |
|
||||
| 373 | 0.11.0 | 371 | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 |
|
||||
| 352 | 0.11.0 | 351 | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 355 | 0.11.0 | 348, 349, 354 | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 355 | 0.11.0 | 349, 354 | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 356 | 0.11.0 | | | **Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 3 | 1.1 |
|
||||
| 372 | 0.11.0 | 371 | | **Key loop-claude's lock, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 |
|
||||
| 374 | 0.11.0 | 360, 372 | | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
|
||||
| 359 | 0.11.0 | 350 | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 361 | 0.11.0 | 360 | | **Start the next item that doesn't touch a waiting pull request's files, in its own worktree and session, while that pull request waits for a human approval, and answer review comments on waiting pull requests as they arrive.** | 4 | 2 | 3 | 7 | 7 | 1.6 by 4, 1.5 by 5 | 0.7 |
|
||||
| 375 | 0.11.0 | 372, 373, 374 | | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
|
||||
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
|
||||
| 309 | 0.12.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.2 |
|
||||
| 299 | 0.12.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.0 |
|
||||
@@ -87,9 +91,15 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 348. Read each project's credentials from the env file its config names, fail naming each missing key, and keep every value out of prompts, transcripts, logs and the archive.
|
||||
### 370. Refuse a Bash command that recursively searches a folder holding an env-file, as `grep -r` or `rg` do, so no credential reaches a transcript.
|
||||
|
||||
lilleman's call, 2026-11-12: credentials (Jira and Confluence API token, GitHub, Mattermost or Slack token) come from a per-project env file such as `~/.claude-projects/<key>.env`, outside the project's repo and named in the config. Which account each service uses is a config setting: a bot account or lilleman's own. A test shows a value never reaches a worker or judge prompt, a log line or the transcript archive, which guards goal 4. Today `~/.claude/.env` serves every project.
|
||||
The env-file-read rule refuses a Grep of a folder that holds `~/.claude/.env` or a config's env-file, but a Bash command only where it spells or names the file itself. A worker that runs `grep -r TOKEN ~/.claude-projects`, or `rg --no-ignore` over `~/.claude`, still prints the credential lines into its transcript, which loop-claude archives under `~/.claude/loop-claude-transcripts` and the backups copy. README suggests keeping the env-file at `~/.claude-projects/<key>.env`, in a folder agents search often. Extend `bin/rule_hook/env_file.py` to refuse a `grep -r`/`-R`, `rg` or `ag` whose folder operand, or the directory `cd` left it in when it names none, holds a guarded file that the tool doesn't skip. A test must show the refusal for each tool. The security pass of item 369's chunk raised it.
|
||||
|
||||
### 371. Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only.
|
||||
|
||||
lilleman's call, 2026-11-13: loop-inbox didn't work out, so it goes, and the parallel chunks in items 372 to 375 don't build on it. An interrupt is answered at loop-claude's terminal only, with `/talk` opening the worker's session there, as before todo item 243. The Mattermost DM keeps telling the human that a loop waits.
|
||||
|
||||
Remove `bin/loop-inbox`, `bin/loop_inbox/`, and the parts of `bin/loop_state/waiting/` that only loop-inbox reads: the question files, `OpenInInbox`, and `input_or`'s watch of the inbox in `bin/loop_effects/effects.py`. Keep what loop-claude still needs, such as the session lock and `running_loops`, where something other than loop-inbox reads it. Remove the decision `loop-inbox: a loop-claude lists itself while it runs ...` and its title at the head of `docs/decisions.md`. Reword the decisions that name loop-inbox beside the terminal, such as the one on `CLAUDE_CODE_SANDBOXED`. Drop loop-inbox from `CLAUDE.md` → "Vocabulary" → "interrupt", the README, `.gitignore` and `presentation/index.html`. The changelog says loop-inbox is gone and that interrupts are answered on loop-claude's terminal.
|
||||
|
||||
### 354. Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.
|
||||
|
||||
@@ -135,6 +145,14 @@ lilleman's call, 2026-11-12: each project names its notifier, server and recipie
|
||||
|
||||
lilleman asked for a Slack driver on 2026-11-12, for clients on Slack. The bot token comes from the project's env file.
|
||||
|
||||
### 373. Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361. A planning pass, on the project's rung or above, predicts for each item of the next release the files it will touch and, within each file, the parts: a function, a class, a section heading, a table row. It writes the prediction into the item's detail, where `chunk-preflight` reads it. Two chunks may run together where their predicted parts don't overlap, even in one file. `todo.md` and `CHANGELOG.md` don't count, since item 374 writes them at merge time.
|
||||
|
||||
A conflict is not a catastrophe; lilleman expects projects where wall-clock time matters most and tokens spent per hour don't, while tokens per delivered chunk still do (goals 1.4 and 1.5). So the pass picks the set that keeps the most chunks running within the project's parallel limit, item 375's config key, and takes an overlap only where it predicts a small change to the same part. The rules for a chunk hold as today: a chunk takes every item that can share its review, an item with R above 5 forms its own chunk, an item waits while an item that blocks it is still in the plan, and only the next release's items start.
|
||||
|
||||
Record each chunk's predicted parts beside the parts its merged diff touched, so a later item can measure how often the predictions miss and tune the pass. Name the source of each part's boundaries per language, such as the Python `ast` module, or say where the pass falls back to line ranges.
|
||||
|
||||
### 352. Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.
|
||||
|
||||
lilleman's calls, 2026-11-12. Without asking, the loop may create child issues in the epic, edit the summary, description and scores of issues it created, and comment on and transition any issue in the epic. It never edits the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. A finished item moves by the transition and to the status the config names, since each Jira workflow differs. An issue the loop files goes into Jira rank by its score among the issues the loop filed. A security finding is filed in the epic like any item, labelled `security` and ranked first, never with a secret's value. R is above 5, so this item ships alone.
|
||||
@@ -147,13 +165,33 @@ lilleman's calls, 2026-11-12: one page per record, whose ID the config names. Th
|
||||
|
||||
lilleman's call, 2026-11-12: the folder replaces the default, as item 347's principles folder does. Readers: the reviewers under `agents/`, the judge's records, larv-review, and the repo check that keeps the standards present.
|
||||
|
||||
### 372. Key loop-claude's lock, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361. Items 373 to 375 run several chunks of one project at once. Today a project has one session and one chunk at a time. This item makes two loop-claudes in one project, each on its own chunk, safe to run side by side. It doesn't yet start them; item 375 does that.
|
||||
|
||||
Key per chunk, not per project: the session lock, the archive keys, routing's state, and loop-claude's record of its running loop. Serialize item 345's commits to the config's folder, `~/.claude-projects/<key>/`, with a file lock, since two chunks may commit there at once. Leave `todo.md`'s and `CHANGELOG.md`'s edits to item 374, which moves them to merge time. A test runs two loops in one project and checks that neither reads or overwrites the other's state.
|
||||
|
||||
`bin/loop_claude/cycle/run.py:154` `rule` and `run.py:94` `archived` are places the comprehension seats found hard: the archive helpers sit in the cycle runner, and `rule` archives twice in an order only the code states. Make them easier to read where the archive keys change.
|
||||
|
||||
### 374. Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361, which also asked that a chunk keep waiting for a human approval while others run. With several chunks open, `chunk-pr merge` merges one pull request at a time. For each it rebases the branch onto the default branch, then writes the item's `todo-item finish` and its changelog bullet, then reruns the gate, then merges. Moving those edits to merge time keeps `todo.md` and `CHANGELOG.md` out of every chunk's conflicts.
|
||||
|
||||
Where the rebase conflicts, the chunk's worker resolves it, and only the review passes whose triggers the resolution meets rerun (`larv-review` §3). The paired ruling reruns against the new base after every rebase that brought in another chunk's merge. This revises `docs/decisions.md`'s entry on the last measured commit, so a ruling never charges one chunk with another's change. A chunk whose pull request waits for the approvals item 360 waits for stays in the queue without blocking the next one. It resumes in its own session when a review comment arrives, answers it, and goes back to waiting.
|
||||
|
||||
`bin/chunk_preflight/choices.py:80` `forge_of` is a place the comprehension seats found hard: forge code split across tools. Where this item touches it, build on item 287's forge module if that has shipped.
|
||||
|
||||
### 359. Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.
|
||||
|
||||
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
|
||||
|
||||
### 361. Start the next item that doesn't touch a waiting pull request's files, in its own worktree and session, while that pull request waits for a human approval, and answer review comments on waiting pull requests as they arrive.
|
||||
### 375. Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.
|
||||
|
||||
lilleman's call, 2026-11-12. Today a project has one session and one chunk at a time; this changes that core, so archive keys, loop-inbox, routing, the session lock and item 345's commits to the project repo all learn more than one open chunk. A chunk whose pull request gets a review comment resumes in its own session. R is above 5, so this item ships alone.
|
||||
lilleman's call, 2026-11-13, splitting item 361. lilleman knows tmux and prefers it. loop-claude runs each chunk in its own window of one tmux session named for the project, such as session `loop-claude-config` with windows `item-372` and `item-373`. It runs up to the number of chunks the project's config allows at once, with 1 as the default, and starts the next chunk item 373's pass allows as each one merges. It uses tmux even at 1, so every project runs the same workflow (goal 1.3). Each window holds a loop-claude for its one chunk, so the interrupt and `/talk` work there as on any terminal. When a chunk waits for the human, loop-claude marks its window, renaming it to end in ` ?` and ringing the bell so tmux's status bar shows it, and clears the mark once it is answered.
|
||||
|
||||
Before starting anything — a worktree, a session, a window — loop-claude checks that tmux is installed at the needed version or later. Where it is missing or older, it stops and names the version it found and the one it needs. The needed version is the oldest that has every tmux command and option loop-claude uses, read from tmux's `CHANGES` file and cited in the decision that records it.
|
||||
|
||||
The config key for the parallel limit is a syntax users write, so a panel seated from the README's audience picks its spelling (`CLAUDE.md` → "Working loop" → "Bench a syntax"). run-heavy already sizes its slots from the machine, at one per 4 CPUs and with memory from `MemTotal`, so a larger VM runs more heavy commands at once without a change here.
|
||||
|
||||
### 319. Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user