// 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() }