@trans-ai/trans-code 0.9.0 → 0.10.1

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.
@@ -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
+ }
@@ -48,3 +48,12 @@ describe('permission mode', () => {
48
48
  expect(PERMISSION_MODES).toEqual(['ask', 'auto', 'readonly']);
49
49
  });
50
50
  });
51
+
52
+ describe('nextPermissionMode', () => {
53
+ test('shift+tab 循环:ask → auto → readonly → ask', async () => {
54
+ const { nextPermissionMode } = await import('./permission.js');
55
+ expect(nextPermissionMode('ask')).toBe('auto');
56
+ expect(nextPermissionMode('auto')).toBe('readonly');
57
+ expect(nextPermissionMode('readonly')).toBe('ask');
58
+ });
59
+ });
@@ -21,6 +21,12 @@ export function getPermissionMode(): PermissionMode {
21
21
  return currentMode;
22
22
  }
23
23
 
24
+ /** Shift+Tab cycling order: ask → auto → readonly → ask. */
25
+ export function nextPermissionMode(current: PermissionMode): PermissionMode {
26
+ const index = PERMISSION_MODES.indexOf(current);
27
+ return PERMISSION_MODES[(index + 1) % PERMISSION_MODES.length]!;
28
+ }
29
+
24
30
  export function setPermissionMode(mode: PermissionMode): void {
25
31
  if (!PERMISSION_MODES.includes(mode)) {
26
32
  throw new Error(`Unknown permission mode: ${mode}. Valid: ${PERMISSION_MODES.join(', ')}`);
@@ -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,123 @@ 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
+ });
176
+
177
+ describe('web tool guidance', () => {
178
+ test('webSearch 已配置 → How to work 含 web_search 优先于记忆的引导', async () => {
179
+ const configDir = await fs.mkdtemp(path.join(tmpdir(), 'transcode-prompt-web-'));
180
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
181
+ try {
182
+ writeFileSync(
183
+ path.join(configDir, 'config.json'),
184
+ JSON.stringify({ webSearch: { provider: 'tavily', apiKey: 'tvly-x' } }),
185
+ );
186
+ const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
187
+ expect(prompt).toContain('web_search');
188
+ expect(prompt).toContain('web_fetch');
189
+ expect(prompt.toLowerCase()).toContain('outside this workspace');
190
+ } finally {
191
+ delete process.env.TRANSCODE_CONFIG_PATH;
192
+ await fs.rm(configDir, { recursive: true, force: true });
193
+ }
194
+ });
195
+
196
+ test('未配置 → 不提 web_search(与工具隐藏一致),仍提 web_fetch', () => {
197
+ const configDir = mkdtempSync(path.join(tmpdir(), 'transcode-prompt-noweb-'));
198
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'empty.json');
199
+ try {
200
+ writeFileSync(path.join(configDir, 'empty.json'), '{}');
201
+ const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
202
+ expect(prompt).not.toContain('web_search');
203
+ expect(prompt).toContain('web_fetch');
204
+ } finally {
205
+ delete process.env.TRANSCODE_CONFIG_PATH;
206
+ rmSync(configDir, { recursive: true, force: true });
207
+ }
208
+ });
209
+ });
@@ -1,6 +1,9 @@
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';
5
+ import { loadConfig } from '../config.js';
6
+ import { normalizeWebSearchConfig } from '../provider/web-search.js';
4
7
 
5
8
  const CONTEXT_FILES = ['TRANS.md', 'AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
6
9
  const MAX_CONTEXT_CHARS = 40_000;
@@ -22,6 +25,8 @@ export interface ProjectContext {
22
25
  cwd: string;
23
26
  gitBranch?: string;
24
27
  projectFiles: { path: string; content: string }[];
28
+ /** User-level memory (global instructions + memories); loaded alongside project files. */
29
+ userMemory?: UserMemory;
25
30
  }
26
31
 
27
32
  async function readOptional(file: string): Promise<string | null> {
@@ -33,6 +38,26 @@ async function readOptional(file: string): Promise<string | null> {
33
38
  }
34
39
  }
35
40
 
41
+ /**
42
+ * Web tool guidance, gated like the tools themselves: web_search is only
43
+ * advertised when configured (the tool is hidden from the table otherwise);
44
+ * web_fetch is always available.
45
+ */
46
+ function webToolLines(): string[] {
47
+ const searchConfigured = normalizeWebSearchConfig(loadConfig().webSearch) !== null;
48
+ return [
49
+ ...(searchConfigured
50
+ ? [
51
+ '- Questions about anything outside this workspace — unfamiliar terms, latest ' +
52
+ 'releases, current documentation — search the web with web_search BEFORE answering ' +
53
+ 'from memory; read a promising result with web_fetch.',
54
+ ]
55
+ : []),
56
+ '- Use web_fetch to read a specific URL (docs, API responses, raw files) when the user ' +
57
+ 'points at one.',
58
+ ];
59
+ }
60
+
36
61
  /** Advertises configured role routing so the model knows it can delegate. */
37
62
  function roleRoutingLines(): string[] {
38
63
  const entries = Object.entries(getRouting()).filter(([role]) => role !== 'default');
@@ -79,7 +104,7 @@ export async function loadProjectContext(cwd: string): Promise<ProjectContext> {
79
104
  budget -= clipped.length;
80
105
  }
81
106
 
82
- return { cwd, gitBranch: await gitBranch(cwd), projectFiles };
107
+ return { cwd, gitBranch: await gitBranch(cwd), projectFiles, userMemory: await loadUserMemory() };
83
108
  }
84
109
 
85
110
  export function buildSystemPrompt(
@@ -113,6 +138,7 @@ export function buildSystemPrompt(
113
138
  'then state a short plan and write the result. Exploration is not the deliverable.',
114
139
  '- Multi-step tasks (3+ steps): create the list with todo_write first, keep exactly one ' +
115
140
  'step in_progress, and mark steps completed as you finish them.',
141
+ ...webToolLines(),
116
142
  ...roleRoutingLines(),
117
143
  '- Reporting counts (tests, checks, matches): grep -c counts matching LINES, including ' +
118
144
  'definitions like `def check(` — read the actual item list instead of trusting a raw count.',
@@ -124,8 +150,27 @@ export function buildSystemPrompt(
124
150
  '- Never claim a command succeeded unless you actually ran it and saw the result.',
125
151
  '- When the task is complete, reply with a short summary of what changed and any verification performed.',
126
152
  '- If a tool fails, read the error and adapt instead of repeating the same call.',
153
+ '- When the user corrects your behavior or states a lasting preference, save it with ' +
154
+ 'memory_save; before relying on a possibly stale memory, verify it still holds.',
127
155
  ];
128
156
 
157
+ const memory = context.userMemory;
158
+ if (memory && (memory.globalInstructions || memory.entries.length > 0 || memory.omitted.length > 0)) {
159
+ sections.push('', '## User memory');
160
+ if (memory.globalInstructions) {
161
+ sections.push('', '### Global instructions', memory.globalInstructions);
162
+ }
163
+ if (memory.entries.length > 0) {
164
+ sections.push('', '### Memory', renderMemoryIndex(memory.entries).trim());
165
+ for (const entry of memory.entries) {
166
+ sections.push('', `#### ${entry.name}`, entry.content);
167
+ }
168
+ }
169
+ if (memory.omitted.length > 0) {
170
+ sections.push('', `(omitted: ${memory.omitted.join(', ')})`);
171
+ }
172
+ }
173
+
129
174
  if (context.projectFiles.length > 0) {
130
175
  sections.push('', '## Project instructions');
131
176
  for (const file of context.projectFiles) {
@@ -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) =>