fix(kvb-org-organize): move the council root out of /tmp with a lossless migration
councilroot.py resolves one durable council root for every script and migrates the old /tmp root under the held locks: a preflight conflict moves nothing, each legacy file is renamed to a staging name before it is copied so a late writer is merged by the catch-up, id-less journals merge by line multiset, a differing whole file is kept beside its namesake, and a crash marker makes install copy the skills and report. One settings-file list, managed drop-ins included, serves councilroot.py and queue.py. Tests run once on unify/skills-20261114 after the merge (operator order 2026-11-14). 🎯 Fix: 88 % 💥 Break: 7 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 82 🚦 Gate: ⛔ fix 88 % < 90, break 7 % > 5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
699f3227c9
commit
8726ed37a7
47 files changed
+2199
-191
No files matched your search
@@ -28,8 +28,8 @@ commit starts from zero.
|
||||
include or target expression means the list may be short: read that line
|
||||
and name the gap. A project without any target keeps the gate open; ask
|
||||
the operator.
|
||||
3. **Status**: `gate.py status --repo <root>`. `gate: green` ends here; a
|
||||
`missing hotfix` reason means back to step 1.
|
||||
3. **Status**: `gate.py status --repo <root>`. `gate: green` ends here;
|
||||
`missing hotfix` means step 1.
|
||||
4. **Admit**: every gate target is heavy and runs only inside
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-queue/scripts/queue.py hold`.
|
||||
Only a single test module
|
||||
@@ -40,17 +40,18 @@ commit starts from zero.
|
||||
background; give the operator `tail -f` on the log:
|
||||
|
||||
```bash
|
||||
queue.py hold --kind <kind> --task <register task> -- gate.py run --repo <root> --target <t> [--target ...] --log-dir /tmp/<slug> [--fail-regex <re> ...]
|
||||
queue.py hold --kind <kind> --task <register task> -- gate.py run --repo <root> --target <t> [--target ...] --log-dir <logs> [--fail-regex <re> ...]
|
||||
```
|
||||
|
||||
`<logs>`: what `${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py dir gates <slug>` prints; stop when it fails.
|
||||
|
||||
Pass one `--fail-regex` per failure line the project prints while exiting
|
||||
0; infinito-nexus needs `FAILED TARGETS: \S`. A non-zero exit, a
|
||||
`make: ***` line, a matching regex or modified tracked files make a
|
||||
target red; the last stops the run. Before each target `run` asks
|
||||
`hotfix.py void` for it and every later one. Exit 3 (`void: merge main
|
||||
for hotfix <slug>, then rerun`): back to step 1, then through the queue
|
||||
again. Exit 75: the worktree is
|
||||
busy, the message names the holder; wait, then rerun.
|
||||
again. Exit 75: busy worktree, holder named; wait, rerun.
|
||||
6. **Judge** every red target by its `status` line and the log around it:
|
||||
caused by the change, already red on the default branch, or the
|
||||
environment. Fix the cause and rerun; looking unrelated never makes it
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
"""Gate rules, branch parents and gate receipts of every repository on this host.
|
||||
|
||||
Args:
|
||||
--db: the SQLite database of rules and parents, default
|
||||
~/.local/state/agents-council/gates.db (GATES_DB overrides it); it
|
||||
survives reboots, the council root under /tmp does not. Only rule and
|
||||
parents add|drop|derive write it; every other command opens it
|
||||
read-only and an absent one as empty.
|
||||
--db: the SQLite database of rules and parents, default gates.db in the
|
||||
durable council root (councilroot.py durable of kvb-org-organize;
|
||||
GATES_DB overrides it). Only rule and parents add|drop|derive write
|
||||
it; every other command opens it read-only and an absent one as
|
||||
empty.
|
||||
|
||||
rule set --repo R --branch B --action A --level L: the branch's own level
|
||||
for one action. rule drop --repo R --branch B --action A removes it.
|
||||
@@ -48,7 +48,8 @@ Args:
|
||||
branch's merge level before it leaves. Each passes when a receipt for the tree meets the resolved
|
||||
level, else prints the command that produces it and exits 1:
|
||||
`gates.py quick` for quick; above it `queue.py hold --receipt <level>`
|
||||
of `make <level>` with INFINITO_TEST_GPU=false, held as kind
|
||||
of `make <level>` with INFINITO_TEST_GPU=false and its log in the
|
||||
council root's gates/, which it creates, held as kind
|
||||
quality-high for e2e, else as the level, with the open register task
|
||||
whose branch is B. post-checkout: parents record on a branch
|
||||
checkout; it exits 0 even when recording fails.
|
||||
@@ -63,9 +64,9 @@ Args:
|
||||
Journals:
|
||||
Receipts {id, repo, tree, level, gpu, log, at} and recorded parents {id,
|
||||
repo, branch, parent} are rows of gate-receipts.jsonl and
|
||||
gate-parents.jsonl in the council root (AGENTS_COUNCIL_ROOT, else
|
||||
/tmp/agents-council), which sandboxed agents can write; the watch hook of
|
||||
kvb-org-organize copies them to ~/.local/state/agents-council, and reading
|
||||
gate-parents.jsonl in the council root (councilroot.py root of
|
||||
kvb-org-organize), which sandboxed agents can write; the watch hook of
|
||||
kvb-org-organize copies them to the host-only durable root, and reading
|
||||
merges both by id; a row whose id is no string is skipped. A receipt
|
||||
carries INFINITO_TEST_GPU of the environment that wrote it as gpu; it
|
||||
meets its own level and every lower one, above quick only with gpu
|
||||
@@ -99,7 +100,6 @@ LEVELS = ("none", "quick", "test", "quality-high", "e2e")
|
||||
ACTIONS = ("commit", "merge", "push", "pr")
|
||||
SOURCES = ("recorded", "derived", "operator")
|
||||
DROPPED = "dropped"
|
||||
DEFAULT_DB = Path.home() / ".local" / "state" / "agents-council" / "gates.db"
|
||||
SKILLS = Path(__file__).resolve().parents[2]
|
||||
QUEUE = SKILLS / "kvb-org-queue" / "scripts" / "queue.py"
|
||||
RASCI = SKILLS / "kvb-org-rasci" / "scripts" / "rasci.py"
|
||||
@@ -137,6 +137,8 @@ def module(name: str, path: Path) -> ModuleType:
|
||||
|
||||
|
||||
watch = module("kvb_gates_watch", SKILLS / "kvb-org-organize" / "scripts" / "watch.py")
|
||||
DEFAULT_DB = watch.KEPT / "gates.db"
|
||||
LOGS = "gates"
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
@@ -250,7 +252,8 @@ def receipted(repo: str, tree: str, level: str) -> bool:
|
||||
def opened(path: Path, write: bool, kept_dir: Path) -> sqlite3.Connection:
|
||||
"""Args:
|
||||
path: gates.db; read-only unless write, in memory when it is missing.
|
||||
write: open it for rule and parent changes.
|
||||
write: open it for rule and parent changes; OSError when path or its
|
||||
directory is a link or path no regular file with a single link.
|
||||
kept_dir: the directory holding the kept gate-parents.jsonl: watch.KEPT
|
||||
on the host, the read-only mount of it in the hub.
|
||||
|
||||
@@ -260,6 +263,7 @@ def opened(path: Path, write: bool, kept_dir: Path) -> sqlite3.Connection:
|
||||
"""
|
||||
if write:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.close(watch.nofollow.open_below(path.parent, path, os.O_RDWR | os.O_CREAT, FILE_MODE))
|
||||
db = sqlite3.connect(path)
|
||||
elif path.exists():
|
||||
db = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True)
|
||||
@@ -466,7 +470,10 @@ def task_of(branch: str) -> str:
|
||||
def producer(worktree: str, branch: str, level: str, tree: str) -> str:
|
||||
if level == "quick":
|
||||
return shlex.join(["python3", str(Path(__file__).resolve()), "quick", "--worktree", worktree])
|
||||
log = Path(tempfile.gettempdir()) / f"gate-{tree[:12]}-{level}.log"
|
||||
try:
|
||||
log = watch.councilroot.directory(watch.ROOT, LOGS) / f"gate-{tree[:12]}-{level}.log"
|
||||
except (OSError, ValueError) as error:
|
||||
return f"nothing until the council root is fixed: {error}"
|
||||
return shlex.join([
|
||||
"env", "-C", worktree, f"INFINITO_TEST_GPU={GPU_OFF}", "python3", str(QUEUE), "hold", "--kind", KINDS[level],
|
||||
"--task", task_of(branch), "--receipt", level, "--log", str(log), "--", "make", level,
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
# Journal
|
||||
|
||||
Each `--message-block` render appends one row to
|
||||
`${AGENTS_COUNCIL_ROOT:-/tmp/agents-council}/scores.jsonl`: time, origin
|
||||
`scores.jsonl` in the council root that `councilroot.py root` prints: time, origin
|
||||
remote, top level path, branch, `sha` null, the six values and the block's
|
||||
digest. The hub's burndown draws it as overlays; no gate reads it. A failed
|
||||
append prints one stderr line and keeps the exit code; a linked council
|
||||
root or a link, FIFO or other non-regular file at the journal fails it
|
||||
without blocking, through `nofollow.py` of `kvb-org-organize`; when that
|
||||
helper is missing or unusable, the line names it. A new council root gets mode
|
||||
helper or `councilroot.py` is missing or unusable, the line names it. A new council root gets mode
|
||||
0700, a new journal 0600.
|
||||
|
||||
The journal lives in `/tmp`, so a reboot or another PC starts empty. Refill
|
||||
The journal survives a reboot, but another PC starts empty. Refill
|
||||
it from the blocks in git history, without a model:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -217,7 +217,11 @@ def main() -> int:
|
||||
except LookupError as error:
|
||||
print(f"backfill: {error}", file=sys.stderr)
|
||||
return 2
|
||||
path = journal_path()
|
||||
try:
|
||||
path = journal_path()
|
||||
except OSError as error:
|
||||
print(f"backfill: journal: {error}", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
keys = known(path)
|
||||
except (OSError, ValueError) as error:
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""Labels and score journal shared by score.py and backfill.py of kvb-check-score.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
/tmp/agents-council when unset or empty. The journal is its scores.jsonl,
|
||||
display data for the hub's burndown only, never a gate input.
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory the
|
||||
kvb-org-organize councilroot.py resolves, shared by every agent on the
|
||||
host. The journal is its scores.jsonl, display data for the hub's
|
||||
burndown only, never a gate input.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +12,6 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from collections.abc import Callable
|
||||
@@ -20,9 +20,10 @@ from types import ModuleType
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
LABELS = Path(__file__).resolve().parents[1] / "labels.json"
|
||||
NOFOLLOW = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts" / "nofollow.py"
|
||||
ORGANIZE = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts"
|
||||
NOFOLLOW = ORGANIZE / "nofollow.py"
|
||||
COUNCIL_ROOT = ORGANIZE / "councilroot.py"
|
||||
JOURNAL = "scores.jsonl"
|
||||
COUNCIL = "/tmp/agents-council"
|
||||
SCP = re.compile(r"(?:[^@/:]+@)?([^/:]+):(?!//)(.+)")
|
||||
FILE_MODE = 0o600
|
||||
|
||||
@@ -39,7 +40,11 @@ def load_labels(path: Path) -> dict:
|
||||
|
||||
|
||||
def journal_path() -> Path:
|
||||
return Path(os.environ.get("AGENTS_COUNCIL_ROOT") or COUNCIL) / JOURNAL
|
||||
"""Returns:
|
||||
scores.jsonl in the council root; OSError naming councilroot.py of
|
||||
kvb-org-organize when it is missing or unusable.
|
||||
"""
|
||||
return helper(COUNCIL_ROOT, "kvb_score_councilroot", lambda loaded: loaded.root()) / JOURNAL
|
||||
|
||||
|
||||
def git(repo: Path | str, *args: str) -> str:
|
||||
@@ -130,13 +135,15 @@ def line(row: dict) -> str:
|
||||
return json.dumps(row, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def unusable(error: Exception) -> OSError:
|
||||
return OSError(f"helper {NOFOLLOW} unusable ({type(error).__name__}): install or update kvb-org-organize")
|
||||
def unusable(path: Path, error: Exception) -> OSError:
|
||||
return OSError(f"helper {path} unusable ({type(error).__name__}): install or update kvb-org-organize")
|
||||
|
||||
|
||||
def nofollow[T](use: Callable[[ModuleType], T]) -> T:
|
||||
def helper[T](path: Path, name: str, use: Callable[[ModuleType], T]) -> T:
|
||||
"""Args:
|
||||
use: what to do with nofollow.py of kvb-org-organize.
|
||||
path: a script of kvb-org-organize.
|
||||
name: the module name it loads under.
|
||||
use: what to do with it.
|
||||
|
||||
Returns:
|
||||
The result of use; its OSError unchanged, any other failure loading
|
||||
@@ -144,17 +151,27 @@ def nofollow[T](use: Callable[[ModuleType], T]) -> T:
|
||||
FileNotFoundError.
|
||||
"""
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("kvb_score_nofollow", NOFOLLOW)
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
loaded = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(loaded)
|
||||
except Exception as error: # noqa: BLE001
|
||||
raise unusable(error) from None
|
||||
raise unusable(path, error) from None
|
||||
try:
|
||||
return use(loaded)
|
||||
except OSError:
|
||||
raise
|
||||
except Exception as error: # noqa: BLE001
|
||||
raise unusable(error) from None
|
||||
raise unusable(path, error) from None
|
||||
|
||||
|
||||
def nofollow[T](use: Callable[[ModuleType], T]) -> T:
|
||||
"""Args:
|
||||
use: what to do with nofollow.py of kvb-org-organize.
|
||||
|
||||
Returns:
|
||||
helper() of it.
|
||||
"""
|
||||
return helper(NOFOLLOW, "kvb_score_nofollow", use)
|
||||
|
||||
|
||||
def append(path: Path, rows: list[dict]) -> None:
|
||||
|
||||
@@ -294,7 +294,11 @@ def journal(args: argparse.Namespace, total: int, block: str) -> None:
|
||||
"fix": plain(args.fix), "break": plain(args.risk), "tokens": plain(args.efficiency),
|
||||
"velocity": plain(args.speed), "security": plain(args.security[0]), "score": total,
|
||||
}
|
||||
path = journal_path()
|
||||
try:
|
||||
path = journal_path()
|
||||
except OSError as error:
|
||||
print(f"score: journal: {error}", file=sys.stderr)
|
||||
return
|
||||
try:
|
||||
here = Path.cwd()
|
||||
append(path, [entry(int(time.time()), origin(here), git_read(here, "branch", "--show-current") or None, None, values, block)])
|
||||
|
||||
@@ -32,6 +32,7 @@ rules forbidding raw commands.
|
||||
joins Step 4) and `worktrees.md` next to this file when present.
|
||||
- **Agent dirs**: pip, npm, pre-commit, act, gh, buildx caches; Ansible and
|
||||
build temp dirs.
|
||||
- **Council root** (`~/.local/state/agents-shared`): `archive/` only.
|
||||
- **Register**: `council.py list --long`; `rasci.py artifacts` (`kvb-org-artefacts`,
|
||||
`--ended` for candidates).
|
||||
- **Queue**: `${CLAUDE_SKILL_DIR}/../kvb-org-queue-cleanup/scripts/cleanup.py
|
||||
|
||||
@@ -9,11 +9,14 @@ approval is the operator's word for one commit, the exact tree it names, only
|
||||
once the operator's pinned passkey signature over it verifies here.
|
||||
|
||||
1. Render the page. `<repo>` is the repository's name, `<branch>` the
|
||||
branch with every `/` as `-`, `<base>` the branch's base and `<table>` a
|
||||
file under `/tmp` holding the kvb-check-score commit table:
|
||||
branch with every `/` as `-`, `<base>` the branch's base, `<table>` a
|
||||
file under `/tmp` holding the kvb-check-score commit table, `<pages>`
|
||||
and `<approvals>` the directories
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py dir pages`
|
||||
and `... dir approvals` print, in the council root the hub reads:
|
||||
|
||||
```bash
|
||||
pkgmgr review --out /tmp/kvb-git-diff/<repo>-<branch>.html --max-file-lines 400 --base <base> --note <table>
|
||||
pkgmgr review --out <pages>/<repo>-<branch>.html --max-file-lines 400 --base <base> --note <table>
|
||||
```
|
||||
|
||||
2. Request the review in the worktree; it ships the staged diff, every file
|
||||
@@ -23,7 +26,7 @@ once the operator's pinned passkey signature over it verifies here.
|
||||
`<agent>` your agent name, which inline feedback is posted to:
|
||||
|
||||
```bash
|
||||
python3 ~/.local/share/kvb-orchestrator/client/approval.py request --port 8737 --title "<subject>" --page /tmp/kvb-git-diff/<repo>-<branch>.html --notes <table> --gate <gate> --score "<score line>" --agent "<agent>"
|
||||
python3 ~/.local/share/kvb-orchestrator/client/approval.py request --port 8737 --title "<subject>" --page <pages>/<repo>-<branch>.html --notes <table> --gate <gate> --score "<score line>" --agent "<agent>"
|
||||
```
|
||||
|
||||
Only a `pass` review can be approved in bulk or by a rule. Tell the
|
||||
@@ -37,7 +40,7 @@ once the operator's pinned passkey signature over it verifies here.
|
||||
first, `<gate>` being the `gate` from step 2:
|
||||
|
||||
```bash
|
||||
python3 ~/.local/share/kvb-orchestrator/client/approval.py verify --port 8737 --approvers ~/.config/kvb-orchestrator/approvers.json --replay /tmp/kvb-orchestrator-approvals/commit.json --review <id> --gate <gate>
|
||||
python3 ~/.local/share/kvb-orchestrator/client/approval.py verify --port 8737 --approvers ~/.config/kvb-orchestrator/approvers.json --replay <approvals>/commit.json --review <id> --gate <gate>
|
||||
```
|
||||
|
||||
Exit 0 only: commit as the calling skill says. Any other exit,
|
||||
|
||||
@@ -26,11 +26,14 @@ hands over, `kvb-git-pr-create`, `kvb-git-update-branches` and
|
||||
output streamed to a log; give the operator `tail -f <log>`:
|
||||
|
||||
```bash
|
||||
queue.py hold --kind <kind> --task <register task> -- python3 <gate.py> hold --repo <root> -- make <target> 2>&1 | tee /tmp/kvb-git-push-<slug>-<N>.log
|
||||
queue.py hold --kind <kind> --task <register task> -- python3 <gate.py> hold --repo <root> -- make <target> 2>&1 | tee <gates>/kvb-git-push-<slug>-<N>.log
|
||||
```
|
||||
|
||||
`<gate.py>` is `${CLAUDE_SKILL_DIR}/../kvb-check-gate/scripts/gate.py`;
|
||||
its worktree lock keeps a sync out while the gate runs.
|
||||
its worktree lock keeps a sync out while the gate runs. `<gates>` is the
|
||||
directory
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py dir gates`
|
||||
prints, so the evidence survives a reboot.
|
||||
5. **Judge** by the gate's own result tables and its failure line
|
||||
(infinito-nexus: the `📊 per-target wall-clock` table and `FAILED
|
||||
TARGETS:`), never by the exit code of a pipe. Green also needs HEAD and
|
||||
|
||||
@@ -14,7 +14,7 @@ outranks them and appoints or recalls at will.
|
||||
## Election
|
||||
|
||||
`${CLAUDE_SKILL_DIR}/scripts/council.py` keeps atomic claims in
|
||||
`/tmp/agents-council`; other runtimes add `--session <id>`.
|
||||
`$(${CLAUDE_SKILL_DIR}/scripts/councilroot.py root)`; other runtimes add `--session <id>`.
|
||||
|
||||
1. Name the office: `work/<slug>` (a piece of work), `cluster/<slug>` (a
|
||||
strand across lines), `<dimension>/<line>` (a line) or `chair`, the slug
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"""Claim, release and list kvb-org-organize offices in the shared council directory.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
/tmp/agents-council unless set, because all agents must agree on it.
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory
|
||||
councilroot.py resolves, shared by every agent on the host.
|
||||
CLAUDE_CODE_SESSION_ID: the caller's session, taken over --session; other
|
||||
runtimes pass --session.
|
||||
PATH: filtered to the directories hookpath.py trusts before git runs.
|
||||
@@ -44,7 +44,7 @@ def sibling(name: str) -> ModuleType:
|
||||
|
||||
nofollow = sibling("nofollow")
|
||||
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
ROOT = sibling("councilroot").root()
|
||||
HEARTBEAT_LIMIT = 3600
|
||||
OFFICE = re.compile(r"^[a-z0-9][a-z0-9._-]*(/[a-z0-9][a-z0-9._-]*)*$")
|
||||
CLAIM = "claim.json"
|
||||
|
||||
+851
@@ -0,0 +1,851 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Usage:
|
||||
councilroot.py root
|
||||
councilroot.py durable
|
||||
councilroot.py dir PART [PART ...]
|
||||
councilroot.py release VERSION
|
||||
councilroot.py migrate [--legacy DIR] [--catch-up]
|
||||
councilroot.py preflight [--legacy DIR] [--settings FILE] [--managed DIR]
|
||||
councilroot.py retire [--days N]
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: the council root when it is an absolute path.
|
||||
XDG_STATE_HOME: else both roots lie below it, when it is an absolute path.
|
||||
HOME: else both lie below ~/.local/state.
|
||||
AGENTS_COUNCIL_LEGACY: the default DIR of migrate and preflight, LEGACY
|
||||
unless set.
|
||||
|
||||
Args:
|
||||
root: print the council root.
|
||||
durable: print the host-only root; AGENTS_COUNCIL_ROOT never moves it.
|
||||
dir: create <root>/PART/... with mode 700 where missing, refusing a
|
||||
level that is a link, not the current user's or writable by group or
|
||||
others, and print it:
|
||||
pages holds the kvb-git-diff review pages the hub reads, approvals
|
||||
the replay stores of approval.py verify, gates the gate logs.
|
||||
release: create agents-release/VERSION beside the roots with mode 700
|
||||
and print it: the kvb-release drafts, which the release skills write
|
||||
with the Edit and Write tools.
|
||||
migrate: move every regular file below DIR, LEGACY unless given, to the
|
||||
same place below the root and remove the emptied directories, through
|
||||
nofollow.py, so no link on either side is followed; each copy is
|
||||
written to a temp file and linked into place, so it never replaces a
|
||||
file. Refuses, moving nothing, while a *.lock below DIR is held or
|
||||
its queue.json holds a job, and, under those locks and unless
|
||||
--catch-up is given, while a regular file cannot be opened or its
|
||||
place below the root is reached through a link (`unmoved <path>:
|
||||
<reason>`) or a whole file the root holds differs (`conflict <file>
|
||||
differs from <legacy file>`). A file the root already holds is never
|
||||
overwritten: an identical one leaves only the root's copy; a .jsonl
|
||||
journal gets the legacy rows it lacks, by id when every row on both
|
||||
sides carries one, else each exact line as often as the legacy side
|
||||
holds it more often, appended or, when every row carries a ts, in ts
|
||||
order; with --catch-up a differing whole file is copied beside its
|
||||
namesake as <name>.legacy-<12 hex digits of its sha256> (`kept
|
||||
<legacy file> beside <file> as <copy>`). Each file is first renamed
|
||||
to <name>.<16 hex digits>.migrating and copied from there, so a
|
||||
writer that opens the old name meanwhile makes a new file for the
|
||||
catch-up; a later run moves a staged file to its old name. A link or
|
||||
another non-regular entry stays (`skipped <path>: <reason>`); a file
|
||||
that fails after the check stays (`unmoved <path>: <reason>`).
|
||||
<durable>/migrate.started exists from the first move to the end of
|
||||
the run, so after a crash it tells the install the move stopped
|
||||
halfway; a completed run removes it. A second run moves nothing new
|
||||
and duplicates no journal row. Run it while no agent, unit or queue
|
||||
job writes either root; the install runs it again with --catch-up
|
||||
after the copy for what the old skills wrote meanwhile.
|
||||
preflight: print to stderr every reason migrate would refuse, and every
|
||||
missing or wrong sandbox.filesystem.allowWrite entry, all files only
|
||||
read: the root and agents-release must be in the user file
|
||||
(--settings, ~/.claude/settings.json unless given); no entry of it,
|
||||
of the managed and user files settings_files() lists (--managed DIR,
|
||||
/etc/claude-code unless given, with its managed-settings.d drop-ins;
|
||||
the queue's permission check reads the same list), of a
|
||||
.claude/settings.json or .claude/settings.local.json up to 8 levels
|
||||
below the pkgmgr repositories and worktrees directories, directory
|
||||
links followed, or in the start directory of a session listed in
|
||||
~/.claude/projects may be the host-only root, inside it or above it.
|
||||
It warns, without failing, while the agents are not suspended. The
|
||||
global install runs it before it copies anything.
|
||||
retire: move every regular file below <root>/gates and <root>/pages
|
||||
changed more than N days ago (30 unless given) to the same place
|
||||
below <root>/archive/<date>, which no reader opens, never following
|
||||
a link, and print the count.
|
||||
|
||||
Exit codes:
|
||||
0 done, 2 usage error, a refused preflight, a busy legacy root, a root
|
||||
that cannot be created, or a legacy or council root that is a link, not
|
||||
a directory of the current user, writable by group or others, or inside
|
||||
the other, 3 a whole file migrate kept in both roots or beside its
|
||||
namesake, 4 nothing moved for the unmoved and conflict lines printed, 5
|
||||
a partial move: a file that failed after the check stays in DIR; any
|
||||
other code is a crash.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import fcntl
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
NAME = "agents-council"
|
||||
SHARED = "agents-shared"
|
||||
RELEASES = "agents-release"
|
||||
QUEUE = "queue.json"
|
||||
LOCK_SUFFIX = ".lock"
|
||||
ARCHIVE = "archive"
|
||||
RETIRED = ("gates", "pages")
|
||||
RETIRE_DAYS = 30
|
||||
DAY_SECONDS = 86400
|
||||
LEGACY = Path("/tmp/agents-council")
|
||||
DIRECTORY_MODE = 0o700
|
||||
PART = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]*")
|
||||
JOURNAL_SUFFIX = ".jsonl"
|
||||
FILE_BITS = 0o755
|
||||
MANAGED = Path("/etc/claude-code")
|
||||
MARKER = "migrate.started"
|
||||
STAGED = re.compile(r"\.[0-9a-f]{16}\.migrating\Z")
|
||||
PROJECT_FILES = ("settings.json", "settings.local.json")
|
||||
PROJECT_DEPTH = 8
|
||||
PRUNED = frozenset({".git", "node_modules", ".venv", "venv", "__pycache__", ".tox", ".cache", ".mypy_cache", ".pytest_cache", ".ruff_cache", "site-packages"})
|
||||
PKGMGR_DIRECTORIES = {"repositories": "~/Repositories/", "worktrees": "~/.local/share/worktrees/"}
|
||||
NIGHT = "night.json"
|
||||
SUSPENDED = ("suspend", "sunset")
|
||||
LOCK_WAIT = 30
|
||||
ENCODED = re.compile(r"[^A-Za-z0-9]")
|
||||
|
||||
|
||||
def state_home() -> Path:
|
||||
state = os.environ.get("XDG_STATE_HOME", "")
|
||||
return Path(state) if os.path.isabs(state) else Path.home() / ".local" / "state"
|
||||
|
||||
|
||||
def durable() -> Path:
|
||||
return state_home() / NAME
|
||||
|
||||
|
||||
def root() -> Path:
|
||||
explicit = os.environ.get("AGENTS_COUNCIL_ROOT", "")
|
||||
return Path(explicit) if os.path.isabs(explicit) else state_home() / SHARED
|
||||
|
||||
|
||||
def directory(base: Path, *parts: str) -> Path:
|
||||
"""Args:
|
||||
base: the directory the parts lie below; its missing parents are
|
||||
created with the default mode.
|
||||
parts: path segments, each matching PART.
|
||||
|
||||
Returns:
|
||||
base/parts, each level from base down created with mode 700 where
|
||||
missing; ValueError for a part that does not match PART or a level
|
||||
that refusal() names: a link, not a directory of the current user,
|
||||
or writable by group or others.
|
||||
"""
|
||||
bad = [part for part in parts if not PART.fullmatch(part)]
|
||||
if bad:
|
||||
raise ValueError(f"not a directory name: {bad[0]!r}")
|
||||
base.parent.mkdir(parents=True, exist_ok=True)
|
||||
levels = [base]
|
||||
for part in parts:
|
||||
levels.append(levels[-1] / part)
|
||||
for level in levels:
|
||||
with contextlib.suppress(FileExistsError):
|
||||
level.mkdir(mode=DIRECTORY_MODE)
|
||||
problem = refusal(level)
|
||||
if problem is not None:
|
||||
raise ValueError(problem)
|
||||
return levels[-1]
|
||||
|
||||
|
||||
def nofollow() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("kvb_councilroot_nofollow", Path(__file__).resolve().parent / "nofollow.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def refusal(path: Path) -> str | None:
|
||||
info = path.lstat()
|
||||
if stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid() and not info.st_mode & 0o022:
|
||||
return None
|
||||
return f"{path} must be a directory of uid {os.getuid()} that group and others cannot write"
|
||||
|
||||
|
||||
def row_ids(text: str) -> list[tuple[str, str]] | None:
|
||||
"""Returns:
|
||||
(id key, line) per non-empty line, the id serialised as JSON; None
|
||||
when a line is no JSON object with an id.
|
||||
"""
|
||||
rows = []
|
||||
for line in text.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except (ValueError, RecursionError):
|
||||
return None
|
||||
if not isinstance(row, dict) or "id" not in row:
|
||||
return None
|
||||
rows.append((json.dumps(row["id"], sort_keys=True), line))
|
||||
return rows
|
||||
|
||||
|
||||
def copied(helper: ModuleType, legacy: Path, source: Path, target_root: Path, target: Path) -> bool:
|
||||
"""Returns:
|
||||
True once source is copied, with its mode and times, to a temp file
|
||||
that is then linked to the name target; False when target exists,
|
||||
which stays untouched.
|
||||
"""
|
||||
*dirs, name = helper.parts_below(target_root, target)
|
||||
with open(helper.open_below(legacy, source, os.O_RDONLY, 0), "rb") as handle:
|
||||
info = os.fstat(handle.fileno())
|
||||
folder = helper.directory(target_root, tuple(dirs), True)
|
||||
temp = f".{name}.{os.urandom(8).hex()}"
|
||||
try:
|
||||
with open(os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, dir_fd=folder), "wb") as out:
|
||||
shutil.copyfileobj(handle, out)
|
||||
out.flush()
|
||||
os.fchmod(out.fileno(), info.st_mode & FILE_BITS)
|
||||
os.utime(out.fileno(), ns=(info.st_atime_ns, info.st_mtime_ns))
|
||||
os.fsync(out.fileno())
|
||||
try:
|
||||
os.link(temp, name, src_dir_fd=folder, dst_dir_fd=folder, follow_symlinks=False)
|
||||
except FileExistsError:
|
||||
return False
|
||||
return True
|
||||
finally:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(temp, dir_fd=folder)
|
||||
os.close(folder)
|
||||
|
||||
|
||||
def content(helper: ModuleType, base: Path, path: Path) -> bytes:
|
||||
with open(helper.open_below(base, path, os.O_RDONLY, 0), "rb") as handle:
|
||||
return handle.read()
|
||||
|
||||
|
||||
def novel(text: str, legacy_text: str) -> tuple[list[str], bool]:
|
||||
"""Returns:
|
||||
The legacy lines text lacks and True when both are id journals: each
|
||||
id once; else each exact line as often as legacy_text holds it more
|
||||
often than text, and False.
|
||||
"""
|
||||
ours, theirs = row_ids(text), row_ids(legacy_text)
|
||||
if ours is not None and theirs is not None:
|
||||
known, fresh = {key for key, _ in ours}, []
|
||||
for key, line in theirs:
|
||||
if key not in known:
|
||||
known.add(key)
|
||||
fresh.append(line)
|
||||
return fresh, True
|
||||
have, fresh = Counter(text.splitlines()), []
|
||||
for line in legacy_text.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
if have[line]:
|
||||
have[line] -= 1
|
||||
else:
|
||||
fresh.append(line)
|
||||
return fresh, False
|
||||
|
||||
|
||||
def in_ts_order(lines: list[str]) -> list[str] | None:
|
||||
"""Returns:
|
||||
lines stably sorted by their numeric ts; None when a line is no JSON
|
||||
object with one.
|
||||
"""
|
||||
stamps = []
|
||||
for line in lines:
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except (ValueError, RecursionError):
|
||||
return None
|
||||
stamp = row.get("ts") if isinstance(row, dict) else None
|
||||
if isinstance(stamp, bool) or not isinstance(stamp, int | float):
|
||||
return None
|
||||
stamps.append(stamp)
|
||||
return [line for _, line in sorted(zip(stamps, lines, strict=True), key=lambda pair: pair[0])]
|
||||
|
||||
|
||||
def merged(helper: ModuleType, legacy: Path, source: Path, target_root: Path, target: Path) -> int:
|
||||
"""Returns:
|
||||
The number of novel() legacy rows target gained, under the flock of
|
||||
target and of its <stem>.lock when one exists (the radio's lock):
|
||||
appended, or for a journal compared by line whose rows all carry a
|
||||
ts and would fall out of order, the whole file replaced in ts order.
|
||||
"""
|
||||
legacy_text = helper.read_text(legacy, source)
|
||||
lock = target.with_suffix(LOCK_SUFFIX)
|
||||
with contextlib.ExitStack() as stack:
|
||||
if lock.is_file() and not lock.is_symlink():
|
||||
stack.enter_context(helper.locked(target_root, lock, 0o600, LOCK_WAIT))
|
||||
handle = stack.enter_context(open(helper.open_below(target_root, target, os.O_RDWR | os.O_APPEND, 0), "a+", encoding="utf-8", errors="replace"))
|
||||
handle.seek(0)
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
text = handle.read()
|
||||
fresh, by_id = novel(text, legacy_text)
|
||||
lines = [line for line in text.splitlines() if line.strip()] + fresh
|
||||
order = None if by_id or not fresh else in_ts_order(lines)
|
||||
if order is None or order == lines:
|
||||
handle.write(("" if not fresh or not text or text.endswith("\n") else "\n") + "".join(f"{line}\n" for line in fresh))
|
||||
else:
|
||||
helper.replace(target_root, target, "".join(f"{line}\n" for line in order), os.fstat(handle.fileno()).st_mode & FILE_BITS)
|
||||
return len(fresh)
|
||||
|
||||
|
||||
def beside(helper: ModuleType, legacy: Path, source: Path, target_root: Path, target: Path) -> Path:
|
||||
"""Returns:
|
||||
target.legacy-<first 12 hex digits of the sha256 of source>, a copy
|
||||
of source beside target unless that name already holds it.
|
||||
"""
|
||||
kept = target.with_name(f"{target.name}.legacy-{hashlib.sha256(content(helper, legacy, source)).hexdigest()[:12]}")
|
||||
copied(helper, legacy, source, target_root, kept)
|
||||
return kept
|
||||
|
||||
|
||||
def destination(legacy: Path, source: Path, target_root: Path) -> Path:
|
||||
"""Returns:
|
||||
The place of source below target_root, a staged() suffix dropped.
|
||||
"""
|
||||
relative = source.relative_to(legacy)
|
||||
return target_root / relative.with_name(STAGED.sub("", relative.name))
|
||||
|
||||
|
||||
def staged(helper: ModuleType, legacy: Path, source: Path) -> Path:
|
||||
"""Returns:
|
||||
source renamed in its directory to <name>.<16 hex digits>.migrating,
|
||||
so a writer that opens the old name afterwards creates a new file the
|
||||
catch-up moves; source itself when it already carries such a name.
|
||||
"""
|
||||
if STAGED.search(source.name):
|
||||
return source
|
||||
*dirs, name = helper.parts_below(legacy, source)
|
||||
stage = f"{name}.{os.urandom(8).hex()}.migrating"
|
||||
fd = helper.directory(legacy, tuple(dirs), False)
|
||||
try:
|
||||
os.rename(name, stage, src_dir_fd=fd, dst_dir_fd=fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
return source.with_name(stage)
|
||||
|
||||
|
||||
def settle(helper: ModuleType, legacy: Path, source: Path, target_root: Path, catch_up: bool) -> tuple[str, str | None]:
|
||||
"""Args:
|
||||
helper: nofollow.py.
|
||||
legacy: the earlier council root.
|
||||
source: a regular file below it.
|
||||
target_root: the council root.
|
||||
catch_up: keep a differing whole file beside its namesake instead of
|
||||
leaving it in legacy.
|
||||
|
||||
Returns:
|
||||
(moved, merged, kept, conflict or unmoved, report line), the line
|
||||
None for a plain move or an identical copy; every copy is made from
|
||||
the staged() file, which a line naming a file left in legacy names.
|
||||
"""
|
||||
target, stage = destination(legacy, source, target_root), source
|
||||
try:
|
||||
stage = staged(helper, legacy, source)
|
||||
if copied(helper, legacy, stage, target_root, target) or content(helper, legacy, stage) == content(helper, target_root, target):
|
||||
helper.unlink(legacy, stage)
|
||||
return "moved", None
|
||||
if target.suffix == JOURNAL_SUFFIX:
|
||||
count = merged(helper, legacy, stage, target_root, target)
|
||||
helper.unlink(legacy, stage)
|
||||
return "merged", f"merged {count} rows of {source} into {target}"
|
||||
if catch_up:
|
||||
kept = beside(helper, legacy, stage, target_root, target)
|
||||
helper.unlink(legacy, stage)
|
||||
return "kept", f"kept {source} beside {target} as {kept}"
|
||||
return "conflict", f"conflict {target} differs from {stage}; both kept"
|
||||
except OSError as error:
|
||||
return "unmoved", f"unmoved {stage}: {error.strerror or error}"
|
||||
|
||||
|
||||
def held(helper: ModuleType, legacy: Path, stack: contextlib.ExitStack) -> list[str]:
|
||||
"""Args:
|
||||
helper: nofollow.py.
|
||||
legacy: the earlier council root.
|
||||
stack: keeps every lock this takes until the move ends.
|
||||
|
||||
Returns:
|
||||
Why the move must wait: each *.lock below legacy another process
|
||||
holds, and a queue.json with jobs or that cannot be read.
|
||||
"""
|
||||
problems = []
|
||||
for folder, _, files in os.walk(legacy):
|
||||
for name in files:
|
||||
path = Path(folder) / name
|
||||
if not name.endswith(LOCK_SUFFIX) or not stat.S_ISREG(path.lstat().st_mode):
|
||||
continue
|
||||
try:
|
||||
lock = helper.open_below(legacy, path, os.O_RDONLY, 0)
|
||||
stack.callback(os.close, lock)
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
problems.append(f"{path} is held")
|
||||
except OSError as error:
|
||||
problems.append(f"{path} cannot be locked: {error.strerror or error}")
|
||||
queue = legacy / QUEUE
|
||||
if queue.exists() or queue.is_symlink():
|
||||
try:
|
||||
entries = json.loads(helper.read_text(legacy, queue)).get("entries")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
entries = None
|
||||
if not isinstance(entries, list):
|
||||
problems.append(f"{queue} is unreadable")
|
||||
elif entries:
|
||||
problems.append(f"{queue} holds {len(entries)} queue jobs")
|
||||
return problems
|
||||
|
||||
|
||||
def prune(helper: ModuleType, legacy: Path) -> None:
|
||||
for folder, _, _ in os.walk(legacy, topdown=False):
|
||||
here = Path(folder)
|
||||
if here == legacy:
|
||||
continue
|
||||
*dirs, name = helper.parts_below(legacy, here)
|
||||
with contextlib.suppress(OSError):
|
||||
fd = helper.directory(legacy, tuple(dirs), False)
|
||||
try:
|
||||
os.rmdir(name, dir_fd=fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
with contextlib.suppress(OSError):
|
||||
os.rmdir(legacy)
|
||||
|
||||
|
||||
class Blocked(Exception):
|
||||
"""Args:
|
||||
lines: the conflicts() lines that kept migrate from moving anything.
|
||||
"""
|
||||
|
||||
def __init__(self, lines: list[str]) -> None:
|
||||
super().__init__("; ".join(lines))
|
||||
self.lines = lines
|
||||
|
||||
|
||||
def migrate(legacy: Path, target: Path, catch_up: bool = False) -> list[str]:
|
||||
"""Args:
|
||||
legacy: the earlier council root.
|
||||
target: the council root.
|
||||
catch_up: move what conflicts() names too, keeping a differing whole
|
||||
file beside its namesake, instead of refusing.
|
||||
|
||||
Returns:
|
||||
The report lines, the moved count first, the rest sorted; ValueError
|
||||
naming the refused root when either is a link, not a directory of the
|
||||
current user, writable by group or others, or lies inside the other,
|
||||
and naming every reason held() finds, moving nothing; without
|
||||
catch_up, Blocked naming every conflicts() line found under the
|
||||
held locks, moving nothing.
|
||||
"""
|
||||
helper = nofollow()
|
||||
if not legacy.exists() and not legacy.is_symlink():
|
||||
unmark(helper)
|
||||
return []
|
||||
problem = refusal(legacy)
|
||||
if problem is not None:
|
||||
raise ValueError(problem)
|
||||
if legacy.resolve() == target.resolve():
|
||||
return []
|
||||
with contextlib.ExitStack() as stack:
|
||||
problems = held(helper, legacy, stack)
|
||||
if problems:
|
||||
raise ValueError("; ".join(problems) + "; nothing moved")
|
||||
blocked = [] if catch_up else conflicts(helper, legacy, target)
|
||||
if blocked:
|
||||
raise Blocked(blocked)
|
||||
return move(legacy, target, catch_up)
|
||||
|
||||
|
||||
def move(legacy: Path, target: Path, catch_up: bool) -> list[str]:
|
||||
target.mkdir(mode=DIRECTORY_MODE, parents=True, exist_ok=True)
|
||||
problem = refusal(target)
|
||||
if problem is not None:
|
||||
raise ValueError(problem)
|
||||
old, new = legacy.resolve(), target.resolve()
|
||||
if old.is_relative_to(new) or new.is_relative_to(old):
|
||||
raise ValueError(f"{legacy} and {target} must not lie inside each other")
|
||||
helper = nofollow()
|
||||
host = directory(durable())
|
||||
helper.replace(host, host / MARKER, f"{legacy} -> {target}\n", 0o600)
|
||||
moved, lines = 0, []
|
||||
for folder, folders, files in os.walk(legacy):
|
||||
here = Path(folder)
|
||||
lines += [f"skipped {here / name}: a link" for name in folders if (here / name).is_symlink()]
|
||||
for name in sorted(files):
|
||||
source = here / name
|
||||
try:
|
||||
regular = stat.S_ISREG(source.lstat().st_mode)
|
||||
except OSError:
|
||||
continue
|
||||
if not regular:
|
||||
lines.append(f"skipped {source}: not a regular file")
|
||||
continue
|
||||
outcome, line = settle(helper, legacy, source, target, catch_up)
|
||||
moved += outcome == "moved"
|
||||
if line is not None:
|
||||
lines.append(line)
|
||||
prune(helper, legacy)
|
||||
unmark(helper)
|
||||
head = [f"moved {moved} files from {legacy} to {target}"] if moved else []
|
||||
return head + sorted(lines)
|
||||
|
||||
|
||||
def unmark(helper: ModuleType) -> None:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
helper.unlink(durable(), durable() / MARKER)
|
||||
|
||||
|
||||
def unmovable(helper: ModuleType, legacy: Path, source: Path, target: Path, twin: Path) -> str | None:
|
||||
"""Returns:
|
||||
The `unmoved` line migrate would print because source cannot be
|
||||
opened as it opens it, or a directory on the way to twin is a link
|
||||
or no directory; None when nothing stops the copy.
|
||||
"""
|
||||
try:
|
||||
os.close(helper.open_below(legacy, source, os.O_RDONLY, 0))
|
||||
*dirs, _ = helper.parts_below(target, twin)
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.close(helper.directory(target, tuple(dirs), False))
|
||||
except OSError as error:
|
||||
return f"unmoved {source}: {error.strerror or error}"
|
||||
return None
|
||||
|
||||
|
||||
def conflicts(helper: ModuleType, legacy: Path, target: Path) -> list[str]:
|
||||
"""Returns:
|
||||
A line per regular file below legacy that migrate could not move, or
|
||||
that is no .jsonl journal and whose namesake below target differs.
|
||||
"""
|
||||
lines = []
|
||||
for folder, _, files in os.walk(legacy):
|
||||
for name in files:
|
||||
source = Path(folder) / name
|
||||
twin = destination(legacy, source, target)
|
||||
if not stat.S_ISREG(source.lstat().st_mode):
|
||||
continue
|
||||
stuck = unmovable(helper, legacy, source, target, twin)
|
||||
if stuck is not None:
|
||||
lines.append(stuck)
|
||||
continue
|
||||
if not (twin.exists() or twin.is_symlink()):
|
||||
continue
|
||||
try:
|
||||
ours, theirs = content(helper, legacy, source), content(helper, target, twin)
|
||||
except OSError as error:
|
||||
lines.append(f"unmoved {source}: {error.strerror or error}")
|
||||
continue
|
||||
if ours != theirs and source.suffix != JOURNAL_SUFFIX:
|
||||
lines.append(f"conflict {twin} differs from {source}")
|
||||
return lines
|
||||
|
||||
|
||||
def written(entry: object, base: Path) -> Path | None:
|
||||
"""Args:
|
||||
entry: one allowWrite entry.
|
||||
base: the directory a relative entry lies below.
|
||||
|
||||
Returns:
|
||||
The normalised path the entry names, a trailing /** dropped; None for
|
||||
anything but a string.
|
||||
"""
|
||||
if not isinstance(entry, str):
|
||||
return None
|
||||
text = entry.removesuffix("/**").rstrip("/") or "/"
|
||||
path = Path(os.path.expanduser(text[1:] if text.startswith("//") else text))
|
||||
return Path(os.path.normpath(base / path))
|
||||
|
||||
|
||||
def allowed(settings: Path, base: Path) -> list[tuple[str, Path]] | None:
|
||||
"""Returns:
|
||||
(entry, path) per sandbox.filesystem.allowWrite entry of settings,
|
||||
relative ones below base; None when it holds no such list.
|
||||
"""
|
||||
try:
|
||||
entries = json.loads(settings.read_text(encoding="utf-8"))["sandbox"]["filesystem"]["allowWrite"]
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
if not isinstance(entries, list):
|
||||
return None
|
||||
return [(entry, path) for entry in entries if (path := written(entry, base)) is not None]
|
||||
|
||||
|
||||
def pkgmgr_roots() -> list[Path]:
|
||||
"""Returns:
|
||||
The repositories and worktrees directories of the directories block
|
||||
of ~/.config/pkgmgr/config.yaml, pkgmgr's defaults where it names
|
||||
none.
|
||||
"""
|
||||
found = dict(PKGMGR_DIRECTORIES)
|
||||
inside = False
|
||||
with contextlib.suppress(OSError):
|
||||
for line in (Path.home() / ".config" / "pkgmgr" / "config.yaml").read_text(encoding="utf-8").splitlines():
|
||||
text = line.split("#", 1)[0]
|
||||
if text[:1].strip():
|
||||
inside = text.strip() == "directories:"
|
||||
continue
|
||||
key, _, value = text.strip().partition(":")
|
||||
if inside and key in found and value.strip():
|
||||
found[key] = value.strip().strip("'\"")
|
||||
return [Path(os.path.expanduser(value)) for value in found.values()]
|
||||
|
||||
|
||||
def settings_files(project: Path | None, managed: Path | None = None) -> list[Path]:
|
||||
"""Args:
|
||||
project: the start directory of a session; None for only the managed
|
||||
and user files.
|
||||
managed: the managed settings directory, MANAGED unless given.
|
||||
|
||||
Returns:
|
||||
Every Claude Code settings file that can apply there:
|
||||
managed-settings.json and managed-settings.d/*.json in name order,
|
||||
~/.claude/settings.json and settings.local.json, then the project's
|
||||
.claude/settings.json and settings.local.json.
|
||||
"""
|
||||
managed = managed or MANAGED
|
||||
files = [managed / "managed-settings.json", *sorted((managed / "managed-settings.d").glob("*.json"))]
|
||||
files += [Path.home() / ".claude" / name for name in PROJECT_FILES]
|
||||
return files + ([] if project is None else [project / ".claude" / name for name in PROJECT_FILES])
|
||||
|
||||
|
||||
def settings_in(folder: Path) -> list[Path]:
|
||||
"""Returns:
|
||||
folder/.claude/settings.json and settings.local.json where they are
|
||||
files, read through a link like Claude Code does.
|
||||
"""
|
||||
return [path for name in PROJECT_FILES if (path := folder / ".claude" / name).is_file()]
|
||||
|
||||
|
||||
def project_settings(top: Path) -> list[Path]:
|
||||
"""Returns:
|
||||
The settings_in() of every directory at most PROJECT_DEPTH levels
|
||||
below top, in walk order, following directory links but entering each
|
||||
real directory once and never one of PRUNED.
|
||||
"""
|
||||
found, seen = [], set()
|
||||
for folder, folders, _ in os.walk(top, followlinks=True):
|
||||
here = Path(folder)
|
||||
real = os.path.realpath(here)
|
||||
if real in seen:
|
||||
folders[:] = []
|
||||
continue
|
||||
seen.add(real)
|
||||
depth = len(here.relative_to(top).parts)
|
||||
folders[:] = sorted(name for name in folders if name not in PRUNED) if depth < PROJECT_DEPTH else []
|
||||
found += settings_in(here)
|
||||
return found
|
||||
|
||||
|
||||
def decoded(folder: Path, rest: str) -> list[Path]:
|
||||
"""Returns:
|
||||
Every directory below folder whose path after folder encodes to rest
|
||||
the way Claude Code names a project: each character but an ASCII
|
||||
letter or digit turned into '-'.
|
||||
"""
|
||||
if not rest:
|
||||
return [folder]
|
||||
try:
|
||||
with os.scandir(folder) as entries:
|
||||
children = sorted((entry.name, entry.path) for entry in entries)
|
||||
except OSError:
|
||||
return []
|
||||
found = []
|
||||
for name, path in children:
|
||||
mark = "-" + ENCODED.sub("-", name)
|
||||
if rest.startswith(mark) and rest[len(mark):][:1] in ("", "-") and os.path.isdir(path):
|
||||
found += decoded(Path(path), rest[len(mark):])
|
||||
return found
|
||||
|
||||
|
||||
def started(projects: Path) -> list[Path]:
|
||||
"""Returns:
|
||||
The decoded() start directory of every Claude Code session folder
|
||||
below projects that still exists.
|
||||
"""
|
||||
try:
|
||||
with os.scandir(projects) as entries:
|
||||
names = sorted(entry.name for entry in entries if entry.is_dir(follow_symlinks=False))
|
||||
except OSError:
|
||||
return []
|
||||
return [folder for name in names for folder in decoded(Path("/"), name)]
|
||||
|
||||
|
||||
def sandbox_problems(settings: Path, managed: Path) -> list[str]:
|
||||
"""Args:
|
||||
settings: the user settings file.
|
||||
managed: the managed settings directory.
|
||||
|
||||
Returns:
|
||||
An add line per agent path the user file's allowWrite lacks, and a
|
||||
drop line per allowWrite entry that is the host-only root, inside it
|
||||
or above it, of settings, of a settings_files() file, of a
|
||||
project_settings() file below pkgmgr_roots(), or of a settings_in()
|
||||
file of a started() session directory; each real file once.
|
||||
"""
|
||||
release, host = state_home() / RELEASES, durable()
|
||||
user = allowed(settings, settings.parent)
|
||||
if user is None:
|
||||
problems = [f"{settings} holds no sandbox.filesystem.allowWrite list; the operator adds {root()} and {release} there"]
|
||||
else:
|
||||
paths = {path for _, path in user}
|
||||
problems = [f"add {path} to sandbox.filesystem.allowWrite in {settings} (operator step)" for path in (root(), release) if path not in paths]
|
||||
files = [(path, path.parent) for path in (*settings_files(None, managed), settings)]
|
||||
files += [(path, path.parent.parent) for top in pkgmgr_roots() for path in project_settings(top)]
|
||||
files += [(path, path.parent.parent) for folder in started(Path.home() / ".claude" / "projects") for path in settings_in(folder)]
|
||||
unique: dict[tuple[str, Path], tuple[Path, Path]] = {}
|
||||
for file, base in files:
|
||||
unique.setdefault((os.path.realpath(file), base.resolve()), (file, base))
|
||||
for file, base in unique.values():
|
||||
problems += [
|
||||
f"{file}: drop allowWrite entry {entry!r} ({path}): the sandbox must never write the host-only {host}"
|
||||
for entry, path in allowed(file, base) or [] if path == host or path in host.parents or host in path.parents
|
||||
]
|
||||
return problems
|
||||
|
||||
|
||||
def suspended(legacy: Path) -> bool:
|
||||
"""Returns:
|
||||
True when night.json exists in legacy or the council root and every
|
||||
one there is in a suspend mode.
|
||||
"""
|
||||
helper, modes = nofollow(), []
|
||||
for base in (legacy, root()):
|
||||
with contextlib.suppress(OSError, ValueError, AttributeError):
|
||||
modes.append(json.loads(helper.read_text(base, base / NIGHT)).get("mode"))
|
||||
return bool(modes) and all(mode in SUSPENDED for mode in modes)
|
||||
|
||||
|
||||
def preflight(settings: Path, managed: Path, legacy: Path) -> list[str]:
|
||||
"""Args:
|
||||
settings: the user settings file, only read.
|
||||
managed: the managed settings directory, only read.
|
||||
legacy: the earlier council root.
|
||||
|
||||
Returns:
|
||||
Every reason the install must stop before it copies anything: the
|
||||
sandbox_problems(), a refused council root, and for an existing
|
||||
legacy root its refusal, held() and conflicts().
|
||||
"""
|
||||
problems = sandbox_problems(settings, managed)
|
||||
target = root()
|
||||
if target.exists() or target.is_symlink():
|
||||
problems += [problem for problem in (refusal(target),) if problem is not None]
|
||||
if not legacy.exists() and not legacy.is_symlink():
|
||||
return problems
|
||||
problem = refusal(legacy)
|
||||
if problem is not None:
|
||||
return [*problems, problem]
|
||||
helper = nofollow()
|
||||
with contextlib.ExitStack() as stack:
|
||||
problems += held(helper, legacy, stack)
|
||||
return problems + conflicts(helper, legacy, target)
|
||||
|
||||
|
||||
def retire(base: Path, days: int, now: float) -> tuple[Path, int]:
|
||||
"""Args:
|
||||
base: the council root.
|
||||
days: files changed longer ago than this move.
|
||||
now: the current epoch time.
|
||||
|
||||
Returns:
|
||||
The dated archive directory and the number of files moved there.
|
||||
"""
|
||||
helper = nofollow()
|
||||
archive = base / ARCHIVE / time.strftime("%Y-%m-%d", time.localtime(now))
|
||||
cutoff, count = now - days * DAY_SECONDS, 0
|
||||
for part in RETIRED:
|
||||
top = base / part
|
||||
if top.is_symlink() or not top.is_dir():
|
||||
continue
|
||||
for folder, _, files in os.walk(top):
|
||||
for name in files:
|
||||
path = Path(folder) / name
|
||||
info = path.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_mtime > cutoff:
|
||||
continue
|
||||
*dirs, _ = helper.parts_below(base, path)
|
||||
source = helper.directory(base, tuple(dirs), False)
|
||||
try:
|
||||
target = helper.directory(base, (*helper.parts_below(base, archive), *dirs), True)
|
||||
try:
|
||||
os.rename(name, name, src_dir_fd=source, dst_dir_fd=target)
|
||||
finally:
|
||||
os.close(target)
|
||||
finally:
|
||||
os.close(source)
|
||||
count += 1
|
||||
return archive, count
|
||||
|
||||
|
||||
def legacy_default() -> Path:
|
||||
return Path(os.environ.get("AGENTS_COUNCIL_LEGACY") or LEGACY)
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="councilroot.py", description=__doc__.splitlines()[0])
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
commands.add_parser("root")
|
||||
commands.add_parser("durable")
|
||||
commands.add_parser("dir").add_argument("parts", nargs="+")
|
||||
commands.add_parser("release").add_argument("version")
|
||||
moving = commands.add_parser("migrate")
|
||||
moving.add_argument("--legacy", type=Path, default=legacy_default())
|
||||
moving.add_argument("--catch-up", action="store_true")
|
||||
check = commands.add_parser("preflight")
|
||||
check.add_argument("--legacy", type=Path, default=legacy_default())
|
||||
check.add_argument("--settings", type=Path, default=Path.home() / ".claude" / "settings.json")
|
||||
check.add_argument("--managed", type=Path, default=MANAGED)
|
||||
commands.add_parser("retire").add_argument("--days", type=int, default=RETIRE_DAYS)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.command == "root":
|
||||
print(root())
|
||||
elif args.command == "durable":
|
||||
print(durable())
|
||||
elif args.command == "dir":
|
||||
print(directory(root(), *args.parts))
|
||||
elif args.command == "release":
|
||||
print(directory(state_home() / RELEASES, args.version))
|
||||
elif args.command == "preflight":
|
||||
problems = preflight(args.settings, args.managed, args.legacy)
|
||||
for problem in problems:
|
||||
print(f"councilroot: preflight: {problem}", file=sys.stderr)
|
||||
if not suspended(args.legacy):
|
||||
print("councilroot: preflight: warning: the agents are not suspended (kvb-org-suspend); the install moves what they write meanwhile in a second migrate after the copy", file=sys.stderr)
|
||||
return 2 if problems else 0
|
||||
elif args.command == "retire":
|
||||
archive, count = retire(root(), args.days, time.time())
|
||||
print(f"archived {count} files into {archive}")
|
||||
else:
|
||||
try:
|
||||
report = migrate(args.legacy, root(), args.catch_up)
|
||||
except Blocked as blocked:
|
||||
print("\n".join([*blocked.lines, f"nothing moved from {args.legacy}"]))
|
||||
return 4
|
||||
print("\n".join(report) or f"nothing to move from {args.legacy}")
|
||||
for code, kinds in ((5, ("unmoved ",)), (3, ("conflict ", "kept "))):
|
||||
if any(line.startswith(kinds) for line in report):
|
||||
return code
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"councilroot: {error}", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -86,6 +86,25 @@ def read_text(root: Path, path: Path) -> str:
|
||||
return data.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def read_tail(root: Path, path: Path, limit: int) -> str:
|
||||
"""Args:
|
||||
root: the trusted directory.
|
||||
path: the file, below root.
|
||||
limit: bytes to read at most; a longer file yields its last limit
|
||||
bytes after the first line break in them, so only whole lines.
|
||||
|
||||
Returns:
|
||||
That text, UTF-8 decoded, undecodable bytes replaced.
|
||||
"""
|
||||
with open(open_below(root, path, os.O_RDONLY, 0), "rb") as handle:
|
||||
size = os.fstat(handle.fileno()).st_size
|
||||
if size <= limit:
|
||||
return handle.read(limit).decode("utf-8", errors="replace")
|
||||
handle.seek(size - limit)
|
||||
data = handle.read(limit)
|
||||
return data[data.find(b"\n") + 1:].decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def locked(root: Path, path: Path, mode: int, wait: float | None) -> Iterator[TextIO]:
|
||||
"""Hold an exclusive flock on a lock file below root, created without truncation.
|
||||
|
||||
@@ -8,8 +8,8 @@ Usage:
|
||||
(kvb-org-queue), <root>/security-accepted.jsonl
|
||||
(kvb-check-security), <root>/gate-receipts.jsonl and
|
||||
<root>/gate-parents.jsonl (kvb-check-gate) whose id it
|
||||
lacks to the same name under
|
||||
~/.local/state/agents-council/
|
||||
lacks to the same name in the host-only root
|
||||
(councilroot.py durable), never through a link
|
||||
watch.py block hook (PreToolUse on Bash): exit 2 for a heavy job while the
|
||||
disk stage is stop or critical, the memory stage is stop
|
||||
or cannot be judged without memory_limits, or a
|
||||
@@ -33,8 +33,9 @@ Usage:
|
||||
REPORT
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: shared state directory; /tmp/agents-council unless set,
|
||||
because every agent on the host must agree on it. Every command creates
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the shared state directory
|
||||
councilroot.py resolves, which survives a reboot and on which every
|
||||
agent on the host agrees. Every command creates
|
||||
it with mode 700; while it is a symlink, another uid's, or group or
|
||||
other writable, a hook mode prints why and exits 0 doing nothing and
|
||||
any other mode exits 2. queue.py and radio.py check it the same way.
|
||||
@@ -114,7 +115,8 @@ def sibling(name: str) -> ModuleType:
|
||||
|
||||
nofollow = sibling("nofollow")
|
||||
hookpath = sibling("hookpath")
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
councilroot = sibling("councilroot")
|
||||
ROOT = councilroot.root()
|
||||
CONFIG = Path(
|
||||
os.environ.get(
|
||||
"AGENTS_COUNCIL_CONFIG",
|
||||
@@ -126,7 +128,7 @@ STAGES = ("ok", "warn", "stop", "critical")
|
||||
STATE = ROOT / "watch.json"
|
||||
SILENCE = ROOT / "radio-silence.json"
|
||||
ALERTS = ROOT / "alerts.jsonl"
|
||||
KEPT = Path.home() / ".local" / "state" / "agents-council"
|
||||
KEPT = councilroot.durable()
|
||||
HISTORY = ROOT / "queue-history.jsonl"
|
||||
KEPT_HISTORY = KEPT / "queue-history.jsonl"
|
||||
ACCEPTED = ROOT / "security-accepted.jsonl"
|
||||
@@ -273,6 +275,13 @@ def guard_root(hook: bool) -> int | None:
|
||||
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
pass
|
||||
except OSError as error:
|
||||
print(
|
||||
f"agents council: cannot create {ROOT} ({error.strerror or error}); a sandbox needs it in allowWrite; "
|
||||
"the council hooks stay off until it exists",
|
||||
file=sys.stdout if hook else sys.stderr,
|
||||
)
|
||||
return 0 if hook else 2
|
||||
st = ROOT.lstat()
|
||||
if stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and not st.st_mode & 0o022:
|
||||
return None
|
||||
@@ -459,14 +468,13 @@ def history_rows(text: str) -> list[tuple[str, str]]:
|
||||
|
||||
|
||||
def keep_rows(origin: Path, target: Path) -> None:
|
||||
# The agents' sandbox cannot write ~/.local/state and /tmp is wiped on reboot, so this hook keeps the rows.
|
||||
# The kept file takes the source's mtime: an unchanged source is skipped without parsing.
|
||||
try:
|
||||
source = origin.stat().st_mtime_ns
|
||||
if target.exists() and target.stat().st_mtime_ns == source:
|
||||
return
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with target.open("a+", encoding="utf-8") as kept:
|
||||
KEPT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with open(nofollow.open_below(KEPT, target, os.O_RDWR | os.O_CREAT | os.O_APPEND, 0o600), "a+", encoding="utf-8") as kept:
|
||||
fcntl.flock(kept, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
kept.seek(0)
|
||||
known = {row_id for row_id, _ in history_rows(kept.read())}
|
||||
@@ -475,7 +483,7 @@ def keep_rows(origin: Path, target: Path) -> None:
|
||||
known.add(row_id)
|
||||
kept.write(line + "\n")
|
||||
kept.flush()
|
||||
os.utime(target, ns=(source, source))
|
||||
os.utime(kept.fileno(), ns=(source, source))
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
`council.py takeover <office> --work "..."` and posts the succession to the
|
||||
radio; everyone else leaves it alone.
|
||||
- After a restart or reboot, run `council.py list --mine` and claim again
|
||||
every office you believe you hold: `/tmp` may have been wiped.
|
||||
every office you believe you hold: claims survive a reboot, but a new
|
||||
session holds none of them.
|
||||
- Only the operator, through the Orchestrator's passkey-signed Hierarchy
|
||||
view, removes a live holder; agents have no override.
|
||||
@@ -16,7 +16,9 @@ Usage:
|
||||
|
||||
Environment:
|
||||
SUBAGENT_MODEL_LOG: the log shared by every session;
|
||||
~/.local/state/agents-council/subagent-model.jsonl unless set.
|
||||
subagent-model.jsonl in the host-only root (councilroot.py durable of
|
||||
kvb-org-organize) unless set. Writes go through its nofollow.py, so
|
||||
a link at the log or its directory fails them.
|
||||
CLAUDE_CODE_SESSION_ID: the session that rates its spawns.
|
||||
"""
|
||||
|
||||
@@ -24,19 +26,27 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
LOG = Path(
|
||||
os.environ.get(
|
||||
"SUBAGENT_MODEL_LOG",
|
||||
str(Path.home() / ".local" / "state" / "agents-council" / "subagent-model.jsonl"),
|
||||
)
|
||||
)
|
||||
ORGANIZE = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts"
|
||||
|
||||
|
||||
def organize(name: str) -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location(f"kvb_perform_{name}", ORGANIZE / f"{name}.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
nofollow = organize("nofollow")
|
||||
LOG = Path(os.environ.get("SUBAGENT_MODEL_LOG") or organize("councilroot").durable() / "subagent-model.jsonl")
|
||||
TASK_CLASS = re.compile(r"^task-class:\s*(\S+)", re.MULTILINE)
|
||||
PENDING = "pending: "
|
||||
SCRIPT = "kvb-org-perform/scripts/log.py"
|
||||
@@ -54,9 +64,8 @@ def now() -> str:
|
||||
|
||||
|
||||
def append(line: dict) -> None:
|
||||
LOG.parent.mkdir(parents=True, exist_ok=True)
|
||||
with LOG.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(line, sort_keys=True) + "\n")
|
||||
LOG.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
nofollow.append(LOG.parent, LOG, json.dumps(line, sort_keys=True) + "\n", 0o600)
|
||||
|
||||
|
||||
def record(line: dict) -> int:
|
||||
|
||||
@@ -7,10 +7,11 @@ Usage:
|
||||
cleanup.py request
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: shared state directory; /tmp/agents-council unless
|
||||
set. Agents append their requests to <root>/queue-cleanup.request,
|
||||
which kvb-org-queue-cleanup.path watches below /tmp/agents-council
|
||||
only. The round lives in ~/.local/state/agents-council, which only
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council root the
|
||||
kvb-org-organize councilroot.py resolves. Agents append their
|
||||
requests to <root>/queue-cleanup.request, which
|
||||
kvb-org-queue-cleanup.path watches below %S/agents-shared only. The
|
||||
round lives in the host-only root (councilroot.py durable), which only
|
||||
the host can write, in queue-cleanup.json under queue-cleanup.lock,
|
||||
written by run alone.
|
||||
CLAUDE_CODE_SESSION_ID: run refuses to start while it is set.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Description=kvb-org-queue-cleanup round on cleanup.py request
|
||||
|
||||
[Path]
|
||||
PathModified=/tmp/agents-council/queue-cleanup.request
|
||||
PathModified=%S/agents-shared/queue-cleanup.request
|
||||
|
||||
[Install]
|
||||
WantedBy=paths.target
|
||||
@@ -3,5 +3,6 @@ Description=One kvb-org-queue-cleanup round: pan-pan, security, delete the jobs
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStartPre=-/usr/bin/python3 -I %h/.claude/skills/kvb-org-organize/scripts/councilroot.py retire
|
||||
ExecStart=/usr/bin/python3 -I %h/.claude/skills/kvb-org-queue-cleanup/scripts/cleanup.py run --window 900
|
||||
TimeoutStartSec=2400
|
||||
@@ -2,8 +2,9 @@
|
||||
"""Ask every agent once, by one newsletter, to estimate the open register tasks that carry no complexity.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory of the kvb-org-rasci register and
|
||||
the radio; /tmp/agents-council unless set.
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory of the
|
||||
kvb-org-rasci register and the radio, as the kvb-org-organize
|
||||
councilroot.py resolves it.
|
||||
|
||||
Args:
|
||||
show: print the newsletter's text, send nothing.
|
||||
|
||||
@@ -10,8 +10,9 @@ Usage:
|
||||
queue.py block hook (PreToolUse on Bash)
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: shared state directory; /tmp/agents-council unless set,
|
||||
because every agent on the host must agree on it. The queue is
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the shared state directory the
|
||||
kvb-org-organize councilroot.py resolves, on which every agent on the
|
||||
host agrees. The queue is
|
||||
<root>/queue.json, every read-modify-write holds <root>/queue.lock.
|
||||
Each hold keeps an exclusive flock on <root>/holds/<tag>.lock, shared
|
||||
with its command, from before its entry exists until it leaves; an
|
||||
@@ -138,6 +139,7 @@ SIBLINGS = {
|
||||
"rasci": SKILLS / "kvb-org-rasci" / "scripts" / "rasci.py",
|
||||
"history": Path(__file__).resolve().parent / "history.py",
|
||||
"nofollow": SKILLS / "kvb-org-organize" / "scripts" / "nofollow.py",
|
||||
"councilroot": SKILLS / "kvb-org-organize" / "scripts" / "councilroot.py",
|
||||
}
|
||||
TOOLS = {"gates": SKILLS / "kvb-check-gate" / "scripts" / "gates.py"}
|
||||
HOST_SKILLS = Path.home() / ".agents" / "skills"
|
||||
@@ -156,7 +158,6 @@ GATE = re.compile(r"\bgate\.py\s+(run|hold)\b")
|
||||
THROUGH_QUEUE = re.compile(r"\bqueue\.py\s+hold\b")
|
||||
BASH_RULE = re.compile(r"Bash(?:\((.*)\))?", re.DOTALL)
|
||||
RULE_PART = re.compile(r"( \*|\*)")
|
||||
MANAGED = Path("/etc/claude-code")
|
||||
BUDGET_KEYS = ("budget_percent.ram", "budget_percent.cpu")
|
||||
HOTFIX = "hotfix/"
|
||||
PYTEST = frozenset({"pytest", "py.test"})
|
||||
@@ -1043,15 +1044,7 @@ def cmd_cancel(args: argparse.Namespace) -> int:
|
||||
|
||||
|
||||
def settings_files(project: Path) -> list[Path]:
|
||||
user = Path.home() / ".claude"
|
||||
return [
|
||||
MANAGED / "managed-settings.json",
|
||||
*sorted((MANAGED / "managed-settings.d").glob("*.json")),
|
||||
user / "settings.json",
|
||||
user / "settings.local.json",
|
||||
project / ".claude" / "settings.json",
|
||||
project / ".claude" / "settings.local.json",
|
||||
]
|
||||
return sibling("councilroot").settings_files(project)
|
||||
|
||||
|
||||
def bash_rule(rule: str) -> re.Pattern | None:
|
||||
|
||||
@@ -7,7 +7,8 @@ description: >
|
||||
|
||||
`${CLAUDE_SKILL_DIR}/scripts/radio.py` is the channel every skill uses to
|
||||
reach other agents, on every runtime. Both channels share one store,
|
||||
`news.jsonl` in the council directory (`/tmp/agents-council`).
|
||||
`news.jsonl` in the council directory, which
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py root` prints.
|
||||
|
||||
```bash
|
||||
radio.py post "<text>" [--to <name> ...] [--session <id>]
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
"""Reach other agents: the radio is immediate, the post waits until a turn ends; one shared store.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
/tmp/agents-council unless set. Rows live in <root>/news.jsonl under
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory the
|
||||
kvb-org-organize councilroot.py resolves, shared by every agent on the
|
||||
host. Rows live in <root>/news.jsonl under
|
||||
<root>/news.lock, the store the old news.py reads and writes too.
|
||||
AGENTS_COUNCIL_CONFIG: config file; its "notify" argv tells the operator
|
||||
of a mayday, its "never_block" and "mayday_allow" regexes name the
|
||||
@@ -89,18 +90,9 @@ from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
# Every agent on the host must agree on one council directory and one config without being told.
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
CONFIG = Path(
|
||||
os.environ.get("AGENTS_COUNCIL_CONFIG", str(Path.home() / ".claude" / "agents-council" / "config.json"))
|
||||
)
|
||||
NEWS = ROOT / "news.jsonl"
|
||||
LOCK = ROOT / "news.lock"
|
||||
SEEN = ROOT / "news-seen"
|
||||
STATE = ROOT / "radio-seen"
|
||||
LISTEN = ROOT / "radio-listen"
|
||||
SILENCE = ROOT / "radio-silence.json"
|
||||
NOTIFIED = ROOT / "radio-notified"
|
||||
FEEDBACK = ROOT / "feedback.json"
|
||||
ORGANIZE = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts"
|
||||
SELF = Path(__file__).resolve()
|
||||
RADIO = ("mayday", "pan-pan", "security", "call", "broadcast")
|
||||
@@ -140,6 +132,17 @@ def organize(name: str) -> ModuleType:
|
||||
return module
|
||||
|
||||
|
||||
ROOT = organize("councilroot").root()
|
||||
NEWS = ROOT / "news.jsonl"
|
||||
LOCK = ROOT / "news.lock"
|
||||
SEEN = ROOT / "news-seen"
|
||||
STATE = ROOT / "radio-seen"
|
||||
LISTEN = ROOT / "radio-listen"
|
||||
SILENCE = ROOT / "radio-silence.json"
|
||||
NOTIFIED = ROOT / "radio-notified"
|
||||
FEEDBACK = ROOT / "feedback.json"
|
||||
|
||||
|
||||
def council() -> ModuleType:
|
||||
return organize("council")
|
||||
|
||||
@@ -149,8 +152,9 @@ def name_of(sid: str) -> str:
|
||||
|
||||
|
||||
def items() -> list[dict]:
|
||||
nofollow = organize("nofollow")
|
||||
try:
|
||||
lines = organize("nofollow").read_text(ROOT, NEWS).splitlines()
|
||||
lines = nofollow.read_tail(ROOT, NEWS, nofollow.READ_LIMIT).splitlines()
|
||||
except OSError:
|
||||
return []
|
||||
rows = []
|
||||
@@ -361,7 +365,11 @@ def store(entries: list[dict]) -> float:
|
||||
for entry in entries:
|
||||
entry["ts"] = ts
|
||||
ts = math.nextafter(ts, math.inf)
|
||||
write_atomic(NEWS, "".join(json.dumps(row) + "\n" for row in [*rows[-(KEPT - len(entries)):], *entries]))
|
||||
cut = max(0, len(rows) - max(0, KEPT - len(entries)))
|
||||
if cut:
|
||||
archive = ROOT / "archive" / f"news-{time.strftime('%Y-%m-%d')}.jsonl"
|
||||
organize("nofollow").append(ROOT, archive, "".join(json.dumps(row) + "\n" for row in rows[:cut]), 0o600)
|
||||
write_atomic(NEWS, "".join(json.dumps(row) + "\n" for row in [*rows[cut:], *entries]))
|
||||
return entries[-1]["ts"]
|
||||
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
"""Keep the RASCI register of the organisation's tasks in a local JSON file.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
the register is <root>/rasci.json, and `show` also lists every work/
|
||||
and cluster/ claim of the council there. The operator's agent order
|
||||
(`agents order`) lies beside it in <root>/agent-order.json, apart from
|
||||
every task row: it breaks ties of equal task priority only.
|
||||
/tmp/agents-council unless set.
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory the
|
||||
kvb-org-organize councilroot.py resolves, shared by every agent on the
|
||||
host; the register is <root>/rasci.json, and `show` also lists every
|
||||
work/ and cluster/ claim of the council there. The operator's agent
|
||||
order (`agents order`) lies beside it in <root>/agent-order.json, apart
|
||||
from every task row: it breaks ties of equal task priority only.
|
||||
|
||||
Exit codes:
|
||||
0 done, 2 usage error.
|
||||
@@ -20,7 +20,6 @@ import contextlib
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
@@ -28,10 +27,6 @@ from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
DB = ROOT / "rasci.json"
|
||||
LOCK = ROOT / "rasci.lock"
|
||||
AGENT_ORDER = ROOT / "agent-order.json"
|
||||
FILE_MODE = 0o600
|
||||
ORGANIZE = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts"
|
||||
COUNCIL = ORGANIZE / "council.py"
|
||||
@@ -88,6 +83,10 @@ def script(name: str, path: Path) -> ModuleType:
|
||||
|
||||
|
||||
nofollow = script("kvb_rasci_nofollow", ORGANIZE / "nofollow.py")
|
||||
ROOT = script("kvb_rasci_councilroot", ORGANIZE / "councilroot.py").root()
|
||||
DB = ROOT / "rasci.json"
|
||||
LOCK = ROOT / "rasci.lock"
|
||||
AGENT_ORDER = ROOT / "agent-order.json"
|
||||
|
||||
|
||||
def load() -> dict[str, dict]:
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
"""Keep the organisation's night mode: one active session, the others drained or suspended.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
the state is <root>/night.json. /tmp/agents-council unless set.
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory the
|
||||
kvb-org-organize councilroot.py resolves, shared by every agent on the
|
||||
host; the state is <root>/night.json.
|
||||
CLAUDE_CODE_SESSION_ID: the calling session.
|
||||
|
||||
Args:
|
||||
@@ -43,20 +44,27 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
STATE = ROOT / "night.json"
|
||||
COUNCIL = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts" / "council.py"
|
||||
ORGANIZE = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts"
|
||||
COUNCIL = ORGANIZE / "council.py"
|
||||
PARTS = {"drain": "drain (kvb-agent-drain)", "suspend": "suspend (kvb-agent-suspend)"}
|
||||
RENAMED = {"evening": "drain", "sunset": "suspend"}
|
||||
|
||||
|
||||
def council() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("council", COUNCIL)
|
||||
def loaded(name: str, path: Path) -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def council() -> ModuleType:
|
||||
return loaded("council", COUNCIL)
|
||||
|
||||
|
||||
ROOT = loaded("kvb_night_councilroot", ORGANIZE / "councilroot.py").root()
|
||||
STATE = ROOT / "night.json"
|
||||
|
||||
|
||||
def migrated(state: object) -> object:
|
||||
if not isinstance(state, dict):
|
||||
return state
|
||||
|
||||
@@ -19,10 +19,11 @@ bar on `<line>`", key results gate green, landed, cleaned up, overview posted.
|
||||
## Step 1: collect
|
||||
|
||||
The register is the swarm's record (stage 2 of `kvb-org-swarm` sets `--branch`
|
||||
and `--base`):
|
||||
and `--base`); `<council>` is what
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py root` prints:
|
||||
|
||||
```bash
|
||||
jq -r --arg base "<line>" 'to_entries[] | select(.value.base == $base and .value.branch) | [.key, .value.branch, .value.workdir // "-", .value.status] | @tsv' "${AGENTS_COUNCIL_ROOT:-/tmp/agents-council}/rasci.json"
|
||||
jq -r --arg base "<line>" 'to_entries[] | select(.value.base == $base and .value.branch) | [.key, .value.branch, .value.workdir // "-", .value.status] | @tsv' "<council>/rasci.json"
|
||||
```
|
||||
|
||||
Per branch: `git log --oneline <line>..<branch>` (empty: already merged, go
|
||||
@@ -44,7 +45,8 @@ the branch becomes a proposal naming the conflicting files.
|
||||
|
||||
The project's full gate on `unify/<goal>` through `queue.py hold`
|
||||
(`kvb-check-gate`), and `security.py` over `<line>..unify/<goal>`
|
||||
(`kvb-check-security`), logs under `/tmp`. Red: find the merge that broke it
|
||||
(`kvb-check-security`), logs under the directory `councilroot.py dir gates`
|
||||
prints. Red: find the merge that broke it
|
||||
(`git bisect start --first-parent`), rebuild the branch without it, which
|
||||
becomes a proposal naming the failing test, and gate again.
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
"""Tell every agent which skills changed and how to use them: one newsletter per update.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
/tmp/agents-council unless set. The last announced revision per
|
||||
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory the
|
||||
kvb-org-organize councilroot.py resolves, shared by every agent on the
|
||||
host. The last announced revision per
|
||||
repository lives in <root>/skills-announced.json.
|
||||
CLAUDE_CODE_SESSION_ID: the sending session, passed on to radio.py.
|
||||
|
||||
@@ -25,14 +26,11 @@ import argparse
|
||||
import functools
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
ANNOUNCED = ROOT / "skills-announced.json"
|
||||
SKILLS = Path(__file__).resolve().parents[2]
|
||||
RADIO = SKILLS / "kvb-org-radio" / "scripts" / "radio.py"
|
||||
ORGANIZE = SKILLS / "kvb-org-organize" / "scripts"
|
||||
@@ -48,6 +46,10 @@ def organize(name: str) -> ModuleType:
|
||||
return module
|
||||
|
||||
|
||||
ROOT = organize("councilroot").root()
|
||||
ANNOUNCED = ROOT / "skills-announced.json"
|
||||
|
||||
|
||||
def git(repo: Path, *args: str) -> str:
|
||||
return subprocess.run([*GIT, *args], cwd=repo, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
@@ -41,5 +41,8 @@ mechanism and the upgrade path, investors read only what the brief proves.
|
||||
- Stay inside the channel's length bounds. Without project bounds: a blog
|
||||
article 600 to 1200 words, a LinkedIn article 400 to 900, a newsletter
|
||||
250 to 500.
|
||||
- Write `/tmp/release-<version>/<channel>/<language>.md`, or the format the
|
||||
project's template names, and report each file's word count.
|
||||
- Write `<drafts>/<channel>/<language>.md`, or the format the project's
|
||||
template names, and report each file's word count. `<drafts>` is the
|
||||
directory `kvb-release` handed over, else the one
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py release <version>`
|
||||
prints.
|
||||
@@ -43,6 +43,9 @@ replaces this one:
|
||||
|
||||
- Every number, name and date comes from `brief.yml`.
|
||||
- No em dashes, no placeholder, no claim the brief does not prove.
|
||||
- Write into `/tmp/release-<version>/` under the file name the project skill
|
||||
sets, else `<channel>/<language>.txt`, and report each file's character
|
||||
count against its limit.
|
||||
- Write into `<drafts>/` under the file name the project skill sets, else
|
||||
`<channel>/<language>.txt`, and report each file's character count
|
||||
against its limit. `<drafts>` is the directory `kvb-release` handed over,
|
||||
else the one
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py release <version>`
|
||||
prints.
|
||||
@@ -14,8 +14,10 @@ the project's own `<prefix>-release-<channel>` skills.
|
||||
|
||||
Run the `kvb-think-listen` skill once for what only the operator knows: the
|
||||
tag, the languages (default English), the audiences, the highlights, what to
|
||||
leave out and the channels wanted. Write the answers to
|
||||
`/tmp/release-<version>/listen.yml` (`tag`, `languages`, `audience`,
|
||||
leave out and the channels wanted. `<drafts>` is the directory
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-organize/scripts/councilroot.py release <version>`
|
||||
prints, which survives a reboot. Write the answers to
|
||||
`<drafts>/listen.yml` (`tag`, `languages`, `audience`,
|
||||
`highlights`, `leave_out`, `channels`) and hand that file to every channel,
|
||||
so the operator answers each question once.
|
||||
|
||||
@@ -31,7 +33,7 @@ so the operator answers each question once.
|
||||
## 3. Brief
|
||||
|
||||
Run the `kvb-think-brainstorm` skill on the headline benefit, then write
|
||||
`/tmp/release-<version>/brief.yml`: version, date, languages, headline
|
||||
`<drafts>/brief.yml`: version, date, languages, headline
|
||||
benefit, three to five benefits each with the changelog lines that prove it,
|
||||
upgrade notes and links. `languages` is the only answer the brief copies from
|
||||
`listen.yml`: an answer steers what a channel stresses, it never backs a
|
||||
@@ -51,12 +53,12 @@ the general method:
|
||||
| entry | changelog | `kvb-release-changelog` |
|
||||
|
||||
Each gets `brief.yml`, `listen.yml` and its channel, runs its own listen and
|
||||
brainstorm, and writes into `/tmp/release-<version>/` under the file name
|
||||
brainstorm, and writes into `<drafts>/` under the file name
|
||||
the project skill sets, else `<channel>/<language>.<ext>`.
|
||||
|
||||
## 5. Check
|
||||
|
||||
Fix in every file under `/tmp/release-<version>/`, subfolders included,
|
||||
Fix in every file under `<drafts>/`, subfolders included,
|
||||
before the hand-over: a leftover placeholder (`TODO`, `XXX`, `<...>`), an
|
||||
em dash, a length outside the channel's bounds, a number absent from
|
||||
`brief.yml`.
|
||||
|
||||
Reference in new issue
Block a user