Skip to content

feat(memory): managed auto-memory and auto-dream system#3087

Open
LaZzyMan wants to merge 41 commits intoQwenLM:mainfrom
LaZzyMan:feat/auto-memory
Open

feat(memory): managed auto-memory and auto-dream system#3087
LaZzyMan wants to merge 41 commits intoQwenLM:mainfrom
LaZzyMan:feat/auto-memory

Conversation

@LaZzyMan
Copy link
Copy Markdown
Collaborator

@LaZzyMan LaZzyMan commented Apr 10, 2026

TLDR

This PR introduces a fully managed auto-memory system — the model now learns from conversations automatically and maintains a persistent, queryable memory store across sessions, without any manual user action.

Two new autonomous background processes drive this:

  • Auto-extract: after each session turn, a forked background agent reads the conversation and extracts durable facts (user preferences, feedback, project context, external references) into topic-scoped Markdown files under ~/.qwen/projects/<canonical-git-root>/memory/
  • Auto-dream: once per day (after 5+ sessions), a second background agent consolidates the stored memories — deduplicates, merges, and prunes stale entries — then rewrites the index

Both processes run entirely out of band; the main conversation is never blocked. All worktrees of the same repository share one memory directory.

What changed

Core — new packages/core/src/memory/ module (~40 files, ~5 000 lines)

File(s) Role
paths.ts, const.ts, types.ts Canonical paths, limits, shared types
store.ts, entries.ts, indexer.ts Read/write memory entries and the MEMORY.md index
scan.ts, recall.ts, relevanceSelector.ts Semantic recall: scan → score → select top-K docs for context injection
extract.ts, extractScheduler.ts, extractionAgentPlanner.ts Auto-extract pipeline: detect new turns, fork agent, parse & persist results
dream.ts, dreamScheduler.ts, dreamAgentPlanner.ts Auto-dream pipeline: schedule, lock, fork agent, consolidate
forget.ts, governance.ts, status.ts /forget semantic matching, governance queries, status reporting
prompt.ts System-prompt injection of recalled memories
state.ts, memoryAge.ts Runtime flags (extraction in-flight), entry age helpers

Core — background task runtime (packages/core/src/background/)

New generic runtime for running tasks out of band without blocking the main loop:

  • taskRegistry.ts — register/lookup named tasks
  • taskScheduler.ts — time-based trigger (checks every minute)
  • taskDrainer.ts — graceful shutdown: drains running tasks before exit

CLI — new and changed commands

Command Change
/memory Replaced simple show/refresh with a full MemoryDialog — toggles for auto-memory and auto-dream, last-dream timestamp, memory count badge, links to open folders and QWEN.md files
/remember Simplified: saves directly to managed store in auto-memory mode (scope flags removed)
/forget <query> New: semantic search then immediate delete
/dream New: manually trigger the consolidation pass

UI — Footer indicator

✦ dreaming appears in the footer while the background dream pass runs, translated across all 6 locales (en, zh, de, ja, pt, ru).

Removed

  • save_memory tool (memoryTool.ts) and all its references — replaced by the extraction agent
  • SaveMemoryToolCall webui component
  • Legacy fallback extract pipeline

Docs and i18n

  • docs/users/features/memory.md — new user-facing guide: QWEN.md vs auto-memory, all commands, settings, troubleshooting
  • docs/users/configuration/settings.mdmemory.enableManagedAutoMemory and memory.enableManagedAutoDream settings documented
  • All new UI strings added to all 6 locales (en, zh, de, ja, pt, ru)

Screenshots / Video Demo

/memory show the manage dialog:
image

/remember will add memory manually:
image

after a turn auto-memory will extract memories from the conversation:
image

auto-memory will be saved in other sessions:
image

dream can be actived by /dream or auto-dream after a turn
image

Reviewer Test Plan

  1. Start a multi-turn session and discuss a project. After a few turns, open the auto-memory folder (via /memory) and verify topic files were created
  2. Run /dream — confirm ✦ dreaming appears in the footer during the run and the dialog reports updated last-dream time
  3. Run /remember prefer snake_case for Python — confirm the entry appears in the memory folder
  4. Run /forget snake_case — confirm the entry is deleted immediately
  5. Start a new session in the same project — verify previously extracted facts appear in the startup context
  6. Set "memory": { "enableManagedAutoMemory": false } in ~/.qwen/settings.json — open /memory dialog and confirm the toggle reflects the change without restart
  7. Switch UI language to de, ja, pt, or ru and open /memory — verify all strings are translated

Testing Matrix

🍏 🪟 🐧
npm run
npx
Docker
Podman - -
Seatbelt - -

Linked issues / bugs

#2991

Closes the managed auto-memory tracking issue.

LaZzyMan added 30 commits April 1, 2026 11:28
Feature 3 - Memory Saved Notification:
- Add HistoryItemMemorySaved type to types.ts
- Create MemorySavedMessage component for rendering '● Saved/Updated N memories'
- In useGeminiStream: detect in-turn memory writes via mapToDisplay's
  memoryWriteCount field and emit 'memory_saved' history item after turn
- In client.ts: capture background dream/extract promises and expose
  via consumePendingMemoryTaskPromises(); useGeminiStream listens
  post-turn and emits 'Updated N memories' notification for background tasks

Feature 4 - Memory Count Badge:
- Add isMemoryOp field to IndividualToolCallDisplay
- Add memoryWriteCount/memoryReadCount to HistoryItemToolGroup
- Add detectMemoryOp() in useReactToolScheduler using isAutoMemPath
- ToolGroupMessage renders '● Recalled N memories, Wrote N memories' badge
  at the top of tool groups that touch memory files

Fix: process.env bracket-access in paths.ts (noPropertyAccessFromIndexSignature)
Fix: MemoryDialog.test.tsx mock useSettings to satisfy SettingsProvider requirement
…ps, fix MEMORY.md path

Problem 1 - Auto-approve memory file operations:
- write-file.ts: getDefaultPermission() checks isAutoMemPath; returns 'allow'
  for managed auto-memory files, 'ask' for all other files
- edit.ts: same pattern

Problem 2 - Feature 4 UX: collapse memory-only tool groups:
- ToolGroupMessage: detect when all tool calls have isMemoryOp set (pure memory
  group) and all are complete; render compact '● Recalled/Wrote N memories
  (ctrl+o to expand)' instead of individual tool call rows
- ctrl+o toggles expand/collapse when isFocused and group is memory-only
- Mixed groups (memory + other tools) keep badge-at-top behaviour
- Expanded state shows individual tool calls with '● Memory operations
  (ctrl+o to collapse)' header

Problem 3 - MEMORY.md path mismatch:
- prompt.ts: Step 2 now references full absolute path ${memoryDir}/MEMORY.md
  so the model writes to the correct location inside the memory directory,
  not to the parent project directory

Fix tests:
- write-file.test.ts: add getProjectRoot to mockConfigInternal
- prompt.test.ts: update assertion to match full-path section header
…ool detection

- Remove duplicate 'Saved N memories' notification: the tool group badge already
  shows 'Wrote N memories'; the separate HistoryItemMemorySaved addItem after
  onComplete was double-counting. Keep only the background-task path
  (consumePendingMemoryTaskPromises).

- Remove ctrl+o expand: Ink's Static area freezes items on first render and
  cannot respond to user input. useInput/useState(isExpanded) in a Static item
  is a no-op. Removed the dead code; memory-only groups now always render as
  the compact summary (no fake interactive hint).

- Fix Edit tool detection: detectMemoryOp was checking for 'edit_file' but the
  real tool name constant is 'edit'. Also removed non-existent 'create_file'
  (write_file covers all writes). Now editing MEMORY.md is correctly identified
  as a memory write op, collapses to 'Wrote N memories', and is auto-approved.
…background agent

The previous implementation ran an AgentHeadless background agent that could
take 5+ minutes with zero UI feedback — user saw a blank screen for the entire
duration and then at most one line of text.

Fix: /dream now returns submit_prompt with the consolidation task prompt so it
runs as a regular AI conversation turn. Tool calls (read_file, write_file, edit,
grep_search, list_directory, glob) are immediately visible as collapsed tool
groups as the model works through the memory files — identical UX to Claude Code.

Also export buildConsolidationTaskPrompt from dreamAgentPlanner so dreamCommand
can reuse the same detailed consolidation prompt that was already written.
Add getMemoryBaseDir() to getDefaultPermission() allow list in ls.ts,
glob.ts, and grep.ts — mirrors the existing pattern in read-file.ts.

Without this, ListFiles/Glob/Grep on ~/.qwen/* would trigger an
approval dialog, blocking /dream at its very first step.
Match Claude Code's headless-agent intent: background memory agents must never
block on interactive permission prompts.

Wrap background runtime config so getApprovalMode() returns YOLO, ensuring any
ask decision is auto-approved instead of hanging forever. Add regression test
covering the wrapped approval mode.
Make managed auto-memory extraction follow the Claude Code architecture:
background extraction now uses a forked agent to read/write memory files
directly, instead of planning patches and applying them with a separate
filesystem pipeline.

Keep the old patch/model path only as fallback if the forked agent fails.
Add regression tests covering the new execution path and tool whitelist.
Delete the old patch/model/heuristic extraction path entirely.
Managed auto-memory extract now runs only through the forked-agent
execution flow, with no planner/apply fallback stages remaining.

Also remove obsolete exports/tests and update scheduler/integration
coverage to use the forked-agent-only architecture.
meta.json, extract-cursor.json, and consolidation.lock are internal
bookkeeping files, not user-visible memories. Move them one level up
to the project state dir (parent of memory/) so that the memory/
directory contains only MEMORY.md and topic files, matching the
clean layout of the upstream reference implementation.

Add getAutoMemoryProjectStateDir() helper in paths.ts and update the
three path accessors + store.test.ts path assertions accordingly.
LaZzyMan added 6 commits April 9, 2026 10:19
The /dream command submits a prompt to the main agent (submit_prompt),
which writes memory files directly. Because it bypasses dreamScheduler,
meta.json was never updated and /memory always showed 'never'.

Fix by:
- Exporting writeDreamManualRunToMetadata() from dream.ts
- Adding optional onComplete callback to SubmitPromptActionReturn and
  SubmitPromptResult (types.ts / commands/types.ts)
- Propagating onComplete through slashCommandProcessor.ts
- Firing onComplete after turn completion in useGeminiStream.ts
- Providing the callback in dreamCommand.ts to write lastDreamAt
…y mode

--global/--project are legacy save_memory tool concepts. In managed
auto-memory mode the forked agent decides the appropriate type
(user/feedback/project/reference) based on the content of the fact.

Also improve the prompt wording to explicitly ask the agent to choose
the correct type, reducing the tendency to default to 'project'.
Subscribe to getManagedAutoMemoryDreamTaskRegistry() in Footer via a
useDreamRunning() hook. While any dream task for the current project is
pending or running, display '✦ dreaming' in the right section of the
footer bar, between Debug Mode and context usage.
… patterns

Five improvements based on Claude Code parity audit:

1. Memoize getAutoMemoryRoot (paths.ts)
   - Add _autoMemoryRootCache Map, keyed by projectRoot
   - findCanonicalGitRoot() walks the filesystem per call; memoize avoids
     repeated git-tree traversal on hot-path schedulers/scanners
   - Expose clearAutoMemoryRootCache() for test teardown

2. Lock file stores PID + isProcessRunning reclaim (dreamScheduler.ts)
   - acquireDreamLock() writes process.pid to the lock file body
   - lockExists() reads PID and calls process.kill(pid, 0); dead/missing
     PID reclaims the lock immediately instead of waiting 2h
   - Stale threshold reduced to 1h (PID-reuse guard, same as CC)

3. Session scan throttle (dreamScheduler.ts)
   - Add SESSION_SCAN_INTERVAL_MS = 10min (same as CC)
   - Add lastSessionScanAt Map<projectRoot, number> to ManagedAutoMemoryDreamRuntime
   - When time-gate passes but session-gate doesn't, throttle prevents
     re-scanning the filesystem on every user turn

4. mtime-based session counting (dreamScheduler.ts)
   - Replace fragile recentSessionIdsSinceDream Set in meta.json with
     filesystem mtime scan (listSessionsTouchedSince)
   - Mirrors Claude Code's listSessionsTouchedSince: reads session JSONL
     files from Storage.getProjectDir()/chats/, filters by mtime > lastDreamAt
   - Immune to meta.json corruption/loss; no per-turn metadata write
   - ManagedAutoMemoryDreamRuntime accepts injectable SessionScannerFn
     for clean unit testing without real session files

5. Extraction mutual exclusion extended to write_file/edit (extractScheduler.ts)
   - historySliceUsesMemoryTool() now checks write_file/edit/replace/create_file
     tool calls whose file_path is within isAutoMemPath()
   - Previously only detected save_memory; missed direct file writes by
     the main agent, causing redundant background extraction
…lify /forget

- Add docs/users/features/memory.md: comprehensive user-facing guide covering
  QWEN.md instructions, auto-memory behaviour, all memory commands, and
  troubleshooting; replaces the placeholder auto-memory.md
- Update docs/users/features/_meta.ts: rename entry auto-memory → memory
- Update docs/users/features/commands.md: add /init, /remember, /forget,
  /dream rows; fix /memory description; remove /init duplicate
- Update docs/users/configuration/settings.md: add memory.* settings section
  (enableManagedAutoMemory, enableManagedAutoDream) between tools and permissions
- Remove /forget --apply flag: preview-then-apply flow replaced with direct
  deletion; update forgetCommand.ts, en.js, zh.js accordingly
- Add all auto-memory i18n keys to de, ja, pt, ru locales (18 keys each):
  Open auto-memory folder, Auto-memory/Auto-dream status lines, never/on/off,
  ✦ dreaming, /forget and /remember usage strings, all managed-memory messages
- Remove dead save_memory branch from extractScheduler.partWritesToMemory()
- Add ✦ dreaming indicator to Footer.tsx with i18n; fix Footer.test.tsx mocks
- Refactor MemoryDialog.tsx auto-dream status line to use i18n
- Remove save_memory tool (memoryTool.ts/test); clean up webui references
- Add extractionPlanner.ts, const.ts and associated tests
- Delete stale docs/users/configuration/memory.md and
  docs/developers/tools/memory.md (content superseded)
@github-actions
Copy link
Copy Markdown
Contributor

Code Review: Auto-Memory System (PR #3087)

📋 Review Summary

This PR introduces a comprehensive auto-memory system that automatically extracts durable facts from conversations and consolidates them through periodic "dream" passes. The implementation spans ~40 new files (~5,000+ lines) in packages/core/src/memory/, new CLI commands (/dream, /forget, /remember), a revamped /memory dialog, and extensive documentation. The architecture is well-structured with clear separation of concerns, but several critical and high-priority issues need addressing before merge.


🔍 General Feedback

Positive aspects:

  • Excellent modular architecture with clear separation between extraction, dream, scheduling, and storage layers
  • Comprehensive test coverage with integration tests covering the full lifecycle
  • Thoughtful design decisions (PID-based locking, session-based throttling, stale lock reclamation)
  • Good internationalization coverage across all 6 locales
  • Well-documented with user-facing docs explaining the system clearly

Architectural observations:

  • The background task runtime (packages/core/src/background/) is a solid generic foundation for future background agents
  • The file-based memory format (Markdown with frontmatter) is pragmatic and user-editable
  • The extraction→dream pipeline mirrors Claude Code's approach effectively

Concerns:

  • Several critical security and reliability gaps in the background agent execution path
  • Missing error handling in key filesystem operations
  • Potential race conditions in the scheduler
  • Some test mocking patterns may hide real-world failures

🎯 Specific Feedback

🔴 Critical

Security & Permissions:

  1. File: packages/core/src/background/backgroundAgentRunner.ts:57-62 - Background agents force ApprovalMode.YOLO to avoid hanging on permission prompts. While the comment acknowledges this safety concern, there's no tool restriction enforcement visible in the code path shown. The toolConfig.tools is mentioned but needs verification that it's actually enforced by the headless agent executor. Recommendation: Add explicit assertion/logging when YOLO mode is engaged, and verify tool restrictions are enforced at the tool invocation layer, not just declared.

  2. File: packages/core/src/memory/dreamAgentPlanner.ts:97-108 - The dream agent is granted access to write_file and edit tools with auto-approve. If the agent is compromised or hallucinates, it could modify arbitrary files within the project. Recommendation: Restrict dream agent to only write within the auto-memory directory by adding path validation in the tool layer.

  3. File: packages/core/src/memory/paths.ts:107-113 - The isAutoMemPath() function uses startsWith with a path separator check, but this is vulnerable to path traversal if projectRoot is attacker-controlled. Recommendation: Use path.relative() and check that the result doesn't start with ...

Data Loss Risk:

  1. File: packages/core/src/memory/dream.ts - The dream consolidation logic (lines 6000-7000 in diff) performs deduplication by deleting files. If the semantic matching is incorrect, users could lose saved memories permanently. Recommendation: Implement a trash/recycle bin pattern where deleted memories are moved to a .trash/ subdirectory for 30 days before permanent deletion.

🟡 High

Reliability & Error Handling:

  1. File: packages/core/src/memory/extractScheduler.ts:176-185 - The runTask method catches errors but the error handling path isn't fully visible. If extraction fails mid-write, memory files could be left in an inconsistent state. Recommendation: Use atomic writes (write to temp file, then rename) for all memory file modifications.

  2. File: packages/core/src/memory/store.ts:55-72 - The ensureAutoMemoryScaffold function uses flag: 'wx' to avoid overwriting existing files, but if the index file is corrupted, there's no recovery mechanism. Recommendation: Add a validation function that can detect and repair corrupted scaffolding.

  3. File: packages/core/src/memory/dreamScheduler.ts:165-180 - The lockExists() function checks if a PID is running, but on container restarts or crash scenarios, the lock file could persist indefinitely. The 1-hour stale threshold helps, but Recommendation: Add a --force-unlock CLI command for manual recovery.

Testing Gaps:

  1. File: packages/core/src/memory/extractAgent.test.ts:47-71 - The test mocks runAutoMemoryExtractionByAgent but doesn't verify the actual agent prompt or response parsing. Recommendation: Add an integration test that validates the full extraction pipeline with a mock LLM response.

  2. File: packages/cli/src/ui/components/MemoryDialog.test.tsx:54-67 - The test only verifies arrow key navigation. Recommendation: Add tests for the toggle switches, folder opening, and error states.

Performance:

  1. File: packages/core/src/memory/paths.ts:84-97 - The getAutoMemoryRoot() function memoizes by projectRoot, but findCanonicalGitRoot() walks the filesystem calling existsSync() for each directory level. For deep directory structures, this could be slow. Recommendation: Add a global LRU cache keyed by filesystem inode or realpath to handle worktree scenarios efficiently.

🟢 Medium

Code Quality:

  1. File: packages/core/src/memory/entries.ts:60-90 - The parseAutoMemoryEntries() function supports both legacy and new formats, but the logic is complex with multiple regex patterns. Recommendation: Extract format detection into a separate function and add unit tests for edge cases (malformed frontmatter, mixed formats).

  2. File: packages/core/src/memory/governance.ts:9000-10000 - The buildHeuristicSuggestions() function has multiple nested loops for duplicate/conflict detection (O(n²)). For large memory stores, this could be slow. Recommendation: Use a Map-based approach for O(n) duplicate detection.

  3. File: packages/core/src/memory/recall.ts - The relevance scoring logic isn't visible in the diff sections read. Recommendation: Ensure there are unit tests for the scoring algorithm with edge cases (empty query, very long query, special characters).

Type Safety:

  1. File: packages/core/src/memory/dreamScheduler.ts:204 - The sessionScanner parameter has a default value but the type SessionScannerFn is exported. Recommendation: Make the parameter required and inject the default at the call site for better testability.

  2. File: packages/cli/src/ui/hooks/useReactToolScheduler.ts:224-237 - The detectMemoryOp() function returns undefined for non-memory operations, but the isMemoryOp field in IndividualToolCallDisplay is optional. Recommendation: Consider using a discriminated union or explicit 'none' value for clarity.


🔵 Low

Documentation:

  1. File: docs/users/features/memory.md - The user documentation is excellent but doesn't mention the 5-session threshold before dream runs or the 24-hour default interval. Recommendation: Add a "How it works" section with these implementation details.

  2. File: packages/core/src/memory/const.ts - No constants file visible in the diff. Recommendation: Centralize magic numbers (MIN_CANDIDATE_LENGTH=12, MAX_INDEX_LINES=200, etc.) in a constants file with explanatory comments.

Naming & Style:

  1. File: packages/core/src/memory/dream.ts - The function runManagedAutoMemoryDream uses "dream" as a metaphor, which is creative but may be unclear to new contributors. Recommendation: Add a JSDoc comment explaining the terminology (dream = consolidation pass).

  2. File: packages/cli/src/i18n/locales/*.js - The translation keys are inline strings. Recommendation: Consider using a keys file or enum for i18n keys to catch typos at compile time.

Developer Experience:

  1. File: packages/core/src/memory/state.ts - The resetAutoMemoryStateForTests() function suggests module-level mutable state. Recommendation: Consider dependency injection for the state to make testing more explicit and avoid test pollution.

✅ Highlights

  • Excellent architecture: The separation between extract, dream, scheduler, registry, and drainer components is clean and follows single-responsibility principles
  • Comprehensive testing: The inclusion of memoryLifecycle.integration.test.ts demonstrates end-to-end thinking
  • Thoughtful throttling: The session-count throttling (SESSION_SCAN_INTERVAL_MS) and lock staleness handling show production-grade thinking
  • Good i18n coverage: All new UI strings are translated across all 6 locales from the start
  • User-editable format: Storing memories as Markdown files with frontmatter is a pragmatic choice that empowers users
  • Background task framework: The generic BackgroundAgentRunner and task registry will enable future background agents beyond memory

Summary

This is an ambitious and well-architected PR that brings Qwen Code to parity with Claude Code's auto-memory capabilities. The core design is sound, but the critical security issues around YOLO mode enforcement and potential data loss in dream deduplication must be addressed before merge. The high-priority reliability improvements (atomic writes, lock recovery) should be implemented to prevent user data loss in edge cases.

Recommended actions:

  1. Address all Critical items before merge
  2. Implement High-priority items in the same PR or as immediate follow-up
  3. Consider Medium/Low items for a follow-up PR to keep this PR focused

Comment on lines +67 to +69
const indentedMatch = rawLine.match(
/^\s{2,}(?:[-*]\s+)?(Why|How to apply|How_to_apply):\s*(.+)$/i,
);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 601d1a8. Changed \s{2,}(?:[-*]\s+)? to [\t ]{2,}(?:[-*][\t ]+)? — using explicit character classes instead of \s eliminates the overlapping quantifier that caused the polynomial backtracking on tab-heavy strings.

Comment on lines +89 to +91
const topLevelMatch = trimmed.match(
/^(?:\*\*)?(Why|How to apply|How_to_apply)(?:\*\*)?:\s*(.+)$/i,
);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 601d1a8. Changed :\s*(.+)$ to :[ \t]*(\S.*)$ — requiring the value to start with a non-whitespace character removes the ambiguity between \s* and .+ that allowed exponential backtracking on strings like why:\t\t\t....

LaZzyMan added a commit that referenced this pull request Apr 10, 2026
- fix(read-file): narrow auto-allow from getMemoryBaseDir() (~/.qwen) to
  isAutoMemPath(projectRoot) to prevent exposing settings.json / OAuth
  credentials without user approval (wenshao review)

- fix(forget): per-entry deletion instead of whole-file unlink
  - assign stable per-entry IDs (relativePath:index for multi-entry files)
    so the model can target individual entries without removing siblings
  - rewrite file keeping unmatched entries; only unlink when file becomes
    empty (wenshao review)

- fix(entries): round-trip correctness for multi-entry new-format bodies
  - parseAutoMemoryEntries: plain-text line closes current entry and opens
    a new one (was silently ignored when current was already set)
  - renderAutoMemoryBody: emit blank line between adjacent entries so the
    parser can detect entry boundaries on re-read (wenshao review)

- fix(entries): resolve two CodeQL polynomial-regex alerts
  - indentedMatch: \s{2,}(?:[-*]\s+)? → [\t ]{2,}(?:[-*][\t ]+)?
  - topLevelMatch: :\s*(.+)$ → :[ \t]*(\S.*)$
  (github-advanced-security review)

- fix(scan.test): use forward-slash literal for relativePath expectation
  since listMarkdownFiles() normalises all separators to '/' on all
  platforms including Windows
@LaZzyMan
Copy link
Copy Markdown
Collaborator Author

All critical findings from @wenshao and @github-advanced-security have been addressed in commit 601d1a8:

# File Issue Fix
1 read-file.ts Auto-allow whitelisted entire ~/.qwen tree Replaced getMemoryBaseDir() with isAutoMemPath(filePath, projectRoot) — scoped to per-project memory root only
2 forget.ts unlink() on whole file destroys unrelated entries Grouped matches by file; rewrite keeping unmatched entries; only unlink when file becomes empty. Per-entry IDs (relativePath:index) prevent sibling removal
3 entries.ts parse→render round-trip loses entries in multi-entry files parseAutoMemoryEntries now closes current entry on each plain-text line; renderAutoMemoryBody emits blank separator between entries
4 entries.ts (CodeQL #1) Polynomial regex \s{2,}(?:[-*]\s+)? Changed to [\t ]{2,}(?:[-*][\t ]+)?
5 entries.ts (CodeQL #2) Polynomial regex :\s*(.+)$ Changed to :[ \t]*(\S.*)$

Ready for re-review.

LaZzyMan added a commit that referenced this pull request Apr 10, 2026
Using path.relative() instead of string startsWith() is more robust
across platforms — it correctly handles Windows path-separator
differences and avoids potential edge cases where a path prefix match
could succeed on non-separator boundaries.

Addresses github-actions review item 3 (PR #3087).
@LaZzyMan
Copy link
Copy Markdown
Collaborator Author

Fixed in 5cd4908. Replaced startsWith(memRoot + path.sep) with path.relative():

const rel = path.relative(memRoot, normalizedPath);
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));

This handles Windows path-separator differences and removes the edge case where a prefix match could succeed on non-separator boundaries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants