respire-memory 0.3.10: diary readback looks up the turn marker lexically and checks every matching candidate (#568)
respire-memory 0.3.10 (luodaoyi, follow-up to #553):
- readDiary looks up the turn's source hash with `diary-search --mode lexical` instead of hybrid, so unrelated semantic matches no longer fill (and overrun) the 4000-character readback budget. Ordinary model diary searches keep the hybrid default.
- readDiary checks every matching candidate (lexical limit 5) for the complete written body, instead of only the first match, so an earlier diary with the same deterministic marker no longer makes a real write "unconfirmed". Source id/version, Unicode ranges, overlap, budgets and no-replay checks are unchanged; any inconsistent fragment still fails closed.
- A model's diary-search/diary-fragment result is held to the requested --max-chars on the compact `details` JSON, in Unicode characters (was: whole envelope <= 8000 UTF-16 units). This is the Runtime's own contract (respire-cli docs/diary-fragments.md: the budget bounds compact-serialized `details`; crates/app/src/diary.rs budget()).
- Settings page and README tell first-time users to install the Respire CLI (`npm install -g rsrs-cli`, risense-ai/respire-cli) and start its Runtime before configuring the plugin; README install line uses the listing's short name `respire-memory`, which magpie's resolver accepts (registry.json name).
Reviewed head 507db0483db4c7caaa49208fb17c93ef436179e2, merged onto origin/main 8b01396, run on mote (macOS):
- packages/respire-memory: `node scripts/check.mjs` and `bun scripts/check.mjs` pass; `bun test` 1 pass 0 fail (Bun 1.4.2).
- root `bun scripts/check.mjs`: exit 0.
- Broken by hand, each red in scripts/check.mjs: readback search back to hybrid (diary-output-too-large); first candidate only (diary-readback-unconfirmed); throw instead of continue on a non-matching candidate; body check removed (missing rejection); old whole-envelope 8000 budget; budget check removed.
- Not guarded by a test (stayed green when broken): the exact budget boundary (only a 4033-vs-4000 fixture; a +33 slack passes), UTF-16 vs code-point counting (fixtures are ASCII), and on the now-lexical readback path the search's own budget check and the source_id filter (the over-budget/unrelated fixtures are hybrid-only).
- Tests use a local http server only; no network.
- Not tried: a real Respire Runtime (author's CI and NPM-LIVE-0.3.10 report cover that). Not on npm yet: first version needs an owner publish; magpie installs it from dist meanwhile.
This commit is contained in:
@@ -6,8 +6,16 @@ This supports agent self-evolution through reusable experience. It does not trai
|
||||
|
||||
## Install
|
||||
|
||||
Install the [Respire CLI](https://github.com/risense-ai/respire-cli) first: this plugin is only the Magpie integration; the CLI provides the memory library and local Runtime. Follow the [npm installation guide](https://www.npmjs.com/package/rsrs-cli), or download your platform from [CLI Releases](https://github.com/risense-ai/respire-cli/releases).
|
||||
|
||||
~~~sh
|
||||
magpie plugin add @magpie-community/gateway-respire-memory
|
||||
npm install -g rsrs-cli
|
||||
~~~
|
||||
|
||||
Prepare your account/model and start/unlock the local HTTP Runtime using the [Runtime guide](https://github.com/risense-ai/respire-cli/blob/main/docs/runtime.md). Check `rsrs --client-only status --json`, then install this plugin:
|
||||
|
||||
~~~sh
|
||||
magpie plugin add respire-memory
|
||||
~~~
|
||||
|
||||
Requires Magpie 0.1.1273+ and Bun 1.3.6+, with an existing unlocked local Respire HTTP Runtime. Page saves reaching hooks require Magpie 0.1.1531+. The magpie-key classification needs a newer host; older hosts may skip that origin. This plugin does not provision an engine, manage accounts/services or reuse private provider credentials.
|
||||
|
||||
@@ -32,28 +32,32 @@ function boundedDiaryArgs(command, args) {
|
||||
|
||||
export async function readDiary(call, id, content, source) {
|
||||
if (!validId(id) || !/^[a-f0-9]{64}$/.test(source ?? '') || !content.includes(source)) throw new Error('diary-readback-source');
|
||||
const found = await call(['diary-search', source, '--limit', '5', '--max-chars', '4000', '--mode', 'hybrid']);
|
||||
// A turn hash is an exact locator, not a semantic history query.
|
||||
const found = await call(['diary-search', source, '--limit', '5', '--max-chars', '4000', '--mode', 'lexical']);
|
||||
if (Array.from(JSON.stringify(found.details ?? {})).length > 4000) throw new Error('diary-output-too-large');
|
||||
const candidate = found.details?.items?.find(item => item.source_id === id && !item.truncated && item.text?.includes(source));
|
||||
if (found.status !== 'ok' || !candidate?.fragment_id || !candidate.source_version) throw new Error('diary-readback-unconfirmed');
|
||||
const fragment = await call(['diary-fragment', id, candidate.fragment_id, '--neighbors', '1', '--max-chars', '4000']);
|
||||
if (Array.from(JSON.stringify(fragment.details ?? {})).length > 4000) throw new Error('diary-output-too-large');
|
||||
const items = fragment.details?.items;
|
||||
if (fragment.status !== 'ok' || !Array.isArray(items) || !items.some(item => item.fragment_id === candidate.fragment_id)
|
||||
|| items.some(item => item.source_id !== id || item.source_version !== candidate.source_version || item.truncated || typeof item.text !== 'string'
|
||||
|| !Number.isInteger(item.start) || !Number.isInteger(item.end) || item.end - item.start !== Array.from(item.text).length)) throw new Error('diary-readback-unconfirmed');
|
||||
const ordered = [...items].sort((a,b) => a.start - b.start);
|
||||
const start = ordered[0].start, text = Array.from(ordered[0].text);
|
||||
let end = ordered[0].end;
|
||||
for (const item of ordered.slice(1)) {
|
||||
const chars = Array.from(item.text), overlap = Math.min(end - item.start, chars.length);
|
||||
if (overlap < 0 || text.slice(item.start - start, item.start - start + overlap).join('') !== chars.slice(0, overlap).join('')) throw new Error('diary-readback-unconfirmed');
|
||||
text.push(...chars.slice(overlap)); end = Math.max(end, item.end);
|
||||
const candidates = found.details?.items?.filter(item => item.source_id === id && !item.truncated && item.text?.includes(source) && item.fragment_id && item.source_version);
|
||||
if (found.status !== 'ok' || !candidates?.length) throw new Error('diary-readback-unconfirmed');
|
||||
for (const candidate of candidates) {
|
||||
const fragment = await call(['diary-fragment', id, candidate.fragment_id, '--neighbors', '1', '--max-chars', '4000']);
|
||||
if (Array.from(JSON.stringify(fragment.details ?? {})).length > 4000) throw new Error('diary-output-too-large');
|
||||
const items = fragment.details?.items;
|
||||
if (fragment.status !== 'ok' || !Array.isArray(items) || !items.some(item => item.fragment_id === candidate.fragment_id)
|
||||
|| items.some(item => item.source_id !== id || item.source_version !== candidate.source_version || item.truncated || typeof item.text !== 'string'
|
||||
|| !Number.isInteger(item.start) || !Number.isInteger(item.end) || item.end - item.start !== Array.from(item.text).length)) throw new Error('diary-readback-unconfirmed');
|
||||
const ordered = [...items].sort((a,b) => a.start - b.start);
|
||||
const start = ordered[0].start, text = Array.from(ordered[0].text);
|
||||
let end = ordered[0].end;
|
||||
for (const item of ordered.slice(1)) {
|
||||
const chars = Array.from(item.text), overlap = Math.min(end - item.start, chars.length);
|
||||
if (overlap < 0 || text.slice(item.start - start, item.start - start + overlap).join('') !== chars.slice(0, overlap).join('')) throw new Error('diary-readback-unconfirmed');
|
||||
text.push(...chars.slice(overlap)); end = Math.max(end, item.end);
|
||||
}
|
||||
if (!text.join('').includes(content)) continue;
|
||||
// Return only the verified write, never adjacent turns from the daily source.
|
||||
return { status: 'ok', summary: { id }, details: { entry: { id, importance: 'trivial', content },
|
||||
diaryReadback: { verified: true, fragments: ordered.map(({ source_id, fragment_id, source_version, start, end }) => ({ source_id, fragment_id, source_version, start, end })) } } };
|
||||
}
|
||||
if (!text.join('').includes(content)) throw new Error('diary-readback-unconfirmed');
|
||||
// Return only the verified write, never adjacent turns from the daily source.
|
||||
return { status: 'ok', summary: { id }, details: { entry: { id, importance: 'trivial', content },
|
||||
diaryReadback: { verified: true, fragments: ordered.map(({ source_id, fragment_id, source_version, start, end }) => ({ source_id, fragment_id, source_version, start, end })) } } };
|
||||
throw new Error('diary-readback-unconfirmed');
|
||||
}
|
||||
|
||||
export function memoryTools(call, { readOnly = false, source } = {}) {
|
||||
@@ -113,7 +117,7 @@ export function memoryTools(call, { readOnly = false, source } = {}) {
|
||||
if (diary && error.message === 'diary-unsupported') diaryUnavailable = true
|
||||
throw error
|
||||
}
|
||||
if (diary && JSON.stringify(doc).length > 8000) throw new Error('diary-output-too-large')
|
||||
if (diary && Array.from(JSON.stringify(doc.details ?? {})).length > Number(args[args.indexOf('--max-chars') + 1])) throw new Error('diary-output-too-large')
|
||||
if (command === 'recall' && ['ok', 'skip'].includes(doc.status)) recalled = true
|
||||
if (command === 'prompt') {
|
||||
if (doc.status !== 'ok' || typeof doc.summary?.instructions !== 'string' || !doc.summary.instructions.trim()) throw new Error('invalid-engine-policy')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/gateway-respire-memory",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.10",
|
||||
"description": "帮助 AI Agent 通过记忆召回、经验积累与后台归档持续自进化",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -7,6 +7,13 @@
|
||||
</head>
|
||||
<body><main>
|
||||
<header><img class="brand brand-light" src="icon-respire-ai-memory-light.svg" width="46" height="46" alt=""><img class="brand brand-dark" src="icon-respire-ai-memory.svg" width="46" height="46" alt=""><div><h1>respire-memory</h1><p>吸即存,呼即取——让 AI Agent 在实践中积累经验,持续自进化。</p></div></header>
|
||||
<section aria-labelledby="setup-title"><h2 id="setup-title">首次使用:先安装 Respire 本体</h2>
|
||||
<p>此插件是 Magpie 的接入层,需要另行安装 <a href="https://github.com/risense-ai/respire-cli" target="_blank" rel="noopener noreferrer">Respire CLI(GitHub 安装说明)</a>。它提供记忆库与本地 Runtime;只安装插件还不能读存记忆。</p>
|
||||
<ol><li>在自己的终端执行 <code>npm install -g rsrs-cli</code>,或从 <a href="https://github.com/risense-ai/respire-cli/releases" target="_blank" rel="noopener noreferrer">CLI Releases</a> 下载对应平台版本。</li>
|
||||
<li>按 <a href="https://github.com/risense-ai/respire-cli/blob/main/docs/runtime.md" target="_blank" rel="noopener noreferrer">CLI Runtime 指南</a>准备账号、模型,启动并解锁本地 HTTP Runtime。</li>
|
||||
<li>执行 <code>rsrs --client-only status --json</code> 确认连接,再在下方配置 Runtime 地址及归档生成模型并保存。</li></ol>
|
||||
<p class="disclosure">插件不会代装 CLI、启动 Runtime 或管理账号;登录与解锁请在 Respire 中完成,不要在此页面输入密码或密钥。</p>
|
||||
</section>
|
||||
<form id="form">
|
||||
<label for="url">本地 Runtime 地址</label>
|
||||
<input id="url" type="url" required value="http://127.0.0.1:15169" autocomplete="off" spellcheck="false" aria-describedby="url-help">
|
||||
@@ -33,6 +40,6 @@
|
||||
<button id="save" type="submit" disabled>保存配置</button>
|
||||
<p id="status" role="status" aria-live="polite">正在读取配置…</p>
|
||||
</form>
|
||||
<section><h2>使用方式</h2><p>召回自动执行。“/nomem”或“#nomem”只跳过本条召回;已开启的采集与后台归档仍可运行。存储是否成功以模型收到的引擎回执为准。</p><p>插件不安装或启动 Runtime。连接失败时原对话继续;共享网关的其他调用者无法使用此插件读取或保存记忆。</p></section>
|
||||
<section><h2>使用方式</h2><p>完成上方 Respire CLI 安装与配置后,召回自动执行。“/nomem”或“#nomem”只跳过本条召回;已开启的采集与后台归档仍可运行。存储是否成功以模型收到的引擎回执为准。</p><p>连接失败时先按 <a href="https://github.com/risense-ai/respire-cli" target="_blank" rel="noopener noreferrer">Respire CLI 说明</a>检查本体与 Runtime;原对话会继续。共享网关的其他调用者无法使用此插件读取或保存记忆。</p></section>
|
||||
</main></body>
|
||||
</html>
|
||||
|
||||
@@ -49,6 +49,7 @@ let generationRound = 0, unknownWrite = false, writes = 0, policyReady = true, e
|
||||
const savedId = '22222222-2222-4222-8222-222222222222';
|
||||
const diaryId = '33333333-3333-4333-8333-333333333333';
|
||||
const commandLog = [];
|
||||
const diaryLookups = [];
|
||||
const entries = new Map([[id, { id, title: 'Example', content: 'Historical evidence', project: '' }]]);
|
||||
const server = createServer(async (req, res) => {
|
||||
assert(!/magpie/i.test(req.headers['user-agent'] ?? ''));
|
||||
@@ -74,8 +75,9 @@ const server = createServer(async (req, res) => {
|
||||
details: command === 'recall' ? (emptyRecall ? [] : [{ id }]) : command === 'prompt' ? null : command === 'chain' && oversizedChain ? { content: 'x'.repeat(16000) } : { entry: entries.get(r.args[2]) ?? entries.get(id) } };
|
||||
if (command === 'show') { envelope.summary.id = r.args[2]; if (r.args[2] === diaryId) wholeDiaryReads++; }
|
||||
if (command === 'diary-search' || command === 'diary-fragment') {
|
||||
const text = command === 'diary-fragment' && brokenDiary ? 'Only the marker remains: ' + (entries.get(diaryId)?.content.split('【来源】回合 ')[1] ?? '') : entries.get(diaryId)?.content ?? '';
|
||||
envelope.details = { items: [{ source_id: diaryId, fragment_id: 'fixture-fragment', source_version: 'fixture-version',
|
||||
const oldMatch = 'Earlier write with the same marker: ' + (entries.get(diaryId)?.content.split('【来源】回合 ')[1] ?? '');
|
||||
const text = command === 'diary-fragment' && (brokenDiary || r.args[3] === 'old-fragment') ? oldMatch : entries.get(diaryId)?.content ?? '';
|
||||
envelope.details = { items: [{ source_id: diaryId, fragment_id: command === 'diary-fragment' ? r.args[3] : 'fixture-fragment', source_version: 'fixture-version',
|
||||
text, start: 0, end: Array.from(text).length, truncated: false }] };
|
||||
if (command === 'diary-fragment') {
|
||||
const chars = Array.from(text), split = Math.floor(chars.length / 2);
|
||||
@@ -84,6 +86,18 @@ const server = createServer(async (req, res) => {
|
||||
{ ...envelope.details.items[0], text: chars.slice(split).join(''), start: split }
|
||||
];
|
||||
}
|
||||
if (command === 'diary-search') {
|
||||
const sourceLookup = /^[a-f0-9]{64}$/.test(r.args[2]), mode = r.args[r.args.indexOf('--mode') + 1];
|
||||
diaryLookups.push({ sourceLookup, mode });
|
||||
if (sourceLookup) envelope.details.items.unshift({ ...envelope.details.items[0], fragment_id: 'old-fragment', text: oldMatch, end: Array.from(oldMatch).length });
|
||||
if ((sourceLookup || r.args[2] === 'over-budget historical fixture') && mode === 'hybrid') {
|
||||
// Real Runtime semantic-ready output exceeded its requested 4000-character budget.
|
||||
const unrelated = { ...envelope.details.items[0], source_id: '44444444-4444-4444-8444-444444444444', text: '' };
|
||||
envelope.details.items.push(unrelated);
|
||||
unrelated.text = 'x'.repeat(Math.max(0, 4033 - Array.from(JSON.stringify(envelope.details)).length));
|
||||
envelope.details.semantic_ready = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (command === 'remember') {
|
||||
if (r.args[2] === 'pending-fixture-content') {
|
||||
@@ -247,6 +261,9 @@ try {
|
||||
const readOnlySource = digest('read-only'); const readonly = makeJob(readOnlySource); readonly.o = { ...o, readOnly: true };
|
||||
await store.put('job-' + readOnlySource, readonly); await processJob(store, 'job-' + readOnlySource); assert.equal(writes, count);
|
||||
const guarded = memoryTools(call);
|
||||
await guarded.run({ command: 'diary-search', args: ['historical project topic'] });
|
||||
assert.equal(diaryLookups.at(-1).mode, 'hybrid', 'Ordinary history lookup must retain its hybrid default');
|
||||
await assert.rejects(() => guarded.run({ command: 'diary-search', args: ['over-budget historical fixture'] }), /diary-output-too-large/);
|
||||
await assert.rejects(() => guarded.run({ command: 'remember', args: ['text', '--force'] }));
|
||||
await assert.rejects(() => guarded.run({ command: 'remember', args: ['text', '--importance', 'important', '--title', 'title', '--parent', id] }));
|
||||
await assert.rejects(() => guarded.run({ command: 'agent-config', args: ['--set', 'readonly=false'] }));
|
||||
@@ -385,6 +402,7 @@ try {
|
||||
const beforeReplay = writes; await processJob(store, name); assert.equal(writes, beforeReplay);
|
||||
}
|
||||
assert.equal(wholeDiaryReads, 0);
|
||||
assert(diaryLookups.filter(x => x.sourceLookup).every(x => x.mode === 'lexical'), 'Current-turn source hashes require exact lexical lookup');
|
||||
console.log('Detached worker check passed: gateway completion -> encrypted queue -> child process -> model tools -> readback.');
|
||||
console.log('Archive checks passed: real HTTP model tool loop, readback, encrypted persistence, unknown-write no-retry, read-only, tool restrictions and source-checked segmentation.');
|
||||
console.log('Review regressions passed: stale/live locks, receipts, capacity, retention, leases, stable history, four-protocol policy dedup/change/revert and neutral user agents.');
|
||||
|
||||
Reference in New Issue
Block a user