@trans-ai/trans-code 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/docs/superpowers/plans/2026-11-22-user-memory.md +243 -0
- package/docs/superpowers/plans/2026-11-22-web-tools.md +192 -0
- package/docs/superpowers/specs/2026-11-22-user-memory-design.md +48 -0
- package/docs/superpowers/specs/2026-11-22-web-tools-design.md +48 -0
- package/package.json +1 -1
- package/src/acp/server.ts +6 -0
- package/src/agent/loop.ts +5 -1
- package/src/agent/memory.test.ts +169 -0
- package/src/agent/memory.ts +207 -0
- package/src/agent/system-prompt.test.ts +87 -1
- package/src/agent/system-prompt.ts +23 -1
- package/src/agent/tools/index.ts +7 -0
- package/src/agent/tools/memory.test.ts +88 -0
- package/src/agent/tools/memory.ts +61 -0
- package/src/agent/tools/types.ts +2 -0
- package/src/agent/tools/web-fetch.test.ts +186 -0
- package/src/agent/tools/web-fetch.ts +137 -0
- package/src/agent/tools/web-search.test.ts +100 -0
- package/src/agent/tools/web-search.ts +41 -0
- package/src/commands.test.ts +104 -1
- package/src/commands.ts +101 -0
- package/src/config.ts +2 -0
- package/src/provider/web-search.test.ts +195 -0
- package/src/provider/web-search.ts +143 -0
- package/src/screens/REPL.tsx +109 -3
- package/src/screens/search-setup.test.ts +89 -0
- package/src/screens/search-setup.ts +57 -0
- package/src/screens/submit.test.ts +8 -0
- package/src/screens/submit.ts +1 -1
- package/src/version.ts +1 -1
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, promises as fs, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {
|
|
6
|
+
USER_MEMORY_BUDGET_CHARS,
|
|
7
|
+
deleteMemory,
|
|
8
|
+
globalInstructionsPath,
|
|
9
|
+
loadUserMemory,
|
|
10
|
+
memoryDir,
|
|
11
|
+
saveMemory,
|
|
12
|
+
} from './memory.js';
|
|
13
|
+
|
|
14
|
+
let root: string;
|
|
15
|
+
|
|
16
|
+
async function withRoot(run: () => Promise<void>): Promise<void> {
|
|
17
|
+
root = mkdtempSync(path.join(tmpdir(), 'transcode-memory-'));
|
|
18
|
+
process.env.TRANSCODE_USER_DIR = root;
|
|
19
|
+
try {
|
|
20
|
+
await run();
|
|
21
|
+
} finally {
|
|
22
|
+
delete process.env.TRANSCODE_USER_DIR;
|
|
23
|
+
rmSync(root, { recursive: true, force: true });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function writeEntryFile(name: string, raw: string): Promise<void> {
|
|
28
|
+
mkdirSync(memoryDir(), { recursive: true });
|
|
29
|
+
await fs.writeFile(path.join(memoryDir(), `${name}.md`), raw, 'utf8');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('memory store', () => {
|
|
33
|
+
test('save→load 往返:文件 + 索引 + frontmatter 三键', async () => {
|
|
34
|
+
await withRoot(async () => {
|
|
35
|
+
const entry = await saveMemory({
|
|
36
|
+
name: 'bun-not-node',
|
|
37
|
+
type: 'feedback',
|
|
38
|
+
content: '所有项目用 bun 跑脚本。',
|
|
39
|
+
description: '用户偏好 bun',
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
expect(entry.name).toBe('bun-not-node');
|
|
43
|
+
expect(entry.type).toBe('feedback');
|
|
44
|
+
|
|
45
|
+
const file = path.join(memoryDir(), 'bun-not-node.md');
|
|
46
|
+
expect(existsSync(file)).toBe(true);
|
|
47
|
+
const raw = await fs.readFile(file, 'utf8');
|
|
48
|
+
expect(raw).toContain('name: bun-not-node');
|
|
49
|
+
expect(raw).toContain('type: feedback');
|
|
50
|
+
expect(raw).toContain('description: 用户偏好 bun');
|
|
51
|
+
expect(raw).toContain('所有项目用 bun 跑脚本。');
|
|
52
|
+
|
|
53
|
+
const index = await fs.readFile(path.join(memoryDir(), 'MEMORY.md'), 'utf8');
|
|
54
|
+
expect(index).toContain('- [bun-not-node](bun-not-node.md) — 用户偏好 bun');
|
|
55
|
+
|
|
56
|
+
const loaded = await loadUserMemory();
|
|
57
|
+
expect(loaded.entries).toHaveLength(1);
|
|
58
|
+
expect(loaded.entries[0]).toEqual(entry);
|
|
59
|
+
expect(loaded.omitted).toEqual([]);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('索引是再生产物:手删 MEMORY.md 后 load 仍返回条目,save 后索引重建', async () => {
|
|
64
|
+
await withRoot(async () => {
|
|
65
|
+
await saveMemory({ name: 'a-first', type: 'user', content: '一', description: 'd1' });
|
|
66
|
+
await saveMemory({ name: 'b-second', type: 'user', content: '二', description: 'd2' });
|
|
67
|
+
await fs.rm(path.join(memoryDir(), 'MEMORY.md'));
|
|
68
|
+
|
|
69
|
+
const loaded = await loadUserMemory();
|
|
70
|
+
expect(loaded.entries.map((e) => e.name)).toEqual(['a-first', 'b-second']);
|
|
71
|
+
|
|
72
|
+
await saveMemory({ name: 'c-third', type: 'user', content: '三', description: 'd3' });
|
|
73
|
+
const index = await fs.readFile(path.join(memoryDir(), 'MEMORY.md'), 'utf8');
|
|
74
|
+
expect(index).toContain('a-first');
|
|
75
|
+
expect(index).toContain('b-second');
|
|
76
|
+
expect(index).toContain('c-third');
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('预算:大 reference + 小 user 超预算 → user 保留、reference 进 omitted', async () => {
|
|
81
|
+
await withRoot(async () => {
|
|
82
|
+
await saveMemory({
|
|
83
|
+
name: 'aaa-big-ref',
|
|
84
|
+
type: 'reference',
|
|
85
|
+
content: 'x'.repeat(USER_MEMORY_BUDGET_CHARS),
|
|
86
|
+
description: '大引用',
|
|
87
|
+
});
|
|
88
|
+
await saveMemory({ name: 'zzz-user', type: 'user', content: '小而重要', description: '用户事实' });
|
|
89
|
+
|
|
90
|
+
const loaded = await loadUserMemory();
|
|
91
|
+
expect(loaded.entries.map((e) => e.name)).toEqual(['zzz-user']);
|
|
92
|
+
expect(loaded.omitted).toEqual(['aaa-big-ref']);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('TRANS.md 超预算 → 截断并附 "... (global instructions truncated)"', async () => {
|
|
97
|
+
await withRoot(async () => {
|
|
98
|
+
writeFileSync(globalInstructionsPath(), 'g'.repeat(USER_MEMORY_BUDGET_CHARS + 500));
|
|
99
|
+
const loaded = await loadUserMemory();
|
|
100
|
+
expect(loaded.globalInstructions).not.toBeNull();
|
|
101
|
+
expect((loaded.globalInstructions ?? '').length).toBeLessThanOrEqual(
|
|
102
|
+
USER_MEMORY_BUDGET_CHARS,
|
|
103
|
+
);
|
|
104
|
+
expect(loaded.globalInstructions).toContain('... (global instructions truncated)');
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('坏 frontmatter(空文件/缺 type/未知 type)→ 跳过该条不崩', async () => {
|
|
109
|
+
await withRoot(async () => {
|
|
110
|
+
await writeEntryFile('empty', '');
|
|
111
|
+
await writeEntryFile('no-frontmatter', '正文没有 frontmatter');
|
|
112
|
+
await writeEntryFile('missing-type', '---\nname: missing-type\ndescription: d\n---\n正文');
|
|
113
|
+
await writeEntryFile('unknown-type', '---\nname: unknown-type\ntype: diary\n---\n正文');
|
|
114
|
+
await saveMemory({ name: 'good-one', type: 'user', content: '好条目', description: 'ok' });
|
|
115
|
+
|
|
116
|
+
const loaded = await loadUserMemory();
|
|
117
|
+
expect(loaded.entries.map((e) => e.name)).toEqual(['good-one']);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('危险 name(空、a/b、..)→ saveMemory 抛错,deleteMemory 返回 false', async () => {
|
|
122
|
+
await withRoot(async () => {
|
|
123
|
+
await expect(saveMemory({ name: ' ', type: 'user', content: 'x' })).rejects.toThrow();
|
|
124
|
+
await expect(saveMemory({ name: 'a/b', type: 'user', content: 'x' })).rejects.toThrow();
|
|
125
|
+
await expect(saveMemory({ name: '..', type: 'user', content: 'x' })).rejects.toThrow();
|
|
126
|
+
|
|
127
|
+
expect(await deleteMemory('a/b')).toBe(false);
|
|
128
|
+
expect(await deleteMemory('..')).toBe(false);
|
|
129
|
+
expect(await deleteMemory('')).toBe(false);
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('description 缺省取 content 首个非空行截 60 字符', async () => {
|
|
134
|
+
await withRoot(async () => {
|
|
135
|
+
const long = 'a'.repeat(80);
|
|
136
|
+
const entry = await saveMemory({ name: 'derived', type: 'user', content: `\n\n${long}` });
|
|
137
|
+
expect(entry.description).toBe('a'.repeat(60));
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('deleteMemory:命中删文件并重写索引,未命中返回 false', async () => {
|
|
142
|
+
await withRoot(async () => {
|
|
143
|
+
await saveMemory({ name: 'keep-me', type: 'user', content: '留', description: 'k' });
|
|
144
|
+
await saveMemory({ name: 'drop-me', type: 'user', content: '删', description: 'd' });
|
|
145
|
+
|
|
146
|
+
expect(await deleteMemory('drop-me')).toBe(true);
|
|
147
|
+
expect(existsSync(path.join(memoryDir(), 'drop-me.md'))).toBe(false);
|
|
148
|
+
const index = await fs.readFile(path.join(memoryDir(), 'MEMORY.md'), 'utf8');
|
|
149
|
+
expect(index).toContain('keep-me');
|
|
150
|
+
expect(index).not.toContain('drop-me');
|
|
151
|
+
expect(await loadUserMemory()).toMatchObject({ entries: [expect.objectContaining({ name: 'keep-me' })] });
|
|
152
|
+
|
|
153
|
+
expect(await deleteMemory('drop-me')).toBe(false);
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
describe('scanEntries robustness', () => {
|
|
159
|
+
test('memory 目录里混入目录/不可读项 → 跳过不崩', async () => {
|
|
160
|
+
await withRoot(async () => {
|
|
161
|
+
const { mkdirSync } = await import('node:fs');
|
|
162
|
+
mkdirSync(path.join(memoryDir(), 'trap.md'), { recursive: true });
|
|
163
|
+
await saveMemory({ name: 'fine-one', type: 'user', content: 'ok', description: 'ok' });
|
|
164
|
+
|
|
165
|
+
const loaded = await loadUserMemory();
|
|
166
|
+
expect(loaded.entries.map((e) => e.name)).toEqual(['fine-one']);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
});
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* User-level memory: global instructions (~/.transcode/TRANS.md) plus a
|
|
7
|
+
* directory of one-fact-per-file memories. Directory files are the source
|
|
8
|
+
* of truth; MEMORY.md is a write-through index regenerated on every
|
|
9
|
+
* save/delete, never read back.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type MemoryType = 'user' | 'feedback' | 'project' | 'reference';
|
|
13
|
+
|
|
14
|
+
export interface MemoryEntry {
|
|
15
|
+
name: string;
|
|
16
|
+
type: MemoryType;
|
|
17
|
+
description: string;
|
|
18
|
+
content: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface UserMemory {
|
|
22
|
+
globalInstructions: string | null;
|
|
23
|
+
entries: MemoryEntry[];
|
|
24
|
+
omitted: string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const USER_MEMORY_BUDGET_CHARS = 12_000;
|
|
28
|
+
|
|
29
|
+
/** Over-budget drop priority: user facts survive longest, pointers go first. */
|
|
30
|
+
const PRIORITY: Record<MemoryType, number> = { user: 3, feedback: 2, project: 1, reference: 0 };
|
|
31
|
+
const MEMORY_TYPES = Object.keys(PRIORITY) as MemoryType[];
|
|
32
|
+
const TRUNCATION_NOTE = '... (global instructions truncated)';
|
|
33
|
+
const DESCRIPTION_MAX_CHARS = 60;
|
|
34
|
+
|
|
35
|
+
// Test isolation mirrors TRANSCODE_SESSIONS_DIR.
|
|
36
|
+
export function userMemoryRoot(): string {
|
|
37
|
+
return process.env.TRANSCODE_USER_DIR ?? path.join(homedir(), '.transcode');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function globalInstructionsPath(): string {
|
|
41
|
+
return path.join(userMemoryRoot(), 'TRANS.md');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function memoryDir(): string {
|
|
45
|
+
return path.join(userMemoryRoot(), 'memory');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Trimmed, separator-free file stem; null when the name cannot be a file. */
|
|
49
|
+
export function sanitizeMemoryName(name: string): string | null {
|
|
50
|
+
const trimmed = name.trim();
|
|
51
|
+
if (!trimmed || trimmed === '.' || trimmed === '..') return null;
|
|
52
|
+
if (trimmed.includes('/') || trimmed.includes('\\')) return null;
|
|
53
|
+
return trimmed;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Line-level frontmatter parse (name/type/description only); null when malformed. */
|
|
57
|
+
export function parseMemoryFile(raw: string): MemoryEntry | null {
|
|
58
|
+
const lines = raw.split('\n');
|
|
59
|
+
let start = 0;
|
|
60
|
+
while (start < lines.length && lines[start].trim() === '') start++;
|
|
61
|
+
if (start >= lines.length || lines[start].trim() !== '---') return null;
|
|
62
|
+
let end = -1;
|
|
63
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
64
|
+
if (lines[i].trim() === '---') {
|
|
65
|
+
end = i;
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (end === -1) return null;
|
|
70
|
+
|
|
71
|
+
let name: string | null = null;
|
|
72
|
+
let type: MemoryType | null = null;
|
|
73
|
+
let description = '';
|
|
74
|
+
for (let i = start + 1; i < end; i++) {
|
|
75
|
+
const colon = lines[i].indexOf(':');
|
|
76
|
+
if (colon === -1) continue;
|
|
77
|
+
const key = lines[i].slice(0, colon).trim();
|
|
78
|
+
const value = lines[i].slice(colon + 1).trim();
|
|
79
|
+
if (key === 'name') name = value;
|
|
80
|
+
else if (key === 'description') description = value;
|
|
81
|
+
else if (key === 'type' && (MEMORY_TYPES as string[]).includes(value)) {
|
|
82
|
+
type = value as MemoryType;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (!name || !type) return null;
|
|
86
|
+
return { name, type, description, content: lines.slice(end + 1).join('\n').trim() };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function renderMemoryFile(entry: MemoryEntry): string {
|
|
90
|
+
return (
|
|
91
|
+
`---\nname: ${entry.name}\ntype: ${entry.type}\ndescription: ${entry.description}\n---\n` +
|
|
92
|
+
`${entry.content}\n`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function renderMemoryIndex(entries: MemoryEntry[]): string {
|
|
97
|
+
if (entries.length === 0) return '';
|
|
98
|
+
return entries.map((e) => `- [${e.name}](${e.name}.md) — ${e.description}`).join('\n') + '\n';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Memory files in display (alphabetical) order; malformed files are skipped. */
|
|
102
|
+
function scanEntries(): MemoryEntry[] {
|
|
103
|
+
let files: string[];
|
|
104
|
+
try {
|
|
105
|
+
files = fs.readdirSync(memoryDir());
|
|
106
|
+
} catch {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
const entries: MemoryEntry[] = [];
|
|
110
|
+
for (const file of files.filter((n) => n.endsWith('.md') && n !== 'MEMORY.md').sort()) {
|
|
111
|
+
try {
|
|
112
|
+
const parsed = parseMemoryFile(fs.readFileSync(path.join(memoryDir(), file), 'utf8'));
|
|
113
|
+
if (parsed) entries.push(parsed);
|
|
114
|
+
} catch {
|
|
115
|
+
// Unreadable item (permissions, a directory, …): skip, like malformed files.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return entries;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Atomic replace: a crash mid-write can never truncate a memory file. */
|
|
122
|
+
function writeAtomic(target: string, data: string): void {
|
|
123
|
+
const tmp = `${target}.tmp`;
|
|
124
|
+
fs.writeFileSync(tmp, data);
|
|
125
|
+
try {
|
|
126
|
+
fs.renameSync(tmp, target);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
try {
|
|
129
|
+
fs.rmSync(tmp, { force: true });
|
|
130
|
+
} catch {
|
|
131
|
+
// Best-effort cleanup; the original error matters more.
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function rewriteIndex(): void {
|
|
138
|
+
writeAtomic(path.join(memoryDir(), 'MEMORY.md'), renderMemoryIndex(scanEntries()));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function deriveDescription(content: string): string {
|
|
142
|
+
const first = content.split('\n').map((l) => l.trim()).find((l) => l.length > 0) ?? '';
|
|
143
|
+
return first.length > DESCRIPTION_MAX_CHARS ? first.slice(0, DESCRIPTION_MAX_CHARS) : first;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function loadUserMemory(): Promise<UserMemory> {
|
|
147
|
+
let globalInstructions: string | null = null;
|
|
148
|
+
let remaining = USER_MEMORY_BUDGET_CHARS;
|
|
149
|
+
try {
|
|
150
|
+
const raw = fs.readFileSync(globalInstructionsPath(), 'utf8').trim();
|
|
151
|
+
if (raw) {
|
|
152
|
+
globalInstructions =
|
|
153
|
+
raw.length > remaining
|
|
154
|
+
? `${raw.slice(0, Math.max(0, remaining - TRUNCATION_NOTE.length - 1))}\n${TRUNCATION_NOTE}`
|
|
155
|
+
: raw;
|
|
156
|
+
remaining -= globalInstructions.length;
|
|
157
|
+
}
|
|
158
|
+
} catch {
|
|
159
|
+
// No global instructions file yet.
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Over budget: drop whole entries (never clip mid-fact), lowest priority
|
|
163
|
+
// first, ties resolved to the last in alphabetical display order.
|
|
164
|
+
const kept = scanEntries();
|
|
165
|
+
const omitted: string[] = [];
|
|
166
|
+
const totalCost = () => kept.reduce((sum, e) => sum + renderMemoryFile(e).length, 0);
|
|
167
|
+
while (totalCost() > remaining && kept.length > 0) {
|
|
168
|
+
let victim = 0;
|
|
169
|
+
for (let i = 1; i < kept.length; i++) {
|
|
170
|
+
if (PRIORITY[kept[i].type] <= PRIORITY[kept[victim].type]) victim = i;
|
|
171
|
+
}
|
|
172
|
+
omitted.push(kept[victim].name);
|
|
173
|
+
kept.splice(victim, 1);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return { globalInstructions, entries: kept, omitted };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export async function saveMemory(input: {
|
|
180
|
+
name: string;
|
|
181
|
+
type: MemoryType;
|
|
182
|
+
content: string;
|
|
183
|
+
description?: string;
|
|
184
|
+
}): Promise<MemoryEntry> {
|
|
185
|
+
const name = sanitizeMemoryName(input.name);
|
|
186
|
+
if (!name) throw new Error(`invalid memory name: ${JSON.stringify(input.name)}`);
|
|
187
|
+
const entry: MemoryEntry = {
|
|
188
|
+
name,
|
|
189
|
+
type: input.type,
|
|
190
|
+
description: input.description?.trim() || deriveDescription(input.content),
|
|
191
|
+
content: input.content.trim(),
|
|
192
|
+
};
|
|
193
|
+
fs.mkdirSync(memoryDir(), { recursive: true });
|
|
194
|
+
writeAtomic(path.join(memoryDir(), `${name}.md`), renderMemoryFile(entry));
|
|
195
|
+
rewriteIndex();
|
|
196
|
+
return entry;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function deleteMemory(name: string): Promise<boolean> {
|
|
200
|
+
const safe = sanitizeMemoryName(name);
|
|
201
|
+
if (!safe) return false;
|
|
202
|
+
const target = path.join(memoryDir(), `${safe}.md`);
|
|
203
|
+
if (!fs.existsSync(target)) return false;
|
|
204
|
+
fs.rmSync(target);
|
|
205
|
+
rewriteIndex();
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
-
import { mkdtempSync, promises as fs, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { mkdirSync, mkdtempSync, promises as fs, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { INIT_PROMPT, buildSystemPrompt, loadProjectContext } from './system-prompt.js';
|
|
@@ -87,3 +87,89 @@ describe('INIT_PROMPT', () => {
|
|
|
87
87
|
expect(INIT_PROMPT.toLowerCase()).toContain('analyze');
|
|
88
88
|
});
|
|
89
89
|
});
|
|
90
|
+
|
|
91
|
+
describe('user memory injection', () => {
|
|
92
|
+
const memory = {
|
|
93
|
+
globalInstructions: 'All projects run on bun.',
|
|
94
|
+
entries: [
|
|
95
|
+
{
|
|
96
|
+
name: 'commit-style-zh',
|
|
97
|
+
type: 'feedback' as const,
|
|
98
|
+
description: '中文 commit 惯例',
|
|
99
|
+
content: 'Commit messages written in Chinese.',
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
omitted: ['stale-pointer'],
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
test('userMemory 有内容 → 渲染 ## User memory 段,位于 ## Project instructions 之前', () => {
|
|
106
|
+
const prompt = buildSystemPrompt({
|
|
107
|
+
cwd: '/tmp',
|
|
108
|
+
projectFiles: [{ path: 'TRANS.md', content: 'project rules' }],
|
|
109
|
+
userMemory: memory,
|
|
110
|
+
});
|
|
111
|
+
expect(prompt).toContain('## User memory');
|
|
112
|
+
expect(prompt.indexOf('## User memory')).toBeLessThan(
|
|
113
|
+
prompt.indexOf('## Project instructions'),
|
|
114
|
+
);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('段内含 Global instructions 原文、索引行、各条 #### name 与正文、omitted 注名行', () => {
|
|
118
|
+
const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [], userMemory: memory });
|
|
119
|
+
expect(prompt).toContain('### Global instructions');
|
|
120
|
+
expect(prompt).toContain('All projects run on bun.');
|
|
121
|
+
expect(prompt).toContain('- [commit-style-zh](commit-style-zh.md) — 中文 commit 惯例');
|
|
122
|
+
expect(prompt).toContain('#### commit-style-zh');
|
|
123
|
+
expect(prompt).toContain('Commit messages written in Chinese.');
|
|
124
|
+
expect(prompt).toContain('(omitted: stale-pointer)');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('userMemory 为空/缺省 → 不渲染该段;How to work 始终含 memory_save 引导行', () => {
|
|
128
|
+
const empty = buildSystemPrompt({
|
|
129
|
+
cwd: '/tmp',
|
|
130
|
+
projectFiles: [],
|
|
131
|
+
userMemory: { globalInstructions: null, entries: [], omitted: [] },
|
|
132
|
+
});
|
|
133
|
+
expect(empty).not.toContain('## User memory');
|
|
134
|
+
expect(empty).toContain('memory_save');
|
|
135
|
+
|
|
136
|
+
const absent = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
|
|
137
|
+
expect(absent).not.toContain('## User memory');
|
|
138
|
+
expect(absent).toContain('memory_save');
|
|
139
|
+
expect(absent).toContain('verify it still holds');
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('loadProjectContext 集成:TRANSCODE_USER_DIR 根下放 TRANS.md + memory 条目 → context.userMemory 装载', async () => {
|
|
143
|
+
const dir = workspace();
|
|
144
|
+
const userRoot = mkdtempSync(path.join(tmpdir(), 'transcode-user-memory-'));
|
|
145
|
+
process.env.TRANSCODE_USER_DIR = userRoot;
|
|
146
|
+
try {
|
|
147
|
+
writeFileSync(path.join(userRoot, 'TRANS.md'), 'Global rule: bun only.\n');
|
|
148
|
+
mkdirSync(path.join(userRoot, 'memory'), { recursive: true });
|
|
149
|
+
writeFileSync(
|
|
150
|
+
path.join(userRoot, 'memory', 'pref-editor.md'),
|
|
151
|
+
'---\nname: pref-editor\ntype: user\ndescription: 编辑器偏好\n---\nVim keybindings everywhere.\n',
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
const context = await loadProjectContext(dir);
|
|
155
|
+
expect(context.userMemory?.globalInstructions).toBe('Global rule: bun only.');
|
|
156
|
+
expect(context.userMemory?.entries[0]?.name).toBe('pref-editor');
|
|
157
|
+
expect(context.userMemory?.omitted).toEqual([]);
|
|
158
|
+
} finally {
|
|
159
|
+
delete process.env.TRANSCODE_USER_DIR;
|
|
160
|
+
rmSync(userRoot, { recursive: true, force: true });
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe('omitted-only user memory', () => {
|
|
166
|
+
test('全部条目超预算被丢 → 段仍渲染且含 omitted 注名', () => {
|
|
167
|
+
const prompt = buildSystemPrompt({
|
|
168
|
+
cwd: '/tmp',
|
|
169
|
+
projectFiles: [],
|
|
170
|
+
userMemory: { globalInstructions: null, entries: [], omitted: ['huge'] },
|
|
171
|
+
});
|
|
172
|
+
expect(prompt).toContain('## User memory');
|
|
173
|
+
expect(prompt).toContain('(omitted: huge)');
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { promises as fs } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { getRouting } from '../provider/provider.js';
|
|
4
|
+
import { loadUserMemory, renderMemoryIndex, type UserMemory } from './memory.js';
|
|
4
5
|
|
|
5
6
|
const CONTEXT_FILES = ['TRANS.md', 'AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
|
|
6
7
|
const MAX_CONTEXT_CHARS = 40_000;
|
|
@@ -22,6 +23,8 @@ export interface ProjectContext {
|
|
|
22
23
|
cwd: string;
|
|
23
24
|
gitBranch?: string;
|
|
24
25
|
projectFiles: { path: string; content: string }[];
|
|
26
|
+
/** User-level memory (global instructions + memories); loaded alongside project files. */
|
|
27
|
+
userMemory?: UserMemory;
|
|
25
28
|
}
|
|
26
29
|
|
|
27
30
|
async function readOptional(file: string): Promise<string | null> {
|
|
@@ -79,7 +82,7 @@ export async function loadProjectContext(cwd: string): Promise<ProjectContext> {
|
|
|
79
82
|
budget -= clipped.length;
|
|
80
83
|
}
|
|
81
84
|
|
|
82
|
-
return { cwd, gitBranch: await gitBranch(cwd), projectFiles };
|
|
85
|
+
return { cwd, gitBranch: await gitBranch(cwd), projectFiles, userMemory: await loadUserMemory() };
|
|
83
86
|
}
|
|
84
87
|
|
|
85
88
|
export function buildSystemPrompt(
|
|
@@ -124,8 +127,27 @@ export function buildSystemPrompt(
|
|
|
124
127
|
'- Never claim a command succeeded unless you actually ran it and saw the result.',
|
|
125
128
|
'- When the task is complete, reply with a short summary of what changed and any verification performed.',
|
|
126
129
|
'- If a tool fails, read the error and adapt instead of repeating the same call.',
|
|
130
|
+
'- When the user corrects your behavior or states a lasting preference, save it with ' +
|
|
131
|
+
'memory_save; before relying on a possibly stale memory, verify it still holds.',
|
|
127
132
|
];
|
|
128
133
|
|
|
134
|
+
const memory = context.userMemory;
|
|
135
|
+
if (memory && (memory.globalInstructions || memory.entries.length > 0 || memory.omitted.length > 0)) {
|
|
136
|
+
sections.push('', '## User memory');
|
|
137
|
+
if (memory.globalInstructions) {
|
|
138
|
+
sections.push('', '### Global instructions', memory.globalInstructions);
|
|
139
|
+
}
|
|
140
|
+
if (memory.entries.length > 0) {
|
|
141
|
+
sections.push('', '### Memory', renderMemoryIndex(memory.entries).trim());
|
|
142
|
+
for (const entry of memory.entries) {
|
|
143
|
+
sections.push('', `#### ${entry.name}`, entry.content);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (memory.omitted.length > 0) {
|
|
147
|
+
sections.push('', `(omitted: ${memory.omitted.join(', ')})`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
129
151
|
if (context.projectFiles.length > 0) {
|
|
130
152
|
sections.push('', '## Project instructions');
|
|
131
153
|
for (const file of context.projectFiles) {
|
package/src/agent/tools/index.ts
CHANGED
|
@@ -5,6 +5,9 @@ import { bashTool } from './bash.js';
|
|
|
5
5
|
import { editFileTool, readFileTool, writeFileTool } from './files.js';
|
|
6
6
|
import { globTool, grepTool } from './search.js';
|
|
7
7
|
import { todoWriteTool } from './todo.js';
|
|
8
|
+
import { memoryDeleteTool, memorySaveTool } from './memory.js';
|
|
9
|
+
import { webFetchTool } from './web-fetch.js';
|
|
10
|
+
import { webSearchTool } from './web-search.js';
|
|
8
11
|
import { createAskModelTool } from './ask-model.js';
|
|
9
12
|
import { createDispatchAgentTool } from './dispatch.js';
|
|
10
13
|
import { readImageBlocks } from './files.js';
|
|
@@ -27,6 +30,10 @@ const dispatchPool = [
|
|
|
27
30
|
bashOutputTool,
|
|
28
31
|
todoWriteTool,
|
|
29
32
|
askModelTool,
|
|
33
|
+
memorySaveTool,
|
|
34
|
+
memoryDeleteTool,
|
|
35
|
+
webFetchTool,
|
|
36
|
+
webSearchTool,
|
|
30
37
|
];
|
|
31
38
|
const dispatchAgentTool = createDispatchAgentTool({
|
|
32
39
|
runLoop: (options) =>
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, promises as fs, rmSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createToolSession, type ToolSession } from './session.js';
|
|
6
|
+
import type { ToolContext } from './types.js';
|
|
7
|
+
import { memoryDeleteTool, memorySaveTool } from './memory.js';
|
|
8
|
+
import { loadUserMemory } from '../memory.js';
|
|
9
|
+
|
|
10
|
+
let root: string;
|
|
11
|
+
|
|
12
|
+
async function withRoot(run: (session: ToolSession) => Promise<void>): Promise<void> {
|
|
13
|
+
root = mkdtempSync(path.join(tmpdir(), 'transcode-memory-tool-'));
|
|
14
|
+
process.env.TRANSCODE_USER_DIR = root;
|
|
15
|
+
const session = createToolSession(root);
|
|
16
|
+
try {
|
|
17
|
+
await run(session);
|
|
18
|
+
} finally {
|
|
19
|
+
delete process.env.TRANSCODE_USER_DIR;
|
|
20
|
+
rmSync(root, { recursive: true, force: true });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function ctx(session: ToolSession): ToolContext {
|
|
25
|
+
return { cwd: session.cwd, session };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('memory tools', () => {
|
|
29
|
+
test('memory_save 经 execute 落盘:文件 + 索引 + 返回含 name/type', async () => {
|
|
30
|
+
await withRoot(async (session) => {
|
|
31
|
+
const out = await memorySaveTool.execute(
|
|
32
|
+
{
|
|
33
|
+
name: 'commit-style-zh',
|
|
34
|
+
type: 'feedback',
|
|
35
|
+
content: 'Commit messages written in Chinese.',
|
|
36
|
+
description: '中文 commit 惯例',
|
|
37
|
+
},
|
|
38
|
+
ctx(session),
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
expect(out).toContain('commit-style-zh');
|
|
42
|
+
expect(out).toContain('feedback');
|
|
43
|
+
|
|
44
|
+
const loaded = await loadUserMemory();
|
|
45
|
+
expect(loaded.entries).toHaveLength(1);
|
|
46
|
+
expect(loaded.entries[0].name).toBe('commit-style-zh');
|
|
47
|
+
const index = await fs.readFile(
|
|
48
|
+
path.join(root, 'memory', 'MEMORY.md'),
|
|
49
|
+
'utf8',
|
|
50
|
+
);
|
|
51
|
+
expect(index).toContain('- [commit-style-zh](commit-style-zh.md) — 中文 commit 惯例');
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('memory_delete 经 execute 删条目,未命中返回 "not found" 文案', async () => {
|
|
56
|
+
await withRoot(async (session) => {
|
|
57
|
+
await memorySaveTool.execute(
|
|
58
|
+
{ name: 'temp-note', type: 'user', content: 'soon gone' },
|
|
59
|
+
ctx(session),
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
const out = await memoryDeleteTool.execute({ name: 'temp-note' }, ctx(session));
|
|
63
|
+
expect(out).not.toContain('not found');
|
|
64
|
+
expect((await loadUserMemory()).entries).toHaveLength(0);
|
|
65
|
+
|
|
66
|
+
const miss = await memoryDeleteTool.execute({ name: 'no-such' }, ctx(session));
|
|
67
|
+
expect(miss).toContain('not found');
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('两工具 isMutating === true(被 plan/readonly 门禁拒绝的根据)', () => {
|
|
72
|
+
expect(memorySaveTool.isMutating).toBe(true);
|
|
73
|
+
expect(memoryDeleteTool.isMutating).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('危险 name 经工具返回 Error 文案而非抛异常', async () => {
|
|
77
|
+
await withRoot(async (session) => {
|
|
78
|
+
const out = await memorySaveTool.execute(
|
|
79
|
+
{ name: 'a/b', type: 'user', content: 'x' },
|
|
80
|
+
ctx(session),
|
|
81
|
+
);
|
|
82
|
+
expect(out).toContain('Error');
|
|
83
|
+
|
|
84
|
+
const del = await memoryDeleteTool.execute({ name: '..' }, ctx(session));
|
|
85
|
+
expect(del).toContain('not found');
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
});
|