All files sensorium-index.ts

70.74% Statements 133/188
58.89% Branches 96/163
75% Functions 24/32
69.56% Lines 112/161

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3721x   1x             1x         1x                     1x   1x     24x                                       20x 18x 18x 191x 16x     2x       19x 19x 19x             19x       20x 20x 28x       21x 21x 28x 28x 17x 14x       20x 20x 29x       15x 15x 20x 12x       13x 13x 13x 13x 13x   13x 13x 13x 13x 13x   13x   11x 11x 11x   42x 11x   11x       17x 15x 10x 6x       5x 5x 5x 5x 5x 5x 5x 8x 7x     5x                                     1x                     7x 7x 7x 7x   7x 9x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x     3x 3x 2x 2x     8x 6x 6x 6x 5x 5x             7x       18x 18x 18x 18x     1x 1x   19x 6x 6x   13x 13x 13x 13x       6x 6x       48x 48x 48x 10x                                               1x                                                                                                                                                                                                              
const DEFAULT_WINDOW = 20;
 
const DEFAULT_WEIGHTS = {
  success: 0.30,
  tool: 0.25,
  cbr: 0.20,
  severity: 0.25,
};
 
const DEFAULT_D_BANDS = {
  low: 0.35,
  high: 0.55,
};
 
const DEFAULT_SEVERITY_RULES = [
  { keywords: ["exfil", "steal", "leak"], score: 1000 },
  { keywords: ["system", "command"], score: 800 },
  { keywords: ["delete", "rm ", "unlink"], score: 600 },
  { keywords: ["exec", "subprocess"], score: 500 },
  { keywords: ["timeout", "timed out"], score: 300 },
  { keywords: ["network", "fetch", "connect"], score: 300 },
  { keywords: ["permission", "denied", "forbidden"], score: 200 },
  { keywords: [], score: 100 },
];
 
const DEFAULT_MAX_CYCLES_MULTIPLIER = 3;
 
const sessionMetrics = new Map();
 
function resolveConfig(cfg) {
  return {
    window: cfg?.sensoriumWindow ?? DEFAULT_WINDOW,
    dBands: {
      low: cfg?.dBandLow ?? DEFAULT_D_BANDS.low,
      high: cfg?.dBandHigh ?? DEFAULT_D_BANDS.high,
    },
    weights: {
      success: cfg?.weightSuccess ?? DEFAULT_WEIGHTS.success,
      tool: cfg?.weightTool ?? DEFAULT_WEIGHTS.tool,
      cbr: cfg?.weightCbr ?? DEFAULT_WEIGHTS.cbr,
      severity: cfg?.weightSeverity ?? DEFAULT_WEIGHTS.severity,
    },
    severityRules: cfg?.severityRules ?? DEFAULT_SEVERITY_RULES,
    maxCyclesMultiplier: cfg?.maxCyclesMultiplier ?? DEFAULT_MAX_CYCLES_MULTIPLIER,
    dGateThreshold: cfg?.dGateThreshold ?? DEFAULT_D_BANDS.low,
    logLevel: cfg?.logLevel || "info",
  };
}
 
function classifySeverity(reason, rules) {
  if (!reason) return 50;
  const lower = reason.toLowerCase();
  for (const rule of rules) {
    if (rule.keywords.some((kw) => lower.includes(kw))) {
      return rule.score;
    }
  }
  return 50;
}
 
function getOrCreateMetrics(sessionKey, cfg) {
  Eif (!sessionMetrics.has(sessionKey)) {
    const resolved = resolveConfig(cfg);
    sessionMetrics.set(sessionKey, {
      cycles: [],
      callCounter: 0,
      lastRecordedSuccess: null,
      config: resolved,
    });
  }
  return sessionMetrics.get(sessionKey);
}
 
function computeSuccessRate(metrics) {
  const recent = metrics.cycles.slice(-metrics.config.window);
  if (recent.length === 0) return null;
  return recent.filter((c) => c.success).length / recent.length;
}
 
function computeToolFailureRate(metrics) {
  const recent = metrics.cycles.slice(-metrics.config.window);
  if (recent.length === 0) return null;
  const totalTools = recent.reduce((sum, c) => sum + (c.totalTools || 0), 0);
  const failedTools = recent.reduce((sum, c) => sum + (c.failedTools || 0), 0);
  if (totalTools === 0) return null;
  return failedTools / totalTools;
}
 
function computeCbrHitRate(metrics) {
  const recent = metrics.cycles.slice(-metrics.config.window);
  if (recent.length === 0) return null;
  return recent.filter((c) => c.cbrHit).length / recent.length;
}
 
function computeAverageSeverity(metrics) {
  const recent = metrics.cycles.slice(-metrics.config.window);
  if (recent.length === 0) return null;
  const avg = recent.reduce((sum, c) => sum + (c.severity ?? 50), 0) / recent.length;
  return avg / 1000;
}
 
function computeDPrime(metrics) {
  const weights = metrics.config.weights;
  const successRate = computeSuccessRate(metrics);
  const toolFailureRate = computeToolFailureRate(metrics);
  const cbrHitRate = computeCbrHitRate(metrics);
  const avgSeverity = computeAverageSeverity(metrics);
 
  const signals = [];
  if (successRate !== null) signals.push({ importance: weights.success, magnitude: successRate });
  if (toolFailureRate !== null) signals.push({ importance: weights.tool, magnitude: 1 - toolFailureRate });
  if (cbrHitRate !== null) signals.push({ importance: weights.cbr, magnitude: cbrHitRate });
  if (avgSeverity !== null) signals.push({ importance: weights.severity, magnitude: 1 - avgSeverity });
 
  if (signals.length === 0) return null;
 
  const maxImportance = Math.max(weights.success, weights.tool, weights.cbr, weights.severity);
  const maxMagnitude = 1.0;
  const n = signals.length;
 
  const numerator = signals.reduce((sum, s) => sum + s.importance * s.magnitude, 0);
  const denominator = maxImportance * maxMagnitude * n;
 
  return numerator / denominator;
}
 
function dGateStatus(dPrime, bands) {
  if (dPrime === null) return "UNKNOWN";
  if (dPrime >= bands.high) return "HIGH_REJECT";
  if (dPrime >= bands.low) return "MEDIUM_CONFIRM";
  return "LOW_ACCEPT";
}
 
function formatSensorium(sessionKey, metrics) {
  const successRate = computeSuccessRate(metrics);
  const toolFailureRate = computeToolFailureRate(metrics);
  const cbrHitRate = computeCbrHitRate(metrics);
  const dPrime = computeDPrime(metrics);
  const status = dGateStatus(dPrime, metrics.config.dBands);
  const recent = metrics.cycles.slice(-5);
  const recentFailures = recent
    .filter((c) => !c.success)
    .map((c) => (c.severity >= 600 ? `[CRIT]${c.reason || "unknown"}` : c.reason || "unknown"))
    .slice(-3);
 
  return [
    "<openclaw_state>",
    `  <session_key>${sessionKey}</session_key>`,
    `  <d_prime>${dPrime !== null ? dPrime.toFixed(4) : "--"}</d_prime>`,
    `  <d_gate_threshold>${metrics.config.dGateThreshold}</d_gate_threshold>`,
    `  <d_gate_status>${status}</d_gate_status>`,
    `  <cycles_tracked>${metrics.cycles.length}</cycles_tracked>`,
    successRate !== null ? `  <session_success_rate>${successRate.toFixed(3)}</session_success_rate>` : `  <session_success_rate>--</session_success_rate>`,
    toolFailureRate !== null ? `  <tool_failure_rate>${toolFailureRate.toFixed(3)}</tool_failure_rate>` : `  <tool_failure_rate>0.000</tool_failure_rate>`,
    cbrHitRate !== null ? `  <cbr_hit_rate>${cbrHitRate.toFixed(3)}</cbr_hit_rate>` : `  <cbr_hit_rate>--</cbr_hit_rate>`,
    recentFailures.length > 0 ? `  <recent_failures>${recentFailures.join(" | ")}</recent_failures>` : `  <recent_failures>none</recent_failures>`,
    "</openclaw_state>",
  ].join("\n");
}
 
function resolveLogLevel(pluginConfig) {
  return pluginConfig?.logLevel || "info";
}
 
const LOG_LEVELS = { debug: 0, info: 1, warn: 2 };
 
function doLog(api, level, msg) {
  const configured = resolveLogLevel(api.pluginConfig);
  if ((LOG_LEVELS[level] ?? 1) >= (LOG_LEVELS[configured] ?? 1)) {
    const fn = level === "debug" ? api.logger.debug : level === "warn" ? api.logger.warn : api.logger.info;
    fn?.(`[policy-sensorium] ${msg}`);
  }
}
 
function extractOutcomeFromMessages(messages, severityRules) {
  let totalTools = 0;
  let failedTools = 0;
  let reason = "";
  let maxSeverity = 50;
 
  for (const msg of messages) {
    if (msg.role === "tool") {
      totalTools++;
      const content = msg.content;
      Eif (typeof content === "string") {
        let isError = false;
        let errReason = "";
        try {
          const parsed = JSON.parse(content);
          isError = !!(parsed.isError || parsed.error || parsed.success === false);
          if (isError) {
            errReason = parsed.error || parsed.message || "tool error";
          }
        } catch {
          const lower = content.toLowerCase();
          if (lower.includes("error") || lower.includes("failed") || lower.includes("exception")) {
            isError = true;
            errReason = content.slice(0, 120);
          }
        }
        if (isError) {
          failedTools++;
          const sev = classifySeverity(errReason, severityRules);
          if (sev > maxSeverity) {
            maxSeverity = sev;
            reason = errReason;
          }
        }
      }
    }
  }
 
  return { totalTools, failedTools, reason, severity: maxSeverity };
}
 
export function resetSessionMetrics(sessionKey) {
  Iif (sessionKey) sessionMetrics.delete(sessionKey);
  else sessionMetrics.clear();
  _mockCounter = 0;
  _keyCounter = 0;
}
 
let _mockCounter = 0;
let _keyCounter = 0;
export function createMockMetrics(cfg, explicitKey) {
  if (explicitKey) {
    const m = getOrCreateMetrics(explicitKey, cfg);
    return { key: explicitKey, m };
  }
  _mockCounter++;
  const key = `__test__${_mockCounter}__${Date.now()}`;
  const m = getOrCreateMetrics(key, cfg);
  return { key, m };
}
 
export function makeKey(n) {
  _keyCounter++;
  return `__key__${n}__${_keyCounter}__${Date.now()}`;
}
 
export function addCycle(metrics, cycle) {
  metrics.cycles.push({ ...cycle, timestamp: Date.now() });
  const maxCycles = metrics.config.window * metrics.config.maxCyclesMultiplier;
  if (metrics.cycles.length > maxCycles) {
    metrics.cycles = metrics.cycles.slice(-metrics.config.window * 2);
  }
}
 
export function getMetrics(sessionKey) {
  return sessionMetrics.get(sessionKey);
}
 
export {
  classifySeverity,
  computeSuccessRate,
  computeToolFailureRate,
  computeCbrHitRate,
  computeAverageSeverity,
  computeDPrime,
  dGateStatus,
  formatSensorium,
  extractOutcomeFromMessages,
  resolveConfig,
  DEFAULT_WEIGHTS,
  DEFAULT_D_BANDS,
  DEFAULT_SEVERITY_RULES,
};
 
const plugin = {
  id: "policy-sensorium",
  name: "Policy Sensorium (CBS)",
  description: "Springdrift-inspired Cognitive Behavior System: injects self-perception signals before each LLM call.",
  kind: "sensorium",
 
  register(api) {
    api.on("before_prompt_build", async (event, ctx) => {
      try {
        const sessionKey =
          ctx.sessionKey?.trim() ||
          (ctx.agentId && ctx.sessionId ? `${ctx.agentId}:${ctx.sessionId}` : null);
        if (!sessionKey) return;
 
        const cfg = api.pluginConfig || {};
        const metrics = getOrCreateMetrics(sessionKey, cfg);
 
        const resolvedCfg = resolveConfig(cfg);
        if (cfg.sensoriumWindow) metrics.config.window = cfg.sensoriumWindow;
        if (cfg.dGateThreshold !== undefined) metrics.config.dGateThreshold = cfg.dGateThreshold;
        if (cfg.dBandLow !== undefined) metrics.config.dBands.low = cfg.dBandLow;
        if (cfg.dBandHigh !== undefined) metrics.config.dBands.high = cfg.dBandHigh;
 
        const messages = event.messages || [];
 
        if (metrics.callCounter > 0) {
          const { totalTools, failedTools, reason, severity } = extractOutcomeFromMessages(messages, resolvedCfg.severityRules);
          const success = failedTools === 0;
          addCycle(metrics, {
            success,
            totalTools,
            failedTools,
            cbrHit: false,
            reason,
            severity,
          });
        }
 
        const dPrime = computeDPrime(metrics);
        const status = dGateStatus(dPrime, metrics.config.dBands);
 
        if (status === "HIGH_REJECT") {
          doLog(api, "warn", `D'=${dPrime?.toFixed(4)} → HIGH_REJECT: blocking high-risk call for session ${sessionKey}`);
        } else if (status === "MEDIUM_CONFIRM") {
          doLog(api, "warn", `D'=${dPrime?.toFixed(4)} → MEDIUM_CONFIRM: requesting operator confirmation`);
        }
 
        const sensorium = formatSensorium(sessionKey, metrics);
        doLog(api, "debug", `Injecting sensorium for ${sessionKey}: D'=${dPrime?.toFixed(4) ?? "--"}, status=${status}`);
 
        metrics.callCounter++;
 
        return { prependContext: sensorium };
      } catch (err) {
        doLog(api, "warn", `before_prompt_build error: ${String(err)}`);
      }
    });
 
    api.registerCommand({
      name: "policy-sensorium",
      description: "Show policy-sensorium CBS metrics for the current session.",
      acceptsArgs: true,
      handler: async (ctx) => {
        const sessionKey =
          ctx.sessionKey?.trim() ||
          (ctx.agentId && ctx.sessionId ? `${ctx.agentId}:${ctx.sessionId}` : null);
 
        if (!sessionKey) {
          return { text: "[policy-sensorium] No session context." };
        }
 
        const metrics = getOrCreateMetrics(sessionKey, {});
        const dPrime = computeDPrime(metrics);
        const status = dGateStatus(dPrime, metrics.config.dBands);
        const successRate = computeSuccessRate(metrics);
        const toolFailureRate = computeToolFailureRate(metrics);
        const cbrHitRate = computeCbrHitRate(metrics);
 
        const recent = metrics.cycles.slice(-3);
        const failLines = recent
          .filter((c) => !c.success)
          .map((c) => `  - ${c.reason || "unknown"} (sev=${c.severity})`);
 
        const lines = [
          `[policy-sensorium] Session: ${sessionKey}`,
          `  D' score:     ${dPrime !== null ? dPrime.toFixed(4) : "--"}`,
          `  D' status:   ${status}`,
          `  Threshold:    ${metrics.config.dGateThreshold}`,
          `  Cycles:       ${metrics.cycles.length} (window ${metrics.config.window})`,
          `  Calls:        ${metrics.callCounter}`,
          `  Success rate: ${successRate !== null ? successRate.toFixed(3) : "--"}`,
          `  Tool fail:    ${toolFailureRate !== null ? toolFailureRate.toFixed(3) : "--"}`,
          `  CBR hit:      ${cbrHitRate !== null ? cbrHitRate.toFixed(3) : "--"}`,
          failLines.length > 0 ? `  Recent failures:\n${failLines.join("\n")}` : `  Recent failures: none`,
        ];
 
        return { text: lines.join("\n") };
      },
    });
  },
};
 
export default plugin;