Skip to content

feat(memory): persist auto-memory scratchpad for skill extraction#25873

Open
SandyTao520 wants to merge 13 commits intomainfrom
st/feat/auto-memory
Open

feat(memory): persist auto-memory scratchpad for skill extraction#25873
SandyTao520 wants to merge 13 commits intomainfrom
st/feat/auto-memory

Conversation

@SandyTao520
Copy link
Copy Markdown
Contributor

@SandyTao520 SandyTao520 commented Apr 23, 2026

Summary

Persist an auto-memory memoryScratchpad into session metadata so skill extraction can use compact workflow hints without relying only on one-line session summaries.

In the 5-trial scratchpad stats eval, the scratchpad path reduced average extractor turns from 13.2 to 11.0 (-16.7%), reduced distractor reads from 3.8 to 2.4 (-36.8%), improved precision from 0.3467 to 0.46 (+32.7%), kept recall at 1.0, and reduced duration from 42812.6ms to 40956.2ms (-4.3%).

Details

  • Persist memoryScratchpad through chat recording, session summary refreshes, and memory service session loading.
  • Backfill scratchpads for sessions that already have summaries without regenerating the summaries.
  • Expose scratchpad-derived workflow hints in the session index used by skill extraction.
  • Keep the recurrence gate strict: workflow hints only route transcript reads and are not standalone evidence for creating a skill.
  • Reuse the shared loadConversationRecord() session parser instead of maintaining a second JSONL parser in summary utilities.
  • Record extraction run metadata (turnCount, durationMs, and terminateReason) so scratchpad impact can be measured.
  • Add eval coverage for scratchpad persistence, scratchpad-vs-summary-only skill extraction behavior, and retrieval quality stats.
  • Sync the prompt-contract unit test with the new workflow-hint wording so preflight stays green.
  • Set GEMINI_CLI_TRUST_WORKSPACE=true for chained and nightly eval workflows so headless eval runs stay aligned with the workspace trust enforcement added in feat(cli): secure .env loading and enforce workspace trust in headless mode #25814.

Related Issues

Closes #25895.

How to Validate

  1. Run npm run preflight.
    Expected result: all workspace checks pass.
  2. Run npm exec -- vitest run packages/core/src/services/sessionSummaryUtils.test.ts packages/core/src/services/memoryService.test.ts packages/core/src/agents/skill-extraction-agent.test.ts.
    Expected result: focused service and prompt-contract tests pass.
  3. Run npm exec -- tsc -p packages/core/tsconfig.json --noEmit.
    Expected result: core typecheck passes.
  4. Run RUN_EVALS=1 npm exec -- vitest run --config evals/vitest.config.ts -t "Session summary persists memory scratchpad for memory-saving sessions".
    Expected result: the eval passes and verifies memoryScratchpad is written into the resumed session log.
  5. Run RUN_EVALS=1 npm exec -- vitest run --config evals/vitest.config.ts -t "memory scratchpad improves repeated-workflow recall versus summary-only index".
    Expected result: the eval passes and scratchpad-enabled retrieval matches or beats the summary-only baseline for the repeated workflow fixture.
  6. Run RUN_EVALS=1 RUN_SCRATCHPAD_STATS=1 SCRATCHPAD_STATS_TRIALS=5 npm exec -- vitest run --config evals/vitest.config.ts -t "reports memory scratchpad retrieval statistics".
    Expected result: the eval passes and writes evals/logs/skill_extraction_scratchpad_stats.json.
  7. Run GEMINI_MODEL=gemini-3-pro-preview GEMINI_CLI_TRUST_WORKSPACE=true npm exec -- vitest run --config evals/vitest.config.ts evals/save_memory.eval.ts -t "Agent remembers user's favorite color".
    Expected result: the trusted eval subprocess can call save_memory successfully.

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

@SandyTao520 SandyTao520 requested review from a team as code owners April 23, 2026 17:14
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the memory system by introducing a persistent 'memory scratchpad' that captures compact workflow hints during sessions. By storing this metadata, the skill extraction process can more effectively identify and route repeated workflows, improving the quality and reliability of extracted skills. The changes include updates to session recording, metadata persistence, and the extraction agent's prompt, supported by new evaluation tools to measure retrieval performance.

Highlights

  • Memory Scratchpad Persistence: Introduced a memoryScratchpad to session metadata, allowing for persistent, compact workflow hints that aid in skill extraction without relying solely on session summaries.
  • Enhanced Skill Extraction: Updated the skill extraction agent to utilize scratchpad-derived workflow hints for better session routing and improved recall of repeated workflows.
  • Evaluation Coverage: Added comprehensive evaluation coverage, including tests for scratchpad persistence, retrieval quality, and statistical reporting on scratchpad effectiveness.
  • Infrastructure Improvements: Updated session loading and recording services to support the new scratchpad metadata and improved session index generation.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-cli gemini-cli Bot added the status/need-issue Pull requests that need to have an associated issue. label Apr 23, 2026
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces "Memory Scratchpads," which extract lightweight workflow metadata—including tool sequences, touched paths, and validation status—from conversation sessions to improve skill extraction recall. The MemoryService and SkillExtractionAgent are updated to leverage these hints for session prioritization and routing. The PR also adds turn count and duration tracking to agent execution, supports JSONL metadata updates, and includes new evaluation tests for retrieval performance. Feedback identifies a maintainability risk due to duplicated JSONL parsing logic in sessionSummaryUtils.ts and suggests refactoring to use the shared loadConversationRecord function.

Note: Security Review did not run due to the size of the PR.

Comment thread packages/core/src/services/sessionSummaryUtils.ts Outdated
# Conflicts:
#	packages/core/src/services/memoryService.test.ts
#	packages/core/src/services/memoryService.ts
#	packages/core/src/services/sessionSummaryUtils.test.ts
#	packages/core/src/services/sessionSummaryUtils.ts
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 23, 2026

Size Change: +12.9 kB (+0.04%)

Total Size: 33.8 MB

Filename Size Change
./bundle/chunk-4ZQ4EUK4.js 0 B -49.2 kB (removed) 🏆
./bundle/chunk-GQUOWGLR.js 0 B -2.73 MB (removed) 🏆
./bundle/chunk-LVK34RCK.js 0 B -3.43 kB (removed) 🏆
./bundle/chunk-PCGEPF5G.js 0 B -14.6 MB (removed) 🏆
./bundle/chunk-RYC3PJIU.js 0 B -669 kB (removed) 🏆
./bundle/chunk-XL2CTS7A.js 0 B -3.8 kB (removed) 🏆
./bundle/core-J3IVDB7M.js 0 B -47.7 kB (removed) 🏆
./bundle/devtoolsService-K24XUB6D.js 0 B -27.8 kB (removed) 🏆
./bundle/gemini-4AOS6GRZ.js 0 B -578 kB (removed) 🏆
./bundle/interactiveCli-2N6WJNNX.js 0 B -1.29 MB (removed) 🏆
./bundle/liteRtServerManager-EVAXIUER.js 0 B -2.08 kB (removed) 🏆
./bundle/oauth2-provider-HPH3EAFX.js 0 B -9.16 kB (removed) 🏆
./bundle/chunk-2TSAQ5WJ.js 3.43 kB +3.43 kB (new file) 🆕
./bundle/chunk-AME4OHJB.js 49.2 kB +49.2 kB (new file) 🆕
./bundle/chunk-G5HP5K46.js 3.8 kB +3.8 kB (new file) 🆕
./bundle/chunk-M26HTKAU.js 2.73 MB +2.73 MB (new file) 🆕
./bundle/chunk-SB6SXDC3.js 14.6 MB +14.6 MB (new file) 🆕
./bundle/chunk-Z6T4S5BD.js 669 kB +669 kB (new file) 🆕
./bundle/core-52FHWQPI.js 47.7 kB +47.7 kB (new file) 🆕
./bundle/devtoolsService-QSHHIWXJ.js 27.8 kB +27.8 kB (new file) 🆕
./bundle/gemini-YAYGYQLM.js 578 kB +578 kB (new file) 🆕
./bundle/interactiveCli-WWAR5OEZ.js 1.29 MB +1.29 MB (new file) 🆕
./bundle/liteRtServerManager-7U3DXMO4.js 2.08 kB +2.08 kB (new file) 🆕
./bundle/oauth2-provider-H2J57YWB.js 9.16 kB +9.16 kB (new file) 🆕
ℹ️ View Unchanged
Filename Size Change
./bundle/bundled/third_party/index.js 8 MB 0 B
./bundle/chunk-34MYV7JD.js 2.45 kB 0 B
./bundle/chunk-5AUYMPVF.js 858 B 0 B
./bundle/chunk-5PS3AYFU.js 1.18 kB 0 B
./bundle/chunk-664ZODQF.js 124 kB 0 B
./bundle/chunk-DAHVX5MI.js 206 kB 0 B
./bundle/chunk-IUUIT4SU.js 56.5 kB 0 B
./bundle/chunk-MTD736U4.js 1.97 MB 0 B
./bundle/chunk-RJTRUG2J.js 39.8 kB 0 B
./bundle/cleanup-M66PXJG4.js 0 B -932 B (removed) 🏆
./bundle/devtools-36NN55EP.js 696 kB 0 B
./bundle/dist-T73EYRDX.js 356 B 0 B
./bundle/events-XB7DADIJ.js 418 B 0 B
./bundle/examples/hooks/scripts/on-start.js 188 B 0 B
./bundle/examples/mcp-server/example.js 1.43 kB 0 B
./bundle/gemini.js 4.97 kB 0 B
./bundle/getMachineId-bsd-TXG52NKR.js 1.55 kB 0 B
./bundle/getMachineId-darwin-7OE4DDZ6.js 1.55 kB 0 B
./bundle/getMachineId-linux-SHIFKOOX.js 1.34 kB 0 B
./bundle/getMachineId-unsupported-5U5DOEYY.js 1.06 kB 0 B
./bundle/getMachineId-win-6KLLGOI4.js 1.72 kB 0 B
./bundle/memoryDiscovery-NSOLCG4U.js 980 B 0 B
./bundle/multipart-parser-KPBZEGQU.js 11.7 kB 0 B
./bundle/node_modules/@google/gemini-cli-devtools/dist/client/main.js 222 kB 0 B
./bundle/node_modules/@google/gemini-cli-devtools/dist/src/_client-assets.js 229 kB 0 B
./bundle/node_modules/@google/gemini-cli-devtools/dist/src/index.js 13.4 kB 0 B
./bundle/node_modules/@google/gemini-cli-devtools/dist/src/types.js 132 B 0 B
./bundle/sandbox-macos-permissive-open.sb 890 B 0 B
./bundle/sandbox-macos-permissive-proxied.sb 1.31 kB 0 B
./bundle/sandbox-macos-restrictive-open.sb 3.36 kB 0 B
./bundle/sandbox-macos-restrictive-proxied.sb 3.56 kB 0 B
./bundle/sandbox-macos-strict-open.sb 4.82 kB 0 B
./bundle/sandbox-macos-strict-proxied.sb 5.02 kB 0 B
./bundle/src-QVCVGIUX.js 47 kB 0 B
./bundle/start-DCBHYVCN.js 0 B -622 B (removed) 🏆
./bundle/tree-sitter-7U6MW5PS.js 274 kB 0 B
./bundle/tree-sitter-bash-34ZGLXVX.js 1.84 MB 0 B
./bundle/cleanup-QSXQUF5Z.js 932 B +932 B (new file) 🆕
./bundle/start-MPSBUT6Z.js 622 B +622 B (new file) 🆕

compressed-size-action

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 23, 2026

55 tests passed successfully on gemini-3-flash-preview.


This is an automated guidance message triggered by steering logic signatures.

Comment thread packages/core/src/services/sessionScratchpadUtils.ts Fixed
typeof args.file_path !== 'string'
) {
return null;
if (activity.type === 'TOOL_CALL_END') {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

we dropped the check for tool name here no?

activity.data['name'] !== READ_FILE_TOOL_NAME should be added here and for the ERROR event too.

const baselineScenario = createWorkflowComparisonSessions(false);
const enhancedScenario = createWorkflowComparisonSessions(true);

const baselineOutcome = await runExtractionAndReadState(config);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

are these two arms running over identical rig environments?

enhanced seems to run on a fresh rig, shouldn't baseline do the same?

summary: session.summary,
memoryScratchpad: session.memoryScratchpad,
startTime: new Date(Date.now() - 7 * 60 * 60 * 1000).toISOString(),
lastUpdated: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString(),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

shouldn't lastUpdated include timestampOffsetMinutes? Currently, every sessions gets updated with current time - 4 hours, with no offset taken into account.

} else {
const baseLlmClient = new BaseLlmClient(contentGenerator, config);
const summaryService = new SessionSummaryService(baseLlmClient);
summary =
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

if the session summary call here fails, and summary is assigned undefined, we still write to the scraptchpad. So, hasSessionSummaryMetadata will keep returning false.

When getPreviousSession is called, we keep returning to the same session and generateAndSaveSummary retries every time (potentially issuing a wasted LLM call each time). We end up doing infinite retries.

const VALIDATION_COMMAND_REGEX =
/\b(test|tests|vitest|jest|pytest|cargo test|npm test|pnpm test|yarn test|bun test|lint|build|check|typecheck)\b/i;
const PATH_KEY_REGEX = /(path|file|dir|directory|cwd|root)/i;
const VALIDATION_TOOL_REGEX = /(test|lint|build|check)/i;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

regex is too broad, will capture suggest something like /(\\b(test|lint|build|check)\\b)/i

return normalized.length > 0 ? normalized : null;
}

function collectPathsFromValue(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

recursion depth here seems unbounded? Perhaps try capping it via a depth param?

return value === null ? null : Number(value.toFixed(4));
}

function average(values: number[]): number {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should this + other low-level functions in this file exist in a utils file (or are there any pre-existing ones we can use?)

const enhancedSignalScore =
enhancedRelevantReads - enhancedDistractorReads;

expect(enhancedRun.candidateSessions).toHaveLength(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks like the eval passes even if enhanced equals baseline exactly. It doesn't validate that scratchpads actually improve anything; a no-op feature would pass.

return undefined;
}

const summary = sanitizeWorkflowSummaryForScratchpad(parts.join(' | '));
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: we are running sanitization twice unnecessarily (here and in memoryService)

if (
session.summary &&
workflowSummary &&
workflowSummary.trim().length > 0 &&
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: this check looks to be redundant given sanitizedWorkflowSummary?.trim() in memoryService

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

Labels

🔒 maintainer only ⛔ Do not contribute. Internal roadmap item.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve auto-memory skill extraction with session scratchpads

3 participants