Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(openclaw-plugin): add session-pattern guard for ingest reply assist (#1136)

Mingjian Que27f61889bfe2
diff --git a/examples/openclaw-plugin/__tests__/ingest-reply-assist-session-patterns.test.ts b/examples/openclaw-plugin/__tests__/ingest-reply-assist-session-patterns.test.ts
new file mode 100644
index 000000000..b769fb246
--- /dev/null
+++ b/examples/openclaw-plugin/__tests__/ingest-reply-assist-session-patterns.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+
+import { memoryOpenVikingConfigSchema } from "../config.js";
+import {
+ compileSessionPatterns,
+ matchesSessionPattern,
+ shouldSkipIngestReplyAssistSession,
+} from "../text-utils.js";
+
+describe("ingest reply assist session patterns", () => {
+ it("parses ignore session patterns from config", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ ingestReplyAssistIgnoreSessionPatterns: [
+ "agent:*:cron:**",
+ "agent:ops:maintenance:**",
+ ],
+ });
+
+ expect(cfg.ingestReplyAssistIgnoreSessionPatterns).toEqual([
+ "agent:*:cron:**",
+ "agent:ops:maintenance:**",
+ ]);
+ });
+
+ it("defaults ignore session patterns to an empty list", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({});
+ expect(cfg.ingestReplyAssistIgnoreSessionPatterns).toEqual([]);
+ });
+
+ it("matches lossless-claw style session globs", () => {
+ const patterns = compileSessionPatterns([
+ "agent:*:cron:**",
+ "agent:ops:maintenance:**",
+ ]);
+
+ expect(matchesSessionPattern("agent:main:cron:nightly:run:1", patterns)).toBe(true);
+ expect(matchesSessionPattern("agent:ops:maintenance:weekly", patterns)).toBe(true);
+ expect(matchesSessionPattern("agent:main:main", patterns)).toBe(false);
+ });
+
+ it("prefers sessionKey over sessionId when deciding whether to skip assist", () => {
+ const patterns = compileSessionPatterns(["agent:*:cron:**"]);
+
+ expect(
+ shouldSkipIngestReplyAssistSession(
+ {
+ sessionId: "agent:main:cron:from-id",
+ sessionKey: "agent:main:main",
+ },
+ patterns,
+ ),
+ ).toBe(false);
+ });
+
+ it("falls back to sessionId when sessionKey is unavailable", () => {
+ const patterns = compileSessionPatterns(["agent:*:cron:**"]);
+
+ expect(
+ shouldSkipIngestReplyAssistSession(
+ {
+ sessionId: "agent:main:cron:nightly:run:1",
+ },
+ patterns,
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index a25037bdc..c4781d8ba 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -27,6 +27,7 @@ export type MemoryOpenVikingConfig = {
ingestReplyAssist?: boolean;
ingestReplyAssistMinSpeakerTurns?: number;
ingestReplyAssistMinChars?: number;
+ ingestReplyAssistIgnoreSessionPatterns?: string[];
/**
* When true (default), emit structured `openviking: diag {...}` lines (and any future
* standard-diagnostics file writes) for assemble/afterTurn. Set false to disable.
@@ -51,6 +52,7 @@ const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;
const DEFAULT_INGEST_REPLY_ASSIST = true;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS = 2;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS = 120;
+const DEFAULT_INGEST_REPLY_ASSIST_IGNORE_SESSION_PATTERNS: string[] = [];
const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;
const DEFAULT_LOCAL_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");
@@ -86,6 +88,22 @@ function toNumber(value: unknown, fallback: number): number {
return fallback;
}
+function toStringArray(value: unknown, fallback: string[]): string[] {
+ if (Array.isArray(value)) {
+ return value
+ .filter((entry): entry is string => typeof entry === "string")
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ }
+ if (typeof value === "string") {
+ return value
+ .split(/[,\n]/)
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ }
+ return fallback;
+}
+
/** True when env is 1 / true / yes (case-insensitive). Used for debug flags without editing plugin JSON. */
function envFlag(name: string): boolean {
const v = process.env[name];
@@ -142,6 +160,7 @@ export const memoryOpenVikingConfigSchema = {
"ingestReplyAssist",
"ingestReplyAssistMinSpeakerTurns",
"ingestReplyAssistMinChars",
+ "ingestReplyAssistIgnoreSessionPatterns",
"emitStandardDiagnostics",
"logFindRequests",
],
@@ -228,6 +247,10 @@ export const memoryOpenVikingConfigSchema = {
Math.floor(toNumber(cfg.ingestReplyAssistMinChars, DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS)),
),
),
+ ingestReplyAssistIgnoreSessionPatterns: toStringArray(
+ cfg.ingestReplyAssistIgnoreSessionPatterns,
+ DEFAULT_INGEST_REPLY_ASSIST_IGNORE_SESSION_PATTERNS,
+ ),
emitStandardDiagnostics:
typeof cfg.emitStandardDiagnostics === "boolean"
? cfg.emitStandardDiagnostics
@@ -350,6 +373,12 @@ export const memoryOpenVikingConfigSchema = {
help: "Minimum sanitized text length required before ingest reply assist can trigger.",
advanced: true,
},
+ ingestReplyAssistIgnoreSessionPatterns: {
+ label: "Ingest Ignore Session Patterns",
+ placeholder: "agent:*:cron:**",
+ help: "Skip ingest reply assist when the session key matches any glob pattern. Use * within one segment and ** across segments.",
+ advanced: true,
+ },
emitStandardDiagnostics: {
label: "Standard diagnostics (diag JSON lines)",
advanced: true,
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index 06d4b058c..e3acc4184 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -8,8 +8,10 @@ import { OpenVikingClient, localClientCache, localClientPendingPromises, isMemor
import type { FindResultItem, PendingClientEntry, CommitSessionResult, OVMessage } from "./client.js";
import { formatMessageFaithful } from "./context-engine.js";
import {
+ compileSessionPatterns,
isTranscriptLikeIngest,
extractLatestUserText,
+ shouldSkipIngestReplyAssistSession,
} from "./text-utils.js";
import {
clampScore,
@@ -273,6 +275,9 @@ const contextEnginePlugin = {
? (api.pluginConfig as Record<string, unknown>)
: {};
const cfg = memoryOpenVikingConfigSchema.parse(api.pluginConfig);
+ const ingestReplyAssistIgnoreSessionPatterns = compileSessionPatterns(
+ cfg.ingestReplyAssistIgnoreSessionPatterns,
+ );
const rawAgentId = rawCfg.agentId;
if (cfg.logFindRequests) {
api.logger.info(
@@ -925,22 +930,28 @@ const contextEnginePlugin = {
}
if (cfg.ingestReplyAssist) {
- const decision = isTranscriptLikeIngest(queryText, {
- minSpeakerTurns: cfg.ingestReplyAssistMinSpeakerTurns,
- minChars: cfg.ingestReplyAssistMinChars,
- });
- if (decision.shouldAssist) {
+ if (shouldSkipIngestReplyAssistSession(ctx ?? {}, ingestReplyAssistIgnoreSessionPatterns)) {
verboseRoutingInfo(
- `openviking: ingest-reply-assist applied (reason=${decision.reason}, speakerTurns=${decision.speakerTurns}, chars=${decision.chars})`,
- );
- prependContextParts.push(
- "<ingest-reply-assist>\n" +
- "The latest user input looks like a multi-speaker transcript used for memory ingestion.\n" +
- "Reply with 1-2 concise sentences to acknowledge or summarize key points.\n" +
- "Do not output NO_REPLY or an empty reply.\n" +
- "Do not fabricate facts beyond the provided transcript and recalled memories.\n" +
- "</ingest-reply-assist>",
+ `openviking: skipping ingest-reply-assist due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,
);
+ } else {
+ const decision = isTranscriptLikeIngest(queryText, {
+ minSpeakerTurns: cfg.ingestReplyAssistMinSpeakerTurns,
+ minChars: cfg.ingestReplyAssistMinChars,
+ });
+ if (decision.shouldAssist) {
+ verboseRoutingInfo(
+ `openviking: ingest-reply-assist applied (reason=${decision.reason}, speakerTurns=${decision.speakerTurns}, chars=${decision.chars})`,
+ );
+ prependContextParts.push(
+ "<ingest-reply-assist>\n" +
+ "The latest user input looks like a multi-speaker transcript used for memory ingestion.\n" +
+ "Reply with 1-2 concise sentences to acknowledge or summarize key points.\n" +
+ "Do not output NO_REPLY or an empty reply.\n" +
+ "Do not fabricate facts beyond the provided transcript and recalled memories.\n" +
+ "</ingest-reply-assist>",
+ );
+ }
}
}
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index cd007ce29..a5ebecf1b 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -113,6 +113,12 @@
"help": "Minimum sanitized text length required before ingest reply assist can trigger.",
"advanced": true
},
+ "ingestReplyAssistIgnoreSessionPatterns": {
+ "label": "Ingest Ignore Session Patterns",
+ "placeholder": "agent:*:cron:**",
+ "help": "Skip ingest reply assist when the session key matches any glob pattern. Use * within one segment and ** across segments.",
+ "advanced": true
+ },
"emitStandardDiagnostics": {
"label": "Standard diagnostics (diag JSON lines)",
"advanced": true,
@@ -191,6 +197,12 @@
"ingestReplyAssistMinChars": {
"type": "number"
},
+ "ingestReplyAssistIgnoreSessionPatterns": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"emitStandardDiagnostics": {
"type": "boolean"
},
diff --git a/examples/openclaw-plugin/text-utils.ts b/examples/openclaw-plugin/text-utils.ts
index a9f4decef..b3c264bf0 100644
--- a/examples/openclaw-plugin/text-utils.ts
+++ b/examples/openclaw-plugin/text-utils.ts
@@ -80,6 +80,52 @@ export type TranscriptLikeIngestDecision = {
chars: number;
};
+export function compileSessionPattern(pattern: string): RegExp {
+ const escaped = pattern
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
+ .replace(/\*\*/g, "\u0000")
+ .replace(/\*/g, "[^:]*")
+ .replace(/\u0000/g, ".*");
+ return new RegExp(`^${escaped}$`);
+}
+
+export function compileSessionPatterns(patterns: string[]): RegExp[] {
+ return patterns.map((pattern) => compileSessionPattern(pattern));
+}
+
+export function matchesSessionPattern(sessionRef: string, patterns: RegExp[]): boolean {
+ return patterns.some((pattern) => pattern.test(sessionRef));
+}
+
+export function resolveSessionPatternCandidate(params: {
+ sessionId?: string;
+ sessionKey?: string;
+}): string | undefined {
+ const sessionKey = typeof params.sessionKey === "string" ? params.sessionKey.trim() : "";
+ if (sessionKey) {
+ return sessionKey;
+ }
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
+ return sessionId || undefined;
+}
+
+export function shouldSkipIngestReplyAssistSession(
+ params: {
+ sessionId?: string;
+ sessionKey?: string;
+ },
+ patterns: RegExp[],
+): boolean {
+ if (patterns.length === 0) {
+ return false;
+ }
+ const candidate = resolveSessionPatternCandidate(params);
+ if (!candidate) {
+ return false;
+ }
+ return matchesSessionPattern(candidate, patterns);
+}
+
function countSpeakerTurns(text: string): number {
let count = 0;
for (const _match of text.matchAll(SPEAKER_TAG_RE)) {