realmwatch.gno
12.59 Kb · 415 lines
1// RealmWatch — the on-chain leash for an autonomous agent.
2//
3// An off-chain agent watches things and posts alerts. This realm is
4// its public control and audit layer:
5//
6// - a registry of what the agent is allowed to watch,
7// - an append-only log of everything the agent did,
8// - a STOP flag and a per-epoch action cap that the REALM enforces.
9//
10// The point: the cap and the kill switch do not live in the agent's
11// code, where a bug (or a prompt injection) could talk the agent out
12// of them. They live here, in the chain's state. A PostAlert that
13// arrives while STOP is set, or after the epoch cap is spent,
14// reverts. The agent cannot sweet-talk a smart contract.
15//
16// Trust model:
17// - The owner (deployer) configures: agent address, watches, cap,
18// STOP. Only the owner can change configuration.
19// - The registered agent address — and only it — can append log
20// entries, and only within the cap and only while not stopped.
21// - The agent may trip STOP itself (self-arrest), but only the
22// owner can clear it.
23// - All privileged entry points require a direct user call
24// (maketx call from the EOA), never a realm-to-realm call, so
25// caller identity cannot be laundered through another contract.
26package realmwatch
27
28import (
29 "chain/runtime"
30 "chain/runtime/unsafe"
31 "strconv"
32 "strings"
33)
34
35// ----------------------------------------------------------------
36// Types
37// ----------------------------------------------------------------
38
39// Watch is one registered monitoring target.
40type Watch struct {
41 ID string // unique, owner-chosen, e.g. "tavern-board"
42 Kind string // "realm" | "balance" | "height"
43 Target string // realm path, g1 address, or "" for height
44 Note string // human note: why this is watched
45 Active bool
46}
47
48// Entry is one append-only log record. Entries are never edited or
49// deleted; Seq is monotone for the life of the realm.
50type Entry struct {
51 Seq uint64
52 Height int64
53 Kind string // "BASELINE" | "CHANGE" | "HEARTBEAT" | "NOTE"
54 Severity string // "INFO" | "WARN" | "CRIT"
55 WatchID string // watch this entry belongs to ("" = system)
56 Summary string // one line, agent-written, human-readable
57}
58
59// ----------------------------------------------------------------
60// State
61// ----------------------------------------------------------------
62
63var (
64 // owner is the package deployer, captured at deploy time from
65 // the transaction origin (see init). If the capture is empty
66 // (e.g. in unit tests), ownership is claimed explicitly via
67 // ClaimOwnership as the first configuration call.
68 owner address
69 agent address
70 stopped = true // STOPPED at birth: the owner must explicitly arm it.
71
72 // Action cap: at most capPerEpoch successful PostAlert calls in
73 // any window of epochLen blocks. epochStart is the block height
74 // the current window began at (0 = not started yet); epochUsed
75 // counts posts in the current window.
76 capPerEpoch uint64 = 12
77 epochLen int64 = 100 // blocks per epoch window
78 epochStart int64
79 epochUsed uint64
80 watchList []*Watch
81 entries []Entry
82 seq uint64
83 maxSummaryLn = 280 // one line, tweet-sized; keeps the log readable
84)
85
86func init() {
87 if o := unsafe.OriginCaller(); o != address("") {
88 owner = o
89 }
90}
91
92// ClaimOwnership sets the owner when the deploy-time capture was
93// empty. It can only ever succeed once, and only while no owner is
94// set; the deployer calls it immediately after addpkg.
95func ClaimOwnership(cur realm) {
96 if owner != address("") {
97 panic("realmwatch: ownership already claimed")
98 }
99 owner = callerOf(cur)
100}
101
102// ----------------------------------------------------------------
103// Guards
104// ----------------------------------------------------------------
105
106// callerOf returns the direct EOA caller of an exported function.
107// It panics unless the call is a direct user call (maketx call), so
108// identity always comes from the transaction signer, never from an
109// intermediate realm.
110func callerOf(cur realm) address {
111 if !cur.Previous().IsUserCall() {
112 panic("realmwatch: direct user calls only")
113 }
114 return cur.Previous().Address()
115}
116
117func assertOwner(cur realm) {
118 if callerOf(cur) != owner {
119 panic("realmwatch: owner only")
120 }
121}
122
123func assertAgent(cur realm) {
124 if agent == address("") {
125 panic("realmwatch: no agent registered")
126 }
127 if callerOf(cur) != agent {
128 panic("realmwatch: agent only")
129 }
130}
131
132// rollEpoch advances the cap window if the current one has expired.
133// Called before every gated action.
134func rollEpoch() {
135 h := runtime.ChainHeight()
136 if epochStart == 0 {
137 epochStart = h
138 return
139 }
140 if epochLen > 0 && h >= epochStart+epochLen {
141 windows := (h - epochStart) / epochLen
142 epochStart += windows * epochLen
143 epochUsed = 0
144 }
145}
146
147// remaining computes the actions left in the current window without
148// mutating state (safe for view calls).
149func remaining() uint64 {
150 if epochStart != 0 && epochLen > 0 {
151 h := runtime.ChainHeight()
152 if h >= epochStart+epochLen {
153 return capPerEpoch // window already expired: full cap
154 }
155 }
156 if epochUsed >= capPerEpoch {
157 return 0
158 }
159 return capPerEpoch - epochUsed
160}
161
162func findWatch(id string) *Watch {
163 for _, w := range watchList {
164 if w.ID == id {
165 return w
166 }
167 }
168 return nil
169}
170
171func validKind(k string) bool {
172 return k == "realm" || k == "balance" || k == "height"
173}
174
175func validEntryKind(k string) bool {
176 return k == "BASELINE" || k == "CHANGE" || k == "HEARTBEAT" || k == "NOTE"
177}
178
179func validSeverity(s string) bool {
180 return s == "INFO" || s == "WARN" || s == "CRIT"
181}
182
183// ----------------------------------------------------------------
184// Owner configuration
185// ----------------------------------------------------------------
186
187// SetAgent registers (or replaces) the agent address allowed to post.
188func SetAgent(cur realm, addr address) {
189 assertOwner(cur)
190 agent = addr
191}
192
193// AddWatch registers a new watch target. Owner only.
194func AddWatch(cur realm, id string, kind string, target string, note string) {
195 assertOwner(cur)
196 if id == "" {
197 panic("realmwatch: watch id required")
198 }
199 if !validKind(kind) {
200 panic("realmwatch: kind must be realm|balance|height")
201 }
202 if kind != "height" && target == "" {
203 panic("realmwatch: target required for this kind")
204 }
205 if findWatch(id) != nil {
206 panic("realmwatch: watch id already exists")
207 }
208 watchList = append(watchList, &Watch{
209 ID: id, Kind: kind, Target: target, Note: note, Active: true,
210 })
211}
212
213// SetWatchActive pauses or resumes a single watch without deleting
214// it. A paused watch rejects agent posts. Owner only.
215func SetWatchActive(cur realm, id string, active bool) {
216 assertOwner(cur)
217 w := findWatch(id)
218 if w == nil {
219 panic("realmwatch: no such watch")
220 }
221 w.Active = active
222}
223
224// SetCap sets the per-epoch action cap and the epoch length in
225// blocks. Changing the cap restarts the current window. Owner only.
226func SetCap(cur realm, cap uint64, epochLenBlocks int64) {
227 assertOwner(cur)
228 if epochLenBlocks <= 0 {
229 panic("realmwatch: epoch length must be positive")
230 }
231 capPerEpoch = cap
232 epochLen = epochLenBlocks
233 epochStart = runtime.ChainHeight()
234 epochUsed = 0
235}
236
237// SetStopped is the kill switch. Owner only. While stopped, every
238// agent post reverts on-chain.
239func SetStopped(cur realm, stop bool) {
240 assertOwner(cur)
241 stopped = stop
242}
243
244// TripStop lets the agent arrest itself: if the agent concludes it
245// is compromised or confused, it can halt itself without waiting for
246// the owner. Only the owner can clear the stop afterwards.
247func TripStop(cur realm) {
248 caller := callerOf(cur)
249 if caller != owner && caller != agent {
250 panic("realmwatch: owner or agent only")
251 }
252 stopped = true
253}
254
255// ----------------------------------------------------------------
256// The agent's one action
257// ----------------------------------------------------------------
258
259// PostAlert appends one entry to the log. This is the agent's ONLY
260// write action, and the realm gates it four ways:
261//
262// 1. caller must be the registered agent, calling directly,
263// 2. STOP must be clear,
264// 3. the named watch must exist and be active,
265// 4. the per-epoch cap must not be exhausted.
266//
267// Any violation panics, the transaction reverts, and nothing is
268// written. Returns the sequence number of the new entry.
269func PostAlert(cur realm, kind string, severity string, watchID string, summary string) string {
270 assertAgent(cur)
271 if stopped {
272 panic("realmwatch: STOP is set — agent is halted")
273 }
274 if !validEntryKind(kind) {
275 panic("realmwatch: bad entry kind")
276 }
277 if !validSeverity(severity) {
278 panic("realmwatch: bad severity")
279 }
280 if len(summary) == 0 || len(summary) > maxSummaryLn {
281 panic("realmwatch: summary must be 1..280 chars")
282 }
283 if strings.Contains(summary, "\n") {
284 panic("realmwatch: summary must be one line")
285 }
286 if watchID != "" {
287 w := findWatch(watchID)
288 if w == nil {
289 panic("realmwatch: no such watch")
290 }
291 if !w.Active {
292 panic("realmwatch: watch is paused")
293 }
294 }
295 rollEpoch()
296 if epochUsed >= capPerEpoch {
297 panic("realmwatch: epoch action cap exhausted")
298 }
299 epochUsed++
300 seq++
301 entries = append(entries, Entry{
302 Seq: seq,
303 Height: runtime.ChainHeight(),
304 Kind: kind,
305 Severity: severity,
306 WatchID: watchID,
307 Summary: summary,
308 })
309 return strconv.FormatUint(seq, 10)
310}
311
312// ----------------------------------------------------------------
313// Views (read-only; safe for qeval / Render)
314// ----------------------------------------------------------------
315
316func Owner() string { return string(owner) }
317func Agent() string { return string(agent) }
318func IsStopped() bool { return stopped }
319func CapPerEpoch() uint64 { return capPerEpoch }
320func EpochUsed() uint64 { return epochUsed }
321func RemainingActions() uint64 { return remaining() }
322func WatchCount() int { return len(watchList) }
323func LogCount() uint64 { return seq }
324
325// WatchIDs returns the registered watch ids, comma-separated, in
326// registration order (active and paused).
327func WatchIDs() string {
328 ids := make([]string, 0, len(watchList))
329 for _, w := range watchList {
330 ids = append(ids, w.ID)
331 }
332 return strings.Join(ids, ",")
333}
334
335// WatchTarget returns "kind|target|active" for one watch, or "".
336func WatchTarget(id string) string {
337 w := findWatch(id)
338 if w == nil {
339 return ""
340 }
341 active := "0"
342 if w.Active {
343 active = "1"
344 }
345 return w.Kind + "|" + w.Target + "|" + active
346}
347
348// EntryAt returns one log entry as
349// "seq|height|kind|severity|watchID|summary", or "" if out of range.
350// seqNo is 1-based, matching Entry.Seq.
351func EntryAt(seqNo uint64) string {
352 if seqNo == 0 || seqNo > uint64(len(entries)) {
353 return ""
354 }
355 e := entries[seqNo-1]
356 return strconv.FormatUint(e.Seq, 10) + "|" +
357 strconv.FormatInt(e.Height, 10) + "|" +
358 e.Kind + "|" + e.Severity + "|" + e.WatchID + "|" + e.Summary
359}
360
361// ----------------------------------------------------------------
362// Render (gnoweb)
363// ----------------------------------------------------------------
364
365func Render(path string) string {
366 var b strings.Builder
367 b.WriteString("# RealmWatch\n\n")
368 if stopped {
369 b.WriteString("**STATUS: STOPPED** — the agent is halted. No posts are accepted.\n\n")
370 } else {
371 b.WriteString("**STATUS: RUNNING** — the agent may post within its cap.\n\n")
372 }
373 b.WriteString("- Owner: `" + string(owner) + "`\n")
374 b.WriteString("- Agent: `" + string(agent) + "`\n")
375 b.WriteString("- Action cap: " + strconv.FormatUint(capPerEpoch, 10) +
376 " actions per epoch\n\n")
377
378 b.WriteString("## Watches\n\n")
379 if len(watchList) == 0 {
380 b.WriteString("(none registered)\n\n")
381 }
382 for _, w := range watchList {
383 state := "active"
384 if !w.Active {
385 state = "paused"
386 }
387 b.WriteString("- `" + w.ID + "` (" + w.Kind + ", " + state + ") — `" +
388 w.Target + "` — " + w.Note + "\n")
389 }
390
391 b.WriteString("\n## Latest log entries\n\n")
392 if len(entries) == 0 {
393 b.WriteString("(empty — the agent has not posted yet)\n")
394 }
395 start := 0
396 if len(entries) > 10 {
397 start = len(entries) - 10
398 }
399 for _, e := range entries[start:] {
400 b.WriteString("- #" + strconv.FormatUint(e.Seq, 10) +
401 " [" + e.Severity + "/" + e.Kind + "] watch `" + e.WatchID +
402 "` @ block " + strconv.FormatInt(e.Height, 10) + " — " + e.Summary + "\n")
403 }
404 // Volatile counters live BELOW the log section on purpose:
405 // config watchers fingerprint everything above the log tail,
406 // and these numbers change with every post — they are not
407 // configuration and must not retrigger the config watch.
408 b.WriteString("\n## Live counters\n\n")
409 b.WriteString("- Actions used this epoch: " + strconv.FormatUint(epochUsed, 10) +
410 " / " + strconv.FormatUint(capPerEpoch, 10) +
411 ", " + strconv.FormatUint(remaining(), 10) + " remaining\n")
412 b.WriteString("- Log entries: " + strconv.FormatUint(seq, 10) + "\n")
413 b.WriteString("\n---\nRealmWatch: don't trust the agent. Read its leash.\n")
414 return b.String()
415}