From 1f84a8be087054405de6a3857f387588e02503a1 Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:22:06 +0200 Subject: [PATCH 1/2] feat: /status and /pause from Telegram Fixes #32 Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 25 ++++++- README.md | 14 ++++ THREAT-MODEL.md | 22 ++++++ internal/gate/check.go | 54 ++++++++++++-- internal/gate/request_test.go | 116 +++++++++++++++++++++++++++++ internal/gate/run.go | 13 +++- internal/gate/status.go | 10 ++- internal/listener/listener.go | 84 +++++++++++++++++++++ internal/listener/listener_test.go | 46 +++++++++++- internal/spool/spool.go | 69 +++++++++++++---- internal/state/state.go | 22 ++++++ 11 files changed, 448 insertions(+), 27 deletions(-) create mode 100644 internal/gate/request_test.go diff --git a/DESIGN.md b/DESIGN.md index 6f0e4b7..7b71e38 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -111,7 +111,7 @@ can be less strict; each example sets what its `apply` needs. | `/var/spool/pullgate/NAME/outbox` | root, group listener, 0770 (no setgid) | messages from root to the listener | | `/var/spool/pullgate/NAME/outbox/*.json` | root, group listener, 0640 | one message | | `/var/spool/pullgate/NAME/inbox` | listener, 0700 | approvals from the listener to root | -| `/var/spool/pullgate/NAME/check` | listener, 0700 | check requests from the listener to root | +| `/var/spool/pullgate/NAME/check` | listener, 0700 | check, status and pause requests from the listener to root | | `/var/lib/pullgate-listener/state.json` | listener, 0600 | the listener's open questions | | `/var/lib/pullgate/_update/` and `.../tmp/` | root, 0700 | the state, the lock and the downloads of `pullgate update` (section 15) | | `/var/spool/pullgate/_update/` | as `NAME/` above | the outbox, inbox and check request of the updates | @@ -473,6 +473,29 @@ these hold, else it answers "This question is closed." and writes nothing: Then it writes the approval, edits the question ("Apply tapped. Waiting for the host." or "Skipped."), and answers the tap. +**`/status` and `/pause`** (code6x/pullgate#32). The same checks of the +sender, the chat and the edit hold, as for `/check`. The text is `/status` +(every instance), `/status NAME`, or `/pause NAME` (more words after NAME +are allowed and dropped: the reason never reaches root). The listener +writes a request file in the check directory: `status` or `pause`, with +exactly its name and a newline in it, and nothing from the message. The +same command for the same instance within 10 seconds writes nothing. Root +takes the requests in its run, as check requests (owned by the listener, +a regular file, the exact content; any other file is removed and does +nothing): + +- `pause`: if there is no pause file, root writes one with the reason + `paused from Telegram at TIME` (the prefix `state.TelegramPause`; no + other reason starts with it). A pause file that is there is never + changed, so that a pause that pullgate or root set keeps its reason. The + pause is never rate-limited; its reply goes out at most once a minute. +- `status`: root sends a notice with the facts of `pullgate status` + (section 13), cleaned and in `
`, at most once a minute. It is
+  read-only.
+- A run that took only these requests does not fetch.
+
+To go on after `/pause`, root runs `pullgate status NAME --resume`.
+
 **`/check`.** The listener writes a check request (section 8) only when all
 of these hold, else it writes nothing:
 
diff --git a/README.md b/README.md
index 63b493e..1b16946 100644
--- a/README.md
+++ b/README.md
@@ -191,6 +191,20 @@ usual Apply question, or "No new commit (the applied commit is …)", or
 - Without `pullgate-check@NAME.path`, the request waits for the next timer
   run.
 
+## Status and pause: `/status`, `/pause`
+
+- `/status` (all instances) or `/status NAME`: the mode, the applied
+  commit, the last tip, the open question, paused or not and why, broken
+  or not. It changes nothing and fetches nothing. At most one answer per
+  instance a minute.
+- `/pause NAME`: pauses the instance. Nothing is fetched, asked or applied
+  until root runs `pullgate status NAME --resume` on the host. If it is
+  paused already, the old pause stays as it is. A reason after NAME is not
+  sent to the host.
+
+As with `/check`, only your user ID in your chat counts, and the listener
+only writes a small request file; root does the work.
+
 ## Update pullgate: `/update`
 
 Once a day `pullgate-update.timer` looks for a new release of pullgate. For
diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md
index 61bb4bc..4b7d00f 100644
--- a/THREAT-MODEL.md
+++ b/THREAT-MODEL.md
@@ -479,6 +479,28 @@ until the owner resets it (DESIGN.md section 8). The run unit has no start
 limit, so the timer goes on. This denies; it never approves. A clock jump back of more than
 a minute allows one more run.
 
+### T18b. `/status` and `/pause` from a stolen token or the listener
+
+*Attack.* Someone with the bot token, or a compromised listener, sends
+`/status` or `/pause`, or writes the request files directly.
+
+*Defense and what is left.* The request files hold only their kind; root
+reads its own state and acts. So the most they can do:
+
+- **See a status**: the mode, the SHAs, the open question, the pause and
+  broken reasons. With the token they can read the questions anyway, which
+  show more. The status holds no key, token or IP address. Root answers at
+  most once a minute.
+- **Pause an instance.** This only stops work: it never applies or
+  approves anything. A thief can deny work in other ways already (not
+  deliver a tap). Root never changes a pause file that is there, so a
+  `/pause` cannot replace the reason of a safety pause, and a later
+  limited `/resume` (code6x/pullgate#33) cannot use it to lift one.
+
+They cannot resume, approve, or change the state: the state directory is
+root's (0700), and any other file in the check directory is removed and
+does nothing (a test).
+
 ### T19. What the bot tells
 
 *Attack or accident.* Someone sends the bot messages to learn what it runs,
diff --git a/internal/gate/check.go b/internal/gate/check.go
index 9ed4579..c95c43e 100644
--- a/internal/gate/check.go
+++ b/internal/gate/check.go
@@ -1,8 +1,12 @@
 package gate
 
 import (
+	"strings"
 	"time"
 
+	"github.com/code6x/pullgate/internal/message"
+	"github.com/code6x/pullgate/internal/spool"
+
 	"github.com/code6x/pullgate/internal/state"
 )
 
@@ -12,20 +16,56 @@ import (
 const CheckInterval = time.Minute
 
 // takeChecks reads and removes the files in the check directory, and
-// returns how many were valid check requests. A bad file is logged and
-// removed. An error of the directory counts as no request (fail closed).
-func (e *Env) takeChecks() int {
-	n, bad, err := e.Spool.TakeChecks(e.Owners.ListenerUID)
+// returns the valid requests. A bad file is logged and removed. An error
+// of the directory counts as no request (fail closed).
+func (e *Env) takeChecks() spool.Requests {
+	r, bad, err := e.Spool.TakeRequests(e.Owners.ListenerUID)
 	for _, b := range bad {
 		e.Log.Warn("bad check request, removed", "err", b)
 	}
 	if err != nil {
 		e.Log.Error("read the check requests", "err", err)
 	}
-	if n > 0 {
-		e.Log.Info("check request taken")
+	if r.Any() {
+		e.Log.Info("requests taken", "check", r.Check, "status", r.Status, "pause", r.Pause)
+	}
+	return r
+}
+
+// pauseRequest acts on /pause: it writes the pause file, unless there is
+// one. A pause that is there already is never changed, so that a later
+// /resume (code6x/pullgate#33) cannot lift it. The pause itself is never
+// rate-limited; its reply is, once a minute.
+func (e *Env) pauseRequest(st *state.State) {
+	now := e.now()
+	var text string
+	if e.Dir.Paused() {
+		text = "⏸ " + e.Cfg.Name + " was paused already: " + message.Code(e.Dir.PauseReason())
+	} else if err := e.Dir.Pause(state.TelegramPause + now.UTC().Format("2006-01-02 15:04 MST")); err != nil {
+		e.Log.Error("write the pause file", "err", err)
+		text = "Error: " + e.Cfg.Name + " could not be paused. See the journal of the host."
+	} else {
+		e.Log.Info("paused from Telegram")
+		text = "⏸ " + e.Cfg.Name + " is paused. Nothing is fetched, asked or applied. To go on, run as root: pullgate status " + e.Cfg.Name + " --resume"
+	}
+	if d := now.Sub(st.PauseNote); d >= CheckInterval || d <= -CheckInterval {
+		st.PauseNote = now
+		e.notice(text)
+	}
+}
+
+// statusRequest answers /status with the facts of "pullgate status",
+// at most once a minute.
+func (e *Env) statusRequest(st *state.State) {
+	now := e.now()
+	if d := now.Sub(st.StatusAt); d < CheckInterval && d > -CheckInterval {
+		e.Log.Warn("status request dropped: the last one was less than a minute ago")
+		return
 	}
-	return n
+	st.StatusAt = now
+	var b strings.Builder
+	e.statusText(&b, st)
+	e.notice("Status:\n" + message.Output(b.String(), 30))
 }
 
 // limitCheck enforces CheckInterval. It returns CheckLimited when the
diff --git a/internal/gate/request_test.go b/internal/gate/request_test.go
new file mode 100644
index 0000000..723ea75
--- /dev/null
+++ b/internal/gate/request_test.go
@@ -0,0 +1,116 @@
+package gate
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/code6x/pullgate/internal/spool"
+	"github.com/code6x/pullgate/internal/state"
+)
+
+func (f *fixture) requestKind(kind string) {
+	f.t.Helper()
+	if err := f.env.Spool.Ensure(f.env.UID, f.env.Owners); err != nil {
+		f.t.Fatal(err)
+	}
+	if err := f.env.Spool.WriteRequest(kind); err != nil {
+		f.t.Fatal(err)
+	}
+}
+
+func TestStatusRequest(t *testing.T) {
+	f := newFixture(t, ``, "")
+	a := f.applyNew("one")
+	f.commit("second", "two", nil) // not fetched: /status does not fetch
+	f.requestKind(spool.RequestStatus)
+	if r := f.run(); r != Nothing {
+		t.Fatalf("run: %s", r)
+	}
+	ms := f.outbox()
+	if len(ms) != 1 || ms[0].Kind != spool.KindNotice || !strings.Contains(ms[0].Text, "applied:") ||
+		!strings.Contains(ms[0].Text, a) || !strings.Contains(ms[0].Text, "paused:      no") {
+		t.Fatalf("status notice: %+v", ms)
+	}
+	if f.state().LastTip != a {
+		t.Fatal("/status must not fetch")
+	}
+	// A second one within a minute is dropped.
+	f.requestKind(spool.RequestStatus)
+	f.run()
+	if len(f.outbox()) != 0 {
+		t.Fatal("a second /status within a minute must get no answer")
+	}
+	// It works while paused, and shows why.
+	f.now = f.now.Add(2 * time.Minute)
+	if err := f.env.Dir.Pause("paused by the owner"); err != nil {
+		t.Fatal(err)
+	}
+	f.requestKind(spool.RequestStatus)
+	f.run()
+	if !contains(f.outbox(), "paused:      yes: paused by the owner") {
+		t.Fatal("the status must show the pause and its reason")
+	}
+}
+
+func TestPauseRequest(t *testing.T) {
+	f := newFixture(t, ``, "")
+	f.applyNew("one")
+	f.requestKind(spool.RequestPause)
+	f.run()
+	if !f.env.Dir.Paused() || !strings.HasPrefix(f.env.Dir.PauseReason(), state.TelegramPause+"2026-11-11 12:00") {
+		t.Fatalf("not paused from Telegram: %q", f.env.Dir.PauseReason())
+	}
+	if !contains(f.outbox(), "is paused. Nothing is fetched") {
+		t.Fatal("no reply")
+	}
+	f.commit("second", "two", nil)
+	if r := f.run(); r != Paused {
+		t.Fatalf("a paused instance does nothing: %s", r)
+	}
+}
+
+func TestPauseRequestKeepsAnOtherPause(t *testing.T) {
+	f := newFixture(t, ``, "")
+	if err := f.env.Dir.Ensure(); err != nil {
+		t.Fatal(err)
+	}
+	if err := f.env.Dir.Pause("the apply of x was cut off"); err != nil {
+		t.Fatal(err)
+	}
+	f.requestKind(spool.RequestPause)
+	f.run()
+	if f.env.Dir.PauseReason() != "the apply of x was cut off" {
+		t.Fatalf("a pause that is there must not change: %q", f.env.Dir.PauseReason())
+	}
+	if !contains(f.outbox(), "was paused already") {
+		t.Fatal("no reply")
+	}
+}
+
+// The listener can only write request files; a bad one pauses nothing.
+func TestListenerCannotPauseByOtherFiles(t *testing.T) {
+	for _, c := range []struct{ name, content string }{
+		{"pause", "pause\nby a thief\n"},
+		{"paused", "x\n"},
+		{"state.json", `{"applied":""}`},
+	} {
+		t.Run(c.name, func(t *testing.T) {
+			f := newFixture(t, ``, "")
+			f.commit("first", "one", nil)
+			f.request()
+			if err := os.WriteFile(filepath.Join(f.env.Spool.CheckDir(), c.name), []byte(c.content), 0o600); err != nil {
+				t.Fatal(err)
+			}
+			f.run()
+			if f.env.Dir.Paused() {
+				t.Fatal("a bad request file must not pause")
+			}
+			if _, err := os.Lstat(filepath.Join(f.env.Spool.CheckDir(), c.name)); err == nil {
+				t.Fatal("root must remove the bad file")
+			}
+		})
+	}
+}
diff --git a/internal/gate/run.go b/internal/gate/run.go
index 869903e..3fec40d 100644
--- a/internal/gate/run.go
+++ b/internal/gate/run.go
@@ -157,7 +157,18 @@ func (e *Env) Run(ctx context.Context) (Result, error) {
 	if err != nil {
 		return "", err
 	}
-	requested := requests > 0
+	if requests.Pause > 0 {
+		e.pauseRequest(st)
+		paused = e.Dir.Paused()
+	}
+	if requests.Status > 0 {
+		e.statusRequest(st)
+	}
+	if (requests.Pause > 0 || requests.Status > 0) && requests.Check == 0 {
+		// Only /status or /pause: they do not fetch.
+		return Nothing, e.Dir.Save(st)
+	}
+	requested := requests.Check > 0
 	if requested {
 		if r := e.limitCheck(st); r != "" {
 			return r, e.Dir.Save(st)
diff --git a/internal/gate/status.go b/internal/gate/status.go
index c1eb849..fb66781 100644
--- a/internal/gate/status.go
+++ b/internal/gate/status.go
@@ -71,6 +71,13 @@ func (e *Env) Status(w io.Writer, f StatusFlags) error {
 		e.edit(closed.ID, "This question for "+code(closed.SHA)+" is closed: the owner ran --ask-again. The next run asks again.")
 		_, _ = fmt.Fprintf(w, "The open question %d for %s is closed. The next run asks again.\n", closed.ID, closed.SHA)
 	}
+	e.statusText(w, st)
+	return nil
+}
+
+// statusText writes the facts of the state, for "pullgate status" and
+// /status.
+func (e *Env) statusText(w io.Writer, st *state.State) {
 	show := func(k, v string) { _, _ = fmt.Fprintf(w, "%-12s %s\n", k+":", v) }
 	show("instance", e.Cfg.Name)
 	show("mode", e.Cfg.Mode)
@@ -92,14 +99,13 @@ func (e *Env) Status(w io.Writer, f StatusFlags) error {
 		show("broken", fmt.Sprintf("since %s, last error: %s", b.Since.Format("2006-01-02 15:04 MST"), b.Reason))
 	}
 	if e.Dir.Paused() {
-		show("paused", "yes: "+e.Dir.PauseFile())
+		show("paused", "yes: "+e.Dir.PauseReason()+" ("+e.Dir.PauseFile()+")")
 	} else {
 		show("paused", "no")
 	}
 	if st.InProgress != nil {
 		show("in progress", fmt.Sprintf("%s of %s since %s", st.InProgress.Phase, st.InProgress.SHA, st.InProgress.Started.Format("2006-01-02 15:04 MST")))
 	}
-	return nil
 }
 
 // forgetOpen removes the open question for sha from the state and returns
diff --git a/internal/listener/listener.go b/internal/listener/listener.go
index d21d16e..dca4364 100644
--- a/internal/listener/listener.go
+++ b/internal/listener/listener.go
@@ -428,6 +428,80 @@ const helpCommand = "/help"
 // section 15).
 const updateCommand = "/update"
 
+// statusCommand and pauseCommand ask root for the status, or to pause an
+// instance (code6x/pullgate#32).
+const (
+	statusCommand = "/status"
+	pauseCommand  = "/pause"
+)
+
+func firstWord(s string) string {
+	if f := strings.Fields(s); len(f) > 0 {
+		return f[0]
+	}
+	return ""
+}
+
+// request writes a status or pause request. Like /check, the file holds
+// no data from the message: root reads its own state and acts.
+func (l *Listener) request(ctx context.Context, m *telegram.Message, kind string) {
+	f := strings.Fields(m.Text)
+	var names []string
+	switch {
+	case kind == spool.RequestStatus && len(f) == 1:
+		names = slices.Clone(l.Cfg.Instances)
+	case len(f) >= 2 && slices.Contains(l.Cfg.Instances, f[1]) && (kind == spool.RequestPause || len(f) == 2):
+		names = []string{f[1]}
+	default:
+		l.Log.Info("message ignored", "reason", "bad "+kind+" arguments", "from", fromID(m))
+		use := "/status or /status NAME"
+		if kind == spool.RequestPause {
+			use = "/pause NAME"
+		}
+		l.sendReply(ctx, m, "Use "+use+". NAME is one of: "+html.EscapeString(strings.Join(l.Cfg.Instances, ", "))+".")
+		return
+	}
+	if l.lastCheck == nil {
+		l.lastCheck = map[string]time.Time{}
+	}
+	now := l.now()
+	var ok, soon, failed []string
+	for _, n := range names {
+		key := kind + ":" + n
+		if d := now.Sub(l.lastCheck[key]); d < CheckGap && d > -CheckGap {
+			soon = append(soon, n)
+			continue
+		}
+		if err := l.dirs(n).WriteRequest(kind); err != nil {
+			l.Log.Error("write the "+kind+" request", "instance", n, "err", err)
+			failed = append(failed, n)
+			continue
+		}
+		l.lastCheck[key] = now
+		ok = append(ok, n)
+	}
+	l.Log.Info(kind+" request taken", "instances", ok)
+	var text []string
+	if len(ok) > 0 {
+		verb := "Asking for the status of"
+		if kind == spool.RequestPause {
+			verb = "Pausing"
+		}
+		line := verb + " " + html.EscapeString(strings.Join(ok, ", ")) + "…"
+		if kind == spool.RequestPause && len(f) > 2 {
+			line += " (the reason is not sent to the host: a request holds no text)"
+		}
+		text = append(text, line)
+	}
+	if len(soon) > 0 {
+		text = append(text, ""+html.EscapeString(strings.Join(soon, ", "))+": this was asked a few seconds ago. Wait for its answer.")
+	}
+	if len(failed) > 0 {
+		text = append(text, "Error: the request for "+html.EscapeString(strings.Join(failed, ", "))+" was not saved. Check the journal of the listener, and that the host ran pullgate once for it.")
+	}
+	l.sendReply(ctx, m, strings.Join(text, "\n"))
+}
+
 // HintGap is the least time between two "Not a command" replies, so that a
 // stuck client or a long paste cannot make the bot fill the chat.
 const HintGap = time.Minute
@@ -443,6 +517,8 @@ func (l *Listener) helpText() string {
 		"pullgate commands:",
 		"/check: look for a new commit now, on every instance",
 		"/check NAME: the same, on one instance",
+		"/status or /status NAME: the mode, the applied commit, the open question, paused or not",
+		"/pause NAME: stop the instance; to go on, root runs pullgate status NAME --resume",
 		"/update: look for a new release of pullgate; a question asks before it is installed",
 		"/help: this list",
 		"",
@@ -476,6 +552,10 @@ func (l *Listener) command(ctx context.Context, m *telegram.Message) {
 		l.update(ctx, m)
 		return
 	}
+	if why == spool.RequestStatus || why == spool.RequestPause {
+		l.request(ctx, m, why)
+		return
+	}
 	if names == nil {
 		l.Log.Info("message ignored", "reason", why, "from", fromID(m))
 		if why == "not a command" {
@@ -540,6 +620,10 @@ func (l *Listener) checkNames(m *telegram.Message) ([]string, string, bool) {
 		return nil, "help", false
 	case m.Text == updateCommand:
 		return nil, "update", false
+	case firstWord(m.Text) == statusCommand:
+		return nil, spool.RequestStatus, false
+	case firstWord(m.Text) == pauseCommand:
+		return nil, spool.RequestPause, false
 	case !strings.HasPrefix(m.Text, checkCommand):
 		return nil, "not a command", false
 	case m.Text == checkCommand:
diff --git a/internal/listener/listener_test.go b/internal/listener/listener_test.go
index 8beaee9..cf75516 100644
--- a/internal/listener/listener_test.go
+++ b/internal/listener/listener_test.go
@@ -393,7 +393,7 @@ func TestHelp(t *testing.T) {
 	if len(ms) != 1 || ms[0].Chat != chat || ms[0].ReplyTo == 0 {
 		t.Fatalf("want one reply: %+v", ms)
 	}
-	for _, want := range []string{"/check", "/check NAME", "/help", "" + inst + "", "" + inst2 + "", "Apply", "Skip", "--pause", "--resume", "--ask-again"} {
+	for _, want := range []string{"/check", "/check NAME", "/help", "" + inst + "", "" + inst2 + "", "Apply", "Skip", "--pause", "--resume", "--ask-again", "/status", "/pause NAME"} {
 		if !strings.Contains(ms[0].Text, want) {
 			t.Errorf("the help must hold %q:\n%s", want, ms[0].Text)
 		}
@@ -620,3 +620,47 @@ func TestUpdateQuestionsAreTheirOwn(t *testing.T) {
 		t.Fatal("the tap must not write to the instance pullgate")
 	}
 }
+
+func TestStatusAndPauseCommands(t *testing.T) {
+	f, d2 := newL2(t)
+	f.say(owner, chat, "/status", false)
+	f.say(owner, chat, "/pause "+inst2+" for the night", false)
+	r1, _, _ := f.d.TakeRequests(os.Geteuid())
+	r2, bad, err := d2.TakeRequests(os.Geteuid())
+	if r1 != (spool.Requests{Status: 1}) || r2 != (spool.Requests{Status: 1, Pause: 1}) || len(bad) != 0 || err != nil {
+		t.Fatalf("requests: %+v %+v %v %v", r1, r2, bad, err)
+	}
+	ms := f.tg.Messages()
+	if len(ms) != 2 || !strings.Contains(ms[0].Text, "Asking for the status of") || !strings.Contains(ms[1].Text, "Pausing "+inst2+"") ||
+		!strings.Contains(ms[1].Text, "the reason is not sent") {
+		t.Fatalf("replies: %+v", ms)
+	}
+	// /pause needs a known name; /status takes no more words.
+	for _, bad := range []string{"/pause", "/pause nope", "/status " + inst + " x"} {
+		f.say(owner, chat, bad, false)
+	}
+	if f.d.HasCheck() || d2.HasCheck() {
+		t.Fatal("a bad command writes no request")
+	}
+	// The same command within CheckGap is not written again.
+	f.say(owner, chat, "/status "+inst, false)
+	f.say(owner, chat, "/status "+inst, false)
+	if r, _, _ := f.d.TakeRequests(os.Geteuid()); r.Status != 0 {
+		t.Fatal("a second /status within CheckGap must not write")
+	}
+}
+
+func TestStatusAndPauseNotForOthers(t *testing.T) {
+	f := newL(t)
+	for _, m := range []struct {
+		from, chat int64
+		edited     bool
+	}{{999, chat, false}, {owner, 999, false}, {owner, chat, true}} {
+		for _, text := range []string{"/status", "/pause " + inst} {
+			f.say(m.from, m.chat, text, m.edited)
+		}
+	}
+	if f.d.HasCheck() || len(f.tg.Messages()) != 0 {
+		t.Fatal("others get no reply and write no request")
+	}
+}
diff --git a/internal/spool/spool.go b/internal/spool/spool.go
index 81d817f..5a244e4 100644
--- a/internal/spool/spool.go
+++ b/internal/spool/spool.go
@@ -257,44 +257,83 @@ func (d Dirs) HasCheck() bool {
 	return false
 }
 
-// TakeChecks reads and removes every file in the check directory (root).
-// It returns how many were valid check requests, and an error for each bad
-// file. A valid request is a regular file named CheckFile, owned by the
-// listener user, with exactly CheckContent in it.
+// Request kinds besides the check request (code6x/pullgate#32). Each has
+// one file name, and its content is the name and a newline: no data from
+// the message.
+const (
+	RequestStatus = "status"
+	RequestPause  = "pause"
+)
+
+// WriteRequest writes a status or pause request (the listener).
+func (d Dirs) WriteRequest(kind string) error {
+	if kind != RequestStatus && kind != RequestPause {
+		return fmt.Errorf("unknown request kind %q", kind)
+	}
+	return writeIn(d.CheckDir(), []byte(kind+"\n"), 0o600, -1, kind)
+}
+
+// Requests counts the valid requests that TakeRequests took.
+type Requests struct{ Check, Status, Pause int }
+
+// Any reports whether there was a valid request.
+func (r Requests) Any() bool { return r.Check+r.Status+r.Pause > 0 }
+
+// TakeChecks is TakeRequests, for callers that know only check requests.
 func (d Dirs) TakeChecks(listenerUID int) (int, []error, error) {
+	r, bad, err := d.TakeRequests(listenerUID)
+	return r.Check, bad, err
+}
+
+// TakeRequests reads and removes every file in the check directory (root).
+// It returns the valid requests, and an error for each bad file. A valid
+// request is a regular file owned by the listener user: CheckFile with
+// exactly CheckContent, or a file named RequestStatus or RequestPause with
+// exactly its name and a newline.
+func (d Dirs) TakeRequests(listenerUID int) (Requests, []error, error) {
+	var r Requests
 	root, err := os.OpenRoot(d.CheckDir())
 	if err != nil {
 		if errors.Is(err, fs.ErrNotExist) {
-			return 0, nil, nil
+			return r, nil, nil
 		}
-		return 0, nil, fmt.Errorf("open the check directory: %w", err)
+		return r, nil, fmt.Errorf("open the check directory: %w", err)
 	}
 	defer func() { _ = root.Close() }()
 	names, err := list(root)
 	if err != nil {
-		return 0, nil, fmt.Errorf("read the check directory: %w", err)
+		return r, nil, fmt.Errorf("read the check directory: %w", err)
 	}
-	n := 0
 	var bad []error
 	for _, name := range names {
 		b, err := readOne(root, name, MaxCheck, listenerUID)
 		if rerr := root.RemoveAll(name); rerr != nil {
-			return n, bad, fmt.Errorf("remove %s/%s: %w. Fix: remove it as root", d.CheckDir(), name, rerr)
+			return r, bad, fmt.Errorf("remove %s/%s: %w. Fix: remove it as root", d.CheckDir(), name, rerr)
+		}
+		var count *int
+		want := ""
+		switch name {
+		case CheckFile:
+			count, want = &r.Check, CheckContent
+		case RequestStatus:
+			count, want = &r.Status, RequestStatus+"\n"
+		case RequestPause:
+			count, want = &r.Pause, RequestPause+"\n"
 		}
 		switch {
 		case err != nil:
-		case name != CheckFile:
-			err = errors.New("not the name of a check request")
-		case string(b) != CheckContent:
-			err = errors.New("not the content of a check request")
+		case count == nil:
+			err = errors.New("not the name of a request")
+		case string(b) != want:
+			err = errors.New("not the content of a request")
 		}
 		if err != nil {
 			bad = append(bad, fmt.Errorf("check file %s: %w", name, err))
 			continue
 		}
-		n++
+		*count++
 	}
-	return n, bad, nil
+	return r, bad, nil
 }
 
 // list returns the names in dir, sorted, without names that start with ".".
diff --git a/internal/state/state.go b/internal/state/state.go
index 73d2611..19528ef 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -11,10 +11,12 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"io"
 	"io/fs"
 	"os"
 	"path/filepath"
 	"sort"
+	"strings"
 	"syscall"
 	"time"
 
@@ -82,6 +84,8 @@ type State struct {
 	LimitNote  time.Time        `json:"limit_note,omitempty"`
 	CheckAt    time.Time        `json:"check_at,omitzero"`   // the last check request that was taken (DESIGN.md section 8)
 	CheckNote  time.Time        `json:"check_note,omitzero"` // the last "too many check requests" reply
+	StatusAt   time.Time        `json:"status_at,omitzero"`  // the last /status that was answered
+	PauseNote  time.Time        `json:"pause_note,omitzero"` // the last reply to /pause
 	NextID     int64            `json:"next_id"`
 }
 
@@ -217,6 +221,24 @@ func (d Dir) Pause(reason string) error {
 	return WriteFileAtomic(d.PauseFile(), []byte(reason+"\n"), 0o644)
 }
 
+// TelegramPause starts the reason of a pause that came from /pause
+// (code6x/pullgate#32). No other reason starts with it.
+const TelegramPause = "paused from Telegram at "
+
+// PauseReason is the first line of the pause file, at most 200 bytes, or
+// "" when there is none. The file is root's; it is never followed.
+func (d Dir) PauseReason() string {
+	f, err := os.OpenFile(d.PauseFile(), os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
+	if err != nil {
+		return ""
+	}
+	defer func() { _ = f.Close() }()
+	b := make([]byte, 200)
+	n, _ := io.ReadFull(f, b)
+	line, _, _ := strings.Cut(string(b[:n]), "\n")
+	return line
+}
+
 // Resume removes the pause file.
 func (d Dir) Resume() error {
 	err := os.Remove(d.PauseFile())

From 4d87b28dc1445ad5c52cfbf9fd9539fe72a3e0ba Mon Sep 17 00:00:00 2001
From: Geno Roupsky <185580+groupsky@users.noreply.github.com>
Date: Thu, 19 Nov 2026 14:25:26 +0200
Subject: [PATCH 2/2] fix: review findings of /status and /pause: path unit, no
 skipped fetch, no replaced pause

Co-Authored-By: Claude Opus 5.5 
---
 DESIGN.md                            | 13 +++++++----
 README.md                            |  3 +--
 THREAT-MODEL.md                      |  9 +++++---
 contrib/systemd/pullgate-check@.path |  6 ++++--
 internal/gate/check.go               | 10 +++++----
 internal/gate/request_test.go        | 15 ++++++-------
 internal/gate/run.go                 |  6 ++----
 internal/listener/listener.go        |  7 +++++-
 internal/state/state.go              | 32 ++++++++++++++++++++++++++++
 9 files changed, 73 insertions(+), 28 deletions(-)

diff --git a/DESIGN.md b/DESIGN.md
index 7b71e38..9f7191c 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -390,8 +390,9 @@ six bytes `check\n`. It holds nothing from the message: not the text, not
 a SHA, not a code. A check request can only start a normal run. It is not
 an approval, and `pullgate apply` never reads this directory.
 
-`pullgate-check@NAME.path` watches the file `check/request`
-(`PathExists=`; another file there starts nothing) and starts `pullgate-run@NAME.service`, the unit of the timer. `pullgate run`,
+`pullgate-check@NAME.path` watches the files `check/request`,
+`check/status` and `check/pause` (`PathExists=`; another file there starts
+nothing) and starts `pullgate-run@NAME.service`, the unit of the timer. `pullgate run`,
 with the lock held (a run that had to wait for the lock, and then finds
 no request, stops: another run took the request):
 
@@ -479,7 +480,8 @@ sender, the chat and the edit hold, as for `/check`. The text is `/status`
 are allowed and dropped: the reason never reaches root). The listener
 writes a request file in the check directory: `status` or `pause`, with
 exactly its name and a newline in it, and nothing from the message. The
-same command for the same instance within 10 seconds writes nothing. Root
+same command for the same instance within a minute writes nothing, and
+gets "asked less than a minute ago". Root
 takes the requests in its run, as check requests (owned by the listener,
 a regular file, the exact content; any other file is removed and does
 nothing):
@@ -489,10 +491,13 @@ nothing):
   other reason starts with it). A pause file that is there is never
   changed, so that a pause that pullgate or root set keeps its reason. The
   pause is never rate-limited; its reply goes out at most once a minute.
+  The file is made with a hard link, which fails when the name exists, so
+  a pause that root writes at the same moment is never replaced.
 - `status`: root sends a notice with the facts of `pullgate status`
   (section 13), cleaned and in `
`, at most once a minute. It is
   read-only.
-- A run that took only these requests does not fetch.
+- Then the normal run goes on, so a stream of `/status` never stops the
+  fetches. After a `/pause`, the run ends as paused.
 
 To go on after `/pause`, root runs `pullgate status NAME --resume`.
 
diff --git a/README.md b/README.md
index 1b16946..74a577d 100644
--- a/README.md
+++ b/README.md
@@ -195,8 +195,7 @@ usual Apply question, or "No new commit (the applied commit is …)", or
 
 - `/status` (all instances) or `/status NAME`: the mode, the applied
   commit, the last tip, the open question, paused or not and why, broken
-  or not. It changes nothing and fetches nothing. At most one answer per
-  instance a minute.
+  or not. It changes nothing. At most one answer per instance a minute.
 - `/pause NAME`: pauses the instance. Nothing is fetched, asked or applied
   until root runs `pullgate status NAME --resume` on the host. If it is
   paused already, the old pause stays as it is. A reason after NAME is not
diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md
index 4b7d00f..bdd766b 100644
--- a/THREAT-MODEL.md
+++ b/THREAT-MODEL.md
@@ -489,11 +489,14 @@ reads its own state and acts. So the most they can do:
 
 - **See a status**: the mode, the SHAs, the open question, the pause and
   broken reasons. With the token they can read the questions anyway, which
-  show more. The status holds no key, token or IP address. Root answers at
-  most once a minute.
+  show more. The status holds no key or token. It shows the error texts
+  that were sent in notices already (the broken reason), and nothing new.
+  Root answers at most once a minute, and a `/status` never skips the
+  normal run, so a stream of them cannot stop the fetches.
 - **Pause an instance.** This only stops work: it never applies or
   approves anything. A thief can deny work in other ways already (not
-  deliver a tap). Root never changes a pause file that is there, so a
+  deliver a tap). Root never changes a pause file that is there (it makes
+  the file with a hard link, which fails if the name exists), so a
   `/pause` cannot replace the reason of a safety pause, and a later
   limited `/resume` (code6x/pullgate#33) cannot use it to lift one.
 
diff --git a/contrib/systemd/pullgate-check@.path b/contrib/systemd/pullgate-check@.path
index cf6567e..ff586d5 100644
--- a/contrib/systemd/pullgate-check@.path
+++ b/contrib/systemd/pullgate-check@.path
@@ -1,14 +1,16 @@
 # Starts pullgate-run@NAME.service when the listener writes a check request
-# for /check on Telegram (DESIGN.md section 8). The run is the normal run:
+# for /check, /status or /pause on Telegram (DESIGN.md sections 8 and 9). The run is the normal run:
 # the same unit, sandbox and lock. Root removes the request and allows at
 # most one requested run per minute.
 [Unit]
 Description=pullgate check requests for %i
 
 [Path]
-# Only the request file counts, so another file in the directory does not
+# Only the request files count, so another file in the directory does not
 # start runs again and again.
 PathExists=/var/spool/pullgate/%i/check/request
+PathExists=/var/spool/pullgate/%i/check/status
+PathExists=/var/spool/pullgate/%i/check/pause
 Unit=pullgate-run@%i.service
 # At most 10 starts a minute. This stops a loop when a run fails before it
 # removes the request. The listener writes at most one request per instance
diff --git a/internal/gate/check.go b/internal/gate/check.go
index c95c43e..1e84e08 100644
--- a/internal/gate/check.go
+++ b/internal/gate/check.go
@@ -39,12 +39,14 @@ func (e *Env) takeChecks() spool.Requests {
 func (e *Env) pauseRequest(st *state.State) {
 	now := e.now()
 	var text string
-	if e.Dir.Paused() {
-		text = "⏸ " + e.Cfg.Name + " was paused already: " + message.Code(e.Dir.PauseReason())
-	} else if err := e.Dir.Pause(state.TelegramPause + now.UTC().Format("2006-01-02 15:04 MST")); err != nil {
+	wrote, err := e.Dir.PauseIfNone(state.TelegramPause + now.UTC().Format("2006-01-02 15:04 MST"))
+	switch {
+	case err != nil:
 		e.Log.Error("write the pause file", "err", err)
 		text = "Error: " + e.Cfg.Name + " could not be paused. See the journal of the host."
-	} else {
+	case !wrote:
+		text = "⏸ " + e.Cfg.Name + " was paused already: " + message.Code(e.Dir.PauseReason())
+	default:
 		e.Log.Info("paused from Telegram")
 		text = "⏸ " + e.Cfg.Name + " is paused. Nothing is fetched, asked or applied. To go on, run as root: pullgate status " + e.Cfg.Name + " --resume"
 	}
diff --git a/internal/gate/request_test.go b/internal/gate/request_test.go
index 723ea75..c852328 100644
--- a/internal/gate/request_test.go
+++ b/internal/gate/request_test.go
@@ -24,18 +24,17 @@ func (f *fixture) requestKind(kind string) {
 func TestStatusRequest(t *testing.T) {
 	f := newFixture(t, ``, "")
 	a := f.applyNew("one")
-	f.commit("second", "two", nil) // not fetched: /status does not fetch
+	f.commit("second", "two", nil)
 	f.requestKind(spool.RequestStatus)
-	if r := f.run(); r != Nothing {
+	// /status never skips the normal run: a stream of them cannot stop
+	// fetches.
+	if r := f.run(); r != Asked {
 		t.Fatalf("run: %s", r)
 	}
 	ms := f.outbox()
-	if len(ms) != 1 || ms[0].Kind != spool.KindNotice || !strings.Contains(ms[0].Text, "applied:") ||
-		!strings.Contains(ms[0].Text, a) || !strings.Contains(ms[0].Text, "paused:      no") {
-		t.Fatalf("status notice: %+v", ms)
-	}
-	if f.state().LastTip != a {
-		t.Fatal("/status must not fetch")
+	if len(ms) != 2 || ms[0].Kind != spool.KindNotice || !strings.Contains(ms[0].Text, "applied:") ||
+		!strings.Contains(ms[0].Text, a) || !strings.Contains(ms[0].Text, "paused:      no") || ms[1].Kind != spool.KindAsk {
+		t.Fatalf("status notice, then the question: %+v", ms)
 	}
 	// A second one within a minute is dropped.
 	f.requestKind(spool.RequestStatus)
diff --git a/internal/gate/run.go b/internal/gate/run.go
index 3fec40d..c616840 100644
--- a/internal/gate/run.go
+++ b/internal/gate/run.go
@@ -164,10 +164,8 @@ func (e *Env) Run(ctx context.Context) (Result, error) {
 	if requests.Status > 0 {
 		e.statusRequest(st)
 	}
-	if (requests.Pause > 0 || requests.Status > 0) && requests.Check == 0 {
-		// Only /status or /pause: they do not fetch.
-		return Nothing, e.Dir.Save(st)
-	}
+	// Then the normal run goes on: /status never skips a fetch, and after
+	// /pause the paused check below ends the run.
 	requested := requests.Check > 0
 	if requested {
 		if r := e.limitCheck(st); r != "" {
diff --git a/internal/listener/listener.go b/internal/listener/listener.go
index dca4364..1f29422 100644
--- a/internal/listener/listener.go
+++ b/internal/listener/listener.go
@@ -435,6 +435,10 @@ const (
 	pauseCommand  = "/pause"
 )
 
+// RequestGap is the least time between two /status or two /pause for the
+// same instance: root answers each at most once a minute.
+const RequestGap = time.Minute
+
 func firstWord(s string) string {
 	if f := strings.Fields(s); len(f) > 0 {
 		return f[0]
@@ -468,7 +472,8 @@ func (l *Listener) request(ctx context.Context, m *telegram.Message, kind string
 	var ok, soon, failed []string
 	for _, n := range names {
 		key := kind + ":" + n
-		if d := now.Sub(l.lastCheck[key]); d < CheckGap && d > -CheckGap {
+		// Root answers each at most once a minute; so does the listener.
+		if d := now.Sub(l.lastCheck[key]); d < RequestGap && d > -RequestGap {
 			soon = append(soon, n)
 			continue
 		}
diff --git a/internal/state/state.go b/internal/state/state.go
index 19528ef..a9e2420 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -221,6 +221,38 @@ func (d Dir) Pause(reason string) error {
 	return WriteFileAtomic(d.PauseFile(), []byte(reason+"\n"), 0o644)
 }
 
+// PauseIfNone writes the pause file only if there is none. It never
+// replaces one, even one that appears at the same time (a hard link
+// fails when the name exists). It reports whether it wrote it.
+func (d Dir) PauseIfNone(reason string) (bool, error) {
+	f, err := os.CreateTemp(filepath.Dir(d.PauseFile()), ".tmp-")
+	if err != nil {
+		return false, err
+	}
+	tmp := f.Name()
+	defer func() { _ = os.Remove(tmp) }()
+	_, werr := f.WriteString(reason + "\n")
+	if werr == nil {
+		werr = f.Chmod(0o644)
+	}
+	if werr == nil {
+		werr = f.Sync()
+	}
+	if cerr := f.Close(); werr == nil {
+		werr = cerr
+	}
+	if werr != nil {
+		return false, werr
+	}
+	if err := os.Link(tmp, d.PauseFile()); err != nil {
+		if errors.Is(err, fs.ErrExist) {
+			return false, nil
+		}
+		return false, err
+	}
+	return true, nil
+}
+
 // TelegramPause starts the reason of a pause that came from /pause
 // (code6x/pullgate#32). No other reason starts with it.
 const TelegramPause = "paused from Telegram at "