From f57ae96e55d99614f555513839cb1a7115b2a903 Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 20 Nov 2026 13:06:55 +0100 Subject: [PATCH 1/2] claude-code: remove the guard on the agent's shell The operator asked for the shell guard to go (2026-11-20): the plugin no longer carries a PreToolUse hook or guard.json, the binary no longer has a guard verb, and the claude_code_guard tool, its record and the refusal-ranked order of the instead-of table are gone. The SessionStart and Stop hooks of the wait list stay, run by the same binary at the same path, which is also the home-fs helper's. The rendered rule against ssh to a mesh machine stays as the session's own and no longer claims a guard enforces it; claude-agent no longer passes the guard's override. --- modules/claude-code/README.md | 39 +- .../cmd/claude-code/agent_account_test.go | 95 +- modules/claude-code/cmd/claude-code/config.go | 42 +- modules/claude-code/cmd/claude-code/guard.go | 811 ------------------ .../claude-code/cmd/claude-code/guard_run.go | 315 ------- .../claude-code/cmd/claude-code/guard_test.go | 328 ------- modules/claude-code/cmd/claude-code/homefs.go | 2 +- .../claude-code/cmd/claude-code/insteadof.go | 27 +- .../cmd/claude-code/insteadof_test.go | 15 +- modules/claude-code/cmd/claude-code/main.go | 16 +- modules/claude-code/cmd/claude-code/mesh.go | 69 +- modules/claude-code/cmd/claude-code/node.go | 9 +- .../cmd/claude-code/session_start_test.go | 2 +- .../claude-code/cmd/claude-code/stop_test.go | 4 +- .../cmd/claude-code/terminal_only_test.go | 20 +- modules/claude-code/cmd/claude-code/waits.go | 2 +- modules/claude-code/files/claude-agent | 6 +- modules/claude-code/module.json | 1 - 18 files changed, 66 insertions(+), 1737 deletions(-) delete mode 100644 modules/claude-code/cmd/claude-code/guard.go delete mode 100644 modules/claude-code/cmd/claude-code/guard_run.go delete mode 100644 modules/claude-code/cmd/claude-code/guard_test.go diff --git a/modules/claude-code/README.md b/modules/claude-code/README.md index 068d73518..e4ec69005 100644 --- a/modules/claude-code/README.md +++ b/modules/claude-code/README.md @@ -28,8 +28,7 @@ And, for where the agent runs as an account of its own (hq ADR 0266): rule and can read no secret the mesh placed for another account. A way found is this module's condition, and the controller's self-check says it urgently. - `/usr/local/bin/claude-agent`, root's, `0755`: starts the agent as that account — `claude` itself when run - as it, otherwise `sudo -iu claude` through the operator's own sudo, carrying the guard's - override only when it is set in the operator's shell. + as it, otherwise `sudo -iu claude` through the operator's own sudo. - `/etc/claude-code/agent-account`, root's, `0644`: the name of that account, the machine fact `agent-account`, for the shell to read — the controller fills no machine fact into shell code. - **`claude` in the operator's interactive zsh is `claude-agent`** where the machine names an agent account: @@ -48,7 +47,7 @@ whenever the node's tool runtime collects the module's tools: | `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh` (with a `timeout` of 660000 ms, mesh_wait's longest wait and a minute, so the agent's one-minute default does not cut a wait, issue 1871), and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's | | `managed-settings.json` | the keys set in this module's `managed_settings` setting — at the controller's terminal alone (hq issue 340) — under the mesh's own keys: the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, the key-helper while the node holds an API-key licence, git's credential file while the node holds the forge's read credential (below), and the two that name the `nox-mesh` marketplace and enable its plugin, and `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` (660000) in `env` beside the operator's own, the mesh's key winning | | `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions, the **"instead of" table** — then the instruction sections registered for every node and for this one | -| `marketplace/` | the `nox-mesh` plugin (hq ADR 0216): the skills, subagents, commands and output styles registered for every node and for this one, offered in a session as `nox-mesh:` — and the **guard on the agent's shell** (`guard/`), the mesh's own hook and the plugin's only one (hq issue 340). Replaced whole, staged beside and swapped in | +| `marketplace/` | the `nox-mesh` plugin (hq ADR 0216): the skills, subagents, commands and output styles registered for every node and for this one, offered in a session as `nox-mesh:` — and this module's binary (`guard/guard`, its path kept so the home-fs helper's path does not move) run by the mesh's own SessionStart and Stop hooks, the plugin's only hooks (hq issue 340, ADR 0489). No PreToolUse hook: the guard on the agent's shell is removed (the operator, 2026-11-20). Replaced whole, staged beside and swapped in | Under the operator's home: `~/.claude/.credentials.json`, only when the licence manager hands this node a subscription token; and what is registered at the **home** scope for this node — a skill, subagent, @@ -126,31 +125,15 @@ The agent kept reaching for `ssh journalctl` while the service manager answered this is not placed) — at start, every ten minutes and on `claude_code_render`, keeps it in its state (`mesh-tools.json`), and renders it into `CLAUDE.md` as one row per seat or module: `/.` and each verb with the commands it replaces. Generated, never written by hand: a verb that gains `replaces` is in - the next render. Ordered by what the guard here refused most, then the machines' seats, the modules, the + the next render. Ordered by the machines' seats, the modules, the mesh's seats; at most sixteen rows, the rest one `mesh_search` away. -- **The guard.** A PreToolUse hook on every tool, judging `Bash`, `Edit`, `Write`, `MultiEdit` and `NotebookEdit` and letting the rest through (but see the account rule below): this module's own - binary (`claude-code guard`), copied root's into the plugin with what it judges with (`guard.json`: the - machines by name, domain and address, and the replaced commands), run by its path under `/etc/claude-code` so - the session cannot change it. It refuses `ssh`, `scp`, `sftp`, `rsync`, `mosh` and `autossh` to a mesh machine - (any `*.internal` name, a machine's name or a name under its domains, one of its addresses, as `ssh -G` reads - the destination; a jump through one too), writing `/etc/hosts` or `/etc/resolv.conf`, and `HOSTALIASES` — - naming the verb that does the job on that machine when one says it replaces the command, and otherwise that a - missing tool is created in the module that owns it, never worked around. **Stated, not silent:** an ssh login - as `git` is the forge's account, which runs nothing but git, and passes; a git remote is never an ssh command - line anyway. -- **The operator's override**: `MESH_GUARD_OVERRIDE=`, exported in the operator's own shell before the - session starts. It is read from the session's environment as the kernel kept it at exec - (`/proc//environ` of the agent's process), so nothing a session does — a command's `export`, a - settings `env` key — can set it, and a command naming it is refused outright. Every override and every - refusal is a line in the module's `guard.log`; an override that cannot be recorded is not honoured. - `claude_code_guard` shows the rules, the data and the record. - -It is a guard against the habit, not a sandbox: a command written to hide what it runs can hide it, and the -record is how a habit that found a way round is seen. +The rule under the table (never `ssh` to a mesh machine, never edit `/etc/hosts` or set `HOSTALIASES` for a +mesh name) is the session's own: nothing on the agent's shell enforces it since the guard was removed (the +operator, 2026-11-20). ## Tools -`claude_code_status`, `claude_code_render`, `claude_code_guard`, `claude_code_pull` (asks the vault for this node's +`claude_code_status`, `claude_code_render`, `claude_code_pull` (asks the vault for this node's licence token now), `claude_code_grant` (for the licence manager), `claude_code_mcp_list`, `claude_code_mcp_unregister` (this node by default; `nodes: "all"` or a list for more). @@ -339,14 +322,6 @@ applied only while the agent's account holds it — and what this module placed goes: the access-token-only credentials file (one holding a refresh token is a login the person made, and stays, said), the home-scope items unless changed by hand, the key kept in the state. -**The guard there refuses every tool call of a session that does not run as the agent's account** — -shell, file edits, reads and the mesh's tools alike — and no override lifts it: the operator's account may become root, and an -agent started in it by habit must do nothing. Its record goes to the machine's journal -(`journalctl -t mesh-claude-code-guard`), which the session's account may add to and not change; -`claude_code_guard` reads it there, keeping only the lines the journal says the guard's own binary wrote. That -is not proof: the account can run the guard's binary itself and add lines in the guard's words. What it -cannot do is remove one. - **An API key is taken only from the agent's own home.** `claude_code_add_api_key` reads a file and removes it, and the runtime runs as the operator: a path anywhere would hand whoever calls it the runtime's credential or the operator's keys. So the file must lie under the home of the account the agent runs as, reached through no diff --git a/modules/claude-code/cmd/claude-code/agent_account_test.go b/modules/claude-code/cmd/claude-code/agent_account_test.go index 66b213e67..19cac6788 100644 --- a/modules/claude-code/cmd/claude-code/agent_account_test.go +++ b/modules/claude-code/cmd/claude-code/agent_account_test.go @@ -1,8 +1,7 @@ package main // Where the agent runs as an account of its own (novox/hq ADR 0266): the home touched through the helper, the -// licence that follows the account, what goes from the operator's home, and the guard that refuses a session -// running as anyone else. +// licence that follows the account, and what goes from the operator's home. import ( "bufio" @@ -11,7 +10,6 @@ import ( "errors" "io" "io/fs" - "net" "os" "path/filepath" "strings" @@ -333,82 +331,6 @@ func TestNothingGoesWhereTheAgentRunsAsTheOperator(t *testing.T) { } } -// ---- the guard -------------------------------------------------------------------------------------------- - -func TestASessionNotRunningAsTheAgentsAccountDoesNothing(t *testing.T) { - g := Guard{Data: GuardData{Node: "anchor", Agent: "agent"}} - echo := HookInput{ToolName: "Bash", ToolInput: map[string]any{"command": "echo hello"}} - v := g.JudgeAs("operator", echo) - if !v.Refuse || v.Rule != "account" || v.Overridable || !strings.Contains(v.Message, "claude-agent") { - t.Fatalf("a session as the operator is refused whatever it runs, with no override: %+v", v) - } - if v := g.JudgeAs("operator", HookInput{ToolName: "Write", ToolInput: map[string]any{"file_path": "/tmp/x"}}); !v.Refuse { - t.Fatal("a file edit too") - } - if v := g.JudgeAs("agent", echo); v.Refuse { - t.Fatalf("the agent's own account runs as before: %+v", v) - } - if v := (Guard{Data: GuardData{Node: "laptop"}}).JudgeAs("operator", echo); v.Refuse { - t.Fatal("where agents run as the operator, the operator's session runs as before") - } -} - -func TestWhereTheAgentHasItsOwnAccountTheRecordIsTheJournal(t *testing.T) { - p, _ := node(t, "anchor") - if d := GuardDataOf(p, nil); d.Agent != "" || strings.HasPrefix(d.Log, JournalRecord) { - t.Fatalf("as the operator: the module's own file; got %+v", d) - } - p.Agent, p.Operator = "agent", "operator" - d := GuardDataOf(p, nil) - if d.Agent != "agent" || d.Log != JournalRecord+GuardJournalID { - t.Fatalf("as an account of its own: the journal, and the account named; got %+v", d) - } - - socket := filepath.Join(t.TempDir(), "journal") - conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: socket, Net: "unixgram"}) - if err != nil { - t.Skipf("no unix datagram socket here: %v", err) - } - defer conn.Close() - was := journalSocket - journalSocket = socket - t.Cleanup(func() { journalSocket = was }) - if err := RecordGuard(d.Log, GuardEntry{Decision: "refused", Rule: "account", Tool: "Bash", Command: "a\nb"}); err != nil { - t.Fatal(err) - } - buf := make([]byte, 4096) - n, _, err := conn.ReadFrom(buf) - if err != nil { - t.Fatal(err) - } - lines := strings.Split(strings.TrimSuffix(string(buf[:n]), "\n"), "\n") - if len(lines) != 3 || lines[0] != "SYSLOG_IDENTIFIER="+GuardJournalID || !strings.HasPrefix(lines[2], "MESSAGE={") { - t.Fatalf("one line per field, the entry as one line of JSON: %q", lines) - } - - readWas := readJournal - t.Cleanup(func() { readJournal = readWas }) - readJournal = func(id string, last int) ([]byte, error) { - if id != GuardJournalID { - t.Fatalf("read %s", id) - } - msg, _ := json.Marshal(strings.TrimPrefix(lines[2], "MESSAGE=")) - forged, _ := json.Marshal(`{"decision":"overridden","rule":"ssh","tool":"Bash","command":"forged"}`) - return []byte(`{"MESSAGE":` + string(msg) + `,"_EXE":"` + HelperPath() + `"}` + "\n" + - `{"MESSAGE":` + string(forged) + `,"_EXE":"/usr/bin/logger"}` + "\n"), nil - } - if got := ReadGuardLog(d.Log, 10); len(got) != 1 || got[0].Rule != "account" || got[0].Command != "a\nb" { - t.Fatalf("the record reads back from the journal: %+v", got) - } - if err := RecordGuard(JournalRecord+"x", GuardEntry{}); err != nil && !strings.Contains(err.Error(), "journal") { - t.Fatal(err) - } - journalSocket = filepath.Join(t.TempDir(), "absent") - if err := RecordGuard(d.Log, GuardEntry{}); err == nil { - t.Fatal("a journal that cannot be reached is an error, so an override is not honoured unrecorded") - } -} - // ---- an API key is taken only from the agent's own home --------------------------------------------------- func TestAnAPIKeyFileOutsideTheAgentsHomeIsRefusedAndKept(t *testing.T) { @@ -439,21 +361,6 @@ func TestAnAPIKeyFileOutsideTheAgentsHomeIsRefusedAndKept(t *testing.T) { } } -func TestTheGuardIsAskedAboutEveryToolAndRefusesEachForAnotherAccount(t *testing.T) { - if GuardMatcher != "*" { - t.Fatalf("the guard is asked about every tool, got %q", GuardMatcher) - } - g := Guard{Data: GuardData{Node: "anchor", Agent: "agent"}} - for _, tool := range []string{"Read", "Grep", "WebFetch", "mcp__mesh__mesh_call", "Task"} { - if v := g.JudgeAs("operator", HookInput{ToolName: tool}); !v.Refuse { - t.Fatalf("%s as another account is refused", tool) - } - if v := g.JudgeAs("agent", HookInput{ToolName: tool}); v.Refuse { - t.Fatalf("%s as the agent's account passes", tool) - } - } -} - func TestAMoveWritesTheAccountFileBesideTheToken(t *testing.T) { p, w := node(t, "anchor") writeFile(t, p.binding(), `{"licence":"personal","kind":"subscription","generation":4}`) diff --git a/modules/claude-code/cmd/claude-code/config.go b/modules/claude-code/cmd/claude-code/config.go index 194363d5f..527bd2141 100644 --- a/modules/claude-code/cmd/claude-code/config.go +++ b/modules/claude-code/cmd/claude-code/config.go @@ -472,40 +472,27 @@ type PluginFile struct { From string `json:",omitempty"` } -// GuardDir is where the guard on the agent's shell lives in the plugin (novox/hq ADR 0245): its binary and -// what it is given. Outside hooks/, so no registered hook's name can be it. +// GuardDir is where this module's binary lives in the plugin, run by the SessionStart and Stop hooks and as the +// home-fs helper (novox/hq ADR 0266). Outside hooks/, so no registered hook's name can be it. Its path is kept so the +// helper's does not move; the guard on the agent's shell that once ran from it is removed (the operator, +// 2026-11-20). const GuardDir = "guard" -// GuardFiles are the guard as the plugin carries it: the binary to copy, what it judges with, and — the same -// binary again — the waits directory the SessionStart and Stop hooks are given (novox/hq ADR 0489, issues -// 1744, 1743). Empty WaitsDir places no such hook. -type GuardFiles struct { +// HookFiles are what the plugin carries to run its hooks: the binary to copy and the waits directory the +// SessionStart and Stop hooks are given (novox/hq ADR 0489, issues 1744, 1743). Empty WaitsDir places no hook. +type HookFiles struct { Exe string - Data GuardData WaitsDir string } -// GuardMatcher is what the guard is asked about: every tool. Its own rules judge the shell and the agent's file -// edits and let every other tool through; the rule of the account agents run as (novox/hq ADR 0266) refuses -// every tool of a session running as another, reading and the mesh's tools included, so that session can do -// nothing at all. -const GuardMatcher = "*" - -// GuardCommand is the hook's command line: by its path under the managed directory, root's — never the -// copy the agent may keep of a plugin, which the session could change. -func GuardCommand() string { - dir := filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir) - return `"` + filepath.Join(dir, "guard") + `" guard "` + filepath.Join(dir, "guard.json") + `"` -} - -// SessionStartCommand is the plugin's SessionStart hook: the guard's own binary, told the session's open +// SessionStartCommand is the plugin's SessionStart hook: this module's binary, told the session's open // waits live under waitsDir (novox/hq ADR 0489 §3, issue 1744). func SessionStartCommand(waitsDir string) string { dir := filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir) return `"` + filepath.Join(dir, "guard") + `" session-start "` + waitsDir + `"` } -// StopCommand is the plugin's Stop hook: the guard's own binary, refusing to end the turn while a wait under +// StopCommand is the plugin's Stop hook: this module's binary, refusing to end the turn while a wait under // waitsDir is open and unwatched, or past its bound and untold (novox/hq ADR 0489 §3-§6, issue 1743). func StopCommand(waitsDir string) string { dir := filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir) @@ -516,9 +503,9 @@ func StopCommand(waitsDir string) string { // over a mesh item of the same kind and name: the node's wins. func Marketplace(c Config) map[string]PluginFile { return MarketplaceWith(c, nil) } -// MarketplaceWith is the marketplace with the guard on the agent's shell, when there is one to place: its -// hook first, before any registered one. -func MarketplaceWith(c Config, guard *GuardFiles) map[string]PluginFile { +// MarketplaceWith is the marketplace with the binary the plugin's hooks run, when there is one to place, and its +// SessionStart and Stop hooks. No PreToolUse hook: the plugin judges no tool call. +func MarketplaceWith(c Config, guard *HookFiles) map[string]PluginFile { root := "plugins/" + Plugin + "/" out := map[string]PluginFile{ ".claude-plugin/marketplace.json": {Content: jsonFile(map[string]any{ @@ -547,9 +534,6 @@ func MarketplaceWith(c Config, guard *GuardFiles) map[string]PluginFile { hooks := map[string][]any{} if guard != nil && guard.Exe != "" { out[root+GuardDir+"/guard"] = PluginFile{From: guard.Exe, Executable: true} - out[root+GuardDir+"/guard.json"] = PluginFile{Content: jsonFile(guard.Data)} - hooks["PreToolUse"] = append(hooks["PreToolUse"], map[string]any{"matcher": GuardMatcher, - "hooks": []any{map[string]any{"type": "command", "command": GuardCommand(), "timeout": 15}}}) if guard.WaitsDir != "" { // A session's wait list (novox/hq ADR 0489): the SessionStart hook names the session's id and its open // waits (issue 1744); the Stop hook keeps the turn open while one is unwatched or untold (issue 1743). @@ -574,7 +558,7 @@ func MarketplaceWith(c Config, guard *GuardFiles) map[string]PluginFile { out[root+"output-styles/"+it.Name+".md"] = PluginFile{Content: it.Files[it.Name+".md"]} } // A hook is never rendered from a registration (novox/hq issue 340): the plugin's hooks are the mesh's own - // guard alone, and any other is the operator's, in the managed settings set at the controller's terminal. + // SessionStart and Stop hooks alone, and any other is the operator's, in the managed settings set at the controller's terminal. } if len(hooks) > 0 { out[root+"hooks/hooks.json"] = PluginFile{Content: jsonFile(map[string]any{"hooks": hooks})} diff --git a/modules/claude-code/cmd/claude-code/guard.go b/modules/claude-code/cmd/claude-code/guard.go deleted file mode 100644 index 9dd2e00bd..000000000 --- a/modules/claude-code/cmd/claude-code/guard.go +++ /dev/null @@ -1,811 +0,0 @@ -package main - -// The guard on the agent's shell (novox/hq ADR 0245): a PreToolUse hook every session on a machine of the -// mesh runs before a shell command or a file edit, delivered in the module's plugin. -// -// It refuses three work-arounds, each with the mesh tool that does the job when one says it replaces the -// command, and otherwise with the rule that a missing tool is created, never worked around: -// -// 1. **ssh to a mesh machine** — `ssh`, `scp`, `sftp`, `rsync`, `mosh` or `autossh` to a machine's name, a -// name under its domains, any `*.internal` name, or one of its addresses; a jump through one too. The -// destination is read as ssh itself reads it (`ssh -G`), so an alias in ~/.ssh/config is no way round. -// **Stated, not silent**: an ssh login as `git` is the forge's account, which runs git and nothing -// else — so `git push` over ssh, and `ssh -T git@`, reach no machine and pass. A git remote is -// never an ssh command line anyway. -// 2. **writing /etc/hosts or /etc/resolv.conf** — by redirect, tee, sed -i, an editor, cp/mv/install onto -// it, or the agent's own Edit and Write tools: a mesh name is the mesh's resolvers' (ADR 0194), and a -// machine's hosts file is its node-hostname seat's. -// 3. **HOSTALIASES**, named anywhere in a command line. -// -// And it refuses any command that names the operator's override, so the agent never sets it (guard_run.go). -// -// The matching is on the command line as a shell would split it — quotes, separators, `$(…)`, `bash -c` — -// and wrappers such as sudo, env and timeout are looked through. It is a guard against the habit of reaching -// for ssh, not a sandbox: a command built to hide what it runs can hide it, and the record of what was -// refused (the module's `guard.log`, read by `claude_code_guard`) is how a habit that found a way round is seen. - -import ( - "fmt" - "net" - "net/url" - "path" - "path/filepath" - "sort" - "strings" -) - -// GuardData is what the hook is given: this machine, the mesh's machines, what replaces what, and where -// its record is kept. Written beside the hook on every render, root's, so the session cannot change it. -type GuardData struct { - Node string `json:"node"` - Machines []Machine `json:"machines"` - Replacements []Replacement `json:"replacements"` - Log string `json:"log"` - // Agent is the account every session here must run as, where the machine names an agent account of its - // own (novox/hq ADR 0266); empty where agents run as the operator. - Agent string `json:"agent,omitempty"` -} - -// HookInput is what the agent hands a PreToolUse hook. -type HookInput struct { - ToolName string `json:"tool_name"` - ToolInput map[string]any `json:"tool_input"` - Cwd string `json:"cwd"` - SessionID string `json:"session_id"` -} - -// Verdict is the guard's answer. -type Verdict struct { - Refuse bool `json:"refuse"` - Rule string `json:"rule,omitempty"` // ssh | hosts-file | hostaliases | override-named | account - Machine string `json:"machine,omitempty"` - Message string `json:"message,omitempty"` - // Overridable is false for a refusal no override lifts: the agent naming the override itself. - Overridable bool `json:"-"` - // Calls are the tools the refusal named, by address without a machine: what the instructions' table - // puts first, the tools the agent most reached round. - Calls []string `json:"calls,omitempty"` -} - -// OverrideVar is the operator's override: set in the operator's own shell before the session starts, -// with why as its value. Read from the session's own environment as it was started, never from what a -// command or a setting put there (guard_run.go). -const OverrideVar = "MESH_GUARD_OVERRIDE" - -// ForgeUser is the forge's ssh account: it runs git, never a shell (stated in ADR 0245). -const ForgeUser = "git" - -// protectedFiles are the files a session never writes for a mesh name. -var protectedFiles = map[string]bool{"/etc/hosts": true, "/etc/resolv.conf": true} - -// SSHView is how ssh itself reads a destination with these options: the host it connects to, the user, -// and the jumps. Empty host when ssh could not say. -type SSHView func(options []string, destination string) (host, user string, jumps []string) - -// Guard judges what a session is about to do. -type Guard struct { - Data GuardData - // SSH reads a destination as ssh does (`ssh -G`); nil reads it from the command line alone. - SSH SSHView - // Resolve is a name's addresses, for a name that is none of the mesh's but may point at a machine. - Resolve func(string) []string -} - -// JudgeAs is the verdict on one tool call of a session running as an account. **On a machine whose agents run -// as an account of their own, a session running as any other does nothing** (novox/hq ADR 0266): the -// operator's account there may become root without a person, and an agent started in it by habit would carry -// that into every command. Refused whatever the command, and no override lifts it — the operator's own shell is -// how the operator acts as themselves. -func (g Guard) JudgeAs(account string, in HookInput) Verdict { - if g.Data.Agent != "" && account != g.Data.Agent { - return Verdict{Refuse: true, Rule: "account", Message: fmt.Sprintf("Refused: on %s agents run as %s, an "+ - "account that cannot become root without a person, and this session runs as %s (novox/hq ADR 0266). "+ - "No tool it calls here is let through. End it, and start the agent with `claude-agent`, which runs it as "+ - "%s; what needs the operator's own rights is the operator's to run in their own shell.", - orThisMachine(g.Data.Node), g.Data.Agent, account, g.Data.Agent)} - } - return g.Judge(in) -} - -func orThisMachine(node string) string { - if node == "" { - return "this machine" - } - return node -} - -// Judge is the verdict on one tool call. -func (g Guard) Judge(in HookInput) Verdict { - switch in.ToolName { - case "Bash": - command, _ := in.ToolInput["command"].(string) - return g.judgeLine(command, 0) - case "Edit", "Write", "MultiEdit", "NotebookEdit": - for _, key := range []string{"file_path", "notebook_path"} { - if p, _ := in.ToolInput[key].(string); p != "" && protectedFiles[filepath.Clean(p)] { - return g.hostsFile(filepath.Clean(p), in.ToolName+" "+filepath.Clean(p)) - } - } - } - return Verdict{} -} - -func (g Guard) judgeLine(line string, depth int) Verdict { - if depth > 4 { - return Verdict{} - } - if strings.Contains(line, OverrideVar) { - return Verdict{Refuse: true, Rule: "override-named", Message: fmt.Sprintf( - "Refused by the mesh's guard (novox/hq ADR 0245): this command names %s, the operator's override. "+ - "It is the operator's alone, set in their own shell before a session starts; a session never sets, "+ - "reads or passes it.", OverrideVar)} - } - if strings.Contains(line, "HOSTALIASES") { - return g.refuseLocal("hostaliases", "HOSTALIASES", "setting HOSTALIASES") - } - for _, words := range simpleCommands(line) { - if v := g.judgeCommand(words, depth); v.Refuse { - return v - } - // What a word runs in its own shell: `$(…)` and backticks inside a quoted word. - for _, w := range words { - for _, inner := range substitutions(w) { - if v := g.judgeLine(inner, depth+1); v.Refuse { - return v - } - } - } - } - return Verdict{} -} - -// wrappers run the command after them; each with the options that take a value. -var wrappers = map[string]string{ - "sudo": "ugCDhpTrt", "doas": "uC", "env": "uSC", "timeout": "sk", "nohup": "", "nice": "n", "ionice": "cnpP", - "command": "", "exec": "a", "time": "fo", "stdbuf": "ioe", "xargs": "aEdIiLlnPs", "setsid": "", "unbuffer": "", - "chronic": "", "flock": "wE", "torsocks": "", "proxychains": "f", "proxychains4": "f", "caffeinate": "", -} - -// shells run their -c argument as a command line. -var shells = map[string]bool{"sh": true, "bash": true, "zsh": true, "dash": true, "ksh": true, "fish": true, "eval": true} - -func (g Guard) judgeCommand(words []string, depth int) Verdict { - words = unwrap(words) - if len(words) == 0 { - return Verdict{} - } - name := path.Base(words[0]) - args := words[1:] - if shells[name] { - if name == "eval" { - return g.judgeLine(strings.Join(args, " "), depth+1) - } - for i, a := range args { - if strings.HasPrefix(a, "-") && !strings.HasPrefix(a, "--") && strings.Contains(a, "c") && i+1 < len(args) { - return g.judgeLine(args[i+1], depth+1) - } - } - } - switch name { - case "ssh", "autossh", "mosh", "slogin": - return g.judgeSSH(name, args, strings.Join(words, " ")) - case "scp", "sftp", "rsync": - return g.judgeCopy(name, args, strings.Join(words, " ")) - } - if target := writesProtected(name, args); target != "" { - return g.hostsFile(target, strings.Join(words, " ")) - } - return Verdict{} -} - -// unwrap takes off what only runs the command: assignments before it, and wrappers with their options. -func unwrap(words []string) []string { - for len(words) > 0 { - w := words[0] - switch { - case w == "!" || w == "{" || w == "}" || w == "then" || w == "do" || w == "else" || w == "if" || w == "while" || - w == "until" || w == "elif": - words = words[1:] - case isAssignment(w): - words = words[1:] - default: - opts, wrapper := wrappers[path.Base(w)] - if !wrapper { - return words - } - base := path.Base(w) - words = words[1:] - for len(words) > 0 { - a := words[0] - if a == "--" { - words = words[1:] - break - } - if base == "env" && isAssignment(a) { - words = words[1:] - continue - } - if !strings.HasPrefix(a, "-") || a == "-" { - break - } - words = words[1:] - if strings.HasPrefix(a, "--") { - continue - } - if f := a[len(a)-1:]; strings.Contains(opts, f) && len(words) > 0 { - words = words[1:] - } - } - // timeout's duration, nice's adjustment as a word: a number before the command. - if (base == "timeout") && len(words) > 0 { - words = words[1:] - } - } - } - return words -} - -func isAssignment(w string) bool { - i := strings.Index(w, "=") - if i <= 0 { - return false - } - for _, r := range w[:i] { - if !(r == '_' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9') { - return false - } - } - return true -} - -// sshOptionsWithValue are ssh's single-letter options that take a value. -const sshOptionsWithValue = "BbcDEeFIiJLlmOoPpQRSWw" - -func (g Guard) judgeSSH(name string, args []string, line string) Verdict { - var options, jumps []string - user := "" - dest, rest := "", []string(nil) - for i := 0; i < len(args); i++ { - a := args[i] - if a == "--" { - if i+1 < len(args) { - dest, rest = args[i+1], args[i+2:] - } - break - } - if name == "autossh" && strings.HasPrefix(a, "-M") { - if a == "-M" { - i++ // autossh's own: the monitoring port - } - continue - } - if strings.HasPrefix(a, "-") && len(a) > 1 { - options = append(options, a) - if name == "mosh" || strings.HasPrefix(a, "--") { - continue // mosh's own options are long, each with its value after `=` - } - for j := 1; j < len(a); j++ { - if !strings.ContainsRune(sshOptionsWithValue, rune(a[j])) { - continue - } - value := a[j+1:] - if value == "" && i+1 < len(args) { - i++ - value = args[i] - options = append(options, value) - } - switch a[j] { - case 'J': - jumps = append(jumps, strings.Split(value, ",")...) - case 'l': - user = value - case 'o': - k, v, _ := strings.Cut(value, "=") - switch strings.ToLower(strings.TrimSpace(k)) { - case "proxyjump": - jumps = append(jumps, strings.Split(v, ",")...) - case "user": - user = strings.TrimSpace(v) - } - } - break - } - continue - } - dest, rest = a, args[i+1:] - break - } - if dest == "" { - return Verdict{} - } - host, destUser := hostOf(dest) - if destUser != "" { - user = destUser - } - if g.SSH != nil && name != "mosh" { - if h, u, j := g.SSH(options, dest); h != "" { - host, user = h, u - jumps = append(jumps, j...) - } - } - remote := strings.Join(rest, " ") - for _, jump := range jumps { - jh, ju := hostOf(jump) - if machine, ok := g.meshHost(jh); ok && ju != ForgeUser { - return g.refuseSSH(machine, jh, remote, line) - } - } - if user == ForgeUser { - return Verdict{} // the forge's account: git and nothing else (stated in ADR 0245) - } - if machine, ok := g.meshHost(host); ok { - return g.refuseSSH(machine, host, remote, line) - } - return Verdict{} -} - -// judgeCopy reads scp's, sftp's and rsync's remote paths, `[user@]host:path` or `scp://[user@]host/…`. -func (g Guard) judgeCopy(name string, args []string, line string) Verdict { - for i := 0; i < len(args); i++ { - a := args[i] - if strings.HasPrefix(a, "-") { - if name != "rsync" && len(a) == 2 && strings.ContainsRune("cFiJloPSXBRD", rune(a[1])) { - i++ - } - if name == "rsync" && (a == "-e" || a == "--rsh") { - i++ - } - continue - } - var host, user string - if strings.Contains(a, "://") { - host, user = hostOf(a) - } else if colon := strings.Index(a, ":"); colon > 0 && !strings.Contains(a[:colon], "/") { - host, user = hostOf(a[:colon]) - } else if name == "sftp" { - host, user = hostOf(a) - } else { - continue - } - if user == ForgeUser { - continue - } - if g.SSH != nil { - if h, u, _ := g.SSH(nil, host); h != "" { - host = h - if u == ForgeUser && user == "" { - continue - } - } - } - if machine, ok := g.meshHost(host); ok { - return g.refuseSSH(machine, host, "", line) - } - } - return Verdict{} -} - -// hostOf reads `[user@]host[:port]`, `ssh://[user@]host[:port]/…` or `[v6]`. -func hostOf(dest string) (host, user string) { - if strings.Contains(dest, "://") { - if u, err := url.Parse(dest); err == nil { - return strings.ToLower(u.Hostname()), u.User.Username() - } - } - if at := strings.LastIndex(dest, "@"); at >= 0 { - user, dest = dest[:at], dest[at+1:] - } - if strings.HasPrefix(dest, "[") { - if end := strings.Index(dest, "]"); end > 0 { - return strings.ToLower(dest[1:end]), user - } - } - if h, _, err := net.SplitHostPort(dest); err == nil && strings.Count(dest, ":") == 1 { - dest = h - } - return strings.TrimSuffix(strings.ToLower(dest), "."), user -} - -// meshHost says whether a host is one of the mesh's machines, and which when it can tell. -func (g Guard) meshHost(host string) (string, bool) { - host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".") - if host == "" { - return "", false - } - if ip := net.ParseIP(host); ip != nil { - for _, m := range g.Data.Machines { - for _, a := range m.Addresses { - if b := net.ParseIP(a); b != nil && b.Equal(ip) { - return m.Name, true - } - } - } - return "", false - } - for _, m := range g.Data.Machines { - if host == strings.ToLower(m.Name) { - return m.Name, true - } - for _, d := range m.Domains { - if host == d || strings.HasSuffix(host, "."+d) { - return m.Name, true - } - } - } - if strings.HasSuffix(host, InternalSuffix) { - return "", true - } - if g.Resolve != nil && !strings.Contains(host, "/") { - for _, a := range g.Resolve(host) { - if m, ok := g.meshHost(a); ok && net.ParseIP(a) != nil { - return m, true - } - } - } - return "", false -} - -// writesProtected is the protected file a command writes, or "". -func writesProtected(name string, args []string) string { - protected := func(a string) string { - a = strings.Trim(a, `"'`) - if strings.HasPrefix(a, "of=") { - a = a[3:] - } - if protectedFiles[filepath.Clean(a)] { - return filepath.Clean(a) - } - return "" - } - // A redirect onto it, from any command. - for i, a := range args { - if (a == ">" || a == ">>") && i+1 < len(args) { - if p := protected(args[i+1]); p != "" { - return p - } - } - } - operands := func() []string { - var out []string - for i := 0; i < len(args); i++ { - if args[i] == ">" || args[i] == ">>" || args[i] == "<" { - i++ - continue - } - out = append(out, args[i]) - } - return out - }() - switch name { - case "tee", "vi", "vim", "nvim", "nano", "emacs", "ed", "ex", "micro", "hx", "helix", "kak", "gedit", "code", - "truncate", "chattr", "chmod", "chown", "rm", "unlink", "shred", "dd", "sponge", "visudo", "vipw": - for _, a := range operands { - if p := protected(a); p != "" { - return p - } - } - case "sed", "perl", "ruby", "awk", "gawk": - inPlace := false - for _, a := range operands { - switch { - case name == "awk" || name == "gawk": - inPlace = inPlace || a == "inplace" - case strings.HasPrefix(a, "--in-place"): - inPlace = true - case strings.HasPrefix(a, "-") && !strings.HasPrefix(a, "--") && strings.Contains(a, "i"): - inPlace = true - } - } - if inPlace { - for _, a := range operands { - if p := protected(a); p != "" { - return p - } - } - } - case "cp", "mv", "install", "ln", "rsync": - var files []string - for _, a := range operands { - if !strings.HasPrefix(a, "-") { - files = append(files, a) - } - } - if len(files) > 1 { - if p := protected(files[len(files)-1]); p != "" { - return p - } - } - } - return "" -} - -// replacementsFor are the mesh's tools that replace a command, the most specific first, each address once. -func (g Guard) replacementsFor(command string) []string { - have := commandWordsOf(command) - type found struct { - address string - weight int - replace string - } - var all []found - for _, r := range g.Data.Replacements { - best := 0 - which := "" - for _, c := range r.Replaces { - want := commandWordsOf(c) - if inOrderWords(want, have) && len(want) > best { - best, which = len(want), c - } - } - if best > 0 { - all = append(all, found{r.Address, best, which}) - } - } - sort.SliceStable(all, func(i, j int) bool { return all[i].weight > all[j].weight }) - var out []string - for _, f := range all { - out = append(out, f.address+"\x00"+f.replace) - } - return out -} - -// callFor is how an address is called for a machine. -func (g Guard) callFor(address, machine string) string { - for _, r := range g.Data.Replacements { - if r.Address != address || !r.NodeScoped { - continue - } - on := machine - if !r.Seat && len(r.On) > 0 && !containsString(r.On, machine) { - on = r.On[0] - } - if on == "" { - on = "" - } - return on + "/" + address - } - return address -} - -func containsString(xs []string, s string) bool { - for _, x := range xs { - if x == s { - return true - } - } - return false -} - -// exact is the replacement that names this exact command, or "". -func (g Guard) exact(command string) string { - for _, r := range g.Data.Replacements { - for _, c := range r.Replaces { - if c == command { - return r.Address - } - } - } - return "" -} - -const missingTool = "No mesh tool says it replaces this. Do not work around it: a missing tool is created in the module " + - "that owns the thing, on the seat it occupies — say what is missing to the operator. First make sure with " + - "`mesh_search` and the command's own words." - -func (g Guard) refuseSSH(machine, host, remote, line string) Verdict { - who := machine - if who == "" { - who = host + " (a mesh name)" - } - var b strings.Builder - var named []string - fmt.Fprintf(&b, "Refused by the mesh's guard (novox/hq ADR 0245): `%s` reaches %s round the mesh's tools.\n", cut(line, 160), who) - switch { - case strings.TrimSpace(remote) == "": - target := machine - if target == "" { - target = "" - } - fmt.Fprintf(&b, "What a machine serves is `mesh_machine %s`; `mesh_search` with what you meant to run finds its tool.\n", target) - default: - calls := g.replacementsFor(remote) - if len(calls) == 0 { - b.WriteString(missingTool + "\n") - break - } - b.WriteString("Call instead, through `mesh_call`:\n") - for i, c := range calls { - if i == 3 { - break - } - address, replaces, _ := strings.Cut(c, "\x00") - named = append(named, address) - fmt.Fprintf(&b, " %s — replaces `%s`\n", g.callFor(address, machine), replaces) - } - } - return Verdict{Refuse: true, Rule: "ssh", Machine: machine, Message: strings.TrimRight(b.String(), "\n"), Overridable: true, - Calls: named} -} - -func (g Guard) refuseLocal(rule, replaced, what string) Verdict { - var b strings.Builder - fmt.Fprintf(&b, "Refused by the mesh's guard (novox/hq ADR 0245): %s is a work-around for a mesh name. "+ - "A mesh name is the mesh's resolvers' to answer, and a machine's own lines in /etc/hosts are its node-hostname seat's.\n", what) - var named []string - if address := g.exact(replaced); address != "" { - named = append(named, address) - fmt.Fprintf(&b, "Call instead, through `mesh_call`: %s — replaces `%s`", g.callFor(address, g.Data.Node), replaced) - } else { - b.WriteString(missingTool) - } - return Verdict{Refuse: true, Rule: rule, Machine: g.Data.Node, Message: b.String(), Overridable: true, Calls: named} -} - -func (g Guard) hostsFile(file, line string) Verdict { - replaced := "edit " + file - return g.refuseLocal("hosts-file", replaced, fmt.Sprintf("writing %s (`%s`)", file, cut(line, 120))) -} - -func cut(s string, n int) string { - s = strings.Join(strings.Fields(s), " ") - if r := []rune(s); len(r) > n { - return string(r[:n-1]) + "…" - } - return s -} - -// commandWordsOf are a command line's words as matched against a replaced command (the mesh MCP server's search rule): -// lower-cased, a program by path reduced to its name, sudo left out. -func commandWordsOf(line string) []string { - var out []string - for i, w := range strings.Fields(strings.ToLower(line)) { - if i == 0 || strings.HasPrefix(w, "/") { - w = path.Base(w) - } - if w == "sudo" { - continue - } - out = append(out, w) - } - return out -} - -func inOrderWords(want, have []string) bool { - i := 0 - for _, h := range have { - if i < len(want) && h == want[i] { - i++ - } - } - return len(want) > 0 && i == len(want) -} - -// ---- the shell's words ------------------------------------------------------------------------------ - -// simpleCommands splits a command line as a shell would into its simple commands' words: quotes -// removed, `;`, `&`, `|`, `&&`, `||`, newlines, parentheses and backticks between commands, `$(` opening -// one; `>` and `>>` kept as words of their own, before what they redirect to. -func simpleCommands(line string) [][]string { - var out [][]string - var words []string - var cur strings.Builder - inWord := false - flushWord := func() { - if inWord { - words = append(words, cur.String()) - cur.Reset() - inWord = false - } - } - flushCommand := func() { - flushWord() - if len(words) > 0 { - out = append(out, words) - } - words = nil - } - r := []rune(line) - for i := 0; i < len(r); i++ { - c := r[i] - switch { - case c == '\\' && i+1 < len(r): - i++ - if r[i] != '\n' { - cur.WriteRune(r[i]) - inWord = true - } - case c == '\'': - inWord = true - for i++; i < len(r) && r[i] != '\''; i++ { - cur.WriteRune(r[i]) - } - case c == '"': - inWord = true - for i++; i < len(r) && r[i] != '"'; i++ { - if r[i] == '\\' && i+1 < len(r) && strings.ContainsRune("\"\\$`", r[i+1]) { - i++ - } - cur.WriteRune(r[i]) - } - case c == '$' && i+1 < len(r) && r[i+1] == '(': - flushCommand() - i++ - case c == ';' || c == '&' || c == '|' || c == '\n' || c == '(' || c == ')' || c == '`': - flushCommand() - case c == '>' || c == '<': - // A file descriptor before it (`2>`) is not a word. - if inWord && isDigits(cur.String()) { - cur.Reset() - inWord = false - } - flushWord() - op := string(c) - if c == '>' && i+1 < len(r) && r[i+1] == '>' { - op = ">>" - i++ - } - if i+1 < len(r) && (r[i+1] == '&' || r[i+1] == '|') { - i++ - } - words = append(words, op) - case c == ' ' || c == '\t': - flushWord() - case c == '#' && !inWord: - for i < len(r) && r[i] != '\n' { - i++ - } - flushCommand() - default: - cur.WriteRune(c) - inWord = true - } - } - flushCommand() - return out -} - -func isDigits(s string) bool { - if s == "" { - return false - } - for _, r := range s { - if r < '0' || r > '9' { - return false - } - } - return true -} - -// substitutions are the command lines a quoted word runs in a shell of its own: `$(…)` and `…`. -func substitutions(word string) []string { - var out []string - for { - i := strings.Index(word, "$(") - if i < 0 { - break - } - rest := word[i+2:] - depth, end := 1, len(rest) - for j, c := range rest { - if c == '(' { - depth++ - } else if c == ')' { - depth-- - if depth == 0 { - end = j - break - } - } - } - out = append(out, rest[:end]) - if end >= len(rest) { - break - } - word = rest[end+1:] - } - parts := strings.Split(word, "`") - for i := 1; i < len(parts); i += 2 { - out = append(out, parts[i]) - } - return out -} diff --git a/modules/claude-code/cmd/claude-code/guard_run.go b/modules/claude-code/cmd/claude-code/guard_run.go deleted file mode 100644 index c135271a6..000000000 --- a/modules/claude-code/cmd/claude-code/guard_run.go +++ /dev/null @@ -1,315 +0,0 @@ -package main - -// The guard as the hook runs it (novox/hq ADR 0245): `claude-code guard `, the tool call on -// standard input, exit 2 with the reason on standard error to refuse — the agent reads it — and 0 to let it be. -// -// **The operator's override.** `MESH_GUARD_OVERRIDE=` lets one session through a refusal — never the -// refusal of a command naming the override itself — and only: -// -// - **from the session's environment as it was started**: read from /proc//environ of the agent's own -// process, which is fixed at exec. A command's `export`, an `env` key in a settings file, a variable the -// session sets for its tools — none of them reaches it. A nested session the agent starts with the -// variable is refused before it starts: the command names the override; -// - **recorded**: every override is a line in the module's guard.log — or, where the agent runs as an account -// of its own, in the machine's journal (novox/hq ADR 0266) — with why, the command and the machine; an -// override that cannot be recorded is not honoured. Refusals are recorded the same way. -// -// A guard that fails — a fault in this code — exits 1, which the agent shows and does not block on: a guard -// that refused every command would stop the session the operator needs to repair it. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net" - "os" - "os/exec" - "os/user" - "path/filepath" - "strconv" - "strings" - "time" -) - -// procRoot and parentPID are where the session's process is found; a test points them at its own. -var ( - procRoot = "/proc" - parentPID = os.Getppid -) - -// GuardLogMax is the size the guard's record grows to before it is kept once as guard.log.1. -const GuardLogMax = 1 << 20 - -// GuardEntry is one line of the guard's record. -type GuardEntry struct { - At string `json:"at"` - Node string `json:"node,omitempty"` - Decision string `json:"decision"` // refused | overridden - Rule string `json:"rule"` - Machine string `json:"machine,omitempty"` - Tool string `json:"tool"` - Command string `json:"command"` - Why string `json:"why,omitempty"` - // Tools are the tools the refusal named instead. - Tools []string `json:"tools,omitempty"` - Session string `json:"session,omitempty"` -} - -// JournalRecord is the guard's record where the agent runs as an account of its own (novox/hq ADR 0266): the -// session's account cannot enter the module's state, and must not be able to rewrite what it was refused, so -// each line goes to the machine's journal, which the account may add to and not change. The record's -// location is then this prefix and the journal's identifier. -const JournalRecord = "journal:" - -// GuardJournalID is the identifier the guard's lines carry in the journal. -const GuardJournalID = "mesh-claude-code-guard" - -// journalSocket is where the journal takes a line; a test points it at its own. -var journalSocket = "/run/systemd/journal/socket" - -// RecordGuard appends one line to the record. -func RecordGuard(path string, e GuardEntry) error { - if path == "" { - return fmt.Errorf("no record is kept here") - } - if id, ok := strings.CutPrefix(path, JournalRecord); ok { - return recordInJournal(id, e) - } - if info, err := os.Stat(path); err == nil && info.Size() > GuardLogMax { - _ = os.Rename(path, path+".1") - } - f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) - if err != nil { - return err - } - raw, _ := json.Marshal(e) - if _, err := f.Write(append(raw, '\n')); err != nil { - f.Close() - return err - } - return f.Close() -} - -// recordInJournal says one line to the journal by its native protocol: the entry as JSON in MESSAGE, one line, -// so nothing in a command can add a field of its own. -func recordInJournal(id string, e GuardEntry) error { - raw, err := json.Marshal(e) - if err != nil { - return err - } - conn, err := net.Dial("unixgram", journalSocket) - if err != nil { - return fmt.Errorf("the journal cannot be reached: %w", err) - } - defer conn.Close() - _, err = conn.Write([]byte("SYSLOG_IDENTIFIER=" + id + "\nPRIORITY=5\nMESSAGE=" + string(raw) + "\n")) - return err -} - -// readJournal is the journal's last lines of the guard's record, read as root through the runtime account's -// sudo where this process is not root: what other accounts said is not the runtime account's to read. As JSON, -// with the field the journal itself sets for the program that wrote the line (_EXE), which no writer chooses — -// and matched on it in the query itself, so lines another program wrote under the guard's identifier cannot -// push the guard's own past the last ones read. -var readJournal = func(id string, last int) ([]byte, error) { - args := []string{"journalctl", "-q", "--no-pager", "-o", "json", "--output-fields=MESSAGE,_EXE", "-t", id, - "_EXE=" + HelperPath(), "-n", strconv.Itoa(last)} - if os.Geteuid() != 0 { - args = append([]string{"sudo", "-n"}, args...) - } - cmd := exec.Command(args[0], args[1:]...) - cmd.Env = append(os.Environ(), "LC_ALL=C", "LANG=C") - return cmd.Output() -} - -// guardsOwnLines keeps, of the journal's JSON lines, the messages the guard's own binary wrote (novox/hq ADR -// 0266). The agent's account may add to the journal under any identifier — `logger -t` — and the journal -// says which program wrote each line; a line another program wrote under the guard's identifier is not the -// guard's record. The agent can still run the guard's binary itself, so the record is the guard's words, not -// proof that each refusal happened in a session: what it cannot do is remove one. -func guardsOwnLines(raw []byte, exe string) []byte { - var out []byte - for _, line := range bytes.Split(raw, []byte("\n")) { - var f struct { - Message any `json:"MESSAGE"` - Exe string `json:"_EXE"` - } - if json.Unmarshal(line, &f) != nil || f.Exe != exe { - continue - } - if m, ok := f.Message.(string); ok { - out = append(append(out, m...), '\n') - } - } - return out -} - -// ReadGuardLog is the record's last lines, newest last. -func ReadGuardLog(path string, last int) []GuardEntry { - read := os.ReadFile - if id, ok := strings.CutPrefix(path, JournalRecord); ok { - read = func(string) ([]byte, error) { - raw, err := readJournal(id, last) - return guardsOwnLines(raw, HelperPath()), err - } - } - raw, err := read(path) - if err != nil { - return []GuardEntry{} - } - lines := strings.Split(strings.TrimSpace(string(raw)), "\n") - if len(lines) > last { - lines = lines[len(lines)-last:] - } - out := []GuardEntry{} - for _, l := range lines { - var e GuardEntry - if json.Unmarshal([]byte(l), &e) == nil { - out = append(out, e) - } - } - return out -} - -// sshDashG reads a destination as ssh does: `ssh -G` prints the configuration it would use and connects -// to nothing, so an alias, a HostName and a ProxyJump in ~/.ssh/config are what is judged. -func sshDashG(options []string, destination string) (host, user string, jumps []string) { - if _, err := exec.LookPath("ssh"); err != nil { - return "", "", nil - } - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - args := append([]string{"-G"}, options...) - args = append(args, "--", destination) - out, err := exec.CommandContext(ctx, "ssh", args...).Output() - if err != nil { - return "", "", nil - } - for _, line := range strings.Split(string(out), "\n") { - k, v, ok := strings.Cut(strings.TrimSpace(line), " ") - if !ok { - continue - } - switch k { - case "hostname": - host = strings.ToLower(v) - case "user": - user = v - case "proxyjump": - if v != "none" { - jumps = append(jumps, strings.Split(v, ",")...) - } - } - } - return host, user, jumps -} - -func quickLookup(name string) []string { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - addrs, _ := net.DefaultResolver.LookupHost(ctx, name) - return addrs -} - -// sessionEnvironment is the environment the agent's own process was started with: the nearest ancestor -// that is the agent, read from what the kernel kept at its exec. -func sessionEnvironment(proc string, pid int) map[string]string { - for i := 0; i < 32 && pid > 1; i++ { - cmdline, _ := os.ReadFile(filepath.Join(proc, strconv.Itoa(pid), "cmdline")) - if isAgent(cmdline) { - raw, err := os.ReadFile(filepath.Join(proc, strconv.Itoa(pid), "environ")) - if err != nil { - return nil - } - env := map[string]string{} - for _, kv := range bytes.Split(raw, []byte{0}) { - if k, v, ok := strings.Cut(string(kv), "="); ok { - env[k] = v - } - } - return env - } - stat, err := os.ReadFile(filepath.Join(proc, strconv.Itoa(pid), "stat")) - if err != nil { - return nil - } - // The parent is the fourth field, after the command's name in parentheses (which may hold spaces). - closing := bytes.LastIndexByte(stat, ')') - fields := strings.Fields(string(stat[closing+1:])) - if len(fields) < 2 { - return nil - } - pid, _ = strconv.Atoi(fields[1]) - } - return nil -} - -// isAgent says whether a process's command line is the agent's: its native binary, or its package run by node. -func isAgent(cmdline []byte) bool { - args := strings.Split(strings.TrimRight(string(cmdline), "\x00"), "\x00") - if len(args) == 0 || args[0] == "" { - return false - } - if filepath.Base(args[0]) == "claude" { - return true - } - if b := filepath.Base(args[0]); (b == "node" || b == "bun") && len(args) > 1 { - return filepath.Base(args[1]) == "claude" || strings.Contains(args[1], "@anthropic-ai/claude-code") - } - return false -} - -// currentAccount is the account the session runs as; a test sets its own. -var currentAccount = func() string { - if u, err := user.Current(); err == nil { - return u.Username - } - return "uid " + strconv.Itoa(os.Getuid()) -} - -// runGuard is the hook: the tool call in, the verdict out as the exit code. -func runGuard(dataPath string, stdin io.Reader, stderr io.Writer) (code int) { - defer func() { - if r := recover(); r != nil { - fmt.Fprintf(stderr, "the mesh's guard failed and judged nothing: %v\n", r) - code = 1 - } - }() - var in HookInput - if err := json.NewDecoder(stdin).Decode(&in); err != nil { - fmt.Fprintf(stderr, "the mesh's guard could not read the tool call: %v\n", err) - return 1 - } - var data GuardData - if raw, err := os.ReadFile(dataPath); err == nil { - _ = json.Unmarshal(raw, &data) - } - g := Guard{Data: data, SSH: sshDashG, Resolve: quickLookup} - v := g.JudgeAs(currentAccount(), in) - if !v.Refuse { - return 0 - } - command, _ := in.ToolInput["command"].(string) - if command == "" { - command, _ = in.ToolInput["file_path"].(string) - } - entry := GuardEntry{At: time.Now().UTC().Format(time.RFC3339), Node: data.Node, Decision: "refused", Rule: v.Rule, - Machine: v.Machine, Tool: in.ToolName, Command: cut(command, 400), Session: in.SessionID, Tools: v.Calls} - if v.Overridable { - if why := strings.TrimSpace(sessionEnvironment(procRoot, parentPID())[OverrideVar]); why != "" { - entry.Decision, entry.Why = "overridden", cut(why, 200) - if err := RecordGuard(data.Log, entry); err == nil { - return 0 - } else { - v.Message += fmt.Sprintf("\nThe operator's override is set, and could not be recorded (%v): an override "+ - "that is not recorded is not honoured.", err) - entry.Decision, entry.Why = "refused", "" - } - } - } - _ = RecordGuard(data.Log, entry) - fmt.Fprintln(stderr, v.Message) - return 2 -} diff --git a/modules/claude-code/cmd/claude-code/guard_test.go b/modules/claude-code/cmd/claude-code/guard_test.go deleted file mode 100644 index aedd86b78..000000000 --- a/modules/claude-code/cmd/claude-code/guard_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package main - -import ( - "bytes" - "encoding/json" - "os" - "path/filepath" - "strconv" - "strings" - "testing" - - "git.novox.be/novox/mesh-sdk/go/seatdef" -) - -// meshForTheGuard is a mesh of two machines and the verbs that replace what an agent runs over ssh, as the -// seats' contract and the modules' manifests say them. -func meshForTheGuard() GuardData { - defined := []seatdef.Definition{ - {Seat: "mesh-module-assigner", Scope: "mesh", Verbs: []seatdef.Verb{ - {Name: "assignments", Description: "Read assignments: one node's key.", Replaces: []string{"hostnamectl", "uptime"}}}}, - {Seat: "node-service-manager", Scope: "node", Verbs: []seatdef.Verb{ - {Name: "status", Description: "One unit as the service manager sees it now: its states.", Replaces: []string{"systemctl status", "systemctl is-active"}}, - {Name: "restart", Description: "Restart one unit.", Replaces: []string{"systemctl restart"}}, - {Name: "journal", Description: "The last lines of one unit's journal.", Replaces: []string{"journalctl"}}}}, - {Seat: "node-hostname", Scope: "node", Verbs: []seatdef.Verb{ - {Name: "add", Description: "Add one address and its names to the operator's lines of /etc/hosts.", Replaces: []string{"edit /etc/hosts", "HOSTALIASES"}}}}, - } - modules := []ModuleTools{{Module: "docker", On: []string{"anchor"}, Replaces: map[string][]string{"docker_logs": {"docker logs"}, "docker_list": {"docker ps"}}}, - {Module: "systemd", On: []string{"anchor", "laptop"}}} - return GuardData{Node: "laptop", Replacements: ReplacementsOf(defined, modules), Machines: []Machine{ - {Name: "anchor", Domains: []string{"anchor" + InternalSuffix, "anchor.example"}, Addresses: []string{"192.0.2.10", "10.10.0.1"}}, - {Name: "laptop", Domains: []string{"laptop" + InternalSuffix}, Addresses: []string{"10.10.0.4"}}, - }} -} - -// noSSH reads a destination from the command line alone; aliases reads one alias as ssh's configuration would. -func aliases(options []string, destination string) (string, string, []string) { - host, user := hostOf(destination) - switch host { - case "a": - return "anchor.example", "operator", nil - case "via-anchor": - return "203.0.113.5", "operator", []string{"anchor"} - case "forge": - return "git.anchor" + InternalSuffix, "git", nil - } - if user == "" { - user = "operator" - } - for i, o := range options { - if o == "-l" && i+1 < len(options) { - user = options[i+1] - } - } - return host, user, nil -} - -func guard() Guard { - return Guard{Data: meshForTheGuard(), SSH: aliases, Resolve: func(name string) []string { - if name == "nas.lan" { - return []string{"192.0.2.10"} - } - return nil - }} -} - -func bash(command string) HookInput { - return HookInput{ToolName: "Bash", ToolInput: map[string]any{"command": command}} -} - -// **ssh to a mesh machine is refused**, by every name and address it has and however the shell spells it, -// and the refusal names the verb that does the job on that machine (novox/hq ADR 0245). -func TestSSHToAMeshMachineIsRefusedNamingTheTool(t *testing.T) { - g := guard() - for command, want := range map[string]string{ - "ssh anchor journalctl -u mesh-config -n 50": "anchor/node-service-manager.journal", - "ssh anchor 'sudo journalctl -fu sshd'": "anchor/node-service-manager.journal", - "ssh -p 22 root@anchor.example systemctl status nats": "anchor/node-service-manager.status", - "ssh anchor.internal systemctl restart nats": "anchor/node-service-manager.restart", - "ssh -o StrictHostKeyChecking=no 10.10.0.1 docker ps -a": "anchor/docker.docker_list", - "ssh anchor docker logs --tail 100 nats": "anchor/docker.docker_logs", - "ssh laptop docker logs x": "anchor/docker.docker_logs", - "ssh a uptime": "mesh-module-assigner.assignments", - "cd /tmp && ssh anchor journalctl": "anchor/node-service-manager.journal", - "sudo -u root ssh anchor journalctl": "anchor/node-service-manager.journal", - "timeout 10 ssh anchor journalctl": "anchor/node-service-manager.journal", - "env LANG=C ssh anchor journalctl": "anchor/node-service-manager.journal", - "bash -c 'ssh anchor journalctl -u x'": "anchor/node-service-manager.journal", - `echo "$(ssh anchor journalctl -n 5)" | tail`: "anchor/node-service-manager.journal", - "for n in anchor laptop; do ssh $n uptime; done; ssh anchor uptime": "mesh-module-assigner.assignments", - "ssh -J anchor 203.0.113.9 journalctl": "anchor/node-service-manager.journal", - "ssh via-anchor journalctl": "anchor/node-service-manager.journal", - "ssh nas.lan journalctl": "anchor/node-service-manager.journal", - "ssh ssh://anchor:2222 journalctl": "anchor/node-service-manager.journal", - } { - v := g.Judge(bash(command)) - if !v.Refuse || v.Rule != "ssh" { - t.Errorf("%q was not refused: %+v", command, v) - continue - } - if !strings.Contains(v.Message, want) { - t.Errorf("%q: the refusal does not name %s:\n%s", command, want, v.Message) - } - } -} - -// What no tool replaces is refused all the same, saying a tool is created, never worked around; a shell -// on a machine is pointed at what the machine serves; copying a file off one is refused too. -func TestSSHWithNoToolForItSaysCreateOne(t *testing.T) { - g := guard() - for command, want := range map[string]string{ - "ssh anchor cat /var/lib/thing/state.json": "a missing tool is created in the module", - "ssh anchor": "mesh_machine anchor", - "ssh build.internal ls": "a missing tool is created", - "scp anchor:/etc/nats/nats.conf /tmp/": "mesh_machine anchor", - "rsync -av root@10.10.0.4:/srv/ ./srv/": "mesh_machine laptop", - "sftp anchor.example": "mesh_machine anchor", - "mosh anchor": "mesh_machine anchor", - "autossh -M 0 -N -L 5432:localhost:5432 anchor": "mesh_machine anchor", - } { - v := g.Judge(bash(command)) - if !v.Refuse { - t.Errorf("%q was not refused", command) - continue - } - if !strings.Contains(v.Message, want) { - t.Errorf("%q: want %q in:\n%s", command, want, v.Message) - } - } -} - -// **What is not a work-around passes**: git over ssh to the forge above all, and ssh beyond the mesh, and -// every command that merely mentions ssh or a machine. -func TestWhatIsNotAWorkAroundPasses(t *testing.T) { - g := guard() - for _, command := range []string{ - "git push -u origin feat/x", - "git clone ssh://git@git.anchor.internal:222/novox/hq.git", - "git fetch ssh://git@git.anchor.internal:222/novox/hq.git main", - `GIT_SSH_COMMAND="ssh -i ~/.ssh/forge -o IdentitiesOnly=yes" git push origin HEAD`, - "git -c core.sshCommand='ssh -p 222' pull", - "ssh -T git@git.anchor.internal -p 222", - "ssh forge", - "scp git@git.anchor.internal:novox/hq.git .", - "ssh github.com", - "ssh -T git@github.com", - "ssh user@203.0.113.7 uptime", - "ssh -V", - "ssh-keygen -t ed25519 -f ~/.ssh/x", - "ssh-add -l", - "man ssh", - "grep -r 'ssh anchor' docs/", - `git commit -m "Stop running ssh anchor journalctl"`, - "echo anchor && journalctl --user -n 5", - "cat /etc/hosts", - "getent hosts anchor.internal", - "cp /etc/hosts /tmp/hosts.copy", - "sed -n 1,5p /etc/hosts", - "curl -s http://anchor.internal:8080/health", - "go test ./...", - } { - if v := g.Judge(bash(command)); v.Refuse { - t.Errorf("%q was refused:\n%s", command, v.Message) - } - } - if v := g.Judge(HookInput{ToolName: "Read", ToolInput: map[string]any{"file_path": "/etc/hosts"}}); v.Refuse { - t.Errorf("reading /etc/hosts was refused") - } - if v := g.Judge(HookInput{ToolName: "Write", ToolInput: map[string]any{"file_path": "/tmp/hosts"}}); v.Refuse { - t.Errorf("writing a file named hosts elsewhere was refused") - } -} - -// **The local work-arounds for a mesh name are refused** with the machine's own hosts verb: writing -// /etc/hosts by any means, the agent's own Edit and Write included, and HOSTALIASES. -func TestTheLocalWorkAroundsForAMeshNameAreRefused(t *testing.T) { - g := guard() - for _, command := range []string{ - "echo '10.10.0.1 anchor' | sudo tee -a /etc/hosts", - "sudo sh -c 'echo 10.10.0.1 anchor >> /etc/hosts'", - "echo x >>/etc/hosts", - "sudo sed -i 's/old/new/' /etc/hosts", - "sudo sed -Ei.bak 's/a/b/' /etc/hosts", - "sudo vim /etc/hosts", - "sudo cp /tmp/hosts /etc/hosts", - "sudo install -m 644 hosts /etc/hosts", - "HOSTALIASES=~/.hosts curl http://anchor/", - "export HOSTALIASES=/tmp/aliases", - } { - v := g.Judge(bash(command)) - if !v.Refuse { - t.Errorf("%q was not refused", command) - continue - } - if !strings.Contains(v.Message, "laptop/node-hostname.add") { - t.Errorf("%q: the refusal does not name this machine's hosts verb:\n%s", command, v.Message) - } - } - for _, tool := range []string{"Edit", "Write", "MultiEdit"} { - v := g.Judge(HookInput{ToolName: tool, ToolInput: map[string]any{"file_path": "/etc/../etc/hosts"}}) - if !v.Refuse || !strings.Contains(v.Message, "node-hostname.add") { - t.Errorf("%s of /etc/hosts was not refused with the verb: %+v", tool, v) - } - } - // The resolver file has no verb that replaces writing it: the refusal says to create one. - v := g.Judge(bash("echo nameserver 192.0.2.53 | sudo tee /etc/resolv.conf")) - if !v.Refuse || !strings.Contains(v.Message, "a missing tool is created") { - t.Errorf("writing the resolver file: %+v", v) - } -} - -// The agent never names the operator's override, and no override lifts that refusal. -func TestACommandNamingTheOverrideIsRefused(t *testing.T) { - g := guard() - for _, command := range []string{ - "export " + OverrideVar + "=because", - OverrideVar + "=x claude -p 'ssh anchor uptime'", - "env " + OverrideVar + "=1 bash", - } { - v := g.Judge(bash(command)) - if !v.Refuse || v.Rule != "override-named" || v.Overridable { - t.Errorf("%q: %+v", command, v) - } - } -} - -// Without the mesh's answer — a controller not asked yet — the mesh's own names are still refused. -func TestWithoutTheMeshsAnswerItsNamesAreStillRefused(t *testing.T) { - g := Guard{} - if v := g.Judge(bash("ssh anchor.internal journalctl")); !v.Refuse || !strings.Contains(v.Message, "a missing tool is created") { - t.Errorf("an internal name without data: %+v", v) - } - if v := g.Judge(bash("echo x | sudo tee -a /etc/hosts")); !v.Refuse { - t.Errorf("the hosts file without data: %+v", v) - } -} - -// fakeProc lays out a process tree: the agent started with env, a shell under it, the hook under that. -func fakeProc(t *testing.T, agentEnv []string) (root string, hookParent int) { - t.Helper() - root = t.TempDir() - write := func(pid, ppid int, cmdline []string, env []string) { - dir := filepath.Join(root, strconv.Itoa(pid)) - _ = os.MkdirAll(dir, 0o755) - _ = os.WriteFile(filepath.Join(dir, "cmdline"), []byte(strings.Join(cmdline, "\x00")+"\x00"), 0o644) - _ = os.WriteFile(filepath.Join(dir, "environ"), []byte(strings.Join(env, "\x00")), 0o644) - _ = os.WriteFile(filepath.Join(dir, "stat"), []byte(strconv.Itoa(pid)+" (some (odd) name) S "+strconv.Itoa(ppid)+" 1 1"), 0o644) - } - write(100, 1, []string{"/opt/claude-code/bin/claude", "--resume"}, agentEnv) - write(200, 100, []string{"/bin/sh", "-c", "hook"}, []string{OverrideVar + "=set-by-the-session"}) - return root, 200 -} - -// **The override is the operator's, from the session as it was started, and recorded** — and a value a -// command or a setting put in the session's later environment is not it. -func TestTheOverrideIsTheOperatorsAndRecorded(t *testing.T) { - data := meshForTheGuard() - data.Log = filepath.Join(t.TempDir(), "guard.log") - path := filepath.Join(t.TempDir(), "guard.json") - raw, _ := json.Marshal(data) - _ = os.WriteFile(path, raw, 0o644) - was, wasPID := procRoot, parentPID - t.Cleanup(func() { procRoot, parentPID = was, wasPID }) - run := func(command string) (int, string) { - var stderr bytes.Buffer - in, _ := json.Marshal(bash(command)) - return runGuard(path, bytes.NewReader(in), &stderr), stderr.String() - } - - // Not set where the session started: the later shell's value is not the operator's. - root, hook := fakeProc(t, []string{"HOME=/home/operator"}) - procRoot, parentPID = root, func() int { return hook } - if code, says := run("ssh anchor journalctl"); code != 2 || !strings.Contains(says, "anchor/node-service-manager.journal") { - t.Fatalf("refused with %d: %s", code, says) - } - // Set by the operator before the session: let through, with why on record. - root, hook = fakeProc(t, []string{"HOME=/home/operator", OverrideVar + "=reading the broker's log by hand while the systemd module is down"}) - procRoot, parentPID = root, func() int { return hook } - if code, says := run("ssh anchor journalctl -u nats"); code != 0 { - t.Fatalf("the operator's override was not honoured: %d %s", code, says) - } - // Never for a command naming the override itself. - if code, _ := run("export " + OverrideVar + "=x"); code != 2 { - t.Fatalf("a command naming the override passed under it: %d", code) - } - record := ReadGuardLog(data.Log, 10) - if len(record) != 3 || record[0].Decision != "refused" || record[1].Decision != "overridden" || - !strings.Contains(record[1].Why, "systemd module is down") || record[1].Machine != "anchor" || record[2].Rule != "override-named" { - t.Fatalf("the record: %+v", record) - } - // An override that cannot be recorded is not honoured. - data.Log = filepath.Join(t.TempDir(), "no", "such", "dir", "guard.log") - raw, _ = json.Marshal(data) - _ = os.WriteFile(path, raw, 0o644) - if code, says := run("ssh anchor journalctl"); code != 2 || !strings.Contains(says, "could not be recorded") { - t.Fatalf("an override not recorded was honoured: %d %s", code, says) - } -} - -// What passes is not recorded, and a guard that cannot read the call says so and blocks nothing. -func TestTheHookExitsAsTheAgentReadsIt(t *testing.T) { - path := filepath.Join(t.TempDir(), "guard.json") - _ = os.WriteFile(path, []byte(`{}`), 0o644) - var stderr bytes.Buffer - in, _ := json.Marshal(bash("git push")) - if code := runGuard(path, bytes.NewReader(in), &stderr); code != 0 || stderr.Len() != 0 { - t.Errorf("git push: %d %q", code, stderr.String()) - } - if code := runGuard(path, strings.NewReader("not json"), &stderr); code != 1 { - t.Errorf("an unreadable call: %d", code) - } -} - -func TestTheAgentsProcessIsKnown(t *testing.T) { - for cmdline, want := range map[string]bool{ - "/opt/claude-code/bin/claude\x00--resume\x00": true, - "claude\x00": true, - "node\x00/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js\x00": true, - "/usr/bin/node\x00/home/x/.local/bin/claude\x00": true, - "/bin/zsh\x00": false, - "node\x00server.js\x00": false, - "/usr/bin/claude-code-tools\x00": false, - } { - if isAgent([]byte(cmdline)) != want { - t.Errorf("%q: want %v", cmdline, want) - } - } -} diff --git a/modules/claude-code/cmd/claude-code/homefs.go b/modules/claude-code/cmd/claude-code/homefs.go index 3bde64e76..7d6ddec59 100644 --- a/modules/claude-code/cmd/claude-code/homefs.go +++ b/modules/claude-code/cmd/claude-code/homefs.go @@ -63,7 +63,7 @@ func FilesFor(p Paths) *Files { return &Files{Home: filepath.Clean(p.Home), Account: p.Agent, Helper: &Helper{Account: p.Agent, Exe: HelperPath()}} } -// HelperPath is the helper's binary: the guard's copy of this module's binary in the plugin, root's and +// HelperPath is the helper's binary: the plugin's copy of this module's binary in the plugin, root's and // readable by every account, so the agent's account runs exactly what the mesh placed. func HelperPath() string { return filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir, "guard") diff --git a/modules/claude-code/cmd/claude-code/insteadof.go b/modules/claude-code/cmd/claude-code/insteadof.go index 98491b0b7..7f4728c28 100644 --- a/modules/claude-code/cmd/claude-code/insteadof.go +++ b/modules/claude-code/cmd/claude-code/insteadof.go @@ -4,12 +4,10 @@ package main // address, not this shell command — generated on every render from what each seat verb and module tool // says it replaces, so it cannot drift from the tools the mesh has. // -// Short: a row per seat or module, its top what this machine's agent reached round most — the tools the -// guard named most often in its record. +// Short: a row per seat or module, the machines' seats first. import ( "fmt" - "sort" "strings" ) @@ -31,17 +29,15 @@ func code(s string) string { return "`" + strings.ReplaceAll(s, "`", "'") + "`" // insteadGroup is one row: a seat or a module, and its verbs that replace a command. type insteadGroup struct { - prefix string // `/node-service-manager.` or `mesh-controller.` - verbs []Replacement - refused int + prefix string // `/node-service-manager.` or `mesh-controller.` + verbs []Replacement } // InsteadOf is the section, or "" when the mesh said nothing replaces anything — an older controller, // or one not yet asked. // // One row per seat or module, every verb of it that replaces a command in the row, so a verb is never cut -// for being late in its seat's list; the rows the guard here named most come first, then the machines' -// seats, the modules' tools and the mesh's own seats in the records' order. +// for being late in its seat's list; the machines' seats first, the modules' tools and the mesh's own seats in the records' order. func InsteadOf(m *MeshTools) string { if m == nil || len(m.Replacements) == 0 { return "" @@ -64,13 +60,8 @@ func InsteadOf(m *MeshTools) string { groups = append(groups, g) } g.verbs = append(g.verbs, r) - g.refused += m.Refused[r.Address] } } - sort.SliceStable(groups, func(i, j int) bool { return groups[i].refused > groups[j].refused }) - for _, g := range groups { - sort.SliceStable(g.verbs, func(i, j int) bool { return m.Refused[g.verbs[i].Address] > m.Refused[g.verbs[j].Address] }) - } more := 0 if len(groups) > InsteadOfRows { more = len(groups) - InsteadOfRows @@ -97,7 +88,15 @@ func InsteadOf(m *MeshTools) string { fmt.Fprintf(&b, "\n%d more seats and modules: `mesh_search` with the command finds the tool for it.\n", more) } b.WriteString("\n- **Never `ssh` to a mesh machine**, and never edit `/etc/hosts` or set `HOSTALIASES` for a mesh\n" + - " name: the guard on this session's shell refuses it and names the tool. Where no tool covers what you\n" + + " name: call the tool the table names instead. Where no tool covers what you\n" + " need, none is worked around: say so, and the tool is created in the module that owns it, on its seat.\n") return b.String() } + +func cut(s string, n int) string { + s = strings.Join(strings.Fields(s), " ") + if r := []rune(s); len(r) > n { + return string(r[:n-1]) + "…" + } + return s +} diff --git a/modules/claude-code/cmd/claude-code/insteadof_test.go b/modules/claude-code/cmd/claude-code/insteadof_test.go index 6901578a4..87f461432 100644 --- a/modules/claude-code/cmd/claude-code/insteadof_test.go +++ b/modules/claude-code/cmd/claude-code/insteadof_test.go @@ -192,14 +192,11 @@ func TestTheInsteadOfTableIsGeneratedFromTheRecords(t *testing.T) { strings.Index(table, "docker.") > strings.Index(table, "`mesh-module-assigner.`") { t.Errorf("not the machines' seats, then modules, then the mesh's:\n%s", table) } - // What the guard here named most comes first: its row, and in its row its verb. - m.Refused = map[string]int{"node-service-manager.journal": 3, "mesh-module-assigner.assignments": 1} - ranked := InsteadOf(&m) - if !strings.Contains(ranked, "| `/node-service-manager.` | `journal` — `journalctl` · `status`") || - strings.Index(ranked, "`mesh-module-assigner.`") > strings.Index(ranked, "`/docker.`") { - t.Errorf("not ranked by the guard's record:\n%s", ranked) + // No guard on the session's shell: the rule is the session's own, and the text claims no guard (the operator, + // 2026-11-20). + if strings.Contains(table, "guard") || !strings.Contains(table, "call the tool the table names instead") { + t.Errorf("the rule names a guard, or not the tool to call:\n%s", table) } - m.Refused = nil if InsteadOf(nil) != "" || InsteadOf(&MeshTools{}) != "" { t.Error("a table from nothing") } @@ -237,10 +234,6 @@ func TestTheMeshsToolsAreKeptOnlyWhenTheyChange(t *testing.T) { if !KeepMeshTools(p, m) || len(ReadMeshTools(p).Machines) != 1 { t.Fatal("a changed answer was not kept") } - d := GuardDataOf(Paths{State: p.State, Node: "laptop"}, ReadMeshTools(p)) - if d.Node != "laptop" || len(d.Replacements) != 4 || !strings.HasSuffix(d.Log, "guard.log") { - t.Errorf("the guard's data: %+v", d) - } } // Where a module runs is read from the seat mesh-module-assigner's assignments (issue 1126 B13), never the controller's answer. diff --git a/modules/claude-code/cmd/claude-code/main.go b/modules/claude-code/cmd/claude-code/main.go index c6736cba8..3ed701bb5 100644 --- a/modules/claude-code/cmd/claude-code/main.go +++ b/modules/claude-code/cmd/claude-code/main.go @@ -339,7 +339,7 @@ func tools(p Paths, servers ServerState, view *ServerView, config ConfigState, c Description: "Claude Code on this machine as the mesh configured it: the licence it holds and when its token expires, what it reports holding, the managed files, the MCP servers registered here. Fingerprints only, never a token.", Run: func(map[string]any) (any, error) { return status(p), nil }}, {Name: "claude_code_render", - Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here — after reading the bus again for what each tool replaces and which machines the mesh has (the instructions' table and the shell's guard).", + Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here — after reading the bus again for what each tool replaces and which machines the mesh has (the instructions' table).", Run: func(map[string]any) (any, error) { answer := map[string]any{} if m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats(), lookup); err != nil { @@ -351,16 +351,6 @@ func tools(p Paths, servers ServerState, view *ServerView, config ConfigState, c answer["rendered"] = out return answer, err }}, - {Name: "claude_code_guard", - Description: "The guard on the agent's shell on this machine (novox/hq ADR 0245): what it refuses — ssh to a mesh machine, writing /etc/hosts or /etc/resolv.conf, HOSTALIASES — the machines and the replaced commands it judges with, the \"instead of\" table rendered into the agent's instructions, and its record of what it refused and what the operator's override let through, newest last.", - Input: map[string]any{"last": map[string]any{"type": "integer", "description": "how many lines of the record (default 50)"}}, - Run: func(a map[string]any) (any, error) { - last := 50 - if n, ok := a["last"].(float64); ok && n > 0 { - last = int(n) - } - return GuardStatus(p, last), nil - }}, {Name: "claude_code_pull", Description: "Ask the licence manager which licence this node holds and the vault for its access token now, and apply it, rather than waiting for its binding or the token to change.", Run: func(map[string]any) (any, error) { return Pull(p, ask, writeManaged) }}, @@ -452,10 +442,6 @@ func persist(what string, attempt func() error, done func(refusals int)) { } func main() { - // The guard on the agent's shell (novox/hq ADR 0245): this binary, run by the agent's hook. - if len(os.Args) == 3 && os.Args[1] == "guard" { - os.Exit(runGuard(os.Args[2], os.Stdin, os.Stderr)) - } // The plugin's SessionStart hook (novox/hq ADR 0489 §1, issue 1744): names the session's id and its open waits. if len(os.Args) == 3 && os.Args[1] == "session-start" { os.Exit(runSessionStart(os.Args[2], os.Stdin, os.Stdout)) diff --git a/modules/claude-code/cmd/claude-code/mesh.go b/modules/claude-code/cmd/claude-code/mesh.go index e8cd63359..639ccb75a 100644 --- a/modules/claude-code/cmd/claude-code/mesh.go +++ b/modules/claude-code/cmd/claude-code/mesh.go @@ -1,7 +1,6 @@ package main -// What the mesh says about its own tools and machines, as the agent's instructions and the guard on its -// shell need it (novox/hq ADR 0245): every seat verb and module tool that says what shell command it +// What the mesh says about its own tools and machines, as the agent's instructions need it (novox/hq ADR 0245): every seat verb and module tool that says what shell command it // replaces, and the mesh's machines by every name and address a session could reach one by. // // Read from the bus at start and every few minutes (issue 1126 B13; the controller that answered this before is @@ -9,7 +8,7 @@ package main // own tools from the manifests the indexer keeps (`mesh-delivery-indexer.modules` and `.manifests`), and the // machines and where each module runs from the seat mesh-module-assigner's `assignments`. Kept in the module's state so // a render never waits for the bus, and rendered whenever it changes. Nothing here is written by hand: a verb -// that gains a `replaces` is in the next render's table and the guard's next refusal. +// that gains a `replaces` is in the next render's table. import ( "context" @@ -58,20 +57,6 @@ type MeshTools struct { Machines []Machine `json:"machines"` // Asked is when the bus was last read whole. Asked string `json:"asked,omitempty"` - // Refused is how often the guard here named each tool instead of a work-around, from its record: the - // table's order. Never kept — read from the record at each render. - Refused map[string]int `json:"-"` -} - -// RefusedCounts are how often the guard's record named each tool, over its last lines. -func RefusedCounts(log string) map[string]int { - out := map[string]int{} - for _, e := range ReadGuardLog(log, 2000) { - for _, t := range e.Tools { - out[t]++ - } - } - return out } // InternalSuffix is the mesh's own names' domain: every machine and service is `.internal` @@ -295,22 +280,9 @@ func KeepMeshTools(p Paths, m MeshTools) bool { return os.Rename(tmp, p.meshTools()) == nil } -// GuardDataOf is what the guard judges with on this machine. -func GuardDataOf(p Paths, m *MeshTools) GuardData { - d := GuardData{Node: p.Node, Log: filepath.Join(p.State, "guard.log"), Machines: []Machine{}, Replacements: []Replacement{}} - if p.Confined() { - // The session's account cannot write the module's state, and must not rewrite its own record (ADR 0266). - d.Agent, d.Log = p.Agent, JournalRecord+GuardJournalID - } - if m != nil { - d.Machines, d.Replacements = m.Machines, m.Replacements - } - return d -} - -// guardFiles is the guard to place: this module's own executable and what it judges with. None where the +// hookFiles is what the plugin's hooks run: this module's own executable and the waits directory. None where the // executable cannot be named — then no hook is written, rather than one that cannot run. -func guardFiles(p Paths, m *MeshTools) *GuardFiles { +func hookFiles(p Paths) *HookFiles { exe, err := os.Executable() if err != nil { return nil @@ -318,7 +290,7 @@ func guardFiles(p Paths, m *MeshTools) *GuardFiles { if resolved, err := filepath.EvalSymlinks(exe); err == nil { exe = resolved } - return &GuardFiles{Exe: exe, Data: GuardDataOf(p, m), WaitsDir: WaitsDirPath(p)} + return &HookFiles{Exe: exe, WaitsDir: WaitsDirPath(p)} } // MeshToolsEvery is how often the machines' addresses are resolved again; the tools and the assignments are read again @@ -361,37 +333,6 @@ func refreshMeshTools(p Paths) { } } -// GuardStatus is what claude_code_guard answers. -func GuardStatus(p Paths, last int) map[string]any { - m := ReadMeshTools(p) - d := GuardDataOf(p, m) - asked := "never: the bus has not been read whole yet" - if m != nil { - asked = m.Asked - } - return map[string]any{ - "refuses": []string{ - "ssh, scp, sftp, rsync, mosh or autossh to a mesh machine: its name, a name under its domains, any *" + InternalSuffix + - " name or one of its addresses, read as ssh reads it (ssh -G); a jump through one too. An ssh login as `" + - ForgeUser + "` is the forge's account and passes", - "writing /etc/hosts or /etc/resolv.conf, by the shell or the agent's Edit and Write", - "HOSTALIASES, named anywhere in a command", - "any command naming " + OverrideVar, - "where the machine names an agent account of its own (novox/hq ADR 0266): every command and file edit of a " + - "session that does not run as it, whatever it is, and no override lifts it", - }, - "agent_account": map[bool]string{true: p.Agent, false: "none of its own: agents run as the operator's account"}[p.Confined()], - "override": OverrideVar + "=, set in the operator's own shell before the session starts; read from the session's " + - "environment as it was started, recorded with why, and not honoured when it cannot be recorded", - "hook": GuardCommand(), - "asked": asked, - "machines": d.Machines, - "replacements": d.Replacements, - "instead_of": InsteadOf(m), - "record": ReadGuardLog(d.Log, last), - } -} - // seatList is the seat list this module holds: the definitions of the seats, read from the seat mesh-catalog and // followed on its events (novox/hq ADR 0635 §1, ADR 0636), the foundation's bootstrapped ones until it answers. var seatList *seatlist.Reader diff --git a/modules/claude-code/cmd/claude-code/node.go b/modules/claude-code/cmd/claude-code/node.go index 011ebb8c8..c5e1e858f 100644 --- a/modules/claude-code/cmd/claude-code/node.go +++ b/modules/claude-code/cmd/claude-code/node.go @@ -84,8 +84,8 @@ func PathsFrom(env func(string) string) (Paths, bool) { Agent: env("MESH_AGENT_ACCOUNT"), Operator: env("MESH_OPERATOR_ACCOUNT"), AgentHome: env("MESH_AGENT_HOME"), OperatorHome: env("MESH_OPERATOR_HOME")} if (p.Home == "") != (p.Agent == "") { - // Half of the agent's account is not "the operator's": taken so, the agent's account rule of the guard - // would be off and its home never written, and nothing would say so. Not launched, said (main). + // Half of the agent's account is not "the operator's": taken so, the agent's + // home would never be written, and nothing would say so. Not launched, said (main). return p, false } if p.Home == "" { @@ -256,11 +256,8 @@ func RenderNow(p Paths, write WriteManaged) ([]string, error) { config.Approved = ApprovedHere(approved, p.Node) } mesh := ReadMeshTools(p) - if mesh != nil { - mesh.Refused = RefusedCounts(GuardDataOf(p, mesh).Log) - } files := RenderWithMesh(facts, settings, binding, p.helperCommand(), Registered(p), config, mesh) - tree, _ := json.Marshal(MarketplaceWith(config, guardFiles(p, mesh))) + tree, _ := json.Marshal(MarketplaceWith(config, hookFiles(p))) files[MarketplaceDir+"/"] = string(tree) names := make([]string, 0, len(files)) for n := range files { diff --git a/modules/claude-code/cmd/claude-code/session_start_test.go b/modules/claude-code/cmd/claude-code/session_start_test.go index a10827095..4edcead14 100644 --- a/modules/claude-code/cmd/claude-code/session_start_test.go +++ b/modules/claude-code/cmd/claude-code/session_start_test.go @@ -114,7 +114,7 @@ func TestSessionStartRejectsAnUnsafeSessionID(t *testing.T) { } // 1744/AC4 is checked together with 1743/AC7 in terminal_only_test.go's -// TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook. +// TestThePluginsOnlyHooksAreTheSessionStartHookAndTheStopHook. // ADR 0490 §2: every session start lists every name on this node with an open wait, from the node-wide // index, with the exact adopt call to make if it is yours — read directly, never by calling back into this diff --git a/modules/claude-code/cmd/claude-code/stop_test.go b/modules/claude-code/cmd/claude-code/stop_test.go index 11ead0cf0..ef97930c0 100644 --- a/modules/claude-code/cmd/claude-code/stop_test.go +++ b/modules/claude-code/cmd/claude-code/stop_test.go @@ -320,9 +320,9 @@ func TestWaitBlocksStopAdvisesMeshWaitOnItsEventOtherwiseAWatcher(t *testing.T) } } -// 1743/AC7's rendering half (hooks.json holds the guard's PreToolUse entry and the Stop entry) is checked +// 1743/AC7's rendering half (hooks.json holds the Stop entry) is checked // together with 1744/AC4 in terminal_only_test.go's -// TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook. claude_code_hook_register still +// TestThePluginsOnlyHooksAreTheSessionStartHookAndTheStopHook. claude_code_hook_register still // refuses a Stop hook (or any other) at every scope. func TestHookRegisterStillRefusesEveryHook(t *testing.T) { p, _ := node(t, "laptop") diff --git a/modules/claude-code/cmd/claude-code/terminal_only_test.go b/modules/claude-code/cmd/claude-code/terminal_only_test.go index 5c41587b6..b4618c5ce 100644 --- a/modules/claude-code/cmd/claude-code/terminal_only_test.go +++ b/modules/claude-code/cmd/claude-code/terminal_only_test.go @@ -261,12 +261,13 @@ func TestTheOperatorsManagedSettingsAreWhatSessionsObey(t *testing.T) { } } -// The plugin's only hooks are the guard, the session-start hook and the Stop hook (novox/hq ADR 0245, ADR -// 0489) — never a hook a registration named, whatever the configuration given holds (novox/hq issue 340). -func TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook(t *testing.T) { +// The plugin's only hooks are the session-start hook and the Stop hook (novox/hq ADR 0489) — no guard on the +// shell (the operator, 2026-11-20), and never a hook a registration named, whatever the configuration given holds +// (novox/hq issue 340). +func TestThePluginsOnlyHooksAreTheSessionStartHookAndTheStopHook(t *testing.T) { c := Config{Mesh: []Item{{Kind: KindHook, Name: "planted", Scope: ScopeMesh, Event: "PreToolUse", Matcher: "Bash", Command: "${HOOK_DIR}/x.sh", Files: map[string]string{"x.sh": "#!/bin/sh\n"}}}} - plugin := MarketplaceWith(c, &GuardFiles{Exe: "/bin/true", WaitsDir: "/home/agent/.claude/nox-mesh/waits"}) + plugin := MarketplaceWith(c, &HookFiles{Exe: "/bin/true", WaitsDir: "/home/agent/.claude/nox-mesh/waits"}) root := "plugins/" + Plugin + "/" var hooks struct { Hooks map[string][]struct { @@ -279,9 +280,14 @@ func TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook(t *test if err := json.Unmarshal([]byte(plugin[root+"hooks/hooks.json"].Content), &hooks); err != nil { t.Fatal(err) } - if len(hooks.Hooks) != 3 || len(hooks.Hooks["PreToolUse"]) != 1 || hooks.Hooks["PreToolUse"][0].Matcher != GuardMatcher || - hooks.Hooks["PreToolUse"][0].Hooks[0].Command != GuardCommand() { - t.Fatalf("the guard's hook: %s", plugin[root+"hooks/hooks.json"].Content) + if len(hooks.Hooks) != 2 || hooks.Hooks["PreToolUse"] != nil { + t.Fatalf("a hook beside the session-start and Stop hooks: %s", plugin[root+"hooks/hooks.json"].Content) + } + if plugin[root+GuardDir+"/guard"].From != "/bin/true" { + t.Fatalf("the binary the hooks run is not placed: %+v", plugin[root+GuardDir+"/guard"]) + } + if _, ok := plugin[root+GuardDir+"/guard.json"]; ok { + t.Fatal("the guard's data is placed") } if len(hooks.Hooks["SessionStart"]) != 1 || hooks.Hooks["SessionStart"][0].Matcher != "startup|resume|clear|compact" || hooks.Hooks["SessionStart"][0].Hooks[0].Command != SessionStartCommand("/home/agent/.claude/nox-mesh/waits") { diff --git a/modules/claude-code/cmd/claude-code/waits.go b/modules/claude-code/cmd/claude-code/waits.go index 3929fc2ae..f3699dec4 100644 --- a/modules/claude-code/cmd/claude-code/waits.go +++ b/modules/claude-code/cmd/claude-code/waits.go @@ -20,7 +20,7 @@ package main // Every file lives under the agent's home (the manifest's `agent-home` resource), which this process — // launched as the operator's account (novox/hq ADR 0193) — cannot itself write when the node names an agent // account of its own (novox/hq ADR 0266): every write below goes through `fsys` (homefs.go), which already -// carries such a write through the sudo helper the guard's binary also serves, exactly as grant.go's +// carries such a write through the sudo helper this module's binary serves, exactly as grant.go's // WriteCredentials does for the agent's own credentials file. Where the node has no agent account of its // own, fsys is the plain filesystem and the write reaches the operator's own home directly. diff --git a/modules/claude-code/files/claude-agent b/modules/claude-code/files/claude-agent index e3d330f2b..0281cdb39 100755 --- a/modules/claude-code/files/claude-agent +++ b/modules/claude-code/files/claude-agent @@ -5,9 +5,5 @@ agent='${machine:agent-account}' if [ "$(id -un)" = "$agent" ]; then exec claude "$@" fi -# Another account, the operator's, becomes the agent's through its own sudo: the person is the authority. The -# operator's override of the guard travels only when it is set in this shell, as it would reach claude. -if [ -n "$MESH_GUARD_OVERRIDE" ]; then - exec sudo -iu "$agent" env MESH_GUARD_OVERRIDE="$MESH_GUARD_OVERRIDE" claude "$@" -fi +# Another account, the operator's, becomes the agent's through its own sudo: the person is the authority. exec sudo -iu "$agent" claude "$@" diff --git a/modules/claude-code/module.json b/modules/claude-code/module.json index 882b366ab..7d598df57 100644 --- a/modules/claude-code/module.json +++ b/modules/claude-code/module.json @@ -82,7 +82,6 @@ "tools": [ "claude_code_status", "claude_code_render", - "claude_code_guard", "claude_code_pull", "claude_code_grant", "claude_code_add_api_key", -- 2.54.0 From 1ae83499ba6ae27ec3d4b2ac0ca1c4e36d5c4a27 Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 20 Nov 2026 13:15:52 +0100 Subject: [PATCH 2/2] claude-code: drop the machines data only the guard read With the guard gone nothing reads the machines' names, domains and addresses: remove Machine, the name lookup and the ten-minute timer that resolved them again, so the tools' table is read only when a followed state changes. Also remove the now unused cut helper. --- .../claude-code/cmd/claude-code/insteadof.go | 8 -- .../cmd/claude-code/insteadof_test.go | 34 +++----- modules/claude-code/cmd/claude-code/main.go | 4 +- modules/claude-code/cmd/claude-code/mesh.go | 77 ++++--------------- 4 files changed, 28 insertions(+), 95 deletions(-) diff --git a/modules/claude-code/cmd/claude-code/insteadof.go b/modules/claude-code/cmd/claude-code/insteadof.go index 7f4728c28..98b9de7f4 100644 --- a/modules/claude-code/cmd/claude-code/insteadof.go +++ b/modules/claude-code/cmd/claude-code/insteadof.go @@ -92,11 +92,3 @@ func InsteadOf(m *MeshTools) string { " need, none is worked around: say so, and the tool is created in the module that owns it, on its seat.\n") return b.String() } - -func cut(s string, n int) string { - s = strings.Join(strings.Fields(s), " ") - if r := []rune(s); len(r) > n { - return string(r[:n-1]) + "…" - } - return s -} diff --git a/modules/claude-code/cmd/claude-code/insteadof_test.go b/modules/claude-code/cmd/claude-code/insteadof_test.go index 87f461432..2396f230e 100644 --- a/modules/claude-code/cmd/claude-code/insteadof_test.go +++ b/modules/claude-code/cmd/claude-code/insteadof_test.go @@ -99,16 +99,10 @@ func aCatalog() fakeCatalog { return f } -func resolving(name string) []string { - return map[string][]string{"anchor": {"10.10.0.1"}, "anchor.internal": {"10.10.0.1"}, "anchor.example": {"192.0.2.10"}, - "laptop": {"127.0.0.1", "10.10.0.4"}}[name] -} - // Issue 1126 B13: what the mesh says of its tools and machines is read from the bus whole, never asked of the -// controller: the seats' verbs, the placed modules' own tools, every machine with its domains and addresses — a -// loopback address never one of them. +// controller: the seats' verbs and the placed modules' own tools. func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { - m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) if err != nil { t.Fatal(err) } @@ -154,7 +148,7 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { case <-time.After(10 * time.Second): t.Fatalf("the seat list was not read: %+v", seatList.Status()) } - got, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), definedSeats(), resolving) + got, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), definedSeats()) var addrs []string for _, r := range got.Replacements { addrs = append(addrs, r.Address) @@ -164,10 +158,6 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { t.Fatalf("replacements from the bus: %v, %v", addrs, err) } }) - if len(m.Machines) != 2 || strings.Join(m.Machines[0].Domains, ",") != "anchor.internal,anchor.example" || - strings.Join(m.Machines[0].Addresses, ",") != "10.10.0.1,192.0.2.10" || strings.Join(m.Machines[1].Addresses, ",") != "10.10.0.4" { - t.Errorf("machines: %+v", m.Machines) - } if m.Replacements[3].Does != "logs" || !m.Replacements[2].NodeScoped || m.Replacements[0].NodeScoped { t.Errorf("the rows: %+v", m.Replacements) } @@ -176,7 +166,7 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { // **The table is generated, not written** (novox/hq ADR 0245): what the records say a verb replaces is a row, // the machines' seats first, and nothing is rendered where the records say nothing. func TestTheInsteadOfTableIsGeneratedFromTheRecords(t *testing.T) { - m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) table := InsteadOf(&m) for _, want := range []string{ "| `/node-service-manager.` | `status` — `systemctl status`, `systemctl is-active` · `journal` — `journalctl` |", @@ -223,15 +213,15 @@ func TestTheInsteadOfTableIsGeneratedFromTheRecords(t *testing.T) { // Asked again with the same answer, nothing is written and nothing renders. func TestTheMeshsToolsAreKeptOnlyWhenTheyChange(t *testing.T) { p := Paths{State: t.TempDir()} - m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) if !KeepMeshTools(p, m) { t.Fatal("the first answer was not kept") } if KeepMeshTools(p, m) { t.Fatal("the same answer was kept again") } - m.Machines = m.Machines[:1] - if !KeepMeshTools(p, m) || len(ReadMeshTools(p).Machines) != 1 { + m.Replacements = m.Replacements[:1] + if !KeepMeshTools(p, m) || len(ReadMeshTools(p).Replacements) != 1 { t.Fatal("a changed answer was not kept") } } @@ -270,20 +260,20 @@ func TestTheMeshIsReadFromTheOwnersFirstViews(t *testing.T) { t.Fatal(err) } } - want, err := ReadMeshToolsFrom(bus, aCatalog(), someSeats(), resolving) + want, err := ReadMeshToolsFrom(bus, aCatalog(), someSeats()) if err != nil { t.Fatal(err) } - got, err := ReadMeshToolsFrom(viewStates{r}, aCatalog(), someSeats(), resolving) + got, err := ReadMeshToolsFrom(viewStates{r}, aCatalog(), someSeats()) if err != nil || !reflect.DeepEqual(got, want) || len(got.Replacements) == 0 { t.Fatalf("from the views: %+v, %v\nfrom the state: %+v", got, err, want) } // A reader not yet answered says so, and reads nothing. // A catalog half with no first view says so, and reads no module as absent. - if _, err := ReadMeshToolsFrom(bus, fakeCatalog{notYet: errors.New("the catalog half has no first view of main yet")}, someSeats(), resolving); err == nil || !strings.Contains(err.Error(), "no first view") { + if _, err := ReadMeshToolsFrom(bus, fakeCatalog{notYet: errors.New("the catalog half has no first view of main yet")}, someSeats()); err == nil || !strings.Contains(err.Error(), "no first view") { t.Fatalf("an unanswered catalog half: %v", err) } - if _, err := ReadMeshToolsFrom(viewStates{newMeshViews()}, aCatalog(), someSeats(), resolving); err == nil || !strings.Contains(err.Error(), "no first view") { + if _, err := ReadMeshToolsFrom(viewStates{newMeshViews()}, aCatalog(), someSeats()); err == nil || !strings.Contains(err.Error(), "no first view") { t.Fatalf("an unanswered first view: %v", err) } } @@ -291,7 +281,7 @@ func TestTheMeshIsReadFromTheOwnersFirstViews(t *testing.T) { // Issue 1126 B13 AC1 (ADR 0590): over the seats the mesh defines, the rendered instructions, their table among them, // name no address of the controller, which is not placed: each job is named by the seat that owns it now. func TestTheRenderedInstructionsNameNoControllerAddress(t *testing.T) { - m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) if err != nil { t.Fatal(err) } diff --git a/modules/claude-code/cmd/claude-code/main.go b/modules/claude-code/cmd/claude-code/main.go index 3ed701bb5..ab5c5a101 100644 --- a/modules/claude-code/cmd/claude-code/main.go +++ b/modules/claude-code/cmd/claude-code/main.go @@ -339,10 +339,10 @@ func tools(p Paths, servers ServerState, view *ServerView, config ConfigState, c Description: "Claude Code on this machine as the mesh configured it: the licence it holds and when its token expires, what it reports holding, the managed files, the MCP servers registered here. Fingerprints only, never a token.", Run: func(map[string]any) (any, error) { return status(p), nil }}, {Name: "claude_code_render", - Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here — after reading the bus again for what each tool replaces and which machines the mesh has (the instructions' table).", + Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here — after reading the bus again for what each tool replaces (the instructions' table).", Run: func(map[string]any) (any, error) { answer := map[string]any{} - if m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats(), lookup); err != nil { + if m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats()); err != nil { answer["asked"] = "the bus could not be read in full (" + err.Error() + "); what was kept is rendered" } else { KeepMeshTools(p, m) diff --git a/modules/claude-code/cmd/claude-code/mesh.go b/modules/claude-code/cmd/claude-code/mesh.go index 639ccb75a..1fac6c010 100644 --- a/modules/claude-code/cmd/claude-code/mesh.go +++ b/modules/claude-code/cmd/claude-code/mesh.go @@ -1,21 +1,19 @@ package main -// What the mesh says about its own tools and machines, as the agent's instructions need it (novox/hq ADR 0245): every seat verb and module tool that says what shell command it -// replaces, and the mesh's machines by every name and address a session could reach one by. +// What the mesh says about its own tools, as the agent's instructions need it (novox/hq ADR 0245): every seat verb +// and module tool that says what shell command it replaces. // -// Read from the bus at start and every few minutes (issue 1126 B13; the controller that answered this before is +// Read from the bus at start and whenever a followed state changes (issue 1126 B13; the controller that answered this before is // not placed, novox/hq ADR 0590): the seats' verbs from the seats' contract (mesh-contracts), the modules' -// own tools from the manifests the indexer keeps (`mesh-delivery-indexer.modules` and `.manifests`), and the -// machines and where each module runs from the seat mesh-module-assigner's `assignments`. Kept in the module's state so +// own tools from the manifests the indexer keeps (`mesh-delivery-indexer.modules` and `.manifests`), and where +// each module runs from the seat mesh-module-assigner's `assignments`. Kept in the module's state so // a render never waits for the bus, and rendered whenever it changes. Nothing here is written by hand: a verb // that gains a `replaces` is in the next render's table. import ( - "context" "encoding/json" "errors" "fmt" - "net" "os" "path/filepath" "sort" @@ -44,25 +42,13 @@ type Replacement struct { On []string `json:"on,omitempty"` } -// Machine is one of the mesh's machines and the names and addresses it is reached by. -type Machine struct { - Name string `json:"name"` - Domains []string `json:"domains,omitempty"` - Addresses []string `json:"addresses,omitempty"` -} - // MeshTools is what the bus said, as kept in the module's state. type MeshTools struct { Replacements []Replacement `json:"replacements"` - Machines []Machine `json:"machines"` // Asked is when the bus was last read whole. Asked string `json:"asked,omitempty"` } -// InternalSuffix is the mesh's own names' domain: every machine and service is `.internal` -// (novox/hq ADR 0194), and a session reaches none of them by ssh. -const InternalSuffix = ".internal" - func (p Paths) meshTools() string { return filepath.Join(p.State, "mesh-tools.json") } // ReadMeshTools is what was kept, or nil. @@ -219,17 +205,8 @@ func ReplacementsOf(defined []seatdef.Definition, modules []ModuleTools) []Repla return out } -// lookup resolves one name, briefly: a name that does not resolve here is no address. -func lookup(name string) []string { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - addrs, _ := net.DefaultResolver.LookupHost(ctx, name) - return addrs -} - -// ReadMeshToolsFrom reads the bus now: the seats' verbs, the placed modules' own tools, and every node assignments names -// with its domains and addresses. A part that cannot be read is left out and said in the error; what was read is kept. -func ReadMeshToolsFrom(st States, cat CatalogHalf, defined []seatdef.Definition, resolve func(string) []string) (MeshTools, error) { +// ReadMeshToolsFrom reads the bus now: the seats' verbs and the placed modules' own tools. A part that cannot be read is left out and said in the error; what was read is kept. +func ReadMeshToolsFrom(st States, cat CatalogHalf, defined []seatdef.Definition) (MeshTools, error) { var m MeshTools placed, err := assignments(st) if err != nil { @@ -238,24 +215,6 @@ func ReadMeshToolsFrom(st States, cat CatalogHalf, defined []seatdef.Definition, } modules, merr := modulesTools(cat, runsOn(placed)) m.Replacements = ReplacementsOf(defined, modules) - for node, p := range placed { - machine := Machine{Name: node, Domains: []string{node + InternalSuffix}} - if d := strings.ToLower(strings.TrimSpace(p.Decided.PublicDomain)); d != "" { - machine.Domains = append(machine.Domains, d) - } - seen := map[string]bool{} - for _, name := range append([]string{node}, machine.Domains...) { - for _, a := range resolve(name) { - if !seen[a] && !net.ParseIP(a).IsLoopback() { - seen[a] = true - machine.Addresses = append(machine.Addresses, a) - } - } - } - sort.Strings(machine.Addresses) - m.Machines = append(m.Machines, machine) - } - sort.Slice(m.Machines, func(i, j int) bool { return m.Machines[i].Name < m.Machines[j].Name }) return m, merr } @@ -293,15 +252,10 @@ func hookFiles(p Paths) *HookFiles { return &HookFiles{Exe: exe, WaitsDir: WaitsDirPath(p)} } -// MeshToolsEvery is how often the machines' addresses are resolved again; the tools and the assignments are read again -// when their followed states change (a views event), not on this timer. -const MeshToolsEvery = 10 * time.Minute - // MeshToolsFirst is how long the first read waits for the first views to be answered. const MeshToolsFirst = 2 * time.Minute -// refreshMeshTools reads the pictures once the first views are answered, and again whenever one changes (and the -// machines' addresses every few minutes), and renders when what it said changed. +// refreshMeshTools reads the pictures once the first views are answered, and again whenever one changes, and renders when what it said changed. func refreshMeshTools(p Paths) { select { case <-meshViews.Ready(): @@ -310,25 +264,22 @@ func refreshMeshTools(p Paths) { } startSeatList(seatlist.StdioBus()) for { - m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats(), lookup) + m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats()) if err != nil { - say("reading what each tool replaces and which machines the mesh has: %v", err) + say("reading what each tool replaces: %v", err) } if (err == nil || len(m.Replacements) > 0) && KeepMeshTools(p, m) { if _, err := RenderNow(p, writeManaged); err != nil { say("rendering what the bus said of the tools: %v", err) } else { - say("the mesh's tools changed: %d replace a command, %d machines; rendered", len(m.Replacements), len(m.Machines)) + say("the mesh's tools changed: %d replace a command; rendered", len(m.Replacements)) } } + <-meshChanged + time.Sleep(2 * time.Second) // a burst of events is one read select { case <-meshChanged: - time.Sleep(2 * time.Second) // a burst of events is one read - select { - case <-meshChanged: - default: - } - case <-time.After(MeshToolsEvery): + default: } } } -- 2.54.0