-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
463 lines (415 loc) · 18.1 KB
/
index.ts
File metadata and controls
463 lines (415 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/**
* systematic-claw — Systematic thinking enforcement plugin for OpenClaw.
*
* Brings Claude Code's structured methodology (TodoWrite, Plan Mode,
* verification-before-completion, hard gates) to any OpenClaw agent.
*
* Architecture: 3-layer enforcement
* Layer 1 (GUIDE): before_prompt_build — workflow detection + state injection
* Layer 2 (ENFORCE): before_tool_call — hard gates (read-before-edit, plan-before-create)
* task_tracker + plan_mode tools
* Layer 3 (AUDIT): after_tool_call — file tracking
* agent_end — completion checklist
* /systematic command — dashboard
*/
import { join } from "node:path";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { getConnection, closeConnection } from "./src/store/connection.js";
import { migrateDatabase } from "./src/store/schema.js";
import { SessionStateStore } from "./src/store/session-state.js";
import { AuditLog } from "./src/store/audit-log.js";
import { buildPromptContext, type GateVerbosity } from "./src/hooks/prompt-inject.js";
import { handleAfterToolCall } from "./src/hooks/tool-verify.js";
import { handleBeforeToolCall, type GateMode } from "./src/hooks/hard-gates.js";
import { handleAgentEnd } from "./src/hooks/completion-check.js";
import { createTaskTrackerTool } from "./src/tools/task-tracker.js";
import { createPlanModeTool } from "./src/tools/plan-mode.js";
import { createDebugTrackerTool } from "./src/tools/debug-tracker.js";
import { createQualityChecklistTool } from "./src/tools/quality-checklist.js";
import { loadDependencyMap } from "./src/tools/common.js";
import { runScaffold, buildOnboardingMessage } from "./src/scaffold.js";
// ─── Default Dangerous Commands ──────────────────────────────
// Patterns for irreversible commands that should be hard-blocked.
// Users can override via config. These are regex pattern strings.
const DEFAULT_DANGEROUS_COMMANDS: string[] = [
// Social media — irreversible public posts
"\\bbird\\s+tweet\\b",
"\\btoot\\s+(post|send)\\b",
// Email — irreversible sends
"\\bgog\\s+gmail\\s+send\\b",
"\\bhimalaya\\s+.*send\\b",
"\\bmutt\\s+-s\\b",
"\\bmail\\s+-s\\b",
"\\bsendmail\\b",
// Destructive filesystem operations
"\\brm\\s+(-[rRf]+\\s+)*(/|~|\\.\\./)", // rm -rf on root, home, or parent
"\\brm\\s+(-[rRf]+\\s+)*.*\\.openclaw/workspace", // rm on workspace files — use trash instead
"\\brm\\s+(-[rRf]+\\s+)*.*workspace-", // rm on agent workspace files
"\\bmkfs\\b",
"\\bdd\\s+of=/dev/",
// Git destructive operations
"\\bgit\\s+push\\s+.*--force\\b",
"\\bgit\\s+reset\\s+--hard\\s+origin/",
// Cloud/infra — irreversible deployments
"\\bkubectl\\s+delete\\b",
"\\bterraform\\s+destroy\\b",
"\\baws\\s+.*delete\\b",
// Payment/financial
"\\bcurl\\s+.*-X\\s+(POST|PUT|DELETE)\\s+.*pay",
];
// ─── Config Resolution ───────────────────────────────────────
type SystematicConfig = {
enabled: boolean;
gateMode: GateMode;
taskTrackerEnabled: boolean;
planModeEnabled: boolean;
completionCheckEnabled: boolean;
memoryEnforcementEnabled: boolean;
debugTrackerEnabled: boolean;
workflowDetectionEnabled: boolean;
dbPath: string;
// Phase 4: New features
dangerousCommands: string[]; // Regex patterns for irreversible commands (hard block)
bootstrapSizeWarnKB: number; // Warn when bootstrap file exceeds this size (KB)
bootstrapSizeBlockKB: number; // Block when bootstrap file exceeds this size (KB)
propagationEnabled: boolean; // Enable dependency propagation checking
dependencyMapPath: string | null; // Path to dependency map JSON (null = use RELATED_FILE_RULES only)
gateVerbosity: GateVerbosity; // Gate annotation visibility: silent (off), summary (1-line), verbose (per-gate)
workspaceRoot: string; // Workspace root path (default: ~/.openclaw/workspace)
scaffoldOnFirstRun: boolean; // Create template files on first run (default: true)
};
function resolveConfig(
raw: Record<string, unknown> | undefined,
fallbackDir: string,
): SystematicConfig {
const r = raw ?? {};
return {
enabled: r.enabled !== false, // enabled by default
gateMode: (r.gateMode === "warn" || r.gateMode === "block") ? r.gateMode : "block",
taskTrackerEnabled: r.taskTrackerEnabled !== false,
planModeEnabled: r.planModeEnabled !== false,
completionCheckEnabled: r.completionCheckEnabled !== false,
memoryEnforcementEnabled: r.memoryEnforcementEnabled !== false, // on by default
debugTrackerEnabled: r.debugTrackerEnabled !== false, // on by default
workflowDetectionEnabled: r.workflowDetectionEnabled !== false,
dbPath: (r.dbPath as string) || join(fallbackDir, "systematic-claw.db"),
// Phase 4 defaults
dangerousCommands: Array.isArray(r.dangerousCommands)
? (r.dangerousCommands as string[])
: DEFAULT_DANGEROUS_COMMANDS,
bootstrapSizeWarnKB: typeof r.bootstrapSizeWarnKB === "number" ? r.bootstrapSizeWarnKB : 28,
bootstrapSizeBlockKB: typeof r.bootstrapSizeBlockKB === "number" ? r.bootstrapSizeBlockKB : 35,
propagationEnabled: r.propagationEnabled !== false,
dependencyMapPath: typeof r.dependencyMapPath === "string" ? r.dependencyMapPath : null,
gateVerbosity: (r.gateVerbosity === "silent" || r.gateVerbosity === "summary" || r.gateVerbosity === "verbose")
? r.gateVerbosity : "summary",
workspaceRoot: typeof r.workspaceRoot === "string"
? r.workspaceRoot
: join(process.env.HOME || process.env.USERPROFILE || "/tmp", ".openclaw", "workspace"),
scaffoldOnFirstRun: r.scaffoldOnFirstRun !== false, // on by default
};
}
// ─── Tool Policy Check ───────────────────────────────────────
function checkToolPolicy(api: OpenClawPluginApi): void {
try {
const config = api.config;
// Check all agents for tool policy coverage
const agents = (config as Record<string, unknown>)?.agents as { list?: Array<{ tools?: { allow?: string[]; alsoAllow?: string[] } }> } | undefined;
if (!agents?.list) return;
const pluginToolNames = ["task_tracker", "plan_mode", "debug_tracker", "quality_checklist"];
let anyMissing = false;
for (const agent of agents.list) {
const policy = agent?.tools;
if (!policy) continue;
const allowed = [...(policy.allow ?? []), ...(policy.alsoAllow ?? [])];
const normalizedAllowed = allowed.map(t => t.toLowerCase().trim());
// Check if group:plugins or individual tool names are present
const hasGroupPlugins = normalizedAllowed.includes("group:plugins");
const hasPluginId = normalizedAllowed.includes("systematic-claw");
if (hasGroupPlugins || hasPluginId) continue;
// Check individual tools
const missing = pluginToolNames.filter(t => !normalizedAllowed.includes(t));
if (missing.length > 0) {
anyMissing = true;
}
}
if (anyMissing) {
api.logger.warn(
`[systematic-claw] ⚠️ Plugin tool'ları (task_tracker, plan_mode, debug_tracker) agent'ların tool policy'sinde bulunamadı. ` +
`Hook'lar (gate'ler, file tracking) çalışır ama tool'lar agent'a görünmez. ` +
`Düzeltme: Agent config'da tools.alsoAllow'a "group:plugins" ekleyin veya /systematic setup komutunu çalıştırın.`
);
}
} catch (err) {
// Non-critical — don't block plugin load, but log for debugging
api.logger.warn(`[systematic-claw] Tool policy check error: ${err instanceof Error ? err.message : err}`);
}
}
// ─── Plugin Definition ───────────────────────────────────────
const systematicPlugin = {
id: "systematic-claw",
name: "Systematic Engine",
description:
"Brings Claude Code's structured methodology to OpenClaw agents — " +
"task tracking, plan mode, hard gates, completion verification, and audit logging",
configSchema: {
parse(value: unknown) {
const raw =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
// Use home dir as fallback for DB path
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
return resolveConfig(raw, join(home, ".openclaw"));
},
},
register(api: OpenClawPluginApi) {
// Always resolve config through our defaults — api.pluginConfig may not include all fields
const rawConfig = api.pluginConfig && typeof api.pluginConfig === "object"
? api.pluginConfig as Record<string, unknown>
: undefined;
const resolved = resolveConfig(rawConfig, join(
process.env.HOME || process.env.USERPROFILE || "/tmp",
".openclaw",
));
if (!resolved.enabled) {
api.logger.info("[systematic-claw] Plugin disabled via config");
return;
}
// ── Tool Policy Check ────────────────────────
// Plugin tools (task_tracker, plan_mode, debug_tracker) need to be in agent's
// tool allowlist. The easiest way is adding "group:plugins" to alsoAllow.
checkToolPolicy(api);
// ── Initialize database ────────────────────────
let db: ReturnType<typeof getConnection>;
try {
db = getConnection(resolved.dbPath);
migrateDatabase(db);
api.logger.info(`[systematic-claw] Database initialized at ${resolved.dbPath}`);
} catch (error) {
api.logger.error(
`[systematic-claw] Failed to initialize database: ${error instanceof Error ? error.message : error}`
);
return;
}
const store = new SessionStateStore(db);
const auditLog = new AuditLog(db);
// ── Scaffold: First-run workspace setup ──────────
let scaffoldResult: import("./src/scaffold.js").ScaffoldResult | null = null;
if (resolved.scaffoldOnFirstRun) {
try {
scaffoldResult = runScaffold(resolved.workspaceRoot);
if (scaffoldResult.isFirstRun) {
api.logger.info(
`[systematic-claw] Scaffold: created ${scaffoldResult.created.length} files ` +
`(${scaffoldResult.created.join(", ")})`
);
}
} catch (err) {
api.logger.warn(
`[systematic-claw] Scaffold failed (non-critical): ${err instanceof Error ? err.message : err}`
);
}
}
// Load user-defined dependency map (if configured)
const dependencyMap = resolved.propagationEnabled
? loadDependencyMap(resolved.dependencyMapPath)
: new Map<string, string[]>();
// ── Layer 1: GUIDE — before_prompt_build ───────
api.on("before_prompt_build", async (event, ctx) => {
try {
// Generate onboarding message once on first prompt after scaffold
let onboardingMsg: string | undefined;
if (scaffoldResult?.isFirstRun) {
onboardingMsg = buildOnboardingMessage(scaffoldResult);
scaffoldResult = null; // Show only once
}
const result = buildPromptContext({
prompt: event.prompt,
sessionStore: store,
auditLog,
sessionKey: ctx.sessionKey,
workflowDetectionEnabled: resolved.workflowDetectionEnabled,
gateVerbosity: resolved.gateVerbosity,
onboardingMessage: onboardingMsg,
});
return result;
} catch (error) {
api.logger.warn(
`[systematic-claw] before_prompt_build error: ${error instanceof Error ? error.message : error}`
);
return undefined;
}
}, { priority: 50 });
// ── Layer 2: ENFORCE — Tools ───────────────────
if (resolved.taskTrackerEnabled) {
api.registerTool((ctx) =>
createTaskTrackerTool({
store,
auditLog,
sessionKey: ctx.sessionKey,
gateMode: resolved.gateMode,
}),
);
api.logger.info("[systematic-claw] task_tracker tool registered");
}
if (resolved.planModeEnabled) {
api.registerTool((ctx) =>
createPlanModeTool({
store,
auditLog,
sessionKey: ctx.sessionKey,
gateMode: resolved.gateMode,
dependencyMap,
}),
);
api.logger.info("[systematic-claw] plan_mode tool registered");
}
// Debug tracker — 4-phase systematic debugging protocol
if (resolved.debugTrackerEnabled) {
api.registerTool((ctx) =>
createDebugTrackerTool({
store,
auditLog,
sessionKey: ctx.sessionKey,
}),
);
api.logger.info("[systematic-claw] debug_tracker tool registered");
}
// Quality checklist — self-review before completion
api.registerTool((ctx) =>
createQualityChecklistTool({
store,
auditLog,
sessionKey: ctx.sessionKey,
}),
);
api.logger.info("[systematic-claw] quality_checklist tool registered");
// ── Layer 2: ENFORCE — Hard Gates ──────────────
api.on("before_tool_call", async (event, ctx) => {
try {
const handler = handleBeforeToolCall({
store,
auditLog,
gateMode: resolved.gateMode,
planModeEnabled: resolved.planModeEnabled,
sessionKey: ctx.sessionKey,
agentId: ctx.agentId,
// Phase 4
dangerousCommands: resolved.dangerousCommands,
bootstrapSizeWarnKB: resolved.bootstrapSizeWarnKB,
bootstrapSizeBlockKB: resolved.bootstrapSizeBlockKB,
});
return handler(event);
} catch (error) {
api.logger.warn(
`[systematic-claw] before_tool_call error: ${error instanceof Error ? error.message : error}`
);
return undefined;
}
}, { priority: 50 });
// ── Layer 3: AUDIT — File Tracking ─────────────
api.on("after_tool_call", async (event, ctx) => {
try {
const handler = handleAfterToolCall({
store,
auditLog,
sessionKey: ctx.sessionKey,
agentId: ctx.agentId,
});
handler(event);
} catch (error) {
api.logger.warn(
`[systematic-claw] after_tool_call error: ${error instanceof Error ? error.message : error}`
);
}
}, { priority: 50 });
// ── Layer 3: AUDIT — Completion Check ──────────
api.on("agent_end", async (event, ctx) => {
try {
const handler = handleAgentEnd({
store,
auditLog,
completionCheckEnabled: resolved.completionCheckEnabled,
memoryEnforcementEnabled: resolved.memoryEnforcementEnabled,
});
handler(event, ctx);
} catch (error) {
api.logger.warn(
`[systematic-claw] agent_end error: ${error instanceof Error ? error.message : error}`
);
}
}, { priority: 50 });
// ── Session tracking ───────────────────────────
api.on("session_start", async (_event, ctx) => {
try {
const sessionKey = ctx.sessionKey ?? "unknown";
store.ensureSession(sessionKey, ctx.agentId);
// Reset session-scoped tracking for fresh start
store.resetSessionTracking(sessionKey);
auditLog.record({
sessionKey,
agentId: ctx.agentId,
eventType: "session_start",
severity: "info",
message: "Session started",
});
} catch (err) {
api.logger.warn(`[systematic-claw] session_start error: ${err instanceof Error ? err.message : err}`);
}
}, { priority: 50 });
// ── /systematic command ────────────────────────
api.registerCommand({
name: "systematic",
description: "Systematic Engine durumu ve istatistikleri",
acceptsArgs: true,
handler: async () => {
try {
const stats = auditLog.getStats();
const lines = [
`📊 **Systematic Engine v0.1.0**`,
``,
`**Config:**`,
` Gate mode: ${resolved.gateMode}`,
` Task tracker: ${resolved.taskTrackerEnabled ? "✅" : "❌"}`,
` Plan mode: ${resolved.planModeEnabled ? "✅" : "❌"}`,
` Completion check: ${resolved.completionCheckEnabled ? "✅" : "❌"}`,
` Memory enforcement: ${resolved.memoryEnforcementEnabled ? "✅" : "❌"}`,
` Workflow detection: ${resolved.workflowDetectionEnabled ? "✅" : "❌"}`,
``,
`**Son 24 saat:**`,
` Tamamlanan session: ${stats.last24h.completed}`,
` Sorunlu tamamlanma: ${stats.last24h.withIssues}`,
` Engellenen tool çağrısı: ${stats.last24h.blockedCalls}`,
` Uyarılar: ${stats.last24h.warnedCalls}`,
` Hatalar: ${stats.last24h.errors}`,
``,
`**Son 7 gün:**`,
` Toplam session: ${stats.last7d.totalSessions}`,
` Tamamlanma oranı: %${stats.last7d.completionRate}`,
` En sık sorun: ${stats.last7d.topIssue}`,
];
return { text: lines.join("\n") };
} catch (error) {
return {
text: `❌ Systematic Engine hatası: ${error instanceof Error ? error.message : error}`,
};
}
},
});
// ── Service: cleanup on gateway stop ───────────
api.registerService({
id: "systematic-audit",
async start(ctx) {
ctx.logger.info("[systematic-claw] Audit service started");
},
async stop() {
closeConnection(resolved.dbPath);
},
});
api.logger.info(
`[systematic-claw] Plugin loaded (gate=${resolved.gateMode}, tasks=${resolved.taskTrackerEnabled}, plan=${resolved.planModeEnabled}, completion=${resolved.completionCheckEnabled})`
);
},
};
export default systematicPlugin;