Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g15gz99k0zsv59wgvyv5ulxzv5f2dkyzvh0zhaga/realmwatch"
gno = "0.9"

[addpkg]
  creator = "g15gz99k0zsv59wgvyv5ulxzv5f2dkyzvh0zhaga"
  height = 1502295
  max_deposit = "100000000ugnot"

realmwatch.gno

// RealmWatch — the on-chain leash for an autonomous agent.
//
// An off-chain agent watches things and posts alerts. This realm is
// its public control and audit layer:
//
//   - a registry of what the agent is allowed to watch,
//   - an append-only log of everything the agent did,
//   - a STOP flag and a per-epoch action cap that the REALM enforces.
//
// The point: the cap and the kill switch do not live in the agent's
// code, where a bug (or a prompt injection) could talk the agent out
// of them. They live here, in the chain's state. A PostAlert that
// arrives while STOP is set, or after the epoch cap is spent,
// reverts. The agent cannot sweet-talk a smart contract.
//
// Trust model:
//   - The owner (deployer) configures: agent address, watches, cap,
//     STOP. Only the owner can change configuration.
//   - The registered agent address — and only it — can append log
//     entries, and only within the cap and only while not stopped.
//   - The agent may trip STOP itself (self-arrest), but only the
//     owner can clear it.
//   - All privileged entry points require a direct user call
//     (maketx call from the EOA), never a realm-to-realm call, so
//     caller identity cannot be laundered through another contract.
package realmwatch

import (
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"
)

// ----------------------------------------------------------------
// Types
// ----------------------------------------------------------------

// Watch is one registered monitoring target.
type Watch struct {
	ID     string // unique, owner-chosen, e.g. "tavern-board"
	Kind   string // "realm" | "balance" | "height"
	Target string // realm path, g1 address, or "" for height
	Note   string // human note: why this is watched
	Active bool
}

// Entry is one append-only log record. Entries are never edited or
// deleted; Seq is monotone for the life of the realm.
type Entry struct {
	Seq      uint64
	Height   int64
	Kind     string // "BASELINE" | "CHANGE" | "HEARTBEAT" | "NOTE"
	Severity string // "INFO" | "WARN" | "CRIT"
	WatchID  string // watch this entry belongs to ("" = system)
	Summary  string // one line, agent-written, human-readable
}

// ----------------------------------------------------------------
// State
// ----------------------------------------------------------------

var (
	// owner is the package deployer, captured at deploy time from
	// the transaction origin (see init). If the capture is empty
	// (e.g. in unit tests), ownership is claimed explicitly via
	// ClaimOwnership as the first configuration call.
	owner   address
	agent   address
	stopped = true // STOPPED at birth: the owner must explicitly arm it.

	// Action cap: at most capPerEpoch successful PostAlert calls in
	// any window of epochLen blocks. epochStart is the block height
	// the current window began at (0 = not started yet); epochUsed
	// counts posts in the current window.
	capPerEpoch  uint64 = 12
	epochLen     int64  = 100 // blocks per epoch window
	epochStart   int64
	epochUsed    uint64
	watchList    []*Watch
	entries      []Entry
	seq          uint64
	maxSummaryLn = 280 // one line, tweet-sized; keeps the log readable
)

func init() {
	if o := unsafe.OriginCaller(); o != address("") {
		owner = o
	}
}

// ClaimOwnership sets the owner when the deploy-time capture was
// empty. It can only ever succeed once, and only while no owner is
// set; the deployer calls it immediately after addpkg.
func ClaimOwnership(cur realm) {
	if owner != address("") {
		panic("realmwatch: ownership already claimed")
	}
	owner = callerOf(cur)
}

// ----------------------------------------------------------------
// Guards
// ----------------------------------------------------------------

// callerOf returns the direct EOA caller of an exported function.
// It panics unless the call is a direct user call (maketx call), so
// identity always comes from the transaction signer, never from an
// intermediate realm.
func callerOf(cur realm) address {
	if !cur.Previous().IsUserCall() {
		panic("realmwatch: direct user calls only")
	}
	return cur.Previous().Address()
}

func assertOwner(cur realm) {
	if callerOf(cur) != owner {
		panic("realmwatch: owner only")
	}
}

func assertAgent(cur realm) {
	if agent == address("") {
		panic("realmwatch: no agent registered")
	}
	if callerOf(cur) != agent {
		panic("realmwatch: agent only")
	}
}

// rollEpoch advances the cap window if the current one has expired.
// Called before every gated action.
func rollEpoch() {
	h := runtime.ChainHeight()
	if epochStart == 0 {
		epochStart = h
		return
	}
	if epochLen > 0 && h >= epochStart+epochLen {
		windows := (h - epochStart) / epochLen
		epochStart += windows * epochLen
		epochUsed = 0
	}
}

// remaining computes the actions left in the current window without
// mutating state (safe for view calls).
func remaining() uint64 {
	if epochStart != 0 && epochLen > 0 {
		h := runtime.ChainHeight()
		if h >= epochStart+epochLen {
			return capPerEpoch // window already expired: full cap
		}
	}
	if epochUsed >= capPerEpoch {
		return 0
	}
	return capPerEpoch - epochUsed
}

func findWatch(id string) *Watch {
	for _, w := range watchList {
		if w.ID == id {
			return w
		}
	}
	return nil
}

func validKind(k string) bool {
	return k == "realm" || k == "balance" || k == "height"
}

func validEntryKind(k string) bool {
	return k == "BASELINE" || k == "CHANGE" || k == "HEARTBEAT" || k == "NOTE"
}

func validSeverity(s string) bool {
	return s == "INFO" || s == "WARN" || s == "CRIT"
}

// ----------------------------------------------------------------
// Owner configuration
// ----------------------------------------------------------------

// SetAgent registers (or replaces) the agent address allowed to post.
func SetAgent(cur realm, addr address) {
	assertOwner(cur)
	agent = addr
}

// AddWatch registers a new watch target. Owner only.
func AddWatch(cur realm, id string, kind string, target string, note string) {
	assertOwner(cur)
	if id == "" {
		panic("realmwatch: watch id required")
	}
	if !validKind(kind) {
		panic("realmwatch: kind must be realm|balance|height")
	}
	if kind != "height" && target == "" {
		panic("realmwatch: target required for this kind")
	}
	if findWatch(id) != nil {
		panic("realmwatch: watch id already exists")
	}
	watchList = append(watchList, &Watch{
		ID: id, Kind: kind, Target: target, Note: note, Active: true,
	})
}

// SetWatchActive pauses or resumes a single watch without deleting
// it. A paused watch rejects agent posts. Owner only.
func SetWatchActive(cur realm, id string, active bool) {
	assertOwner(cur)
	w := findWatch(id)
	if w == nil {
		panic("realmwatch: no such watch")
	}
	w.Active = active
}

// SetCap sets the per-epoch action cap and the epoch length in
// blocks. Changing the cap restarts the current window. Owner only.
func SetCap(cur realm, cap uint64, epochLenBlocks int64) {
	assertOwner(cur)
	if epochLenBlocks <= 0 {
		panic("realmwatch: epoch length must be positive")
	}
	capPerEpoch = cap
	epochLen = epochLenBlocks
	epochStart = runtime.ChainHeight()
	epochUsed = 0
}

// SetStopped is the kill switch. Owner only. While stopped, every
// agent post reverts on-chain.
func SetStopped(cur realm, stop bool) {
	assertOwner(cur)
	stopped = stop
}

// TripStop lets the agent arrest itself: if the agent concludes it
// is compromised or confused, it can halt itself without waiting for
// the owner. Only the owner can clear the stop afterwards.
func TripStop(cur realm) {
	caller := callerOf(cur)
	if caller != owner && caller != agent {
		panic("realmwatch: owner or agent only")
	}
	stopped = true
}

// ----------------------------------------------------------------
// The agent's one action
// ----------------------------------------------------------------

// PostAlert appends one entry to the log. This is the agent's ONLY
// write action, and the realm gates it four ways:
//
//  1. caller must be the registered agent, calling directly,
//  2. STOP must be clear,
//  3. the named watch must exist and be active,
//  4. the per-epoch cap must not be exhausted.
//
// Any violation panics, the transaction reverts, and nothing is
// written. Returns the sequence number of the new entry.
func PostAlert(cur realm, kind string, severity string, watchID string, summary string) string {
	assertAgent(cur)
	if stopped {
		panic("realmwatch: STOP is set — agent is halted")
	}
	if !validEntryKind(kind) {
		panic("realmwatch: bad entry kind")
	}
	if !validSeverity(severity) {
		panic("realmwatch: bad severity")
	}
	if len(summary) == 0 || len(summary) > maxSummaryLn {
		panic("realmwatch: summary must be 1..280 chars")
	}
	if strings.Contains(summary, "\n") {
		panic("realmwatch: summary must be one line")
	}
	if watchID != "" {
		w := findWatch(watchID)
		if w == nil {
			panic("realmwatch: no such watch")
		}
		if !w.Active {
			panic("realmwatch: watch is paused")
		}
	}
	rollEpoch()
	if epochUsed >= capPerEpoch {
		panic("realmwatch: epoch action cap exhausted")
	}
	epochUsed++
	seq++
	entries = append(entries, Entry{
		Seq:      seq,
		Height:   runtime.ChainHeight(),
		Kind:     kind,
		Severity: severity,
		WatchID:  watchID,
		Summary:  summary,
	})
	return strconv.FormatUint(seq, 10)
}

// ----------------------------------------------------------------
// Views (read-only; safe for qeval / Render)
// ----------------------------------------------------------------

func Owner() string            { return string(owner) }
func Agent() string            { return string(agent) }
func IsStopped() bool          { return stopped }
func CapPerEpoch() uint64      { return capPerEpoch }
func EpochUsed() uint64        { return epochUsed }
func RemainingActions() uint64 { return remaining() }
func WatchCount() int          { return len(watchList) }
func LogCount() uint64         { return seq }

// WatchIDs returns the registered watch ids, comma-separated, in
// registration order (active and paused).
func WatchIDs() string {
	ids := make([]string, 0, len(watchList))
	for _, w := range watchList {
		ids = append(ids, w.ID)
	}
	return strings.Join(ids, ",")
}

// WatchTarget returns "kind|target|active" for one watch, or "".
func WatchTarget(id string) string {
	w := findWatch(id)
	if w == nil {
		return ""
	}
	active := "0"
	if w.Active {
		active = "1"
	}
	return w.Kind + "|" + w.Target + "|" + active
}

// EntryAt returns one log entry as
// "seq|height|kind|severity|watchID|summary", or "" if out of range.
// seqNo is 1-based, matching Entry.Seq.
func EntryAt(seqNo uint64) string {
	if seqNo == 0 || seqNo > uint64(len(entries)) {
		return ""
	}
	e := entries[seqNo-1]
	return strconv.FormatUint(e.Seq, 10) + "|" +
		strconv.FormatInt(e.Height, 10) + "|" +
		e.Kind + "|" + e.Severity + "|" + e.WatchID + "|" + e.Summary
}

// ----------------------------------------------------------------
// Render (gnoweb)
// ----------------------------------------------------------------

func Render(path string) string {
	var b strings.Builder
	b.WriteString("# RealmWatch\n\n")
	if stopped {
		b.WriteString("**STATUS: STOPPED** — the agent is halted. No posts are accepted.\n\n")
	} else {
		b.WriteString("**STATUS: RUNNING** — the agent may post within its cap.\n\n")
	}
	b.WriteString("- Owner: `" + string(owner) + "`\n")
	b.WriteString("- Agent: `" + string(agent) + "`\n")
	b.WriteString("- Action cap: " + strconv.FormatUint(capPerEpoch, 10) +
		" actions per epoch\n\n")

	b.WriteString("## Watches\n\n")
	if len(watchList) == 0 {
		b.WriteString("(none registered)\n\n")
	}
	for _, w := range watchList {
		state := "active"
		if !w.Active {
			state = "paused"
		}
		b.WriteString("- `" + w.ID + "` (" + w.Kind + ", " + state + ") — `" +
			w.Target + "` — " + w.Note + "\n")
	}

	b.WriteString("\n## Latest log entries\n\n")
	if len(entries) == 0 {
		b.WriteString("(empty — the agent has not posted yet)\n")
	}
	start := 0
	if len(entries) > 10 {
		start = len(entries) - 10
	}
	for _, e := range entries[start:] {
		b.WriteString("- #" + strconv.FormatUint(e.Seq, 10) +
			" [" + e.Severity + "/" + e.Kind + "] watch `" + e.WatchID +
			"` @ block " + strconv.FormatInt(e.Height, 10) + " — " + e.Summary + "\n")
	}
	// Volatile counters live BELOW the log section on purpose:
	// config watchers fingerprint everything above the log tail,
	// and these numbers change with every post — they are not
	// configuration and must not retrigger the config watch.
	b.WriteString("\n## Live counters\n\n")
	b.WriteString("- Actions used this epoch: " + strconv.FormatUint(epochUsed, 10) +
		" / " + strconv.FormatUint(capPerEpoch, 10) +
		", " + strconv.FormatUint(remaining(), 10) + " remaining\n")
	b.WriteString("- Log entries: " + strconv.FormatUint(seq, 10) + "\n")
	b.WriteString("\n---\nRealmWatch: don't trust the agent. Read its leash.\n")
	return b.String()
}

realmwatch_test.gno

package realmwatch

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/urequire/v0"
)

// Test actors. In the test harness the deploy-time origin capture
// is empty, so the test owner claims ownership explicitly in the
// first test (the same path a deployer would use if the capture
// ever came back empty on-chain).
var (
	ownerTestAddr = testutils.TestAddress("rw-owner")
	agentAddr     = testutils.TestAddress("rw-agent")
	randoAddr     = testutils.TestAddress("rw-rando")
)

// NOTE: testing.SetRealm is frame-scoped — it must be called
// directly in the test body, not via a helper, or it is lost when
// the helper returns. Hence the longhand SetRealm calls below.

// Ownership is claimable exactly once, by whoever calls first while
// it is unclaimed; afterwards the claim path is closed forever.
func TestClaimOwnership(cur realm, t *testing.T) {
	urequire.Equal(t, Owner(), "")
	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	ClaimOwnership(cross(cur))
	urequire.Equal(t, Owner(), string(ownerTestAddr))

	testing.SetRealm(testing.NewUserRealm(randoAddr))
	urequire.AbortsContains(t, cur, "already claimed", func() {
		ClaimOwnership(cross(cur))
	})
}

// The realm is born STOPPED: before the owner arms it, even a
// correctly registered agent cannot post.
func TestBornStopped(cur realm, t *testing.T) {
	urequire.True(t, IsStopped(), "realm must be born stopped")
	urequire.Equal(t, LogCount(), uint64(0))

	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	SetAgent(cross(cur), agentAddr)
	AddWatch(cross(cur), "w1", "realm", "gno.land/r/demo/counter", "demo counter realm")

	testing.SetRealm(testing.NewUserRealm(agentAddr))
	urequire.AbortsContains(t, cur, "STOP is set", func() {
		PostAlert(cross(cur), "BASELINE", "INFO", "w1", "baseline fp=abc")
	})
	urequire.Equal(t, LogCount(), uint64(0))
}

// Configuration is owner-only, and the owner is not the agent:
// holding the leash does not let you write the log.
func TestOwnerOnly(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(randoAddr))
	urequire.AbortsContains(t, cur, "owner only", func() {
		SetAgent(cross(cur), randoAddr)
	})
	urequire.AbortsContains(t, cur, "owner only", func() {
		SetStopped(cross(cur), false)
	})
	urequire.AbortsContains(t, cur, "owner only", func() {
		AddWatch(cross(cur), "evil", "realm", "gno.land/r/demo/counter", "x")
	})

	testing.SetRealm(testing.NewUserRealm(agentAddr))
	urequire.AbortsContains(t, cur, "owner only", func() {
		SetCap(cross(cur), 999, 100)
	})
}

// Happy path: owner arms the realm, the agent posts, the log and
// the cap accounting move exactly as specified.
func TestArmAndPost(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	SetStopped(cross(cur), false)
	urequire.False(t, IsStopped())

	before := RemainingActions()
	testing.SetRealm(testing.NewUserRealm(agentAddr))
	seqStr := PostAlert(cross(cur), "BASELINE", "INFO", "w1", "baseline fp=abc")
	urequire.Equal(t, seqStr, "1")
	urequire.Equal(t, LogCount(), uint64(1))
	urequire.Equal(t, RemainingActions(), before-1)

	entry := EntryAt(1)
	urequire.True(t, strings.Contains(entry, "|BASELINE|INFO|w1|baseline fp=abc"),
		"entry round-trip mismatch: "+entry)
	urequire.Equal(t, EntryAt(0), "")
	urequire.Equal(t, EntryAt(99), "")
	urequire.Equal(t, WatchTarget("w1"), "realm|gno.land/r/demo/counter|1")
	urequire.Equal(t, WatchIDs(), "w1")
}

// Only the registered agent may write — not a stranger, and not
// even the owner.
func TestAgentOnly(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(randoAddr))
	urequire.AbortsContains(t, cur, "agent only", func() {
		PostAlert(cross(cur), "NOTE", "INFO", "", "intrusion attempt")
	})
	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	urequire.AbortsContains(t, cur, "agent only", func() {
		PostAlert(cross(cur), "NOTE", "INFO", "", "owner self-post")
	})
	urequire.Equal(t, LogCount(), uint64(1))
}

// Malformed posts are rejected before anything is written.
func TestValidation(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(agentAddr))
	urequire.AbortsContains(t, cur, "bad entry kind", func() {
		PostAlert(cross(cur), "EXPLODE", "INFO", "w1", "boom")
	})
	urequire.AbortsContains(t, cur, "bad severity", func() {
		PostAlert(cross(cur), "NOTE", "MEH", "w1", "meh")
	})
	urequire.AbortsContains(t, cur, "one line", func() {
		PostAlert(cross(cur), "NOTE", "INFO", "w1", "two\nlines")
	})
	urequire.AbortsContains(t, cur, "no such watch", func() {
		PostAlert(cross(cur), "NOTE", "INFO", "ghost", "boo")
	})
	urequire.AbortsContains(t, cur, "1..280", func() {
		PostAlert(cross(cur), "NOTE", "INFO", "w1", "")
	})
	urequire.Equal(t, LogCount(), uint64(1))
}

// A paused watch rejects posts; a system entry (no watch) is fine.
func TestPausedWatch(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	AddWatch(cross(cur), "w2", "balance", string(randoAddr), "rando balance")
	SetWatchActive(cross(cur), "w2", false)
	urequire.Equal(t, WatchTarget("w2"), "balance|"+string(randoAddr)+"|0")

	testing.SetRealm(testing.NewUserRealm(agentAddr))
	urequire.AbortsContains(t, cur, "watch is paused", func() {
		PostAlert(cross(cur), "CHANGE", "WARN", "w2", "balance moved")
	})
	PostAlert(cross(cur), "NOTE", "INFO", "", "system note: watch w2 paused by owner")
	urequire.Equal(t, LogCount(), uint64(2))
}

// The cap is enforced by the realm: the (cap+1)-th post in an epoch
// reverts, and RemainingActions reads 0.
func TestCapExhaustion(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	SetCap(cross(cur), 2, 100000) // long epoch: no roll during the test
	urequire.Equal(t, RemainingActions(), uint64(2))

	testing.SetRealm(testing.NewUserRealm(agentAddr))
	PostAlert(cross(cur), "HEARTBEAT", "INFO", "", "hb 1")
	PostAlert(cross(cur), "HEARTBEAT", "INFO", "", "hb 2")
	urequire.Equal(t, RemainingActions(), uint64(0))
	urequire.AbortsContains(t, cur, "cap exhausted", func() {
		PostAlert(cross(cur), "HEARTBEAT", "INFO", "", "hb 3 — one too many")
	})

	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	SetCap(cross(cur), 12, 100) // restore defaults for later tests
	urequire.Equal(t, RemainingActions(), uint64(12))
}

// The agent can arrest itself; only the owner can release it.
func TestTripStop(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(agentAddr))
	TripStop(cross(cur))
	urequire.True(t, IsStopped())
	urequire.AbortsContains(t, cur, "STOP is set", func() {
		PostAlert(cross(cur), "NOTE", "INFO", "", "posting while arrested")
	})
	urequire.AbortsContains(t, cur, "owner only", func() {
		SetStopped(cross(cur), false)
	})

	testing.SetRealm(testing.NewUserRealm(randoAddr))
	urequire.AbortsContains(t, cur, "owner or agent only", func() {
		TripStop(cross(cur))
	})

	testing.SetRealm(testing.NewUserRealm(ownerTestAddr))
	SetStopped(cross(cur), false)
	urequire.False(t, IsStopped())
	testing.SetRealm(testing.NewUserRealm(agentAddr))
	PostAlert(cross(cur), "NOTE", "INFO", "", "released by owner; resuming")
}

// Render shows the leash state to any human with a browser.
func TestRender(cur realm, t *testing.T) {
	out := Render("")
	urequire.True(t, strings.Contains(out, "STATUS: RUNNING"))
	urequire.True(t, strings.Contains(out, "## Watches"))
	urequire.True(t, strings.Contains(out, "w1"))
	urequire.True(t, strings.Contains(out, "Read its leash"))
}