@dashclaw/openclaw-plugin 1.6.2 → 1.6.4

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/dist/index.js CHANGED
@@ -21,7 +21,11 @@
21
21
  */
22
22
  import { definePluginEntry, } from 'openclaw/plugin-sdk/plugin-entry';
23
23
  import { DashClaw, } from 'dashclaw';
24
+ import { existsSync, readFileSync, statSync } from 'node:fs';
25
+ import { randomUUID } from 'node:crypto';
26
+ import { resolve as resolvePath } from 'node:path';
24
27
  import { maybeAutoPair } from './auto-pairing.js';
28
+ import { runLivenessProbe, shouldProbeNow, PROBE_AGENT_ID } from './liveness-probe.js';
25
29
  /**
26
30
  * Resolve the DashClaw URL from (in order of precedence):
27
31
  * 1. `config.dashclawUrl` (canonical plugin-config key)
@@ -52,10 +56,14 @@ function numberFromConfig(value, fallback, allowNegative = true) {
52
56
  return fallback;
53
57
  return value;
54
58
  }
59
+ function enabledEnvFlag(value) {
60
+ return typeof value === 'string' && ['1', 'true'].includes(value.toLowerCase());
61
+ }
55
62
  function resolveConfig(raw) {
56
63
  const cfg = raw ?? {};
57
64
  const env = typeof process !== 'undefined' && process?.env ? process.env : {};
58
65
  const failClosed = cfg.failClosed !== false; // default true
66
+ const requireExecutionClaims = enabledEnvFlag(env.DASHCLAW_REQUIRE_EXECUTION_CLAIMS);
59
67
  const autoPairing = cfg.autoPairing !== false; // default true
60
68
  const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
61
69
  const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
@@ -70,6 +78,7 @@ function resolveConfig(raw) {
70
78
  agentId,
71
79
  defaultModel,
72
80
  failClosed,
81
+ requireExecutionClaims,
73
82
  autoPairing,
74
83
  riskScoreDefault,
75
84
  highRiskTools,
@@ -220,6 +229,75 @@ const PACKAGE_COMMANDS = new Set([
220
229
  const DEPLOY_PATTERN = /(?:git\s+push|deploy|vercel|kubectl|terraform|docker\s+push|helm)/i;
221
230
  const DESTRUCTIVE_PATTERN = /(?:rm\s+-rf|DROP\s+TABLE|DELETE\s+FROM|TRUNCATE)/i;
222
231
  const SENSITIVE_PATH_PATTERN = /(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)/i;
232
+ // Interpreters/runners that indicate the next non-flag token is a local
233
+ // script file worth attaching as evidence (see incident: `node
234
+ // tmp/domain-buy.mjs <name>` was graded from self-declared risk alone
235
+ // because the plugin attached no `act`).
236
+ const SCRIPT_RUNNERS = new Set([
237
+ 'node', 'nodejs', 'python', 'python2', 'python3', 'bash', 'sh', 'zsh',
238
+ 'deno', 'bun', 'tsx', 'ts-node', 'ruby', 'perl', 'php', 'npx',
239
+ ]);
240
+ const SCRIPT_CONTENT_MAX_BYTES = 64 * 1024;
241
+ const SCRIPT_EXCERPT_MAX_CHARS = 6144;
242
+ /**
243
+ * Find the first chain segment (split on &&, ||, ;, |) whose command word,
244
+ * after stripping a leading `cd ...` segment, env assignments, `timeout N`,
245
+ * and `sudo`, is a known script runner — then return the next non-flag
246
+ * token as the candidate script path. Returns undefined when no segment
247
+ * qualifies.
248
+ */
249
+ function findScriptPathToken(command) {
250
+ const segments = command.split(/&&|\|\||;|\|/);
251
+ for (const segment of segments) {
252
+ const tokens = segment.trim().split(/\s+/).filter(Boolean);
253
+ if (tokens.length === 0 || tokens[0] === 'cd')
254
+ continue;
255
+ while (tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0]))
256
+ tokens.shift();
257
+ if (tokens[0] === 'timeout')
258
+ tokens.splice(0, 2);
259
+ if (tokens[0] === 'sudo')
260
+ tokens.shift();
261
+ if (tokens.length === 0)
262
+ continue;
263
+ const cmdWord = tokens[0].replace(/^.*[/\\]/, '');
264
+ if (!SCRIPT_RUNNERS.has(cmdWord))
265
+ continue;
266
+ const pathToken = tokens.slice(1).find((t) => !t.startsWith('-'));
267
+ if (pathToken)
268
+ return pathToken;
269
+ }
270
+ return undefined;
271
+ }
272
+ /**
273
+ * Attach the local script's content when a shell command invokes one, so
274
+ * the server's evidence classifier sees what actually runs instead of
275
+ * grading only the self-declared risk_score. Fail-soft everywhere: any
276
+ * resolution, stat, or read error yields no `script` at all. Sensitive
277
+ * paths (.env, credentials, keys) still attach `path` for policy matching
278
+ * but never their content.
279
+ */
280
+ function detectLocalScript(command, workspace) {
281
+ try {
282
+ const rawPath = findScriptPathToken(command);
283
+ if (!rawPath)
284
+ return undefined;
285
+ const resolved = resolvePath(workspace || process.cwd(), rawPath);
286
+ if (SENSITIVE_PATH_PATTERN.test(rawPath)) {
287
+ return existsSync(resolved) ? { path: rawPath } : undefined;
288
+ }
289
+ if (!existsSync(resolved))
290
+ return undefined;
291
+ const stat = statSync(resolved);
292
+ if (!stat.isFile() || stat.size > SCRIPT_CONTENT_MAX_BYTES)
293
+ return undefined;
294
+ const content = readFileSync(resolved, 'utf8');
295
+ return { path: rawPath, content_excerpt: content.slice(0, SCRIPT_EXCERPT_MAX_CHARS) };
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
223
301
  function classifyBash(command, defaultRisk) {
224
302
  if (!command) {
225
303
  return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: [], declaredGoal: 'Bash: (empty)' };
@@ -276,12 +354,14 @@ function classifyFile(toolName, params, defaultRisk) {
276
354
  }
277
355
  return { actionType: 'apply', riskScore: defaultRisk, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
278
356
  }
279
- function classifyToolCall(toolName, params, config) {
357
+ function classifyToolCall(toolName, params, config, workspace) {
280
358
  const defaultRisk = config.highRiskTools.has(toolName) ? 85 : config.riskScoreDefault;
281
359
  const classified = TOOL_CLASSIFIERS
282
360
  .map((classify) => classify(toolName, params, defaultRisk))
283
361
  .find((result) => result !== null);
284
- return classified ?? classifyDefaultTool(toolName, params, defaultRisk);
362
+ const base = classified ?? classifyDefaultTool(toolName, params, defaultRisk);
363
+ const act = buildGuardAct(toolName, params, workspace);
364
+ return act ? { ...base, act } : base;
285
365
  }
286
366
  const WRITE_TOOLS = new Set(['write', 'edit', 'apply_patch']);
287
367
  const REVIEW_TOOLS = new Set([
@@ -292,6 +372,35 @@ const REVIEW_TOOLS = new Set([
292
372
  'memory_get',
293
373
  'image',
294
374
  ]);
375
+ /**
376
+ * Translate OpenClaw tool params into the narrow evidence-first guard wire
377
+ * contract. Do not truncate the command or the file path: a lost suffix
378
+ * could hide the risk. If a value exceeds the server contract, omit it and
379
+ * retain the normal classified request. File content is intentionally
380
+ * excluded, since a path is sufficient for protected/sensitive-path
381
+ * policies and content may itself be sensitive. Shell commands that
382
+ * execute a local script (e.g. `node tmp/domain-buy.mjs`) are the
383
+ * exception: the script's content is what actually runs, so its first
384
+ * 6144 chars are attached via `script.content_excerpt` (see
385
+ * detectLocalScript) — bounded per the server contract, not exempt from it.
386
+ */
387
+ function buildGuardAct(toolName, params, workspace) {
388
+ if (toolName === 'bash' || toolName === 'exec') {
389
+ const command = params?.command;
390
+ if (typeof command === 'string' && command.length > 0 && command.length <= 8192) {
391
+ const script = detectLocalScript(command, workspace);
392
+ return script ? { kind: 'shell', command, script } : { kind: 'shell', command };
393
+ }
394
+ return undefined;
395
+ }
396
+ if (WRITE_TOOLS.has(toolName)) {
397
+ const path = params?.file_path ?? params?.path;
398
+ if (typeof path === 'string' && path.length > 0 && path.length <= 1024) {
399
+ return { kind: 'file', file: { path } };
400
+ }
401
+ }
402
+ return undefined;
403
+ }
295
404
  const TOOL_CLASSIFIERS = [
296
405
  classifyShellTool,
297
406
  classifyWriteTool,
@@ -357,10 +466,49 @@ function registerRunCleanup(api, config) {
357
466
  function registerOutcomeRecorder(api, config) {
358
467
  api.on('after_tool_call', async (event, _ctx) => handleAfterToolCall(event, config));
359
468
  }
469
+ /**
470
+ * Enforcement-liveness probe on `session_start` (v8.2; per-seam since
471
+ * drizzle/0072). Proves the `before_tool_call` veto above actually HOLDS a
472
+ * synthetic action, and files the verdict under `runtime: openclaw` so this
473
+ * seam is scored on its own instead of inheriting another runtime's green.
474
+ *
475
+ * Fire-and-forget, like maybeAutoPair: session start is never delayed or
476
+ * failed by it. Self-throttled to once per 12h.
477
+ *
478
+ * It drives handleBeforeToolCall — the REAL handler, not a copy — under a
479
+ * synthetic identity. `smoke-` prefixed agents are excluded from every
480
+ * aggregate, and the identity swap is orthogonal to the enforcement mechanics
481
+ * being probed, so it costs no seam fidelity while keeping the probe's guard
482
+ * rows out of the operator's real numbers.
483
+ */
484
+ function registerLivenessProbe(api, config) {
485
+ api.on('session_start', async (_event, _ctx) => {
486
+ if (!config.dashclawUrl || !config.dashclawApiKey)
487
+ return;
488
+ if (!shouldProbeNow())
489
+ return;
490
+ const probeConfig = { ...config, agentId: PROBE_AGENT_ID };
491
+ void runLivenessProbe({
492
+ dashclawUrl: config.dashclawUrl,
493
+ dashclawApiKey: config.dashclawApiKey,
494
+ driveSeam: (event) => handleBeforeToolCall(event, probeConfig),
495
+ }).catch((err) => {
496
+ console.warn(`[dashclaw-governance] liveness probe failed: ${errorMessage(err) || 'unknown'}`);
497
+ });
498
+ });
499
+ }
360
500
  async function handleBeforeToolCall(event, config) {
361
501
  const { toolName, params, toolCallId, runId } = event;
362
502
  const key = callKey(toolName, toolCallId, runId);
363
- const classification = classifyToolCall(toolName, params, config);
503
+ if (!toolCallId && pendingActions.has(key)) {
504
+ return {
505
+ block: true,
506
+ blockReason: 'OpenClaw did not provide a stable tool call ID and another matching call is still open. ' +
507
+ 'Execution was interrupted because its outcome could not be correlated safely.',
508
+ };
509
+ }
510
+ const workspace = typeof event.workspace === 'string' ? event.workspace : undefined;
511
+ const classification = classifyToolCall(toolName, params, config, workspace);
364
512
  const client = getBeforeClient(config);
365
513
  if ('result' in client)
366
514
  return client.result;
@@ -419,15 +567,25 @@ async function maybeStartSession(event, client, config) {
419
567
  }
420
568
  async function guardClassifiedAction(client, classification, config) {
421
569
  try {
422
- return {
423
- value: await client.guard({
424
- action_type: classification.actionType,
425
- risk_score: classification.riskScore,
426
- declared_goal: classification.declaredGoal,
427
- reversible: classification.reversible,
428
- systems_touched: classification.systemsTouched,
429
- }),
430
- };
570
+ const raw = await client.guard({
571
+ action_type: classification.actionType,
572
+ risk_score: classification.riskScore,
573
+ declared_goal: classification.declaredGoal,
574
+ reversible: classification.reversible,
575
+ systems_touched: classification.systemsTouched,
576
+ client_capabilities: ['execution_claims'],
577
+ ...(classification.act ? { act: classification.act } : {}),
578
+ });
579
+ const validated = validateGuardDecision(raw, config.requireExecutionClaims);
580
+ if ('reason' in validated) {
581
+ return {
582
+ result: {
583
+ block: true,
584
+ blockReason: validated.reason,
585
+ },
586
+ };
587
+ }
588
+ return { value: validated.value };
431
589
  }
432
590
  catch (err) {
433
591
  const msg = errorMessage(err) || 'unknown error';
@@ -443,6 +601,28 @@ async function guardClassifiedAction(client, classification, config) {
443
601
  return { result: undefined };
444
602
  }
445
603
  }
604
+ const GUARD_DECISIONS = new Set(['allow', 'block', 'warn', 'require_approval']);
605
+ const EXECUTION_CLAIM_TIMEOUT_MS = 30_000;
606
+ function validateGuardDecision(value, requireExecutionClaims) {
607
+ if (!value || typeof value !== 'object') {
608
+ return { reason: 'DashClaw returned a malformed guard response; tool execution was interrupted.' };
609
+ }
610
+ const response = value;
611
+ if (typeof response.decision !== 'string' || !GUARD_DECISIONS.has(response.decision)) {
612
+ return { reason: 'DashClaw returned a malformed or unknown guard decision; tool execution was interrupted.' };
613
+ }
614
+ if (response.decision === 'block') {
615
+ return { value: value };
616
+ }
617
+ const advertised = 'execution_claim_required' in response || 'claim_protocol' in response;
618
+ const validClaims = response.execution_claim_required === true && response.claim_protocol === 1;
619
+ if ((requireExecutionClaims || advertised) && !validClaims) {
620
+ return {
621
+ reason: 'DashClaw server upgrade required: execution-claim protocol 1 was not advertised, so this tool call cannot run safely.',
622
+ };
623
+ }
624
+ return { value: value };
625
+ }
446
626
  function blockResultForDecision(decision, toolName) {
447
627
  if (decision.decision === 'block') {
448
628
  return {
@@ -462,6 +642,11 @@ async function openActionRecord(ctx) {
462
642
  const approval = await waitForRequiredApproval(ctx, created.value);
463
643
  if (approval)
464
644
  return approval;
645
+ if (ctx.decision.execution_claim_required === true && ctx.decision.claim_protocol === 1) {
646
+ const claim = await claimExecution(ctx, created.value.actionId);
647
+ if (claim)
648
+ return claim;
649
+ }
465
650
  rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
466
651
  return;
467
652
  }
@@ -474,14 +659,21 @@ async function createGovernanceAction(ctx) {
474
659
  risk_score: riskScore,
475
660
  reversible,
476
661
  systems_touched: systemsTouched,
662
+ client_capabilities: ['execution_claims'],
663
+ ...(ctx.classification.act ? { act: ctx.classification.act } : {}),
477
664
  metadata: { openclaw_tool_name: ctx.toolName },
478
665
  });
479
- return {
480
- value: {
481
- actionId: created.action_id ?? created.action?.action_id ?? created.action?.id,
482
- status: created.action?.status,
483
- },
484
- };
666
+ const ids = [created.action_id, created.action?.action_id, created.action?.id]
667
+ .filter((id) => typeof id === 'string' && id.length > 0);
668
+ if (ids.length === 0 || new Set(ids).size !== 1) {
669
+ return {
670
+ result: {
671
+ block: true,
672
+ blockReason: 'DashClaw action response did not contain one exact action ID; tool execution was interrupted.',
673
+ },
674
+ };
675
+ }
676
+ return { value: { actionId: ids[0], status: created.action?.status } };
485
677
  }
486
678
  catch (err) {
487
679
  const msg = errorMessage(err) || 'unknown';
@@ -497,10 +689,70 @@ async function createGovernanceAction(ctx) {
497
689
  return { result: undefined };
498
690
  }
499
691
  }
692
+ async function claimExecution(ctx, actionId) {
693
+ const attemptId = randomUUID();
694
+ const body = {
695
+ claim_execution: true,
696
+ attempt_id: attemptId,
697
+ agent_id: ctx.config.agentId,
698
+ ...(ctx.classification.act ? { act: ctx.classification.act } : {}),
699
+ };
700
+ let response;
701
+ let payload;
702
+ const controller = new AbortController();
703
+ const timeoutError = new Error(`execution claim timed out after ${EXECUTION_CLAIM_TIMEOUT_MS}ms`);
704
+ const timer = setTimeout(() => controller.abort(timeoutError), EXECUTION_CLAIM_TIMEOUT_MS);
705
+ const aborted = new Promise((_resolve, reject) => {
706
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason instanceof Error ? controller.signal.reason : timeoutError), { once: true });
707
+ });
708
+ try {
709
+ response = await Promise.race([
710
+ fetch(`${ctx.config.dashclawUrl}/api/actions/${encodeURIComponent(actionId)}`, {
711
+ method: 'PATCH',
712
+ headers: {
713
+ 'Content-Type': 'application/json',
714
+ 'x-api-key': ctx.config.dashclawApiKey,
715
+ },
716
+ body: JSON.stringify(body),
717
+ signal: controller.signal,
718
+ }),
719
+ aborted,
720
+ ]);
721
+ if (!response.ok) {
722
+ return {
723
+ block: true,
724
+ blockReason: `DashClaw execution claim failed (HTTP ${response.status}); reconcile action ${actionId} before retrying.`,
725
+ };
726
+ }
727
+ payload = await Promise.race([response.json(), aborted]);
728
+ }
729
+ catch (err) {
730
+ return {
731
+ block: true,
732
+ blockReason: `DashClaw execution claim failed (${errorMessage(err) || 'response lost'}); ` +
733
+ `reconcile action ${actionId} before retrying.`,
734
+ };
735
+ }
736
+ finally {
737
+ clearTimeout(timer);
738
+ }
739
+ const claimed = payload;
740
+ if (!claimed
741
+ || claimed.claimed !== true
742
+ || claimed.action_id !== actionId
743
+ || claimed.attempt_id !== attemptId) {
744
+ return {
745
+ block: true,
746
+ blockReason: `DashClaw execution claim returned a malformed acknowledgement; ` +
747
+ `reconcile action ${actionId} before retrying.`,
748
+ };
749
+ }
750
+ return undefined;
751
+ }
500
752
  async function waitForRequiredApproval(ctx, created) {
501
753
  const needsApproval = ctx.decision.decision === 'require_approval' ||
502
754
  created.status === 'pending_approval';
503
- if (!needsApproval || !created.actionId)
755
+ if (!needsApproval)
504
756
  return undefined;
505
757
  const timeout = ctx.config.approvalWaitMs;
506
758
  try {
@@ -692,6 +944,7 @@ const pluginEntry = definePluginEntry({
692
944
  registerTokenAttribution(api, config);
693
945
  registerRunCleanup(api, config);
694
946
  registerOutcomeRecorder(api, config);
947
+ registerLivenessProbe(api, config);
695
948
  },
696
949
  });
697
950
  export default pluginEntry;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Enforcement-liveness probe for the OpenClaw seam (roadmap v8.2, per-seam
3
+ * since drizzle/0072).
4
+ *
5
+ * Why this is TypeScript instead of the canonical `hooks/enforcement_liveness_probe.py`.
6
+ * That script probes a seam it can SPAWN: it reads a harness config file, runs
7
+ * the installed hook command as a subprocess, and emulates the harness's
8
+ * contract around it. OpenClaw's seam has none of those parts. Governance here
9
+ * is an in-process `before_tool_call` handler whose return value the gateway
10
+ * obeys directly — there is no config file to read, no command to run, and no
11
+ * exit code to interpret. A subprocess probe cannot reach it at all. So this
12
+ * module reuses the python probe's CONTRACT (same synthetic held action, same
13
+ * witness rule, same three verdicts, same POST payload) while driving the seam
14
+ * the only way it can be driven: by calling it.
15
+ *
16
+ * The witness rule is preserved exactly, and it is the point. The verdict never
17
+ * comes from what the guard DECIDED — the decision ledger is what kept lying in
18
+ * v4.72.1. It comes from whether the held action executed: if the seam does not
19
+ * veto, the probe performs the write the seam should have stopped, and the
20
+ * file's existence is the evidence.
21
+ *
22
+ * Verdicts:
23
+ * held the seam vetoed the synthetic action; the witness was never written.
24
+ * executed the seam let it through and the witness file exists.
25
+ * unprovable the seam ran but enforcement cannot be proven (no policy holds
26
+ * the probe action, or the probe could not run). Rendered broken
27
+ * on the surfaces — you cannot claim enforcement you cannot prove.
28
+ */
29
+ /** `smoke-` is the established synthetic marker: these guard rows are excluded
30
+ * from every aggregate, exactly as the python probe's agent id is. */
31
+ export declare const PROBE_AGENT_ID = "smoke-liveness-probe";
32
+ export declare const PROBE_RUNTIME = "openclaw";
33
+ export interface SeamResult {
34
+ block?: boolean;
35
+ blockReason?: string;
36
+ }
37
+ export interface ProbeCheck {
38
+ id: string;
39
+ title: string;
40
+ status: 'pass' | 'fail';
41
+ detail?: string;
42
+ durationMs?: number;
43
+ }
44
+ export interface LivenessRun {
45
+ source: string;
46
+ runtime: string;
47
+ verdict: 'held' | 'executed' | 'unprovable';
48
+ detail: string;
49
+ witness: {
50
+ path: string;
51
+ executed: boolean;
52
+ };
53
+ checks: ProbeCheck[];
54
+ startedAt: string;
55
+ finishedAt: string;
56
+ }
57
+ export interface ProbeOptions {
58
+ /** Drives the REAL before_tool_call handler with the synthetic event. */
59
+ driveSeam: (event: {
60
+ toolName: string;
61
+ params: Record<string, unknown>;
62
+ toolCallId: string;
63
+ runId: string;
64
+ }) => Promise<SeamResult | void>;
65
+ dashclawUrl: string;
66
+ dashclawApiKey: string;
67
+ source?: string;
68
+ /** Overridable so tests do not touch the real home directory. */
69
+ witnessRoot?: string;
70
+ now?: () => number;
71
+ fetchImpl?: typeof fetch;
72
+ }
73
+ /**
74
+ * Once per 12h, mirroring the python probe's SessionStart throttle. Returns
75
+ * true when this session should probe, and stamps the marker as it does so —
76
+ * a failure to stamp never blocks the run.
77
+ */
78
+ export declare function shouldProbeNow(root?: string, now?: number): boolean;
79
+ export declare function runLivenessProbe(options: ProbeOptions): Promise<LivenessRun>;
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Enforcement-liveness probe for the OpenClaw seam (roadmap v8.2, per-seam
3
+ * since drizzle/0072).
4
+ *
5
+ * Why this is TypeScript instead of the canonical `hooks/enforcement_liveness_probe.py`.
6
+ * That script probes a seam it can SPAWN: it reads a harness config file, runs
7
+ * the installed hook command as a subprocess, and emulates the harness's
8
+ * contract around it. OpenClaw's seam has none of those parts. Governance here
9
+ * is an in-process `before_tool_call` handler whose return value the gateway
10
+ * obeys directly — there is no config file to read, no command to run, and no
11
+ * exit code to interpret. A subprocess probe cannot reach it at all. So this
12
+ * module reuses the python probe's CONTRACT (same synthetic held action, same
13
+ * witness rule, same three verdicts, same POST payload) while driving the seam
14
+ * the only way it can be driven: by calling it.
15
+ *
16
+ * The witness rule is preserved exactly, and it is the point. The verdict never
17
+ * comes from what the guard DECIDED — the decision ledger is what kept lying in
18
+ * v4.72.1. It comes from whether the held action executed: if the seam does not
19
+ * veto, the probe performs the write the seam should have stopped, and the
20
+ * file's existence is the evidence.
21
+ *
22
+ * Verdicts:
23
+ * held the seam vetoed the synthetic action; the witness was never written.
24
+ * executed the seam let it through and the witness file exists.
25
+ * unprovable the seam ran but enforcement cannot be proven (no policy holds
26
+ * the probe action, or the probe could not run). Rendered broken
27
+ * on the surfaces — you cannot claim enforcement you cannot prove.
28
+ */
29
+ import { mkdirSync, existsSync, rmSync, statSync, writeFileSync } from 'node:fs';
30
+ import { homedir } from 'node:os';
31
+ import { join } from 'node:path';
32
+ /** `smoke-` is the established synthetic marker: these guard rows are excluded
33
+ * from every aggregate, exactly as the python probe's agent id is. */
34
+ export const PROBE_AGENT_ID = 'smoke-liveness-probe';
35
+ export const PROBE_RUNTIME = 'openclaw';
36
+ const THROTTLE_MS = 12 * 60 * 60 * 1000;
37
+ function probeRoot() {
38
+ return join(homedir(), '.dashclaw', 'liveness-probe');
39
+ }
40
+ /**
41
+ * Once per 12h, mirroring the python probe's SessionStart throttle. Returns
42
+ * true when this session should probe, and stamps the marker as it does so —
43
+ * a failure to stamp never blocks the run.
44
+ */
45
+ export function shouldProbeNow(root = probeRoot(), now = Date.now()) {
46
+ const marker = join(root, '.last-run-openclaw');
47
+ try {
48
+ if (now - statSync(marker).mtimeMs < THROTTLE_MS)
49
+ return false;
50
+ }
51
+ catch {
52
+ // no marker yet: first run in this install
53
+ }
54
+ try {
55
+ mkdirSync(root, { recursive: true });
56
+ writeFileSync(marker, String(now), 'utf8');
57
+ }
58
+ catch {
59
+ // a throttle we cannot record is still a probe worth running
60
+ }
61
+ return true;
62
+ }
63
+ /**
64
+ * The synthetic held action: a Write to a probe-owned `.env` path outside the
65
+ * workspace. Identical in shape to the python probe's, so both seams are
66
+ * judged against the same class of action — the path trips sensitive-path and
67
+ * outside-workspace risk boosts and matches protected-path/.env policy rules,
68
+ * while remaining a file the probe owns and may safely create when the seam
69
+ * fails open (broken enforcement is exactly when it WILL be written).
70
+ */
71
+ function syntheticEvent(witnessPath, runId) {
72
+ return {
73
+ toolName: 'Write',
74
+ params: {
75
+ file_path: witnessPath,
76
+ content: `DashClaw enforcement-liveness probe witness ${runId} — if this file exists, an action the policy should have held EXECUTED.`,
77
+ },
78
+ toolCallId: `elp-${runId}`,
79
+ runId: `liveness-probe-${runId}`,
80
+ };
81
+ }
82
+ export async function runLivenessProbe(options) {
83
+ const now = options.now ?? Date.now;
84
+ const startedAt = new Date(now()).toISOString();
85
+ const t0 = now();
86
+ // Not crypto: this only has to be unique per run so concurrent probes do not
87
+ // share a witness path.
88
+ const runId = `${now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
89
+ const witnessDir = join(options.witnessRoot ?? probeRoot(), runId);
90
+ const witnessPath = join(witnessDir, '.env');
91
+ const checks = [];
92
+ let verdict;
93
+ let detail;
94
+ let witnessExecuted = false;
95
+ const seamT0 = now();
96
+ let seam = undefined;
97
+ let seamError = null;
98
+ try {
99
+ seam = await options.driveSeam(syntheticEvent(witnessPath, runId));
100
+ }
101
+ catch (err) {
102
+ seamError = err instanceof Error ? err.message : String(err);
103
+ }
104
+ const seamMs = now() - seamT0;
105
+ if (seamError) {
106
+ // The handler threw. OpenClaw treats a throwing hook as non-blocking, so
107
+ // the tool would have proceeded — same fail-open reading the python probe
108
+ // applies to a hook that cannot run.
109
+ verdict = 'unprovable';
110
+ detail = `The governance hook threw instead of deciding (${seamError}) — the gateway would have let the action proceed, and enforcement cannot be proven this run.`;
111
+ checks.push({ id: 'seam', title: 'before_tool_call threw', status: 'fail', detail, durationMs: seamMs });
112
+ }
113
+ else if (seam && seam.block) {
114
+ verdict = 'held';
115
+ detail = seam.blockReason
116
+ ? `Probe action vetoed at the seam: ${seam.blockReason}`
117
+ : 'Probe action vetoed at the seam; the witness was never executed.';
118
+ checks.push({ id: 'seam', title: 'Hook held the synthetic action', status: 'pass', detail, durationMs: seamMs });
119
+ }
120
+ else {
121
+ // The seam let it through: execute the witness, exactly as the gateway
122
+ // would have. Its existence is the evidence — never the ledger.
123
+ try {
124
+ mkdirSync(witnessDir, { recursive: true });
125
+ writeFileSync(witnessPath, `executed by openclaw liveness probe ${runId} at ${new Date(now()).toISOString()}\n`, 'utf8');
126
+ witnessExecuted = existsSync(witnessPath);
127
+ }
128
+ catch {
129
+ witnessExecuted = false;
130
+ }
131
+ verdict = 'unprovable';
132
+ detail =
133
+ 'No policy held the probe action — the seam ran and allowed it. Add or scope a policy that blocks writes to *.env (protected paths or risk_threshold) so enforcement is provable.';
134
+ checks.push({
135
+ id: 'seam',
136
+ title: 'Hook let the synthetic action proceed',
137
+ status: 'fail',
138
+ detail,
139
+ durationMs: seamMs,
140
+ });
141
+ }
142
+ checks.push({
143
+ id: 'witness',
144
+ title: 'Witness: did the held action execute?',
145
+ status: witnessExecuted ? 'fail' : 'pass',
146
+ detail: `${witnessPath} ${witnessExecuted ? 'EXISTS — the action executed' : 'absent'}`,
147
+ });
148
+ try {
149
+ rmSync(witnessDir, { recursive: true, force: true });
150
+ }
151
+ catch {
152
+ // best effort — a leftover witness never changes a verdict already decided
153
+ }
154
+ const run = {
155
+ source: options.source ?? 'session-start',
156
+ runtime: PROBE_RUNTIME,
157
+ verdict,
158
+ detail,
159
+ witness: { path: witnessPath, executed: witnessExecuted },
160
+ checks,
161
+ startedAt,
162
+ finishedAt: new Date(now()).toISOString(),
163
+ };
164
+ await reportRun(run, options);
165
+ void t0;
166
+ return run;
167
+ }
168
+ async function reportRun(run, options) {
169
+ const base = (options.dashclawUrl || '').replace(/\/+$/, '');
170
+ if (!base || !options.dashclawApiKey)
171
+ return;
172
+ const doFetch = options.fetchImpl ?? fetch;
173
+ try {
174
+ await doFetch(`${base}/api/enforcement-liveness`, {
175
+ method: 'POST',
176
+ headers: { 'content-type': 'application/json', 'x-api-key': options.dashclawApiKey },
177
+ body: JSON.stringify(run),
178
+ });
179
+ }
180
+ catch (err) {
181
+ // A verdict we cannot file is not a reason to break session start. The
182
+ // seam going quiet is itself rendered `stale` by the fleet rollup.
183
+ console.warn(`[dashclaw-governance] liveness verdict not reported: ${err instanceof Error ? err.message : 'unknown'}`);
184
+ }
185
+ }
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "id": "dashclaw-governance",
3
3
  "name": "DashClaw Governance",
4
- "description": "Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.",
5
- "version": "1.6.2",
4
+ "description": "Policy checks, remote approvals, and execution claims at OpenClaw's supported tool hook boundary.",
5
+ "version": "1.6.4",
6
6
  "entry": "dist/index.js",
7
7
  "main": "./dist/index.js",
8
8
  "configSchema": {