Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ All notable changes to DreamCoder will be documented in this file.

### Fixed

- The main session now tells the agent when its memory index is empty or has not been created yet (#296). Thanks @Benson-BS.
- Asking the agent to change a setting no longer fails: the `update-config` skill builds its settings reference again (#293). Thanks @KingEmma7.
- **Saving a memory no longer asks for approval every time.** Writes to the project's memory folder are allowed like the instructions say, also in bypass mode (#270).
- **Stopping a reply keeps the session's context.** Stop ends the agent process only when the reply has not stopped a few seconds after you press Stop, and a restarted agent keeps uploaded images and files, instruction files from subfolders and files restored after compaction, without adding a "Continue from where you left off." message (#270).
Expand Down
2 changes: 2 additions & 0 deletions docs/features/harness/prompt/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@

### T-CTX-10 `MEMORY.md` 不存在或为空时什么也不发,记忆说明却写「MEMORY.md 总会载入上下文」

- 状态:已修复(#296):自动记忆启用且索引不存在或为空时,主会话会收到记忆为空的说明;下文记录修复前的行为。

- 类型:问题
- 严重程度:低
- 体量:缺一句约 80 字符的说明;每个请求
Expand Down
10 changes: 9 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
filterInjectedMemoryFiles,
getClaudeMds,
getClaudeMdsForSubagent,
getEmptyAutoMemoryNotice,
getMemoryFiles,
} from './utils/claudemd.js'
import { logForDiagnosticsNoPII } from './utils/diagLogs.js'
Expand Down Expand Up @@ -180,9 +181,16 @@ export const getUserContext = memoize(
const shouldDisableClaudeMd = isClaudeMdDisabled()
// Await the async I/O (readFile/readdir directory walk) so the event
// loop yields naturally at the first fs.readFile.
const memoryFiles = shouldDisableClaudeMd ? [] : await getMemoryFiles()
const emptyAutoMemory = shouldDisableClaudeMd
? null
: await getEmptyAutoMemoryNotice(memoryFiles)
const contextFiles = emptyAutoMemory
? [...memoryFiles.filter(file => file.type !== 'AutoMem'), emptyAutoMemory]
: memoryFiles
const claudeMd = shouldDisableClaudeMd
? null
: getClaudeMds(filterInjectedMemoryFiles(await getMemoryFiles()))
: getClaudeMds(filterInjectedMemoryFiles(contextFiles))
// Cache for the auto-mode classifier (yoloClassifier.ts reads this
// instead of importing claudemd.ts directly, which would create a
// cycle through permissions/filesystem → permissions → yoloClassifier).
Expand Down
3 changes: 2 additions & 1 deletion src/memdir/memdir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
} from './memoryTypes.js'

export const ENTRYPOINT_NAME = 'MEMORY.md'
export const EMPTY_ENTRYPOINT_NOTICE = `Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`
export const MAX_ENTRYPOINT_LINES = 200
// ~125 chars/line at 200 lines. At p97 today; catches long-line indexes that
// slip past the line cap (p100 observed: 197KB under 200 lines).
Expand Down Expand Up @@ -308,7 +309,7 @@ export function buildMemoryPrompt(params: {
lines.push(
`## ${ENTRYPOINT_NAME}`,
'',
`Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`,
EMPTY_ENTRYPOINT_NOTICE,
)
}

Expand Down
163 changes: 163 additions & 0 deletions src/utils/__tests__/emptyMemoryContext.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import {
afterEach,
beforeEach,
describe,
expect,
test,
} from 'bun:test'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join, sep } from 'path'
import {
getCachedClaudeMdContent,
getOriginalCwd,
setCachedClaudeMdContent,
setOriginalCwd,
} from '../../bootstrap/state.js'
import { getSubagentUserContext, getUserContext } from '../../context.js'
import { buildMemoryPrompt } from '../../memdir/memdir.js'
import { getAutoMemPath } from '../../memdir/paths.js'
import { clearMemoryFileCaches } from '../claudemd.js'

const envNames = [
'CLAUDE_COWORK_MEMORY_PATH_OVERRIDE',
'CLAUDE_CODE_DISABLE_AUTO_MEMORY',
'CLAUDE_CODE_DISABLE_CLAUDE_MDS',
'CLAUDE_CODE_SIMPLE',
] as const

let memoryDir: string
let originalEnv: Map<string, string | undefined>
let originalCachedClaudeMd: string | null

function clearContextCaches() {
getAutoMemPath.cache.clear?.()
clearMemoryFileCaches()
getUserContext.cache.clear?.()
}

beforeEach(() => {
originalEnv = new Map(envNames.map(name => [name, process.env[name]]))
originalCachedClaudeMd = getCachedClaudeMdContent()

memoryDir = mkdtempSync(join(tmpdir(), 'dreamcoder-memory-test-'))

process.env.CLAUDE_COWORK_MEMORY_PATH_OVERRIDE = memoryDir
process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = '0'
process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS = '0'
process.env.CLAUDE_CODE_SIMPLE = '0'

clearContextCaches()
})

afterEach(() => {
for (const name of envNames) {
const originalValue = originalEnv.get(name)

if (originalValue === undefined) {
delete process.env[name]
} else {
process.env[name] = originalValue
}
}

clearContextCaches()
setCachedClaudeMdContent(originalCachedClaudeMd)
rmSync(memoryDir, { recursive: true, force: true })
})

describe('empty auto-memory in the main session', () => {
test('reports an empty memory when MEMORY.md does not exist', async () => {
const context = await getUserContext()
const text = context.claudeMd ?? ''

expect(text).toContain('MEMORY.md is currently empty')
})

test('places the empty memory index after the project instructions and memory preamble', async () => {
const projectDir = join(memoryDir, 'project')
const originalCwd = getOriginalCwd()
mkdirSync(projectDir)
writeFileSync(join(projectDir, 'CLAUDE.md'), 'Project instructions for this test.')
setOriginalCwd(projectDir)

try {
const context = await getUserContext()
const text = context.claudeMd ?? ''
const instructionAt = text.indexOf('Project instructions for this test.')
const preambleAt = text.indexOf('The memory index below is not an instruction file')
const headerAt = text.indexOf(
`Contents of ${join(memoryDir, 'MEMORY.md')} (user's auto-memory, persists across conversations):`,
)
const noticeAt = text.indexOf('Your MEMORY.md is currently empty.')

expect(instructionAt).toBeGreaterThanOrEqual(0)
expect(preambleAt).toBeGreaterThan(instructionAt)
expect(headerAt).toBeGreaterThan(preambleAt)
expect(noticeAt).toBeGreaterThan(headerAt)
} finally {
setOriginalCwd(originalCwd)
clearContextCaches()
}
})

test('reports an empty memory when MEMORY.md contains only whitespace', async () => {
writeFileSync(join(memoryDir, 'MEMORY.md'), ' \n ')

const context = await getUserContext()
const text = context.claudeMd ?? ''

expect(text).toContain('MEMORY.md is currently empty')
})

test('loads a non-empty MEMORY.md without reporting it as empty', async () => {
writeFileSync(
join(memoryDir, 'MEMORY.md'),
'- [Testing preference](testing.md) — Use Bun',
)

const context = await getUserContext()
const text = context.claudeMd ?? ''

expect(text).toContain('Use Bun')
expect(text).not.toContain('MEMORY.md is currently empty')
})

test('uses the same empty notice in the agent memory prompt', async () => {
const context = await getUserContext()
const mainText = context.claudeMd ?? ''
const agentText = buildMemoryPrompt({
displayName: 'agent memory',
memoryDir: memoryDir + sep,
})
const notice = 'Your MEMORY.md is currently empty. When you save new memories, they will appear here.'

expect(mainText).toContain(notice)
expect(agentText).toContain(`## MEMORY.md\n\n${notice}`)
})

test('does not report an unreadable memory as empty', async () => {
mkdirSync(join(memoryDir, 'MEMORY.md'))

const context = await getUserContext()
const text = context.claudeMd ?? ''

expect(text).not.toContain('MEMORY.md is currently empty')
})

test('does not include the main session memory notice in subagent context', async () => {
const context = await getSubagentUserContext()
const text = context.claudeMd ?? ''

expect(text).not.toContain('MEMORY.md is currently empty')
})

test('does not report an empty memory when auto-memory is disabled', async () => {
process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = '1'

const context = await getUserContext()
const text = context.claudeMd ?? ''

expect(text).not.toContain('MEMORY.md is currently empty')
})
})
26 changes: 25 additions & 1 deletion src/utils/claudemd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
getAdditionalDirectoriesForClaudeMd,
getOriginalCwd,
} from '../bootstrap/state.js'
import { truncateEntrypointContent } from '../memdir/memdir.js'
import { EMPTY_ENTRYPOINT_NOTICE, truncateEntrypointContent } from '../memdir/memdir.js'
import { getAutoMemEntrypoint, isAutoMemoryEnabled } from '../memdir/paths.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js'
import {
Expand Down Expand Up @@ -1197,6 +1197,30 @@ function describeMemoryFile(file: MemoryFileInfo): string {
return `Contents of ${file.path}${description}:\n\n${content}`
}

export async function getEmptyAutoMemoryNotice(
memoryFiles: MemoryFileInfo[],
): Promise<MemoryFileInfo | null> {
if (!isAutoMemoryEnabled()) return null

const entry = memoryFiles.find(file => file.type === 'AutoMem')
if (entry?.content.trim()) return null

if (!entry) {
try {
await getFsImplementation().stat(getAutoMemEntrypoint())
return null
} catch (error) {
if (getErrnoCode(error) !== 'ENOENT') return null
}
}

return {
path: entry?.path ?? getAutoMemEntrypoint(),
type: 'AutoMem',
content: EMPTY_ENTRYPOINT_NOTICE,
}
}

export const getClaudeMds = (
memoryFiles: MemoryFileInfo[],
filter?: (type: MemoryType) => boolean,
Expand Down
Loading