nowledge-mem 0.1.2: opt-in capture filtering, by SadWood (#567)

nowledge-mem 0.1.2 (SadWood): opt-in capture filtering. `captureFilter: "off"|"human"`
(default "off") and `captureCindy` (default false). Human mode imports only user/assistant
text (tool results dropped, commentary on tool calls kept); with captureCindy and
ctx.agent === "cindy" it removes complete, recognized leading Cindy host notes and keeps
anything unknown, incomplete, fenced, quoted or carrying a scheduled-run/handoff marker
verbatim. Only the copy sent to POST /threads/import changes; external IDs still hash the
original text and occurrence index, so off-mode IDs are unchanged. No new network route.

Reviewed head fed33102005d118507ab14cdc2765a2761254329, merged locally onto origin/main
8b01396 (0fb659a), all on mote:
- node --test packages/nowledge-mem/capture-filter.test.mjs: 52/52.
- bun test packages/nowledge-mem: 105 pass, 1 skip (live).
- Differential test of 0.1.1 vs 0.1.2 hooks (9 requests over chat/responses/anthropic/
  gemini, Cindy notes, tools, images, repeats; 6 off-mode option sets incl. recall and
  captureTools false): import payloads, returned request and reports byte-identical
  (tool_version aside). Human+Cindy mode returns the same request to the model as 0.1.1.
- Full bun test, HOME=$(mktemp -d): 4419 pass, 9 skip, 0 fail. bun scripts/check.mjs: ok.
- Broken by hand, each red: request mutated in capture (34 red); unclosed directory tag
  stripped, truncated UI-language note matched, unterminated context note stripped,
  fences ignored (quoted/fenced/incomplete test red each); default "human" (defaults +
  off-diff red); filtered index in IDs; no trim in off mode; mixed-source guard removed;
  Cindy cleanup for any agent or without opt-in.
Not tried: a real Mem server or a real Cindy session.
This commit is contained in:
SadWood
2026-10-31 22:39:34 +08:00
committed by GitHub
parent f7e0dcb823
commit 5b1ae40256
10 changed files with 829 additions and 14 deletions
+164
View File
@@ -0,0 +1,164 @@
# Capture filtering
These options change only the copy sent to `POST /threads/import`. They do not
edit inference requests, recalled context, system prompts, tool declarations,
tool execution or replies shown to the user. No model is called to classify or
rewrite the conversation. Existing MCP configuration is independent.
## Configuration
In Magpie's plugin **Options**, merge these fields into the existing connection
settings (do not replace the Server URL, API key, Space or profile):
```json
{
"capture": true,
"captureFilter": "human",
"captureCindy": false
}
```
`captureFilter` accepts only `"off"` (default, existing behavior) or `"human"`.
`captureCindy` accepts a boolean, default `false`. Invalid values fail validation;
they do not silently select a more aggressive mode. The existing page preserves
advanced options that it does not display. Capture itself still defaults off.
Human mode keeps text from user and assistant messages and excludes tool results
even when `captureTools` is true. It preserves assistant commentary attached to a
completed tool call, all final text parts, attachment captions, repeated real
utterances, code indentation and long text. It does not synthesize image/file
placeholders or import attachment bytes. The existing protocol parser excludes
structured thinking/reasoning; this option does not try to recognize reasoning
from prose or remove arbitrary `<think>` examples.
The first retained user message supplies the title, cached after a successful
import for the lifetime of the bounded in-process title cache. A transcript with no retained user text is skipped rather than written
as an assistant-only Thread. The source remains `magpie`; Space and Agent/profile
metadata, Thread identity, occurrence indices and existing credential checks are
preserved. Filtering runs *after* the original settlement and credential checks:
a secret in a removed tool argument or Cindy note still blocks capture.
## Optional Cindy cleanup
Set `"captureCindy": true` only to opt into cleaning Cindy's known host notes.
It is effective only with `"captureFilter": "human"` and Magpie's host-derived
`ctx.agent === "cindy"`. A plain `pi`, `omp`, unknown or other agent is not
assumed to be Cindy. The gateway does not inspect launch environment variables,
permission files, databases or local transcripts. It never treats an API key or
a user-authored marker as authentication.
Magpie's [Cindy adapter](https://github.com/yetone/magpie/blob/main/internal/agent/cindy.go)
uses its Cindy agent key for the imported endpoints.
A manually configured provider may report a different agent. In that case the
cleanup remains inactive; use the native integration rather than forcing a
weaker text-only identity guess. Existing local/magpie-key origin restrictions
still apply, including to remotely forwarded requests.
Only complete, recognized *leading* templates are removed: UI language, current
and legacy client notes, directory grants, WeChat channel headers, Side Chat
notes, and explicitly delimited handoff/rebuild/fork notes. Unknown or incomplete
templates stop cleanup and stay verbatim. Fenced/quoted examples, notes later in
user text and all assistant text stay untouched. Exactly matching raw templates
pasted at the beginning of a Cindy user message cannot be distinguished from
host notes; quote or fence such examples, or disable this option.
Scheduled-run and partner-handoff messages can combine host bookkeeping, event
data, a user's request, constraints and a partner's objective in one wire
message. The gateway has no trusted per-span provenance for those messages. If
any of the guarded scheduled-run or handoff markers appears anywhere in Cindy
user text, cleanup preserves the **entire** message, including recognized notes
before it. This is a conservative stop, not a claim that the marker proves a
scheduled run or identifies a speaker. An ordinary user, quoted example or
fenced sample containing a marker also stops cleanup. Unknown variants may not
contain those markers and are not reliably classified. These messages and their
host text may still be saved and used for the Thread title.
The imported `role=user` is the incoming protocol role, not verified authorship:
the receiving application may display a combined partner objective as a user
message. This filter cannot split or attribute those spans safely; it does not
remove the objective or identify it as human-authored. Use a native integration
with trustworthy per-message provenance when correct attribution is required.
A user-pasted exact *older* recognized leading template without a guarded marker
can still be stripped; disable `captureCindy` to preserve it. There is no safe
text-only way to distinguish that paste from the host's identical text.
WeChat display names and explicit ownership survive as `metadata.cindy_origin`;
group/non-owner speech also keeps a short speaker label. Recognized channel and
client headers lose their transport chat/user/device IDs. This is not a general
PII scrubber and does not remove identifiers from genuine dialogue.
Recognition is bounded to 32 stacked prefixes, 64 Ki UTF-16 code units per
multiline wrapper and 8192 code units for a single-line template. Unrecognized or
oversized suffixes stay intact. These scan bounds do not truncate dialogue;
the original 512 KiB UTF-8 serialized-message import limit still applies.
## What the gateway cannot know
`human` means a conservative user/assistant **wire-text projection**, not proof
that every `role=user` text was typed by a human. In particular, it cannot recover
OMP's native `attribution=agent`, a skill's original `details.prompt`, Pi entry
IDs/timestamps or Cindy's parent-session header and creation boundary when those
are absent from the request. Internal continuations already flattened into user
text stay intact. Literal user `/skill:...` commands are retained, but expanded
skills cannot be reconstructed into their original drafts.
A Side Chat note is cleaned as a note; inherited parent messages are **not**
trimmed or deduplicated by text. No parent Mem Thread binding is inferred. Use the
native Pi/OMP integration for exact lifecycle capture, branch scoping and selected
Thread continuation. A gateway request carrying only an opaque previous-response
reference still cannot supply missing history. Capture remains best-effort,
not a durable queue; this change does not repair backend distillation, browser
DOM extraction, native worker scheduling or old saved data.
## Regression sources and coverage
All fixtures are synthetic. Public reports motivate invariants here; these tests
do **not** claim to reproduce or fix the reports' other integrations end to end.
| Source | Reused scenario / invariant | Gateway boundary |
|---|---|---|
| [OMP PR #782](https://github.com/nowledge-co/community/pull/782) at `66fee750ca16c087d50c960b514dba3e626233e5` | `fixtures/dialogue-projection.json` adapts the expected dialogue; wire test matches its role/text oracle, including commentary, literal skills, captions, complete long text and repeated occurrences | Native attribution filtering, original-skill reconstruction and native message IDs are not asserted |
| [Pi/Cindy PR #785](https://github.com/nowledge-co/community/pull/785) at `594b1520fb7a187f1deddc660a4602665d85ff3b` | `fixtures/cindy-context.json` is copied unchanged; known prefix recognition, stacked notes, CRLF, indentation, incomplete/quoted examples, speaker attribution and transport-ID removal | Explicit option + Magpie `cindy` identity replaces native launcher markers; no fork-boundary inference |
| [community #200](https://github.com/nowledge-co/community/issues/200) | Recognized Cindy preambles do not become the title; the acknowledged title stays stable | Not an LLM title generator or universal preamble detector |
| [community #544](https://github.com/nowledge-co/community/issues/544) and [nowledge-mem #182](https://github.com/nowledge-co/nowledge-mem/issues/182) | Structured reasoning is excluded while all final text parts and commentary survive across Chat, Responses, Anthropic and Gemini shapes | Not a browser selector fix |
| [community #756](https://github.com/nowledge-co/community/issues/756), [#698](https://github.com/nowledge-co/community/issues/698) | Bounded prefix recognition, unchanged UTF-8 import cap, long CJK/emoji text kept below the cap | No native transcript scanning, new workers or Working Memory compressor |
| [nowledge-mem #161](https://github.com/nowledge-co/nowledge-mem/issues/161) | Capture filtering leaves inference requests, tools, recalled content and live output unchanged | Not a backend cache-routing fix |
| [community #459](https://github.com/nowledge-co/community/issues/459) | An unsuccessful import is not recorded as an acknowledged filtered replay; a later event can succeed | No new retry worker or persistent delivery guarantee |
Additional synthetic scheduled-run and partner-handoff tests preserve mixed
source text, task constraints, quoted/fenced examples and original message IDs.
They do not verify real host payloads or identify authors. Other negative tests
retain inherited Side Chat history and ambiguous OMP user text, and enforce
opt-in, source restrictions, secrets in removed content,
unsettled tools, incomplete output and package/default contracts.
Run the focused suite with either runtime:
```sh
node --test packages/nowledge-mem/capture-filter.test.mjs
HOME=$(mktemp -d) bun test packages/nowledge-mem
```
The tests stub Mem's HTTP endpoints and inspect outbound request bodies. They
prove filtering/transport contracts, not real-Mem persistence or live-host capture.
## Changing policy and returning to upstream
External message IDs use the original normalized message text and occurrence index,
so changing filtering or Cindy cleanup preserves IDs for retained messages and the
legacy off-mode ID format. Existing Threads are not automatically migrated; the
result of reimporting changed content depends on the receiving service. Identical
utterances at different positions remain distinct.
Run only one capture owner for a given session. Do not enable both original and
forked gateway plugins, or native capture plus gateway capture, for the same
traffic. Keep your existing MCP tools; this option does not register them.
A temporary fork can return to upstream after the PR is merged **and the installed
upstream artifact actually includes these options**, not merely after a merge
notification. Preserve the connection/options, disable the temporary plugin,
install/update the upstream package, and validate one new synthetic session in a
disposable Space before resuming real captures. Confirm one Thread, clean text,
correct origin/Space and one successful append. If native lifecycle/Side Chat
accuracy remains required, keep the native capture path instead. This document
does not automatically install, publish, migrate or change any live configuration.
+15 -2
View File
@@ -132,6 +132,15 @@ derived value for all of them.
Set `"capture": true` explicitly to opt in.
- `captureTools`: default **true**. Include client tool results as `tool`
messages. Turn it off to import only what the user and the assistant wrote.
- `captureFilter`: `"off"` (default) or `"human"`. Human mode stores only
user/assistant text, including commentary attached to completed tool calls;
it excludes tool results regardless of `captureTools`. Only the saved copy
changes. See [capture filtering and its limits](CAPTURE_FILTER.md).
- `captureCindy`: default **false**. With `captureFilter: "human"`, remove
complete known leading Cindy notes only when Magpie identifies the agent
as `cindy`. Mixed scheduled or partner handoff text is conservatively retained;
the protocol role does not establish authorship. It does not infer native Side
Chat boundaries. Configure both options in Plugins → Options.
- `allowInsecureHttp`: default **false**. Permits plain HTTP to a server that
is not a loopback address. Prefer HTTPS.
- `port`: the loopback port of the page's connection test, default 3479. Change
@@ -189,7 +198,9 @@ sent plus the assistant's reply, and imported with `POST /threads/import`:
directory — not their raw values.
Messages are text only. Assistant tool-call steps with no text are not
messages; client tool results are included while `captureTools` is on. The
messages; client tool results are included while `captureTools` is on and
`captureFilter` is `"off"`. In `"human"` mode, the title comes from the first
retained user message and is cached after a successful import. The
recalled `<nowledge-mem-reference>` blocks are stripped before import, so
Memory is never learned as a new conversation. A conversation with a
credential-like assignment, URL password, bearer token or common key format in
@@ -199,7 +210,8 @@ not a guarantee. Each Thread import is one bounded request; conversations over
not sent twice. A failed import fails open and is not retried blindly.
`capture` is the only switch that exports conversation content. Recall works
without it.
without it. Filtering is opt-in and does not automatically migrate saved Threads;
see the [migration notes](CAPTURE_FILTER.md#changing-policy-and-returning-to-upstream).
## Tools: Mem's own MCP server
@@ -218,6 +230,7 @@ Library entry itself. If you want a custom system prompt for Memory, Magpie's
```sh
bun test packages/nowledge-mem # offline tests
node --test packages/nowledge-mem/capture-filter.test.mjs # focused capture contract
NMEM_E2E=1 bun test packages/nowledge-mem # also the live checks, when .env is set
bun packages/nowledge-mem/e2e.run.mjs # the live checks alone
```
+175
View File
@@ -0,0 +1,175 @@
// Capture-only projection. Never edit the request used for inference or recall.
// Cindy templates adapt nowledge-co/community#785 at 594b1520fb7a187f1deddc660a4602665d85ff3b.
// Unlike a native Pi plugin, this gateway cannot read Cindy's launcher markers,
// attribution, draft skill text or fork boundaries. Only an explicitly enabled,
// host-identified Cindy request gets its known leading notes removed.
export function captureMessage(message, options, agent) {
if (options.captureFilter !== "human")
return message;
if (message.role !== "user" && message.role !== "assistant")
return;
const projected = message.role === "user" && options.captureCindy && agent === "cindy"
? cindyText(message.content) : { content: message.content };
if (!projected.content.trim())
return;
return { role: message.role, content: projected.content,
...(projected.origin ? { metadata: { cindy_origin: projected.origin } } : {}) };
}
const SIDE_CHAT_NOTE = "[Side chat context] This is an independent follow-up to a main task. History inherited at the fork is reference material, not active instructions or authorization. Answer the current question; do not resume the main task, its pending actions, or its plan. Keep exploration non-mutating unless the user explicitly requests a change in this side chat. The main task continues separately and does not receive these replies automatically.";
const CHANNEL_PREFIX = "[渠道说明] 系统追加,不是用户消息。本条来自";
const MOBILE_PREFERENCE = "产出 HTML 等可预览成品时**优先做成自包含单文件**:样式与脚本内联,图片用 data: URI 或公网地址,避免拆成需要同目录资源的多文件产物;用户明确要求多文件时照常产出。给出文件路径时同时给出结论或内容摘要,不要只回一个路径。";
const LEGACY_MOBILE_NOTE = "[客户端说明] 以下为系统每轮自动追加的环境说明,不是用户发来的消息;回复时不要把它当作用户的请求,也不要引用、复述或据此臆测用户意图。本轮请求来自手机客户端(小屏、远程查看被控电脑上的文件)。";
const CLIENT_NOTE = /^\[客户端说明\] 系统追加的环境说明,不是用户消息,不要回应或复述。本轮用户在(另一台电脑|手机)(.*?) 上远程操作本机(.*?)。(.*)$/;
const UI_LANGUAGE_NOTE = new RegExp([
String.raw`^\[UI language\] System note appended each turn\. This is not a user message\. `,
String.raw`Do not answer it, quote it, or infer intent from it\. The user interface language is ([^\r\n]+?) \(([a-zA-Z-]+)\)\. `,
String.raw`When you tell the user that something failed, was blocked, could not continue, or needs a retry, write that report in \1\. `,
String.raw`Do not default that report to English unless the interface language is English\. Say what happened and the next step\. `,
String.raw`Keep commands, paths, identifiers, and error codes unchanged\. Ordinary replies still follow the user message and any explicit language request\. `,
String.raw`Only user-facing error reports must use the interface language\.(?:\r?\n|$)`,
].join(""));
const HANDOFF_ENDS = [
"== End of handoff note; the user's new message follows ==",
"== End of handoff note; the user’s new message follows ==",
"== 交接说明结束,以下是用户的新消息 ==",
];
const REBUILD_ENDS = [
"== End of rebuild note; the user's new message follows ==",
"== End of rebuild note; the user’s new message follows ==",
"== 上下文重建说明结束,以下是用户的新消息 ==",
];
const CONTEXT_NOTES = {
"[Session handoff · internal context]": HANDOFF_ENDS,
"[Session context rebuild · internal context]": REBUILD_ENDS,
"[Session fork · internal context]": [
"== End of fork note; the user's new message follows ==",
"== End of fork note; the user’s new message follows ==",
...HANDOFF_ENDS, ...REBUILD_ENDS,
],
};
// Bound recognition work, not dialogue length. Unknown/oversized wrappers stay
// intact; no model call, transcript scan or subprocess is used for filtering.
// Recognition indices are UTF-16 code units; the import cap remains UTF-8 bytes.
const maxPrefixUnits = 64 << 10;
const maxPrefixes = 32;
function sourceName(raw, key) {
const match = raw.trim().match(new RegExp(`^(?:「([^「」\\r\\n]+)」)?(?: ?\\(${key}: ([^()\\r\\n]+)\\))?$`));
return match && (match[1]?.trim() || match[2]?.trim()) ? match[1] : false;
}
function clientPrefix(line, remainder) {
if (line !== LEGACY_MOBILE_NOTE + MOBILE_PREFERENCE) {
const match = line.match(CLIENT_NOTE);
if (!match || sourceName(match[2], "device_id") === false || sourceName(match[3], "device_id") === false)
return;
if (match[4] && (match[1] !== "手机" || match[4] !== MOBILE_PREFERENCE))
return;
}
return { remainder };
}
function channelPrefix(line, remainder) {
if (!line.startsWith(CHANNEL_PREFIX) || !line.endsWith("。"))
return;
const match = line.slice(CHANNEL_PREFIX.length, -1).match(/^(?:微信| WeChat )(私聊|群)(.*)$/);
if (!match)
return;
const refs = match[2].split(",发言人");
if (refs.length > 2)
return;
const chatName = sourceName(refs[0], "chat_id");
if (chatName === false)
return;
const origin = { channel: "wechat", chat_kind: match[1] === "群" ? "group" : "direct" };
if (chatName)
origin.chat_name = chatName;
if (refs.length === 2) {
const ownership = refs[1].match(/(?:,)?(不是主人|是主人)$/);
const sender = ownership ? refs[1].slice(0, ownership.index) : refs[1];
const senderName = !sender.trim() && ownership ? undefined : sourceName(sender, "user_id");
if (senderName === false)
return;
if (senderName)
origin.sender_name = senderName;
if (ownership)
origin.sender_is_owner = ownership[1] === "是主人";
}
return { remainder, origin };
}
function contextPrefix(content, heading) {
const terminators = Object.hasOwn(CONTEXT_NOTES, heading) ? CONTEXT_NOTES[heading] : undefined;
if (!terminators)
return;
let fence;
for (const match of content.slice(0, maxPrefixUnits + 1).matchAll(/^.*(?:\r?\n|$)/gm)) {
if (match.index + match[0].length > maxPrefixUnits)
return;
const line = match[0].replace(/\r?\n$/, "");
const marker = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
if (marker) {
if (!fence)
fence = marker[1];
else if (marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim())
fence = undefined;
continue;
}
if (!fence && terminators.includes(line))
return { remainder: content.slice(match.index + match[0].length) };
}
}
function knownPrefix(content) {
if (content.startsWith(SIDE_CHAT_NOTE)) {
const remainder = content.slice(SIDE_CHAT_NOTE.length);
if (!remainder || /^\r?\n/.test(remainder))
return { remainder };
}
for (const tag of ["cindy-extra-writable-directories", "cindy-extra-reference-directories"]) {
if (!content.startsWith(`<${tag}>\n`) && !content.startsWith(`<${tag}>\r\n`))
continue;
const close = `</${tag}>`;
const end = content.slice(0, maxPrefixUnits).indexOf(close);
if (end < 0 || end + close.length > maxPrefixUnits)
return;
const remainder = content.slice(end + close.length);
return remainder === "" || /^\r?\n/.test(remainder) ? { remainder } : undefined;
}
const head = content.slice(0, 8193);
const newline = head.indexOf("\n");
const end = newline < 0 ? content.length : newline;
if (end > 8192)
return;
const line = content.slice(0, end).replace(/\r$/, "");
const note = content.match(UI_LANGUAGE_NOTE);
if (note)
return { remainder: content.slice(note[0].length) };
const remainder = newline < 0 ? "" : content.slice(newline + 1);
return channelPrefix(line, remainder) || clientPrefix(line, remainder) || contextPrefix(content, line);
}
// These strings only make cleanup more conservative. They are not evidence of
// origin or identity: a user can write or quote any of them. Keep the whole
// message, including any recognized earlier prefix, when boundaries are unclear.
const mixedSourceMarkers = [
"主人开启了自动跟进;这一轮由宿主的任务事件唤醒,不是主人刚说的话。",
"[Scheduled run context]", "[Routine checkpoint]", "[Silent scheduled run]",
"[Task delivery]", "[消息来源]", "[任务来源]",
];
function cindyText(content) {
if (mixedSourceMarkers.some((marker) => content.includes(marker)))
return { content };
let remainder = content;
let origin;
for (let count = 0; count < maxPrefixes; count++) {
const prefix = knownPrefix(remainder);
if (!prefix)
break;
// Consume separator lines, never indentation in the actual message.
remainder = prefix.remainder.replace(/^(?:[ \t]*\r?\n)+/, "");
origin = prefix.origin || origin;
}
let speaker = "";
if (origin && (origin.chat_kind === "group" || origin.sender_is_owner === false)) {
speaker = origin.sender_name ? `发言人「${origin.sender_name}」:\n`
: origin.sender_is_owner === false ? "发言人(非主人):\n" : "群聊发言人:\n";
}
return { content: remainder.trim() ? speaker + remainder : "", ...(origin ? { origin } : {}) };
}
@@ -0,0 +1,390 @@
// Run with node --test or bun test. No network, credentials or live Mem writes.
// Scenario provenance and gateway-only limits: CAPTURE_FILTER.md.
import { test, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { onRequest, onResponse, reset } from "./nowledge-mem.hooks.mjs";
import { resolveOptions, sha256 } from "./mem.mjs";
import { open, close, notice } from "./conversation.mjs";
const fixture = JSON.parse(readFileSync(new URL("./fixtures/cindy-context.json", import.meta.url), "utf8"));
const mixedFixture = JSON.parse(readFileSync(new URL("./fixtures/cindy-scheduled-handoff.json", import.meta.url), "utf8"));
const user = (content) => ({ role: "user", content });
const assistant = (content) => ({ role: "assistant", content });
const reply = (content = "Complete final answer") => ({ choices: [{ finish_reason: "stop", message: assistant(content) }] });
const body = (messages) => ({ model: "fixture-model", stream: true, messages });
const human = { captureFilter: "human", captureCindy: true };
let writes, calls, savedFetch;
beforeEach(() => {
reset();
writes = []; calls = [];
savedFetch = globalThis.fetch;
globalThis.fetch = async (url, init) => {
calls.push({ url: String(url), init });
if (url.pathname === "/threads/import") {
writes.push(JSON.parse(init.body));
return Response.json({ success: true, failed_count: 0, results: [{ success: true }] });
}
if (url.pathname === "/memories/search")
return Response.json([{ memory: { id: "fixture-memory", title: "Past decision", content: "Remembered context" }, similarity_score: 0.9 }]);
if (url.pathname === "/context/bundle")
return Response.json({ rendered_markdown: "Fixture owner profile" });
throw new Error("Unexpected test route");
};
});
afterEach(() => { globalThis.fetch = savedFetch; reset(); });
function context(options = {}, extra = {}) {
return {
protocol: "chat", origin: "local", agent: "cindy", session: "fixture-session", cwd: "/fixture/项目",
options: { serverUrl: "https://mem.invalid", apiKey: "fixture-key", recall: false, capture: true, ...options },
state: {}, signal: new AbortController().signal, success: true, report() {}, ...extra,
};
}
async function capture(request, response = reply(), options = {}, extra = {}) {
const ctx = context(options, extra);
const accepted = await onRequest(request, ctx);
ctx.request = accepted ?? request;
await onResponse(response, ctx);
return ctx;
}
const contents = () => writes.at(-1)?.messages.map((m) => m.content);
function freeze(value) {
if (value && typeof value === "object") {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
// The first three cases are regression witnesses: they must fail on 0.1.1.
test("capture options default off and reject invalid enum/boolean values", () => {
const defaults = resolveOptions({}, {});
assert.equal(defaults.captureFilter, "off");
assert.equal(defaults.captureCindy, false);
for (const value of ["auto", "Human", "", null, true, 1, {}])
assert.throws(() => resolveOptions({ captureFilter: value }, {}), /invalid/);
for (const value of ["true", 1, null])
assert.throws(() => resolveOptions({ captureCindy: value }, {}), /invalid/);
});
test("human mode excludes tools but retains commentary attached to a tool call", async () => {
const request = body([
user("Please inspect the file"),
{ ...assistant("I will inspect the relevant section."), tool_calls: [{ id: "call-1", type: "function", function: { name: "read", arguments: "{}" } }] },
{ role: "tool", tool_call_id: "call-1", content: "TOOL-ONLY-NOISE" },
]);
await capture(freeze(request), freeze(reply()), { ...human, captureTools: false });
assert.deepEqual(contents(), ["Please inspect the file", "I will inspect the relevant section.", "Complete final answer"]);
});
test("Cindy stacked notes do not become dialogue or the Thread title (#200)", async () => {
const request = body([user([fixture.side, fixture.language, fixture.client, fixture.writable, fixture.handoff, "Inspect the capture filter"].join("\n\n"))]);
const original = structuredClone(request);
await capture(request, reply(), human);
assert.deepEqual(contents(), ["Inspect the capture filter", "Complete final answer"]);
assert.equal(writes[0].title, "Inspect the capture filter");
assert.deepEqual(request, original);
});
for (const name of ["side", "channel", "client", "language", "writable", "referenceDirectories", "handoff", "rebuild", "fork"]) {
test(`Cindy recognizes complete ${name} prefix with CRLF`, async () => {
await capture(body([user(fixture[name].replaceAll("\n", "\r\n") + "\r\n\r\n indented code\n remains")]), reply(), human);
assert.equal(contents()[0], " indented code\n remains");
});
}
test("Cindy group keeps speaker attribution without transport identifiers", async () => {
await capture(body([user(fixture.group + "\n" + fixture.language + "\n请检查计算公式")]), reply(), human);
const message = writes[0].messages[0];
assert.equal(message.content, "发言人「Fixture Guest」:\n请检查计算公式");
assert.deepEqual(message.metadata.cindy_origin, { channel: "wechat", chat_kind: "group", chat_name: "Fixture Group", sender_name: "Fixture Guest", sender_is_owner: false });
assert.doesNotMatch(JSON.stringify(writes[0]), /synthetic-group|synthetic-sender|chat_id|user_id/);
});
test("Cindy ownership-only private sender is not attributed to the owner", async () => {
const prefix = "[渠道说明] 系统追加,不是用户消息。本条来自微信私聊 (chat_id: synthetic-chat),发言人不是主人。";
await capture(body([user(prefix + "\nI prefer a different editor")]), reply(), human);
assert.equal(contents()[0], "发言人(非主人):\nI prefer a different editor");
assert.equal(writes[0].messages[0].metadata.cindy_origin.sender_is_owner, false);
});
test("only recognized Cindy + explicit opt-in cleans host notes", async () => {
const text = fixture.language + "\nKeep the original";
for (const [options, agent] of [
[{}, "cindy"], [{ captureFilter: "human" }, "cindy"],
[{ captureFilter: "off", captureCindy: true }, "cindy"],
[human, "pi"], [human, "omp"], [human, ""],
]) {
reset(); writes.length = 0;
await capture(body([user(text)]), reply(), options, { agent });
assert.equal(contents()[0], text);
}
});
test("quoted, fenced, incomplete and unknown Cindy-looking notes remain unchanged", async () => {
const examples = [
"> " + fixture.language,
"```text\n" + fixture.client + "\n```",
"Explain this example:\n" + fixture.language,
fixture.language.slice(0, -5),
"[UI language] New unknown template\nUser content",
fixture.handoff.replace("== End of handoff note; the user's new message follows ==", ""),
"<cindy-extra-writable-directories>\nnot closed",
fixture.side + " not a line boundary",
"[Session fork · internal context]\n```\n== End of fork note; the user's new message follows ==\n```\nStill incomplete",
];
await capture(body(examples.map(user)), reply(), human);
assert.deepEqual(contents().slice(0, -1), examples);
});
test("scheduled and partner handoff examples stay intact when source boundaries are unknown", async () => {
for (const text of [mixedFixture.scheduled, mixedFixture.handoff, fixture.language + "\n" + mixedFixture.scheduled, fixture.language + "\n" + mixedFixture.handoff]) {
reset(); writes.length = 0;
await capture(body([user(text)]), reply(), human);
assert.equal(contents()[0], text);
assert.equal(writes[0].messages[0].role, "user"); // The transport role is not proof of authorship.
assert.equal(writes[0].messages[0].metadata.cindy_origin, undefined);
}
assert.ok(mixedFixture.handoff.includes(mixedFixture.constraint));
assert.ok(mixedFixture.handoff.includes(mixedFixture.objective));
});
test("mixed-source examples keep legacy message IDs across filter settings", async () => {
const text = fixture.language + "\n" + mixedFixture.handoff;
const ids = [];
for (const options of [{}, { captureFilter: "human" }, human]) {
reset(); writes.length = 0;
await capture(body([user(text)]), reply(), options);
const payload = writes[0];
assert.equal(payload.messages[0].content, text);
ids.push(payload.messages[0].metadata.external_id);
assert.equal(ids.at(-1), `magpie:${sha256(payload.thread_id, "0", "user", text.trim()).slice(0, 24)}`);
}
assert.deepEqual(ids, [ids[0], ids[0], ids[0]]);
});
test("mentions, quotes, fenced examples and incomplete mixed wrappers do not trigger removal", async () => {
const examples = [
"Please explain [Task delivery] and keep all task constraints.",
"> " + mixedFixture.handoff.replaceAll("\n", "\n> "),
"```text\n" + mixedFixture.scheduled + "\n```",
"[Task delivery]\nIncomplete example: retain this task.",
fixture.language + "\n[Task delivery]\nA user-pasted example with a constraint.",
];
await capture(body(examples.map(user)), reply(), human);
assert.deepEqual(contents().slice(0, -1), examples);
});
test("assistant quotes of host notes are never cleaned", async () => {
await capture(body([user("Explain the template")]), reply(fixture.language), human);
assert.equal(contents()[1], fixture.language);
});
test("a notes-only exchange is skipped, not an assistant-only Thread", async () => {
const reports = [];
await capture(body([user(fixture.language)]), reply(), human, { report: (...args) => reports.push(args) });
assert.equal(writes.length, 0);
assert.equal(reports.at(-1)?.[0], "skipped");
});
test("filter keeps complete long CJK text and attachment captions, not image bytes", async () => {
const long = "中文完整记录🙂".repeat(4000);
const request = body([user([{ type: "text", text: fixture.language + "\n" + long }, { type: "image_url", image_url: { url: "data:image/png;base64,fixture" } }, { type: "text", text: "图:设备铭牌" }])]);
await capture(request, reply("完整答复"), human);
assert.equal(contents()[0], long + "\n图:设备铭牌");
assert.doesNotMatch(JSON.stringify(writes[0]), /base64|\[image\]/);
});
test("multiple text parts keep indentation after host-prefix removal", async () => {
await capture(body([user([{ type: "text", text: fixture.language }, { type: "text", text: " first\n second" }])]), reply(), human);
assert.equal(contents()[0], " first\n second");
});
test("repeated real messages retain distinct occurrence IDs and replay is idempotent", async () => {
const request = body([user(fixture.language + "\nAgain"), assistant("Previous reply"), user(fixture.language + "\nAgain")]);
await capture(structuredClone(request), reply(), human);
const first = structuredClone(writes[0]);
assert.notEqual(first.messages[0].metadata.external_id, first.messages[2].metadata.external_id);
await capture(structuredClone(request), reply(), human);
assert.equal(writes.length, 1);
const next = body([...request.messages, assistant("Complete final answer"), user("New turn")]);
await capture(next, reply("Next answer"), human);
assert.equal(writes[1].thread_id, first.thread_id);
assert.deepEqual(writes[1].messages.slice(0, 4), first.messages);
assert.equal(writes[1].title, first.title);
});
test("filter preserves Space and Agent provenance", async () => {
await capture(body([user(fixture.language + "\nDo the work")]), reply(), { ...human, spaceId: "fixture-space", agentId: "fixture-profile", hostAgentId: "fixture-host" });
assert.equal(writes[0].space_id, "fixture-space");
assert.equal(writes[0].metadata.agent, "cindy");
assert.equal(writes[0].metadata.agent_id, "fixture-profile");
assert.equal(writes[0].metadata.host_agent_id, "fixture-host");
assert.equal(writes[0].metadata.cwd, sha256("/fixture/项目"));
});
test("no native metadata: preserve inherited side-chat history and internal-looking user text", async () => {
await capture(body([user("Parent request"), assistant("Parent reply"), user(fixture.side + "\nNew question"), user("Continue the plan. This is an internal summary.")]), reply(), human);
assert.deepEqual(contents(), ["Parent request", "Parent reply", "New question", "Continue the plan. This is an internal summary.", "Complete final answer"]);
});
test("human mode never bypasses the original credential guard, including removed content", async () => {
for (const request of [
body([user(fixture.handoff.replace("Synthetic history index", "api_key=not-a-real-key") + "\nSafe question")]),
body([user("Question"), { ...assistant("Working"), tool_calls: [{ id: "s", type: "function", function: { name: "read", arguments: '{"token":"not-a-real-key"}' } }] }, { role: "tool", tool_call_id: "s", content: "safe" }]),
]) {
await capture(request, reply(), human);
assert.equal(writes.length, 0);
}
});
test("unsettled tools and incomplete output remain ineligible before filtering", async () => {
const pending = body([user("Do work"), { ...assistant("Working"), tool_calls: [{ id: "p", type: "function", function: { name: "read", arguments: "{}" } }] }]);
await capture(pending, reply(), human);
await capture(body([user("Question")]), { choices: [{ finish_reason: "length", message: assistant("Partial") }] }, human);
assert.equal(writes.length, 0);
});
test("capture remains opt-in and never broadens the source allowlist", async () => {
for (const origin of ["gateway-key", "remote", undefined])
await capture(body([user("Question")]), reply(), human, { origin });
await capture(body([user("Question")]), reply(), { ...human, capture: false });
assert.equal(writes.length, 0);
await capture(body([user("Question")]), reply(), human, { origin: "magpie-key" });
assert.equal(writes.length, 1);
});
test("read-side recall, tools and live replies are unaffected by capture filtering (#161)", async () => {
const make = () => ({ ...body([user(fixture.language + "\nQuestion")]), tools: [{ type: "function", function: { name: "read", parameters: { type: "object" } } }] });
const originalReply = freeze(reply());
const off = await capture(make(), originalReply, { recall: true });
const expected = structuredClone(off.request);
reset();
const filtered = await capture(make(), originalReply, { ...human, recall: true });
assert.deepEqual(filtered.request, expected);
assert.equal(contents()[0], "Question");
assert.doesNotMatch(JSON.stringify(writes.at(-1)), /Remembered context|Fixture owner profile/);
});
test("large captures retain the existing UTF-8 size guard (#756, #698)", async () => {
await capture(body([user("中".repeat(180000))]), reply(), human);
assert.equal(writes.length, 0);
await capture(body([user("z".repeat(490000))]), reply(), human);
assert.equal(contents()[0].length, 490000);
});
test("a failed import is not acknowledged as a successful filtered replay (#459)", async () => {
const original = globalThis.fetch;
let fail = true;
globalThis.fetch = async (url, init) => fail && url.pathname === "/threads/import" ? Response.json({ success: false, failed_count: 1 }) : original(url, init);
const request = () => body([user(fixture.language + "\nKeep this")]);
await capture(request(), reply(), human);
assert.equal(writes.length, 0);
fail = false;
await capture(request(), reply(), human);
assert.equal(writes.length, 1);
});
for (const protocol of ["responses", "anthropic", "gemini"]) {
test(`human ${protocol} capture keeps final text, not thinking or tool results (#544 / #182)`, async () => {
const prompt = fixture.language + "\nQuestion";
const request = protocol === "responses" ? { model: "m", input: [{ role: "user", content: [{ type: "input_text", text: prompt }] }] }
: protocol === "anthropic" ? { model: "m", messages: [{ role: "user", content: [{ type: "text", text: prompt }] }] }
: { contents: [{ role: "user", parts: [{ text: prompt }] }] };
const response = protocol === "responses" ? { status: "completed", output: [{ type: "reasoning", summary: [{ type: "summary_text", text: "THINKING" }] }, { type: "message", role: "assistant", content: [{ type: "output_text", text: "Final part one" }, { type: "output_text", text: "Final part two" }] }] }
: protocol === "anthropic" ? { role: "assistant", stop_reason: "end_turn", content: [{ type: "thinking", thinking: "THINKING" }, { type: "text", text: "Final part one" }, { type: "text", text: "Final part two" }] }
: { candidates: [{ finishReason: "STOP", content: { role: "model", parts: [{ thought: true, text: "THINKING" }, { text: "Final part one" }, { text: "Final part two" }] } }] };
await capture(freeze(request), freeze(response), human, { protocol });
assert.deepEqual(contents(), ["Question", "Final part one\nFinal part two"]);
});
}
test("OMP wire projection matches #782's dialogue oracle for information present on the wire", async () => {
const oracle = JSON.parse(readFileSync(new URL("./fixtures/dialogue-projection.json", import.meta.url), "utf8"));
// Native attribution/custom records do not exist here. A literal slash command
// is retained; an expanded skill cannot be reconstructed by this gateway.
const request = body([
{ role: "system", content: "INTERNAL system instructions" },
user("Synthetic human question"),
{ ...assistant("I will check the change"), tool_calls: [{ id: "oracle-read", type: "function", function: { name: "read", arguments: "{}" } }] },
{ role: "tool", tool_call_id: "oracle-read", content: "INTERNAL tool output" },
{ ...assistant("Synthetic assistant answer"), reasoning_content: "INTERNAL thinking" },
user("/skill:review fixture"),
user([{ type: "text", text: "Look at these" }, { type: "image_url", image_url: { url: "data:image/png;base64,INTERNAL" } }, { type: "file", file: { file_data: "INTERNAL", filename: "fixture.txt" } }]),
]);
await capture(freeze(request), freeze(reply("I reviewed the attachments")), { captureFilter: "human" }, { agent: "omp" });
assert.deepEqual(writes[0].messages.map(({ role, content }) => ({ role, content })), oracle.messages);
assert.doesNotMatch(JSON.stringify(writes[0]), /INTERNAL|\[image\]|\[file\]/);
});
test("default-off capture retains the legacy tool result and whitespace policy", async () => {
const request = body([user(" Question "), { ...assistant(" Working "), tool_calls: [{ id: "legacy", type: "function", function: { name: "read", arguments: "{}" } }] }, { role: "tool", tool_call_id: "legacy", content: " Result " }]);
await capture(request, reply(" Done "));
assert.deepEqual(contents(), ["Question", "Working", "Result", "Done"]);
reset(); writes.length = 0;
await capture(request, reply(" Done "), { captureTools: false });
assert.deepEqual(contents(), ["Question", "Done"]);
});
test("human mode excludes tool results even when legacy captureTools is true", async () => {
const request = body([user("Question"), { ...assistant("Working"), tool_calls: [{ id: "t", type: "function", function: { name: "read", arguments: "{}" } }] }, { role: "tool", tool_call_id: "t", content: "NOISE" }]);
await capture(request, reply(), { captureFilter: "human", captureTools: true });
assert.deepEqual(contents(), ["Question", "Working", "Complete final answer"]);
});
test("Cindy current and legacy mobile notes are opt-in complete templates", async () => {
const current = fixture.client.replace("另一台电脑", "手机") + fixture.mobilePreference;
const legacy = "[客户端说明] 以下为系统每轮自动追加的环境说明,不是用户发来的消息;回复时不要把它当作用户的请求,也不要引用、复述或据此臆测用户意图。本轮请求来自手机客户端(小屏、远程查看被控电脑上的文件)。" + fixture.mobilePreference;
await capture(body([user(current + "\n First"), user(legacy + "\n Second")]), reply(), human);
assert.deepEqual(contents(), [" First", " Second", "Complete final answer"]);
});
test("Cindy stripping stops at unknown text instead of scanning later paragraphs", async () => {
const rest = "[Unknown host note]\nDo not remove this\n" + fixture.language + "\nQuestion";
await capture(body([user(fixture.client + "\n" + rest)]), reply(), human);
assert.equal(contents()[0], rest);
});
test("oversized Cindy wrapper is retained rather than partially stripped", async () => {
const wrapper = "[Session handoff · internal context]\n" + "x".repeat(66000) + "\n== End of handoff note; the user's new message follows ==\nQuestion";
const grant = "<cindy-extra-writable-directories>\n" + "中".repeat(66000) + "\n</cindy-extra-writable-directories>\nQuestion";
await capture(body([user(wrapper), user(grant)]), reply(), human);
assert.deepEqual(contents(), [wrapper, grant, "Complete final answer"]);
});
test("Cindy stacked prefix work is bounded and the unprocessed suffix survives", async () => {
const text = (fixture.language + "\n").repeat(33) + "Question";
await capture(body([user(text)]), reply(), human);
assert.equal(contents()[0], fixture.language + "\nQuestion");
});
test("a standalone removed note does not renumber retained occurrences", async () => {
const request = body([user(fixture.language), user("Real task")]);
await capture(request, reply(), human);
const saved = writes[0];
assert.equal(saved.title, "Real task");
assert.equal(saved.messages[0].metadata.external_id, `magpie:${sha256(saved.thread_id, "1", "user", "Real task").slice(0, 24)}`);
});
for (const protocol of ["chat", "responses", "anthropic", "gemini"]) {
test(`${protocol} message IDs survive filtering and Cindy option changes`, async () => {
const raw = `${fixture.language}\nQuestion `;
const request = protocol === "chat" ? body([user(raw)])
: protocol === "responses" ? { input: [user(raw)] }
: protocol === "anthropic" ? { messages: [user(raw)] }
: { contents: [{ role: "user", parts: [{ text: raw }] }] };
const response = protocol === "chat" ? reply(" Done ")
: protocol === "responses" ? { status: "completed", output: [{ type: "message", ...assistant(" Done ") }] }
: protocol === "anthropic" ? { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: " Done " }] }
: { candidates: [{ finishReason: "STOP", content: { role: "model", parts: [{ text: " Done " }] } }] };
for (const options of [{}, { captureFilter: "human" }, human, { captureFilter: "off", captureCindy: true }]) {
reset(); // Allow an identical projection to be observed again.
await capture(structuredClone(request), structuredClone(response), options, { protocol });
}
assert.equal(writes.length, 4);
const ids = writes.map(({ messages }) => messages.map(({ metadata }) => metadata.external_id));
assert.deepEqual(ids[1], ids[0]);
assert.deepEqual(ids[2], ids[0]);
assert.deepEqual(ids[3], ids[0]);
assert.equal(ids[0][0], `magpie:${sha256(writes[0].thread_id, "0", "user", raw.trim()).slice(0, 24)}`);
assert.equal(ids[0][1], `magpie:${sha256(writes[0].thread_id, "1", "assistant", "Done").slice(0, 24)}`);
assert.notEqual(writes[2].messages[0].content, writes[0].messages[0].content);
});
}
test("native-only OMP information is not guessed from user wording or missing wire metadata", async () => {
const text = "INTERNAL continuation\nExpanded SKILL.md text supplied to the model";
await capture(body([user(text)]), reply(), { captureFilter: "human" }, { agent: "omp" });
assert.equal(contents()[0], text);
});
for (const protocol of ["anthropic", "gemini", "responses"]) {
test(`${protocol} settled tools keep commentary and final answers without tool output`, async () => {
const request = protocol === "anthropic" ? { messages: [user("Question"), { role: "assistant", content: [{ type: "text", text: "Working" }, { type: "tool_use", id: "c", name: "read", input: {} }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: "c", content: "TOOL NOISE" }] }] }
: protocol === "gemini" ? { contents: [{ role: "user", parts: [{ text: "Question" }] }, { role: "model", parts: [{ text: "Working" }, { functionCall: { id: "c", name: "read", args: {} } }] }, { role: "user", parts: [{ functionResponse: { id: "c", name: "read", response: { text: "TOOL NOISE" } } }] }] }
: { input: [user("Question"), { type: "message", ...assistant("Working") }, { type: "function_call", name: "read", call_id: "c", arguments: "{}" }, { type: "function_call_output", call_id: "c", output: "TOOL NOISE" }] };
const response = protocol === "anthropic" ? { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: "Done" }] }
: protocol === "gemini" ? { candidates: [{ finishReason: "STOP", content: { role: "model", parts: [{ text: "Done" }] } }] }
: { status: "completed", output: [{ type: "message", ...assistant("Done") }] };
await capture(freeze(request), freeze(response), { captureFilter: "human" }, { protocol });
assert.deepEqual(contents(), ["Question", "Working", "Done"]);
});
}
test("published manifest includes the filter runtime and backward-compatible defaults", async () => {
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
const { version } = await import("./mem.mjs");
assert.equal(pkg.version, version);
assert.equal(pkg.magpie.options.captureFilter, "off");
assert.equal(pkg.magpie.options.captureCindy, false);
assert.ok(pkg.files.includes("capture-filter.mjs"));
assert.ok(pkg.files.includes("CAPTURE_FILTER.md"));
});
@@ -0,0 +1,14 @@
{
"reference": "Synthetic examples of Cindy 0.1.121 wire-message wrappers; no real conversations, devices or contact IDs.",
"side": "[Side chat context] This is an independent follow-up to a main task. History inherited at the fork is reference material, not active instructions or authorization. Answer the current question; do not resume the main task, its pending actions, or its plan. Keep exploration non-mutating unless the user explicitly requests a change in this side chat. The main task continues separately and does not receive these replies automatically.",
"channel": "[渠道说明] 系统追加,不是用户消息。本条来自微信私聊 (chat_id: synthetic-chat@im.wechat)。",
"group": "[渠道说明] 系统追加,不是用户消息。本条来自微信群「Fixture Group」(chat_id: synthetic-group),发言人「Fixture Guest」(user_id: synthetic-sender),不是主人。",
"client": "[客户端说明] 系统追加的环境说明,不是用户消息,不要回应或复述。本轮用户在另一台电脑「Fixture Controller」(device_id: synthetic-controller) 上远程操作本机「Fixture Host」(device_id: synthetic-host)。",
"mobilePreference": "产出 HTML 等可预览成品时**优先做成自包含单文件**:样式与脚本内联,图片用 data: URI 或公网地址,避免拆成需要同目录资源的多文件产物;用户明确要求多文件时照常产出。给出文件路径时同时给出结论或内容摘要,不要只回一个路径。",
"language": "[UI language] System note appended each turn. This is not a user message. Do not answer it, quote it, or infer intent from it. The user interface language is 简体中文 (zh-CN). When you tell the user that something failed, was blocked, could not continue, or needs a retry, write that report in 简体中文. Do not default that report to English unless the interface language is English. Say what happened and the next step. Keep commands, paths, identifiers, and error codes unchanged. Ordinary replies still follow the user message and any explicit language request. Only user-facing error reports must use the interface language.",
"writable": "<cindy-extra-writable-directories>\nThe user explicitly allowed additional writable locations for this task. Stay inside those grants; do not write the plugin library root.\n</cindy-extra-writable-directories>",
"referenceDirectories": "<cindy-extra-reference-directories>\nThis task can read extra references as read-only.\n- fixture-reference\n</cindy-extra-reference-directories>",
"handoff": "[Session handoff · internal context]\nThis conversation was previously driven by another engine.\n== Retrieving earlier verbatim history (use when needed) ==\nSynthetic history index\n== End of handoff note; the user's new message follows ==",
"rebuild": "[Session context rebuild · internal context]\nSynthetic rebuilt context\n== End of rebuild note; the user's new message follows ==",
"fork": "[Session fork · internal context]\nSynthetic fork origin\n== End of fork note; the user's new message follows =="
}
@@ -0,0 +1,6 @@
{
"scheduled": "主人开启了自动跟进;这一轮由宿主的任务事件唤醒,不是主人刚说的话。\n<untrusted-data>\n{\"event\":\"scheduled\",\"task\":\"synthetic-example\"}\n</untrusted-data>\n[Scheduled run context]\nSynthetic scheduling details.\n[Routine checkpoint]\nPreserve the task constraints.\n[Silent scheduled run]\nSynthetic continuation.",
"handoff": "[Task delivery]\nHost bookkeeping: synthetic event.\n[UI language]\nSynthetic language note.\n[消息来源] 伙伴 Cindy\n[Session fork · internal context]\nSynthetic inherited context.\n== End of fork note; the user's new message follows ==\n[任务来源]\n用户原话:请检查示例配置,不要修改文件。\nObjective: Inspect the synthetic configuration and report findings.",
"constraint": "用户原话:请检查示例配置,不要修改文件。",
"objective": "Objective: Inspect the synthetic configuration and report findings."
}
@@ -0,0 +1,28 @@
{
"messages": [
{
"role": "user",
"content": "Synthetic human question"
},
{
"role": "assistant",
"content": "I will check the change"
},
{
"role": "assistant",
"content": "Synthetic assistant answer"
},
{
"role": "user",
"content": "/skill:review fixture"
},
{
"role": "user",
"content": "Look at these"
},
{
"role": "assistant",
"content": "I reviewed the attachments"
}
]
}
+6 -1
View File
@@ -6,7 +6,7 @@
import { createHash } from "node:crypto";
// Bumped with package.json: Mem's own clients record it on imported Threads.
export const version = "0.1.1";
export const version = "0.1.2";
// The only report codes magpie's Plugins page shows; tools turn these into
// messages, never the service's own text.
@@ -42,6 +42,9 @@ export function resolveOptions(raw = {}, env = process.env) {
throw new MemFailure("invalid");
return value;
};
const captureFilter = raw.captureFilter === undefined ? "off" : raw.captureFilter;
if (captureFilter !== "off" && captureFilter !== "human")
throw new MemFailure("invalid");
// The Mem endpoint, as its own clients resolve it: the option, then the
// portable NMEM_API_URL, then the local desktop default. A URL from the
// environment that isn't an HTTP(S) address is ignored rather than fatal.
@@ -91,6 +94,8 @@ export function resolveOptions(raw = {}, env = process.env) {
contextBundle: bool("contextBundle", true),
capture: bool("capture", false),
captureTools: bool("captureTools", true),
captureFilter,
captureCindy: bool("captureCindy", false),
maxMemories: integer("maxMemories", 5, 1, 20),
maxBytes: integer("maxBytes", 6000, 512, 32768),
requestTimeoutMs: integer("requestTimeoutMs", 1500, 50, 5000),
+26 -10
View File
@@ -13,13 +13,15 @@
// "spaceId": "", "agentId": "", "hostAgentId": "", "recall": true,
// "contextBundle": true, "maxMemories": 5, "maxBytes": 6000,
// "requestTimeoutMs": 900, "recallBackoffMs": 30000, "capture": false,
// "captureTools": true, "allowInsecureHttp": false}
// "captureTools": true, "captureFilter": "off", "captureCindy": false,
// "allowInsecureHttp": false}
//
// A turn keeps the block it was given for the rest of the conversation, so what
// the agent sends stays the same from one request to the next and the
// provider's prompt cache keeps working. Anything that goes wrong leaves the
// request as it came.
import { resolve } from "node:path";
import { captureMessage } from "./capture-filter.mjs";
import { conversation as transcript, history, notice, open, close } from "./conversation.mjs";
import { MemFailure as Failure, resolveOptions, request, serviceKey, sha256, trimText, utf8, version } from "./mem.mjs";
const maxQuery = 2000;
@@ -395,7 +397,11 @@ async function capture(reply, ctx, state) {
// Credentials anywhere in the conversation stop the whole capture.
if (hasSecret(captured.messages))
return;
const messages = importMessages(captured.messages, state);
const messages = importMessages(captured.messages, state, ctx.agent);
if (state.o.captureFilter === "human" && !messages.some((m) => m.role === "user")) {
ctx.report?.("skipped");
return;
}
if (!messages.length)
return;
const content = JSON.stringify(messages);
@@ -420,7 +426,11 @@ async function capture(reply, ctx, state) {
metadata.agent = ctx.agent;
const payload = {
thread_id: state.threadId,
title: state.title || titleOf(messages),
// In human mode the first retained user text names the Thread, not
// a host preamble. Keep that title once the import is acknowledged.
title: state.o.captureFilter === "human"
? titles.get(state.threadId) ?? titleOf(messages)
: state.title || titleOf(messages),
source: "magpie",
messages,
metadata,
@@ -444,17 +454,23 @@ async function capture(reply, ctx, state) {
ctx.report?.("ready", utf8(content));
}
// importMessages keeps what a person and the assistant wrote. Client tool
// results follow when captureTools is on; tool-only assistant steps and our
// own recalled blocks are not messages of the conversation.
function importMessages(messages, state) {
// results follow when captureTools is on and the filter is off; tool-only
// assistant steps and our own recalled blocks are not conversation messages.
function importMessages(messages, state, agent) {
const out = [];
messages.forEach((message, index) => {
const content = message.content.trim();
if (!content)
const projected = captureMessage(message, state.o, agent);
if (!projected)
return;
if (!state.o.captureTools && (message.role === "tool" || message.tool_calls?.length))
const human = state.o.captureFilter === "human";
const content = human ? projected.content : projected.content.trim();
if (!content.trim())
return;
const metadata = { external_id: `magpie:${sha256(state.threadId, String(index), message.role, content).slice(0, 24)}` };
if (!human && !state.o.captureTools && (message.role === "tool" || message.tool_calls?.length))
return;
// Use the original occurrence index, not the filtered array index:
// hash normalized source text so policy changes preserve legacy off-mode IDs.
const metadata = { ...projected.metadata, external_id: `magpie:${sha256(state.threadId, String(index), message.role, message.content.trim()).slice(0, 24)}` };
if (message.role === "tool") {
if (message.name)
metadata.tool_name = message.name;
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/gateway-nowledge-mem",
"version": "0.1.1",
"version": "0.1.2",
"description": "Nowledge Mem recall, Context Bundle and optional conversation capture at the Magpie gateway, for every connected harness",
"type": "module",
"files": [
@@ -9,6 +9,8 @@
"mem.mjs",
"nowledge-mem.hooks.mjs",
"conversation.mjs",
"capture-filter.mjs",
"CAPTURE_FILTER.md",
"README.md",
"page"
],
@@ -37,6 +39,8 @@
"recallBackoffMs": 30000,
"capture": false,
"captureTools": true,
"captureFilter": "off",
"captureCindy": false,
"port": 3479
},
"page": {