openclaw-warden 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Roy Zhu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,221 @@
1
+ # OpenClaw Warden
2
+
3
+ OpenClaw Warden is a small guardrail CLI for production OpenClaw deployments. It keeps your gateway stable by validating configuration changes, versioning them with git, and running health/agent probes with automatic restart when needed.
4
+
5
+ ## Why this exists
6
+
7
+ Over 72 hours of hands-on deployment:
8
+ - Day 1: excitement + pitfalls
9
+ - Day 2: crashes + git saved the day
10
+ - Day 3: stable operation + feature expansion
11
+
12
+ OpenClaw now runs in my production environment and handles daily automation workloads. It still has sharp edges, but overall it is stable. It is not perfect, yet it is the closest open-source agent framework I have seen to "production usable."
13
+
14
+ Tools are like people: nothing is perfect. The important part is knowing the strengths and weaknesses and deciding which trade-offs you can accept. OpenClaw's strengths are strong, and its weaknesses are clear. For me, the 72 hours were worth it because it made the real-world potential of AI agents tangible.
15
+
16
+ OpenClaw Warden exists to make those trade-offs safer and easier to manage.
17
+
18
+ ## What it does
19
+
20
+ - Validates OpenClaw config using the official schema to prevent crash loops
21
+ - Stores config in a git-managed workspace and syncs it to `~/.openclaw/openclaw.json`
22
+ - Runs periodic health checks and agent probes with backoff
23
+ - Restarts the gateway and notifies the last active channel after failure
24
+
25
+ ## Layout
26
+ - `warden.config.json`: Warden configuration
27
+ - `config/openclaw.json`: managed OpenClaw config (git-tracked)
28
+ - `state/schema.json`: OpenClaw config schema (generated)
29
+ - `src/warden.js`: CLI entry
30
+
31
+ ## Initialization
32
+ `openclaw-warden init` creates `warden.config.json` in the current directory (if missing), and pulls `~/.openclaw/openclaw.json` into `./config/openclaw.json`.
33
+
34
+ **Important:** `config/openclaw.json` is always created relative to the directory containing `warden.config.json`. Put the config where you want the managed OpenClaw config to live.
35
+
36
+ ## Quick start
37
+
38
+ ```bash
39
+ # Run without cloning the repo
40
+ npx openclaw-warden init
41
+ # or
42
+ bunx openclaw-warden init
43
+
44
+ # Generate/update schema (auto-clone OpenClaw source)
45
+ npx openclaw-warden schema:update
46
+
47
+ # Validate config
48
+ npx openclaw-warden config:validate
49
+
50
+ # Watch config -> validate -> sync to ~/.openclaw/openclaw.json -> git commit
51
+ npx openclaw-warden watch
52
+
53
+ # Heartbeat loop (every 5 minutes with 30/40/50s backoff)
54
+ npx openclaw-warden heartbeat
55
+
56
+ # Watch + heartbeat
57
+ npx openclaw-warden run
58
+ ```
59
+
60
+ ## Background (daemon)
61
+ Run in the background (no foreground terminal needed):
62
+
63
+ ```bash
64
+ npx openclaw-warden daemon:start
65
+ npx openclaw-warden daemon:status
66
+ npx openclaw-warden daemon:stop
67
+ ```
68
+
69
+ Default pid/log paths:
70
+ - pid: `os.tmpdir()/openclaw-warden/warden.pid`
71
+ - log: `os.tmpdir()/openclaw-warden/warden.log`
72
+
73
+ ## System service (recommended)
74
+ If you need auto-start after reboot, install a system service.
75
+
76
+ ### Linux (systemd --user)
77
+ ```bash
78
+ openclaw-warden service:template > ~/.config/systemd/user/openclaw-warden.service
79
+ systemctl --user daemon-reload
80
+ systemctl --user enable --now openclaw-warden
81
+ ```
82
+
83
+ ### macOS (launchd)
84
+ ```bash
85
+ openclaw-warden service:template > ~/Library/LaunchAgents/ai.openclaw.warden.plist
86
+ launchctl load -w ~/Library/LaunchAgents/ai.openclaw.warden.plist
87
+ ```
88
+
89
+ ### Windows (Task Scheduler)
90
+ ```powershell
91
+ openclaw-warden service:template | Out-File -Encoding unicode $env:TEMP\openclaw-warden.xml
92
+ schtasks /Create /TN OpenClawWarden /XML $env:TEMP\openclaw-warden.xml /F
93
+ ```
94
+
95
+ > Tip: service templates assume `openclaw-warden` is on PATH (use `npm i -g openclaw-warden`).
96
+
97
+ ## Config location strategy
98
+ - Prefer `./warden.config.json` in the current directory
99
+ - If missing, fall back to the global config directory:
100
+ - macOS: `~/Library/Application Support/openclaw-warden/warden.config.json`
101
+ - Linux: `~/.config/openclaw-warden/warden.config.json`
102
+ - Windows: `%APPDATA%\openclaw-warden\warden.config.json`
103
+
104
+ `init` creates the config in the current directory by default. Use `--global` to write to the global path:
105
+
106
+ ```bash
107
+ npx openclaw-warden init --global
108
+ ```
109
+
110
+ ## Configuration (warden.config.json)
111
+
112
+ ```json
113
+ {
114
+ "paths": {
115
+ "repoConfig": "./config/openclaw.json",
116
+ "liveConfig": "~/.openclaw/openclaw.json",
117
+ "schemaFile": "./state/schema.json"
118
+ },
119
+ "schema": {
120
+ "source": "git",
121
+ "repoUrl": "https://github.com/openclaw/openclaw.git",
122
+ "ref": "main",
123
+ "checkoutDir": "./state/openclaw",
124
+ "useLocalDeps": true,
125
+ "exportCommand": "node --import tsx -e \"import { buildConfigSchema } from './src/config/schema.ts'; console.log(JSON.stringify(buildConfigSchema(), null, 2));\""
126
+ },
127
+ "git": {
128
+ "enabled": true,
129
+ "autoInit": true
130
+ },
131
+ "heartbeat": {
132
+ "intervalMinutes": 5,
133
+ "waitSeconds": [30, 40, 50],
134
+ "checkCommand": "node ./src/check-health.js",
135
+ "agentProbe": {
136
+ "enabled": true,
137
+ "fallbackAgentId": "main",
138
+ "command": "node ./src/check-agent-probe.js"
139
+ },
140
+ "notifyOnRestart": true,
141
+ "notifyCommand": "openclaw agent --agent {agentId} -m \"[warden] gateway restarted after failed health check\" --channel last --deliver",
142
+ "restartCommand": "openclaw gateway restart"
143
+ }
144
+ }
145
+ ```
146
+
147
+ ### Commands
148
+ - `config:pull` (alias: `pull`): copy live config into the repo + git commit
149
+ - `config:push` (alias: `push`): validate and sync repo config to the live path + git commit
150
+ - `config:validate` (alias: `validate`): validate repo config against schema
151
+ - `schema:update`: update schema from OpenClaw source
152
+ - `watch`: watch repo config and auto-apply on changes
153
+ - `heartbeat`: run health/agent probes loop
154
+ - `run`: watch + heartbeat
155
+
156
+ ### checkCommand / notifyCommand / restartCommand / placeholders
157
+ - `checkCommand`: health check (**exit code 0 = healthy**)
158
+ - `agentProbe`: optional agent probe after gateway health
159
+ - `notifyOnRestart`: send notification after restart
160
+ - `notifyCommand`: notification command (recommended to use `openclaw agent ... --channel last --deliver`)
161
+ - `restartCommand`: restart command
162
+
163
+ Supported placeholders:
164
+ - `{id}`: heartbeat id
165
+ - `{repoConfig}`: managed config path
166
+ - `{liveConfig}`: live config path
167
+ - `{agentId}`: default agent id from last health check
168
+ - `{sessionId}`: latest session id from sessions.json
169
+ - `{sessionKey}`: latest session key
170
+
171
+ ### Logging
172
+ - Default: `os.tmpdir()/openclaw-warden/warden.log` (stdout preserved)
173
+ - Optional: set `logging.file` to override
174
+
175
+ ### Default health check script
176
+ - `src/check-health.js` runs `openclaw gateway call health --json`, parses the last JSON object and checks `ok: true`
177
+ - Writes recent session info to `os.tmpdir()/openclaw-warden/health.json` for notify/agent probe use
178
+ - Only requires `openclaw` in PATH
179
+
180
+ ### Default agent probe script
181
+ - `src/check-agent-probe.js` reads `health.json` for `agentId` (fallback `main`), runs
182
+ `openclaw agent --agent <id> -m "healthcheck" --json --timeout 60`
183
+ and checks `status: "ok"`
184
+
185
+ ## Notes
186
+ - `schema:update` auto-clones OpenClaw source (default: main) and generates schema locally.
187
+ - By default, OpenClaw repo dependencies are not installed; warden reuses its own `node_modules` (`useLocalDeps: true`).
188
+ - All git operations only affect this repo; `~/.openclaw/` is never git-managed.
189
+
190
+ ## Acknowledgements
191
+ This project exists because OpenClaw makes production agent workflows practical. Thank you to the OpenClaw team and community for building it.
192
+
193
+ ## Release workflow
194
+
195
+ ### Versioning and changelog
196
+ This project uses `standard-version` for semantic versioning and changelog generation.
197
+
198
+ - Generate/refresh changelog only:
199
+ ```bash
200
+ npm run changelog
201
+ ```
202
+
203
+ - Create a release (bumps version, updates changelog, creates a git tag):
204
+ ```bash
205
+ npm run release
206
+ # or
207
+ npm run release:patch
208
+ npm run release:minor
209
+ npm run release:major
210
+ ```
211
+
212
+ Then push commits and tags:
213
+ ```bash
214
+ git push --follow-tags
215
+ ```
216
+
217
+ ### npm publish via GitHub Actions
218
+ Publishing is automated when a tag like `v1.2.3` is pushed.
219
+
220
+ Required secret:
221
+ - `NPM_TOKEN` (npm access token with publish permission)
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "openclaw-warden",
3
+ "version": "0.1.0",
4
+ "description": "OpenClaw config guard + heartbeat monitor",
5
+ "type": "module",
6
+ "bin": {
7
+ "openclaw-warden": "./src/warden.js"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/royisme/openclaw-warden.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/royisme/openclaw-warden/issues"
15
+ },
16
+ "homepage": "https://github.com/royisme/openclaw-warden#readme",
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "package.json"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "license": "MIT",
26
+ "scripts": {
27
+ "warden": "node ./src/warden.js",
28
+ "start": "node ./src/warden.js run",
29
+ "changelog": "standard-version --skip.bump --skip.commit --skip.tag",
30
+ "release": "standard-version",
31
+ "release:patch": "standard-version --release-as patch",
32
+ "release:minor": "standard-version --release-as minor",
33
+ "release:major": "standard-version --release-as major"
34
+ },
35
+ "dependencies": {
36
+ "ajv": "^8.17.1",
37
+ "ajv-formats": "^3.0.1",
38
+ "tsx": "^4.21.0",
39
+ "zod": "^3.24.2"
40
+ },
41
+ "devDependencies": {
42
+ "standard-version": "^9.5.0"
43
+ }
44
+ }
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ function extractJson(text) {
8
+ if (!text) return null;
9
+ const lines = text.split(/\r?\n/).filter(Boolean);
10
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
11
+ const line = lines[i].trim();
12
+ if (!line.startsWith("{")) continue;
13
+ try {
14
+ return JSON.parse(line);
15
+ } catch {
16
+ // keep searching
17
+ }
18
+ }
19
+ const lastBrace = text.lastIndexOf("{");
20
+ if (lastBrace >= 0) {
21
+ const candidate = text.slice(lastBrace).trim();
22
+ try {
23
+ return JSON.parse(candidate);
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+
31
+ function readHealthCache() {
32
+ const filePath = path.join(os.tmpdir(), "openclaw-warden", "health.json");
33
+ if (!fs.existsSync(filePath)) return null;
34
+ try {
35
+ const raw = fs.readFileSync(filePath, "utf8");
36
+ return JSON.parse(raw);
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ const cache = readHealthCache();
43
+ const agentId = cache?.agentId || "main";
44
+
45
+ const res = spawnSync(
46
+ "openclaw",
47
+ ["agent", "--agent", agentId, "-m", "healthcheck", "--json", "--timeout", "60"],
48
+ {
49
+ encoding: "utf8",
50
+ stdio: ["ignore", "pipe", "pipe"],
51
+ },
52
+ );
53
+
54
+ const stdout = res.stdout || "";
55
+ const data = extractJson(stdout);
56
+ if (data && data.status === "ok") {
57
+ process.exit(0);
58
+ }
59
+
60
+ process.exit(1);
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import fsp from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ function extractJson(text) {
9
+ if (!text) return null;
10
+ const lines = text.split(/\r?\n/).filter(Boolean);
11
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
12
+ const line = lines[i].trim();
13
+ if (!line.startsWith("{")) continue;
14
+ try {
15
+ return JSON.parse(line);
16
+ } catch {
17
+ // keep searching
18
+ }
19
+ }
20
+ const lastBrace = text.lastIndexOf("{");
21
+ if (lastBrace >= 0) {
22
+ const candidate = text.slice(lastBrace).trim();
23
+ try {
24
+ return JSON.parse(candidate);
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ return null;
30
+ }
31
+
32
+ async function readSessionId(sessionsPath, sessionKey) {
33
+ if (!sessionsPath || !sessionKey) return null;
34
+ try {
35
+ const raw = await fsp.readFile(sessionsPath, "utf8");
36
+ const data = JSON.parse(raw);
37
+ if (!data || typeof data !== "object") return null;
38
+ const entry = data[sessionKey];
39
+ if (!entry || typeof entry !== "object") return null;
40
+ return entry.sessionId || null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ async function writeHealthCache(payload) {
47
+ try {
48
+ const dir = path.join(os.tmpdir(), "openclaw-warden");
49
+ await fsp.mkdir(dir, { recursive: true });
50
+ const filePath = path.join(dir, "health.json");
51
+ await fsp.writeFile(filePath, JSON.stringify(payload, null, 2), "utf8");
52
+ } catch {
53
+ // ignore cache errors
54
+ }
55
+ }
56
+
57
+ const res = spawnSync("openclaw", ["gateway", "call", "health", "--json"], {
58
+ encoding: "utf8",
59
+ stdio: ["ignore", "pipe", "pipe"],
60
+ });
61
+
62
+ const stdout = res.stdout || "";
63
+ const data = extractJson(stdout);
64
+ if (data && data.ok === true) {
65
+ let agentId = data.defaultAgentId || null;
66
+ const recent = data.sessions?.recent?.[0];
67
+ const sessionKey = recent?.key || null;
68
+ if (
69
+ !agentId &&
70
+ typeof sessionKey === "string" &&
71
+ sessionKey.startsWith("agent:")
72
+ ) {
73
+ const parts = sessionKey.split(":");
74
+ agentId = parts[1] || null;
75
+ }
76
+ const sessionsPath = data.sessions?.path || null;
77
+ const sessionId = await readSessionId(sessionsPath, sessionKey);
78
+ await writeHealthCache({
79
+ ok: true,
80
+ agentId,
81
+ sessionKey,
82
+ sessionId,
83
+ sessionsPath,
84
+ updatedAt: Date.now(),
85
+ });
86
+ process.exit(0);
87
+ }
88
+
89
+ process.exit(1);