🚚 export: 16 files (moves)
M .gitignore M docs/windows-powershell-utf8.md M plugins/bevy/README.md M plugins/orbit/README.md M plugins/orbit/skills/orbit/references/review-recipes.md M plugins/project-uv/README.md M plugins/spire/CLAUDE.md R plugins/spire/agents/attacker.md -> plugins/spire/agents/advocate.md M plugins/spire/agents/igor.md M plugins/spire/agents/zathras.md M plugins/spire/skills/adepts/roster.sh M plugins/spire/skills/implementation/references/models.md A plugins/spire/skills/quire/tests/test_roster.py R plugins/spire/skills/workpad/SKILL.md -> plugins/spire/skills/quire/SKILL.md R plugins/spire/skills/workpad/tests/test_workpad.py -> plugins/spire/skills/quire/tests/test_quire.py R plugins/spire/skills/workpad/workpad.py -> plugins/spire/skills/quire/quire.py
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
---
|
||||
name: quire
|
||||
description: Decides WHERE and WHEN to put working documents — reports, plans, goals, brainstorms, designs, journals, research, specs, tickets, bug notes. Use this skill whenever the user asks you to write a "report", "plan", "goal", "brainstorm", "design", "journal", "research note", "spec", or anything "in the quire" (formerly "workpad"; the old word still applies) — and also when another skill is about to drop a markdown file somewhere ad-hoc (e.g. a plugin's own `docs/<plugin>/` subdirectory, the repo root, `/tmp`, or alongside source code). If a quire exists, the quire wins for documents. Non-document output (raw state, streams, gate output) goes to scratch. This skill steers other skills toward one predictable place for markdown documents.
|
||||
allowed-tools: Bash(uv:*)
|
||||
---
|
||||
|
||||
# Quire
|
||||
|
||||
Scope: markdown *about* the work (reports, plans, brainstorms, post-mortems). Decides **where** a document goes and **which kind** it is, not its contents. Wins over any other skill's folder (plugin-named folder, sibling `notes/`, repo root).
|
||||
|
||||
## Where the quire lives
|
||||
|
||||
First hit wins:
|
||||
|
||||
1. **Explicit user instruction** in this conversation.
|
||||
2. **`QUIRE_FOLDER`.** Subshells may not inherit it: try `just quire-folder` (or an equivalent recipe; `just` loads `.env`), then `printenv QUIRE_FOLDER`. Non-empty path = base.
|
||||
3. **`WORKPAD_FOLDER`** (old name, fallback): same way, `just workpad-folder`, then `printenv WORKPAD_FOLDER`.
|
||||
4. **External tickets folder** outside the repo (e.g. `../<repo>-tickets/`, or `GITEA_TICKETS_DIR`), if configured: base `<tickets-folder>/quire/`, or `<tickets-folder>/workpad/` if only that exists; tickets beside it as `<tickets-folder>/<id>/`. Unsure one exists: ask.
|
||||
5. **`/docs/quire`** at the project root, if it exists. If `docs/workpad/` also exists, use `docs/quire/` and say once that the old folder is there too.
|
||||
6. **`/docs/workpad`**, if it exists.
|
||||
7. **`/.quire`**, if it exists.
|
||||
8. **`/.workpad`**, if it exists.
|
||||
9. **Else ask** where, offering `docs/quire/` (or `.quire/` without `/docs`); confirm before creating folders. Non-interactive agents (Athanor, gremlins, reviewer, other closed-door agents) take the offer and flag it.
|
||||
|
||||
## Folder structure
|
||||
|
||||
Always: `brainstorm/` (options, half-formed ideas), `goals/` (acceptance criteria, milestones), `designs/` (architecture, RFC-style), `plans/` (steps to execute), `reports/` (findings, status).
|
||||
|
||||
On demand: `archive/` (superseded), `bugs/`, `journals/` (append-only narratives), `research/` (external research, prior art), `specs/` (frozen), `tickets/<id>/` (Ticket context), `adepts/` (`spire:adepts`), `logs/` (Tiers).
|
||||
|
||||
Create an on-demand folder when needed, never speculatively. Unknown folders are the user's; ignore them.
|
||||
|
||||
## Tiers
|
||||
|
||||
- `reports/`: lasting reports, handoffs included. Tracked.
|
||||
- `logs/<YYYY-MM-DD-hh>-<slug>/`: readable record of one build: `run.md`, `trunk-notes.md`, `review-<scope>.md`, `recheck-<scope>.md`, `brief-<block>.md`. Git-ignored by the guard below. Stays in the main quire under an active ticket context.
|
||||
- **scratch**: `<repo>/.spire/scratch/<run-slug>/<agent-or-job>/`: raw state (streams, gate output, job files). Git-ignored. `<repo>` = the run log's checkout; run log in another repo or none: the cwd's. Override: `SPIRE_SCRATCH` (gremlins: `--scratch`).
|
||||
- Git-ignored (`logs/`, scratch, trash): Grep and Glob skip them; use the explicit path or `ls`.
|
||||
- `W` = `uv run --script "${CLAUDE_SKILL_DIR}/quire.py"`: any OS or shell, no POSIX snippets, JSON out; `--run <run log>` sets `<repo>`. Briefs to other agents: its absolute path. If `${CLAUDE_SKILL_DIR}` appears literally, it is this SKILL.md's own folder; resolve it there and do not search elsewhere.
|
||||
- **Trash**: at build close Igor moves the run dir to `<repo>/.spire/trash/<YYYY-MM-DD>/`, also when `SPIRE_SCRATCH` is set: `W trash <dir>…`. Ignored by the guard; the user empties it.
|
||||
- **7-day sweep**: run dirs with no file modified in 7 days and no `keep` file: `W sweep --move` (scratch root).
|
||||
- **Ignore guard** (fallback: `/spire:init` writes `/.spire/` and `<quire>/logs/` to the root `.gitignore`, or `.git/info/exclude`). Before the first write to `logs/` or `.spire/`, the dispatcher starting the run runs it itself (the Athanor at build start; Igor or Zathras before a dispatch writing there). Never overwrites; `.spire/.gitignore` covers scratch and trash: `W guard <quire>`.
|
||||
|
||||
**Never commit:** scratch, `logs/`, gremlin state, Playwright or browser auth state, walker and probe scripts, briefs, real-data dumps, `__pycache__`.
|
||||
- Browser state and walker or probe scripts live in the run's scratch dir. Promote a script to `scripts/` or tests only by explicit decision.
|
||||
- During a build the Athanor commits code plus the files its brief names. Igor commits other quire files after a hand-back, by explicit paths, never while an Athanor commits in the same checkout.
|
||||
- A link into scratch or `logs/` is a pointer only: the claim stands on the quoted line.
|
||||
|
||||
## Ticket context
|
||||
|
||||
**Ticket folder**: `<quire>/tickets/<id>/` (or `<tickets-folder>/<id>/`), created on demand once the id is known.
|
||||
|
||||
**Active** only when: the user named the ticket this session ("we're on #42"), a ticket skill opened or created its folder this conversation, or the user asked for a file in the ticket. A folder existing or a number in the branch name does not count. Ticket-shaped but unnamed: ask once, keep the answer. The most recently named ticket stays active until the user switches. Reply names the ticket beside the path.
|
||||
|
||||
Routing while active:
|
||||
|
||||
- **Ticket folder:** `plans/`, `designs/`, `brainstorm/`, `reports/`, `bugs/`.
|
||||
- **Main quire:** `journals/`, `logs/`, `goals/`.
|
||||
- **`research/`, `specs/`:** main quire if another ticket would want it, else the ticket folder; a spec outliving the ticket is promoted to the main quire on close.
|
||||
|
||||
Ticket folder: same kind subfolders, naming and subfolder rules; root holds only ticket-level files (`context.md`), never loose plans or reports. Main-quire files written under a ticket context carry the id in the slug (`2026-05-05-14-42-auth-token-leak.md`).
|
||||
|
||||
## File naming
|
||||
|
||||
`YYYY-MM-DD-hh-` prefix: required in `reports/`, `plans/`, `journals/`, `bugs/`, `research/`; optional in `goals/`, `designs/`, `specs/`. Then a kebab-case topic slug: `2026-05-05-14-auth-token-leak.md`, not `2026-05-05-14-report.md`.
|
||||
|
||||
## When to create a subfolder
|
||||
|
||||
One artifact, one file. **Multiple related files** (research cascade, report with appendices, plan with design notes): a dated subfolder (`reports/2026-05-05-15-q2-perf-audit/overview.md`, …); files inside drop the date prefix.
|
||||
|
||||
## Picking the right kind of document
|
||||
|
||||
- **Plan vs. spec:** default `plans/`; `specs/` only for a source of truth not expected to change.
|
||||
- **Goal vs. plan:** what to reach vs. how.
|
||||
- **Report vs. journal:** a snapshot, revised vs. append-only (post-mortems, multi-day bug hunts, correction narratives).
|
||||
- **Brainstorm vs. design:** options without commitment vs. one approach to build from.
|
||||
|
||||
## Lifecycles
|
||||
|
||||
Feature: `brainstorm → goal → design → plan`. Reactive: `report → design → plan`, `report → plan`, or just `plan`; a design only for a non-trivial fix. Skip stages that don't earn their keep. A new stage = a new file in the next folder; the earlier one stays.
|
||||
|
||||
## Defaults
|
||||
|
||||
"Write a report / plan / brainstorm on X" = a file in the right folder, named as above, plus a short reply with the path, not the contents.
|
||||
|
||||
Another skill's markdown artifact: that skill owns contents, this one location and name (ticket routing included). Out of scope: document format, ticket lifecycle, search tooling.
|
||||
|
||||
## Hand-back
|
||||
|
||||
Final message when a brief asks for it: five fixed headings, one line per item; detail stays in the files.
|
||||
|
||||
- **Done**: work done, with commits.
|
||||
- **Open**: unfinished work, extra work found, surviving findings, the stop reason if stopped early.
|
||||
- **Decisions taken (override if you disagree)**: each default taken, with its flag.
|
||||
- **Blocking decisions**: only points with no acceptable default; usually empty; at the end, never mid-run.
|
||||
- **Paths**: outputs, run log, reviews, scratch run dir, leftovers outside scratch.
|
||||
@@ -0,0 +1,247 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.12"
|
||||
# dependencies = []
|
||||
# ///
|
||||
"""spire:quire helper: ignore guard, stale-run sweep, trash move. See SKILL.md (Tiers).
|
||||
|
||||
Stdlib only, no shell-outs, so it runs the same on Linux, macOS and Windows. Each command prints
|
||||
one JSON object. Exit 0 ok, 1 when some move failed, 2 refused or a usage error.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Refusal(Exception):
|
||||
def __init__(self, error: str, **fields):
|
||||
super().__init__(error)
|
||||
self.payload = {"error": error, **fields}
|
||||
|
||||
|
||||
class _Parser(argparse.ArgumentParser):
|
||||
def error(self, message):
|
||||
raise Refusal("usage", detail=message)
|
||||
|
||||
|
||||
def _abs(p) -> Path:
|
||||
return Path(os.path.abspath(str(p)))
|
||||
|
||||
|
||||
def _ceilings() -> set:
|
||||
return {os.path.normcase(os.path.realpath(c))
|
||||
for c in os.environ.get("GIT_CEILING_DIRECTORIES", "").split(os.pathsep) if c}
|
||||
|
||||
|
||||
def checkout(start: Path):
|
||||
"""(toplevel, git common dir) of the checkout holding `start`, else None. Reads `.git` the way
|
||||
git does instead of running it: a dir is the common dir; a file (worktree, submodule) names a
|
||||
gitdir, whose `commondir` file, if any, points to the common dir. Starts at the nearest existing
|
||||
ancestor, resolved, and does not climb into GIT_CEILING_DIRECTORIES."""
|
||||
while not start.is_dir() and start.parent != start:
|
||||
start = start.parent
|
||||
start, ceil = start.resolve(), _ceilings()
|
||||
for d in (start, *start.parents):
|
||||
if d != start and os.path.normcase(str(d)) in ceil:
|
||||
return None
|
||||
g = d / ".git"
|
||||
if g.is_dir():
|
||||
return d, g.resolve()
|
||||
if g.is_file():
|
||||
try:
|
||||
text = g.read_text(encoding="utf-8").strip()
|
||||
if not text.startswith("gitdir:"):
|
||||
return None
|
||||
gitdir = Path(os.path.join(d, text[len("gitdir:"):].strip()))
|
||||
common = gitdir / "commondir"
|
||||
if common.is_file():
|
||||
gitdir = Path(os.path.join(gitdir, common.read_text(encoding="utf-8").strip()))
|
||||
except OSError:
|
||||
return None
|
||||
return d, gitdir.resolve()
|
||||
return None
|
||||
|
||||
|
||||
def _key(p: Path) -> str:
|
||||
return os.path.normcase(str(p))
|
||||
|
||||
|
||||
def repo_of(args) -> Path:
|
||||
"""`--repo`; else gremlins' scratch rule (`grm/store.py` `scratch_root`): the run log's
|
||||
checkout, the cwd's when the run log is in another repo (worktrees of one repo are one repo) or
|
||||
in none, else the run log's dir. Without `--run`, the cwd's checkout."""
|
||||
if args.repo:
|
||||
return _abs(args.repo)
|
||||
try:
|
||||
cwd = checkout(_abs(Path.cwd()))
|
||||
except OSError: # cwd deleted
|
||||
cwd = None
|
||||
if args.run:
|
||||
run_dir = _abs(args.run).parent
|
||||
run = checkout(run_dir)
|
||||
if run is not None and (cwd is None or _key(run[1]) == _key(cwd[1])):
|
||||
return run[0]
|
||||
return cwd[0] if cwd is not None else run_dir
|
||||
if cwd is None:
|
||||
raise Refusal("no git checkout above the cwd; pass --repo", cwd=os.getcwd())
|
||||
return cwd[0]
|
||||
|
||||
|
||||
def ensure_ignore(d: Path) -> bool:
|
||||
"""Create `d` and a `*` .gitignore in it; never overwrite one. True if written."""
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with open(d / ".gitignore", "x", encoding="utf-8", newline="\n") as f:
|
||||
f.write("*\n")
|
||||
except FileExistsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def trash_dir(repo: Path) -> Path:
|
||||
return repo / ".spire" / "trash" / datetime.date.today().isoformat()
|
||||
|
||||
|
||||
def free_name(parent: Path, name: str) -> Path:
|
||||
"""`parent/name`, else `parent/name-2`, `-3`, … : the first that does not exist."""
|
||||
dst, i = parent / name, 2
|
||||
while dst.exists() or dst.is_symlink():
|
||||
dst, i = parent / ("%s-%d" % (name, i)), i + 1
|
||||
return dst
|
||||
|
||||
|
||||
def move_to_trash(repo: Path, srcs) -> dict:
|
||||
tdir = trash_dir(repo)
|
||||
ensure_ignore(repo / ".spire")
|
||||
moved, errors = [], []
|
||||
for s in srcs:
|
||||
src = _abs(s)
|
||||
if not src.exists() and not src.is_symlink():
|
||||
errors.append({"src": str(src), "error": "missing"})
|
||||
continue
|
||||
if src == tdir or src in tdir.parents:
|
||||
errors.append({"src": str(src), "error": "holds the trash dir"})
|
||||
continue
|
||||
tdir.mkdir(parents=True, exist_ok=True)
|
||||
dst = free_name(tdir, src.name)
|
||||
try:
|
||||
shutil.move(str(src), str(dst))
|
||||
except OSError as e:
|
||||
errors.append({"src": str(src), "error": str(e)})
|
||||
continue
|
||||
moved.append({"src": str(src), "dst": str(dst)})
|
||||
return {"trash": str(tdir), "moved": moved, "errors": errors}
|
||||
|
||||
|
||||
def newest_mtime(d: Path) -> float:
|
||||
"""Newest mtime of `d` and everything under it, symlinks not followed."""
|
||||
newest = d.lstat().st_mtime
|
||||
for root, dirs, files in d.walk():
|
||||
for n in dirs + files:
|
||||
try:
|
||||
newest = max(newest, (root / n).lstat().st_mtime)
|
||||
except OSError:
|
||||
pass
|
||||
return newest
|
||||
|
||||
|
||||
def cmd_guard(args) -> dict:
|
||||
repo = repo_of(args)
|
||||
written, present = [], []
|
||||
for d in (_abs(args.quire) / "logs", repo / ".spire"):
|
||||
(written if ensure_ignore(d) else present).append(str(d / ".gitignore"))
|
||||
return {"written": written, "present": present}
|
||||
|
||||
|
||||
def check_scratch_root(root: Path, repo: Path) -> None:
|
||||
"""Refuse a root that may hold repo content: one holding `repo`, one inside a checkout but not
|
||||
under its `.spire/scratch`, and one outside every checkout without the `*` .gitignore that
|
||||
gremlins writes in each scratch root."""
|
||||
rr = root.resolve()
|
||||
if rr in (repo.resolve(), *repo.resolve().parents):
|
||||
raise Refusal("not a scratch root: holds the repo", root=str(root))
|
||||
co = checkout(rr)
|
||||
if co is not None:
|
||||
if rr.relative_to(co[0]).parts[:2] != (".spire", "scratch"):
|
||||
raise Refusal("not a scratch root: in a checkout, not under its .spire/scratch",
|
||||
root=str(root), checkout=str(co[0]))
|
||||
return
|
||||
try:
|
||||
marked = (rr / ".gitignore").read_text(encoding="utf-8").strip() == "*"
|
||||
except OSError:
|
||||
marked = False
|
||||
if not marked:
|
||||
raise Refusal("not a scratch root: no `*` .gitignore", root=str(root))
|
||||
|
||||
|
||||
def cmd_sweep(args) -> dict:
|
||||
repo = repo_of(args)
|
||||
root = _abs(args.root or os.environ.get("SPIRE_SCRATCH") or repo / ".spire" / "scratch")
|
||||
cutoff = time.time() - args.days * 86400
|
||||
stale, kept = [], []
|
||||
if root.is_dir():
|
||||
check_scratch_root(root, repo)
|
||||
for d in sorted(root.iterdir()):
|
||||
if d.is_symlink() or not d.is_dir():
|
||||
continue
|
||||
if newest_mtime(d) < cutoff:
|
||||
(kept if (d / "keep").exists() else stale).append(str(d))
|
||||
out = {"root": str(root), "days": args.days, "stale": stale, "kept": kept}
|
||||
if args.move:
|
||||
out.update(move_to_trash(repo, stale))
|
||||
return out
|
||||
|
||||
|
||||
def cmd_trash(args) -> dict:
|
||||
return move_to_trash(repo_of(args), args.dirs)
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
p = _Parser(prog="quire.py", description=__doc__.splitlines()[0])
|
||||
sub = p.add_subparsers(dest="cmd", required=True, parser_class=_Parser)
|
||||
common = _Parser(add_help=False)
|
||||
common.add_argument("--run", help="the run log; <repo> follows gremlins' scratch rule")
|
||||
common.add_argument("--repo", help="checkout root (default: from --run, else the cwd's checkout)")
|
||||
g = sub.add_parser("guard", parents=[common], help="write `*` .gitignore files in <quire>/logs "
|
||||
"and <repo>/.spire; never overwrite")
|
||||
g.add_argument("quire", help="the quire base dir")
|
||||
s = sub.add_parser("sweep", parents=[common], help="list run dirs under the scratch root with no "
|
||||
"entry modified in --days and no `keep` file")
|
||||
s.add_argument("root", nargs="?", help="scratch root (default: $SPIRE_SCRATCH, else "
|
||||
"<repo>/.spire/scratch)")
|
||||
s.add_argument("--days", type=float, default=7)
|
||||
s.add_argument("--move", action="store_true", help="move the stale dirs to trash")
|
||||
t = sub.add_parser("trash", parents=[common], help="move dirs to <repo>/.spire/trash/<YYYY-MM-DD>/, "
|
||||
"suffix -2, -3 on a name collision; never overwrite")
|
||||
t.add_argument("dirs", nargs="+")
|
||||
return p
|
||||
|
||||
|
||||
COMMANDS = {"guard": cmd_guard, "sweep": cmd_sweep, "trash": cmd_trash}
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
sys.stdout.write(json.dumps(obj) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
try:
|
||||
args = _parser().parse_args(argv)
|
||||
out = COMMANDS[args.cmd](args)
|
||||
except Refusal as e:
|
||||
_emit(e.payload)
|
||||
return 2
|
||||
except OSError as e:
|
||||
_emit({"error": str(e), "type": type(e).__name__})
|
||||
return 2
|
||||
_emit(out)
|
||||
return 1 if out.get("errors") else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,305 @@
|
||||
import contextlib
|
||||
import datetime
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
SKILL = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(SKILL))
|
||||
sys.path.insert(0, str(SKILL.parent / "gremlins"))
|
||||
|
||||
import quire # noqa: E402
|
||||
from grm import store # noqa: E402
|
||||
|
||||
DAY = 86400
|
||||
|
||||
|
||||
class QuireTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp()).resolve()
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
env = mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.tmp)})
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
os.environ.pop("SPIRE_SCRATCH", None)
|
||||
self.repo = self.tmp / "repo"
|
||||
(self.repo / ".git").mkdir(parents=True)
|
||||
self.wp = self.repo / "docs" / "quire"
|
||||
self.scratch = self.repo / ".spire" / "scratch"
|
||||
self.trash = self.repo / ".spire" / "trash" / datetime.date.today().isoformat()
|
||||
|
||||
def w(self, *args, code=0, repo=True):
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
rc = quire.main([*args, "--repo", str(self.repo)] if repo else list(args))
|
||||
lines = buf.getvalue().splitlines()
|
||||
self.assertEqual(len(lines), 1, lines)
|
||||
out = json.loads(lines[0])
|
||||
self.assertEqual(rc, code, out)
|
||||
return out
|
||||
|
||||
def run_dir(self, name, age_days=0, files=("a.txt",)):
|
||||
d = self.scratch / name
|
||||
(d / "sub").mkdir(parents=True)
|
||||
for f in files:
|
||||
(d / "sub" / f).write_text("x", encoding="utf-8")
|
||||
t = time.time() - age_days * DAY
|
||||
for root, dirs, fs in d.walk(top_down=False):
|
||||
for n in dirs + fs:
|
||||
os.utime(root / n, (t, t))
|
||||
os.utime(d, (t, t))
|
||||
return d
|
||||
|
||||
def chdir(self, d):
|
||||
cwd = os.getcwd()
|
||||
os.chdir(d)
|
||||
self.addCleanup(os.chdir, cwd)
|
||||
|
||||
# guard
|
||||
|
||||
def test_guard_writes_then_is_idempotent(self):
|
||||
out = self.w("guard", str(self.wp))
|
||||
self.assertEqual(sorted(out["written"]), sorted([str(self.wp / "logs" / ".gitignore"),
|
||||
str(self.repo / ".spire" / ".gitignore")]))
|
||||
self.assertEqual(out["present"], [])
|
||||
for d in (self.wp / "logs", self.repo / ".spire"):
|
||||
self.assertEqual((d / ".gitignore").read_bytes(), b"*\n")
|
||||
out = self.w("guard", str(self.wp))
|
||||
self.assertEqual(out["written"], [])
|
||||
self.assertEqual(len(out["present"]), 2)
|
||||
|
||||
def test_guard_never_overwrites(self):
|
||||
(self.repo / ".spire").mkdir()
|
||||
(self.repo / ".spire" / ".gitignore").write_text("mine\n", encoding="utf-8")
|
||||
out = self.w("guard", str(self.wp))
|
||||
self.assertEqual(out["present"], [str(self.repo / ".spire" / ".gitignore")])
|
||||
self.assertEqual((self.repo / ".spire" / ".gitignore").read_text(encoding="utf-8"), "mine\n")
|
||||
self.assertEqual((self.wp / "logs" / ".gitignore").read_bytes(), b"*\n")
|
||||
|
||||
def test_repo_defaults_to_cwd_toplevel(self):
|
||||
(self.repo / "deep" / "er").mkdir(parents=True)
|
||||
cwd = os.getcwd()
|
||||
os.chdir(self.repo / "deep" / "er")
|
||||
self.addCleanup(os.chdir, cwd)
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
self.assertEqual(quire.main(["guard", str(self.wp)]), 0)
|
||||
self.assertTrue((self.repo / ".spire" / ".gitignore").exists())
|
||||
|
||||
def test_guard_honours_both_base_names(self):
|
||||
# Regression guard against a future hard-coded folder name in cmd_guard, not a behaviour proof.
|
||||
for name in ("quire", "workpad"):
|
||||
base = self.repo / "docs" / name
|
||||
self.w("guard", str(base))
|
||||
self.assertEqual((base / "logs" / ".gitignore").read_bytes(), b"*\n")
|
||||
|
||||
def test_no_repo_is_refused(self):
|
||||
# review R2 m5: a checkout above the cwd (here self.repo; on a host, maybe $HOME) is not
|
||||
# found past GIT_CEILING_DIRECTORIES, as with git
|
||||
bare = self.repo / "ceiling" / "bare"
|
||||
bare.mkdir(parents=True)
|
||||
self.chdir(bare)
|
||||
with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.repo / "ceiling")}):
|
||||
self.assertIn("--repo", self.w("trash", "x", code=2, repo=False)["error"])
|
||||
|
||||
def git(self, *args, cwd):
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false",
|
||||
*args], cwd=str(cwd), check=True, capture_output=True, timeout=60)
|
||||
|
||||
@unittest.skipUnless(shutil.which("git"), "needs git")
|
||||
def test_repo_matches_gremlins_scratch_root(self):
|
||||
main, other, bare = self.tmp / "main", self.tmp / "other", self.tmp / "bare"
|
||||
for d in (main, other, bare):
|
||||
d.mkdir()
|
||||
for d in (main, other):
|
||||
self.git("init", "-q", cwd=d)
|
||||
self.git("commit", "-q", "--no-verify", "--allow-empty", "-m", "i", cwd=main)
|
||||
self.git("worktree", "add", "-q", str(self.tmp / "wt"), cwd=main)
|
||||
wt = self.tmp / "wt"
|
||||
log = lambda top: top / "docs" / "quire" / "logs" / "x" / "run.md" # dir not created
|
||||
cases = [(wt, main, main), (main, wt, wt), (other, main, other), (bare, main, main),
|
||||
(wt / "src", bare, wt), (bare, bare, None)]
|
||||
(wt / "src").mkdir()
|
||||
for cwd, run_top, want in cases:
|
||||
with self.subTest(cwd=cwd.name, run=run_top.name):
|
||||
self.chdir(cwd)
|
||||
run = log(run_top)
|
||||
out = self.w("sweep", "--run", str(run), repo=False)
|
||||
self.assertEqual(out["root"], str(store.scratch_root(run)))
|
||||
if want is not None:
|
||||
self.assertEqual(out["root"], str(want / ".spire" / "scratch"))
|
||||
|
||||
def test_worktree_resolves_to_the_run_logs_checkout(self):
|
||||
# no git needed: a worktree's `.git` file names <common>/worktrees/<name>, whose `commondir`
|
||||
# file points back to <common>
|
||||
main, wt = self.tmp / "main", self.tmp / "wt"
|
||||
(main / ".git" / "worktrees" / "wt").mkdir(parents=True)
|
||||
(main / ".git" / "worktrees" / "wt" / "commondir").write_text("../..\n", encoding="utf-8")
|
||||
wt.mkdir()
|
||||
(wt / ".git").write_text("gitdir: %s\n" % (main / ".git" / "worktrees" / "wt"), encoding="utf-8")
|
||||
self.chdir(wt)
|
||||
run = main / "docs" / "quire" / "logs" / "x" / "run.md"
|
||||
self.assertEqual(self.w("sweep", "--run", str(run), repo=False)["root"],
|
||||
str(main / ".spire" / "scratch"))
|
||||
src = wt / "run-dir"
|
||||
src.mkdir()
|
||||
self.assertEqual(self.w("trash", str(src), "--run", str(run), repo=False)["trash"],
|
||||
str(main / ".spire" / "trash" / datetime.date.today().isoformat()))
|
||||
self.assertEqual(self.w("sweep", repo=False)["root"], str(wt / ".spire" / "scratch"))
|
||||
|
||||
# trash
|
||||
|
||||
def test_trash_collision_suffix(self):
|
||||
srcs = []
|
||||
for i in range(3):
|
||||
d = self.tmp / ("src%d" % i) / "run"
|
||||
d.mkdir(parents=True)
|
||||
(d / "f").write_text(str(i), encoding="utf-8")
|
||||
srcs.append(d)
|
||||
out = self.w("trash", str(srcs[0]))
|
||||
self.assertEqual(out["moved"], [{"src": str(srcs[0]), "dst": str(self.trash / "run")}])
|
||||
out = self.w("trash", str(srcs[1]), str(srcs[2]))
|
||||
self.assertEqual([m["dst"] for m in out["moved"]],
|
||||
[str(self.trash / "run-2"), str(self.trash / "run-3")])
|
||||
for i, n in enumerate(("run", "run-2", "run-3")):
|
||||
self.assertEqual((self.trash / n / "f").read_text(encoding="utf-8"), str(i))
|
||||
self.assertFalse(any(s.exists() for s in srcs))
|
||||
self.assertEqual((self.repo / ".spire" / ".gitignore").read_bytes(), b"*\n")
|
||||
|
||||
def test_trash_never_overwrites_a_file_of_the_same_name(self):
|
||||
self.trash.mkdir(parents=True)
|
||||
(self.trash / "run").write_text("old", encoding="utf-8")
|
||||
src = self.tmp / "run"
|
||||
src.mkdir()
|
||||
out = self.w("trash", str(src))
|
||||
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "run-2"))
|
||||
self.assertEqual((self.trash / "run").read_text(encoding="utf-8"), "old")
|
||||
|
||||
def test_trash_name_with_spaces(self):
|
||||
src = self.tmp / "my run dir"
|
||||
src.mkdir()
|
||||
(src / "a b.txt").write_text("x", encoding="utf-8")
|
||||
self.w("trash", str(src))
|
||||
src.mkdir()
|
||||
out = self.w("trash", str(src) + os.sep)
|
||||
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "my run dir-2"))
|
||||
self.assertTrue((self.trash / "my run dir" / "a b.txt").exists())
|
||||
|
||||
def test_trash_missing_and_self_are_errors(self):
|
||||
src = self.tmp / "ok"
|
||||
src.mkdir()
|
||||
out = self.w("trash", str(self.tmp / "nope"), str(self.repo / ".spire"), str(src), code=1)
|
||||
self.assertEqual([e["error"] for e in out["errors"]], ["missing", "holds the trash dir"])
|
||||
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "ok"))
|
||||
self.assertTrue((self.repo / ".spire" / ".gitignore").exists())
|
||||
|
||||
# sweep
|
||||
|
||||
def test_sweep_age_and_keep(self):
|
||||
old = self.run_dir("old", age_days=8)
|
||||
self.run_dir("fresh", age_days=1)
|
||||
kept = self.run_dir("kept", age_days=30, files=("a.txt", "keep"))
|
||||
mixed = self.run_dir("mixed", age_days=30)
|
||||
(mixed / "sub" / "new.txt").write_text("x", encoding="utf-8") # one fresh file deep down
|
||||
(self.scratch / ".gitignore").write_text("*\n", encoding="utf-8")
|
||||
out = self.w("sweep")
|
||||
self.assertEqual(out["root"], str(self.scratch))
|
||||
self.assertEqual(out["stale"], [str(kept), str(old)]) # `keep` counts only at the top
|
||||
self.assertEqual(out["kept"], [])
|
||||
(kept / "keep").write_text("", encoding="utf-8")
|
||||
os.utime(kept / "keep", (time.time() - 30 * DAY,) * 2)
|
||||
os.utime(kept, (time.time() - 30 * DAY,) * 2)
|
||||
out = self.w("sweep")
|
||||
self.assertEqual(out["stale"], [str(old)])
|
||||
self.assertEqual(out["kept"], [str(kept)])
|
||||
self.assertEqual(self.w("sweep", "--days", "10")["stale"], [])
|
||||
self.assertTrue(old.exists()) # listing moves nothing
|
||||
|
||||
def test_sweep_move(self):
|
||||
old = self.run_dir("old run", age_days=8)
|
||||
fresh = self.run_dir("fresh", age_days=0)
|
||||
out = self.w("sweep", str(self.scratch), "--move")
|
||||
self.assertEqual(out["moved"], [{"src": str(old), "dst": str(self.trash / "old run")}])
|
||||
self.assertFalse(old.exists())
|
||||
self.assertTrue((self.trash / "old run" / "sub" / "a.txt").exists())
|
||||
self.assertTrue(fresh.exists())
|
||||
|
||||
def test_sweep_missing_root(self):
|
||||
out = self.w("sweep", str(self.tmp / "none"), "--move")
|
||||
self.assertEqual((out["stale"], out["moved"]), ([], []))
|
||||
|
||||
def test_sweep_refuses_a_root_that_is_not_scratch(self):
|
||||
# review R2 m1: SPIRE_SCRATCH set to the repo listed `.git` and `docs` as stale
|
||||
(self.wp / "logs").mkdir(parents=True)
|
||||
(self.wp / "logs" / ".gitignore").write_text("*\n", encoding="utf-8")
|
||||
old = time.time() - 10 * DAY
|
||||
for p in (self.repo / ".git", self.repo / "docs", self.wp, self.wp / "logs"):
|
||||
os.utime(p, (old, old))
|
||||
home = self.tmp / "home"
|
||||
(home / "stuff").mkdir(parents=True)
|
||||
os.utime(home / "stuff", (old, old))
|
||||
for root in (self.repo, self.repo / "docs", self.wp / "logs", self.tmp, home):
|
||||
with self.subTest(root=root):
|
||||
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(root)}):
|
||||
out = self.w("sweep", "--move", code=2)
|
||||
self.assertIn("not a scratch root", out["error"])
|
||||
self.assertEqual(self.w("sweep", str(root), "--move", code=2)["error"], out["error"])
|
||||
self.assertTrue((self.repo / ".git").is_dir() and (self.wp / "logs").is_dir())
|
||||
self.assertTrue((home / "stuff").is_dir())
|
||||
self.assertFalse((self.repo / ".spire" / "trash").exists())
|
||||
|
||||
def test_sweep_outside_root_needs_the_scratch_ignore(self):
|
||||
shared = self.tmp / "shared"
|
||||
self.scratch = shared
|
||||
old = self.run_dir("old", age_days=8)
|
||||
(shared / ".gitignore").write_text("*\n", encoding="utf-8") # gremlins writes it
|
||||
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(shared)}):
|
||||
out = self.w("sweep", "--move")
|
||||
self.assertEqual(out["moved"], [{"src": str(old), "dst": str(self.trash / "old")}])
|
||||
|
||||
def test_sweep_does_not_follow_symlinks(self):
|
||||
fresh = self.tmp / "fresh-target"
|
||||
(fresh / "d").mkdir(parents=True)
|
||||
(fresh / "f").write_text("x", encoding="utf-8")
|
||||
old = self.run_dir("old", age_days=8)
|
||||
lonely = self.run_dir("lonely", age_days=8)
|
||||
try:
|
||||
for link, target in ((old / "link-f", fresh / "f"), (old / "link-d", fresh / "d"),
|
||||
(self.scratch / "link-run", lonely)):
|
||||
os.symlink(target, link, target_is_directory=target.is_dir())
|
||||
if os.utime not in os.supports_follow_symlinks:
|
||||
raise NotImplementedError
|
||||
t = time.time() - 8 * DAY
|
||||
for p in (old / "link-f", old / "link-d", self.scratch / "link-run"):
|
||||
os.utime(p, (t, t), follow_symlinks=False)
|
||||
os.utime(old, (t, t))
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("cannot create or date symlinks here")
|
||||
out = self.w("sweep")
|
||||
self.assertEqual(out["stale"], [str(lonely), str(old)]) # link targets are fresh; link-run skipped
|
||||
|
||||
# entry point
|
||||
|
||||
def test_script_runs_standalone(self):
|
||||
r = subprocess.run([sys.executable, str(SKILL / "quire.py"), "guard", str(self.wp),
|
||||
"--repo", str(self.repo)], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(len(json.loads(r.stdout)["written"]), 2)
|
||||
|
||||
def test_usage_error_is_json(self):
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
self.assertEqual(quire.main(["sweep", "--days", "x"]), 2)
|
||||
self.assertEqual(json.loads(buf.getvalue())["error"], "usage")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Tests for spire:adepts roster.sh base-folder resolution (quire, with workpad fallbacks)."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROSTER = Path(__file__).resolve().parents[2] / "adepts" / "roster.sh"
|
||||
|
||||
|
||||
class RosterTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp(prefix="roster-"))
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.cwd = self.tmp / "proj"
|
||||
self.cwd.mkdir()
|
||||
bindir = self.tmp / "bin"
|
||||
bindir.mkdir()
|
||||
stub = bindir / "just"
|
||||
stub.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") # prints nothing, fails
|
||||
stub.chmod(0o755)
|
||||
self.bindir = bindir
|
||||
|
||||
def adept(self, base):
|
||||
d = self.cwd / base / "adepts" / "foo"
|
||||
d.mkdir(parents=True)
|
||||
(d / "CLAUDE.md").write_text("---\nsummary: test adept\nstatus: active\n---\n", encoding="utf-8")
|
||||
|
||||
def project_md(self, label, base):
|
||||
(self.cwd / ".claude" / "spire").mkdir(parents=True)
|
||||
(self.cwd / ".claude" / "spire" / "project.md").write_text(
|
||||
f"- **{label}**: `{base}`\n", encoding="utf-8")
|
||||
|
||||
def run_roster(self, **env):
|
||||
e = {k: v for k, v in os.environ.items() if k not in ("QUIRE_FOLDER", "WORKPAD_FOLDER")}
|
||||
e["PATH"] = f"{self.bindir}{os.pathsep}{e['PATH']}"
|
||||
e.update(env)
|
||||
r = subprocess.run(["bash", str(ROSTER)], cwd=self.cwd, env=e, capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
return r.stdout
|
||||
|
||||
def test_quire_alone(self):
|
||||
self.adept("docs/quire")
|
||||
out = self.run_roster()
|
||||
self.assertIn("docs/quire/adepts/", out)
|
||||
self.assertIn("**foo**", out)
|
||||
|
||||
def test_workpad_alone(self):
|
||||
self.adept("docs/workpad")
|
||||
out = self.run_roster()
|
||||
self.assertIn("docs/workpad/adepts/", out)
|
||||
self.assertIn("**foo**", out)
|
||||
|
||||
def test_both_quire_wins_with_note(self):
|
||||
self.adept("docs/quire")
|
||||
self.adept("docs/workpad")
|
||||
out = self.run_roster()
|
||||
self.assertIn("## Adept roster — docs/quire/adepts/", out)
|
||||
self.assertIn("docs/workpad", out.replace("## Adept roster — docs/quire/adepts/", ""))
|
||||
self.assertIn("also exists", out)
|
||||
|
||||
def test_quire_label(self):
|
||||
self.adept("custom/q")
|
||||
self.project_md("Quire", "custom/q")
|
||||
self.assertIn("custom/q/adepts/", self.run_roster())
|
||||
|
||||
def test_workpad_label(self):
|
||||
self.adept("custom/w")
|
||||
self.project_md("Workpad", "custom/w")
|
||||
self.assertIn("custom/w/adepts/", self.run_roster())
|
||||
|
||||
def test_quire_folder_over_workpad_folder(self):
|
||||
self.adept("qf")
|
||||
self.adept("wf")
|
||||
out = self.run_roster(QUIRE_FOLDER="qf", WORKPAD_FOLDER="wf")
|
||||
self.assertIn("## Adept roster — qf/adepts/", out)
|
||||
|
||||
def test_just_quire_folder_recipe(self):
|
||||
# the stub answers only `just quire-folder`; docs/quire exists so the recipe must beat detection
|
||||
(self.bindir / "just").write_text(
|
||||
'#!/bin/sh\n[ "$1" = quire-folder ] && { echo qf; exit 0; }\nexit 1\n', encoding="utf-8")
|
||||
self.adept("qf")
|
||||
self.adept("docs/quire")
|
||||
out = self.run_roster()
|
||||
self.assertIn("## Adept roster — qf/adepts/", out)
|
||||
|
||||
def test_workpad_folder_alone(self):
|
||||
# docs/quire exists so the fallback must beat folder detection
|
||||
self.adept("wf")
|
||||
self.adept("docs/quire")
|
||||
out = self.run_roster(WORKPAD_FOLDER="wf")
|
||||
self.assertIn("## Adept roster — wf/adepts/", out)
|
||||
|
||||
def test_quire_folder_beats_existing_workpad_dir(self):
|
||||
self.adept("qf")
|
||||
self.adept("docs/workpad")
|
||||
out = self.run_roster(QUIRE_FOLDER="qf")
|
||||
self.assertIn("## Adept roster — qf/adepts/", out)
|
||||
|
||||
def test_label_beats_folder_detection(self):
|
||||
self.adept("custom/q")
|
||||
self.adept("docs/quire")
|
||||
self.project_md("Quire", "custom/q")
|
||||
self.assertIn("## Adept roster — custom/q/adepts/", self.run_roster())
|
||||
|
||||
def test_dot_quire_beats_dot_workpad(self):
|
||||
self.adept(".quire")
|
||||
self.adept(".workpad")
|
||||
self.assertIn("## Adept roster — .quire/adepts/", self.run_roster())
|
||||
|
||||
def test_dot_workpad_found_alone(self):
|
||||
self.adept(".workpad")
|
||||
self.assertIn("## Adept roster — .workpad/adepts/", self.run_roster())
|
||||
|
||||
def test_none_found_names_docs_quire(self):
|
||||
out = self.run_roster()
|
||||
self.assertIn("none (no docs/quire/adepts/)", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user