mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-07-24 00:30:59 -07:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad5e01ceaf | |||
| 957195be4c | |||
| ca91aab74e | |||
| 651ad55357 | |||
| fc8c1bee0c | |||
| ac81288e1e | |||
| 6cfef6d15d | |||
| ccd1854c66 | |||
| 3fdc43734b |
@@ -3,6 +3,7 @@
|
||||
"extensionReloading": true,
|
||||
"modelSteering": true,
|
||||
"autoMemory": true,
|
||||
"memoryManager": true,
|
||||
"topicUpdateNarration": true,
|
||||
"voiceMode": true,
|
||||
"adk": {
|
||||
|
||||
@@ -5,176 +5,178 @@
|
||||
*/
|
||||
|
||||
module.exports = async ({ github, context, core }) => {
|
||||
const rawLabels = process.env.LABELS_OUTPUT;
|
||||
core.info(`Raw labels JSON: ${rawLabels}`);
|
||||
let parsedLabels;
|
||||
try {
|
||||
// First, try to parse the raw output as JSON.
|
||||
parsedLabels = JSON.parse(rawLabels);
|
||||
} catch (jsonError) {
|
||||
// If that fails, check for a markdown code block.
|
||||
core.warning(
|
||||
`Direct JSON parsing failed: ${jsonError.message}. Trying to extract from a markdown block.`,
|
||||
);
|
||||
const jsonMatch = rawLabels.match(/```json\s*([\s\S]*?)\s*```/);
|
||||
if (jsonMatch && jsonMatch[1]) {
|
||||
try {
|
||||
parsedLabels = JSON.parse(jsonMatch[1].trim());
|
||||
} catch (markdownError) {
|
||||
core.setFailed(
|
||||
`Failed to parse JSON even after extracting from markdown block: ${markdownError.message}\nRaw output: ${rawLabels}`,
|
||||
);
|
||||
return;
|
||||
const extractJson = (raw) => {
|
||||
if (!raw || raw === '[]' || raw === '') return [];
|
||||
try {
|
||||
// First, try to parse the raw output as JSON.
|
||||
return JSON.parse(raw);
|
||||
} catch (jsonError) {
|
||||
// If that fails, check for a markdown code block.
|
||||
core.info('Direct JSON parsing failed. Trying to extract from a markdown block.');
|
||||
const jsonMatch = raw.match(/```json\s*([\s\S]*?)\s*```/);
|
||||
if (jsonMatch && jsonMatch[1]) {
|
||||
try {
|
||||
return JSON.parse(jsonMatch[1].trim());
|
||||
} catch (markdownError) {
|
||||
core.warning(`Failed to parse extracted JSON from markdown block: ${markdownError.message}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If no markdown block, try to find a raw JSON array in the output.
|
||||
// The CLI may include debug/log lines (e.g. telemetry init, YOLO mode)
|
||||
// before the actual JSON response.
|
||||
const jsonArrayMatch = rawLabels.match(
|
||||
/\[\s*\{\s*"issue_number"[\s\S]*\}\s*\]/,
|
||||
);
|
||||
|
||||
// Try to find a raw JSON array in the output.
|
||||
const jsonArrayMatch = raw.match(/\[\s*\{\s*"issue_number"[\s\S]*\}\s*\]/);
|
||||
if (jsonArrayMatch) {
|
||||
try {
|
||||
parsedLabels = JSON.parse(jsonArrayMatch[0]);
|
||||
return JSON.parse(jsonArrayMatch[0]);
|
||||
} catch (extractError) {
|
||||
// It's possible the regex matched from a `[STARTUP]` log all the way to the end
|
||||
// of the JSON array. We need to be more aggressive and find the FIRST `[ { "issue_number"`
|
||||
core.warning(
|
||||
`Strict array match failed: ${extractError.message}. Attempting to clean leading noisy brackets.`,
|
||||
);
|
||||
const fallbackMatch = rawLabels.match(
|
||||
/(\[\s*\{\s*"issue_number"[\s\S]*)/,
|
||||
);
|
||||
const fallbackMatch = raw.match(/(\[\s*\{\s*"issue_number"[\s\S]*)/);
|
||||
if (fallbackMatch) {
|
||||
try {
|
||||
// We might have grabbed trailing noise too, so we find the last closing bracket
|
||||
const cleaned = fallbackMatch[0].substring(
|
||||
0,
|
||||
fallbackMatch[0].lastIndexOf(']') + 1,
|
||||
);
|
||||
parsedLabels = JSON.parse(cleaned);
|
||||
const cleaned = fallbackMatch[0].substring(0, fallbackMatch[0].lastIndexOf(']') + 1);
|
||||
return JSON.parse(cleaned);
|
||||
} catch (fallbackError) {
|
||||
core.setFailed(
|
||||
`Found JSON-like content but failed to parse: ${fallbackError.message}\nRaw output: ${rawLabels}`,
|
||||
);
|
||||
return;
|
||||
core.warning(`Failed to parse extracted JSON using fallback regex: ${fallbackError.message}`);
|
||||
}
|
||||
} else {
|
||||
core.setFailed(
|
||||
`Found JSON-like content but failed to parse: ${extractError.message}\nRaw output: ${rawLabels}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
core.setFailed(
|
||||
`Output is not valid JSON and does not contain extractable JSON.\nRaw output: ${rawLabels}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
core.info(`Parsed labels JSON: ${JSON.stringify(parsedLabels)}`);
|
||||
core.warning('No valid JSON could be extracted from input.');
|
||||
return [];
|
||||
};
|
||||
|
||||
for (const entry of parsedLabels) {
|
||||
const issueNumber = entry.issue_number;
|
||||
if (!issueNumber) {
|
||||
core.info(
|
||||
`Skipping entry with no issue number: ${JSON.stringify(entry)}`,
|
||||
);
|
||||
continue;
|
||||
// Collect all outputs from environment variables
|
||||
// Prioritize EFFORT results over STANDARD results by processing Effort FIRST
|
||||
// so that its labels appear first in the merged arrays (and thus win in mutually exclusive logic)
|
||||
const effortRaw = process.env.LABELS_OUTPUT_EFFORT;
|
||||
const standardRaw = process.env.LABELS_OUTPUT_STANDARD;
|
||||
const genericRaw = process.env.LABELS_OUTPUT;
|
||||
|
||||
const resultsByIssue = new Map();
|
||||
|
||||
const processResults = (results, sourceName) => {
|
||||
for (const entry of results) {
|
||||
const issueNumber = entry.issue_number;
|
||||
if (!issueNumber) continue;
|
||||
|
||||
if (!resultsByIssue.has(issueNumber)) {
|
||||
resultsByIssue.set(issueNumber, {
|
||||
issue_number: issueNumber,
|
||||
labels_to_add: [...(entry.labels_to_add || [])],
|
||||
labels_to_remove: [...(entry.labels_to_remove || [])],
|
||||
explanation: entry.explanation || '',
|
||||
effort_analysis: entry.effort_analysis || '',
|
||||
});
|
||||
} else {
|
||||
const existing = resultsByIssue.get(issueNumber);
|
||||
// Combine labels
|
||||
existing.labels_to_add = [...new Set([...existing.labels_to_add, ...(entry.labels_to_add || [])])];
|
||||
existing.labels_to_remove = [...new Set([...existing.labels_to_remove, ...(entry.labels_to_remove || [])])];
|
||||
|
||||
// Combine explanations (if different)
|
||||
if (entry.explanation && !existing.explanation.includes(entry.explanation)) {
|
||||
existing.explanation = existing.explanation
|
||||
? `${existing.explanation}\n\n${entry.explanation}`
|
||||
: entry.explanation;
|
||||
}
|
||||
|
||||
// Take effort analysis if present
|
||||
if (entry.effort_analysis && !existing.effort_analysis) {
|
||||
existing.effort_analysis = entry.effort_analysis;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Order matters: Effort first so its labels win in conflict resolution
|
||||
processResults(extractJson(effortRaw), 'EFFORT');
|
||||
processResults(extractJson(standardRaw), 'STANDARD');
|
||||
processResults(extractJson(genericRaw), 'GENERIC');
|
||||
|
||||
const finalResults = Array.from(resultsByIssue.values());
|
||||
core.info(`Aggregated triage results for ${finalResults.length} issues.`);
|
||||
|
||||
for (const entry of finalResults) {
|
||||
const issueNumber = entry.issue_number;
|
||||
let labelsToAdd = entry.labels_to_add || [];
|
||||
let labelsToRemove = entry.labels_to_remove || [];
|
||||
let existingLabels = [];
|
||||
|
||||
labelsToRemove.push('status/need-triage');
|
||||
|
||||
if (labelsToAdd.includes('status/manual-triage')) {
|
||||
// If the AI flagged it for manual triage, remove bot-triaged if it exists
|
||||
labelsToRemove.push('status/bot-triaged');
|
||||
// Ensure we don't accidentally try to add bot-triaged if the AI returned it
|
||||
labelsToAdd = labelsToAdd.filter((l) => l !== 'status/bot-triaged');
|
||||
} else {
|
||||
// Standard successful bot triage
|
||||
labelsToAdd.push('status/bot-triaged');
|
||||
}
|
||||
|
||||
// Deduplicate arrays
|
||||
labelsToAdd = [...new Set(labelsToAdd)];
|
||||
labelsToRemove = [...new Set(labelsToRemove)];
|
||||
|
||||
// Fetch existing labels to auto-resolve conflicts
|
||||
// Fetch existing labels early
|
||||
try {
|
||||
const { data: issueData } = await github.rest.issues.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
});
|
||||
const existingLabels = issueData.labels.map((l) =>
|
||||
existingLabels = issueData.labels.map((l) =>
|
||||
typeof l === 'string' ? l : l.name,
|
||||
);
|
||||
|
||||
const hasNewArea = labelsToAdd.some((l) => l.startsWith('area/'));
|
||||
if (hasNewArea) {
|
||||
const existingAreas = existingLabels.filter((l) =>
|
||||
l.startsWith('area/'),
|
||||
);
|
||||
labelsToRemove.push(...existingAreas);
|
||||
}
|
||||
|
||||
const hasNewPriority = labelsToAdd.some((l) => l.startsWith('priority/'));
|
||||
if (hasNewPriority) {
|
||||
const existingPriorities = existingLabels.filter((l) =>
|
||||
l.startsWith('priority/'),
|
||||
);
|
||||
labelsToRemove.push(...existingPriorities);
|
||||
}
|
||||
|
||||
const hasNewKind = labelsToAdd.some((l) => l.startsWith('kind/'));
|
||||
if (hasNewKind) {
|
||||
const existingKinds = existingLabels.filter((l) =>
|
||||
l.startsWith('kind/'),
|
||||
);
|
||||
labelsToRemove.push(...existingKinds);
|
||||
}
|
||||
|
||||
// Re-deduplicate and filter out labels we are trying to add
|
||||
labelsToRemove = [...new Set(labelsToRemove)].filter(
|
||||
(l) => !labelsToAdd.includes(l),
|
||||
);
|
||||
} catch (e) {
|
||||
core.warning(
|
||||
`Failed to fetch existing labels for #${issueNumber}: ${e.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Enforce mutually exclusive area labels
|
||||
const areaLabelsToAdd = labelsToAdd.filter((l) => l.startsWith('area/'));
|
||||
if (areaLabelsToAdd.length > 1) {
|
||||
core.warning(
|
||||
`Issue #${issueNumber} has multiple area labels to add: ${areaLabelsToAdd.join(', ')}. Keeping only the first one.`,
|
||||
);
|
||||
const firstArea = areaLabelsToAdd[0];
|
||||
labelsToAdd = labelsToAdd.filter(
|
||||
(l) => !l.startsWith('area/') || l === firstArea,
|
||||
);
|
||||
// Programmatic Priority Downgrade Logic
|
||||
if (labelsToAdd.includes('status/need-information')) {
|
||||
const targetPriority = labelsToAdd.find((l) => l.startsWith('priority/'));
|
||||
if (targetPriority) {
|
||||
let downgradedPriority = null;
|
||||
if (targetPriority === 'priority/p0') downgradedPriority = 'priority/p1';
|
||||
if (targetPriority === 'priority/p1') downgradedPriority = 'priority/p2';
|
||||
|
||||
if (downgradedPriority) {
|
||||
core.info(`Programmatically downgrading ${targetPriority} to ${downgradedPriority} due to status/need-information`);
|
||||
labelsToAdd = labelsToAdd.filter((l) => l !== targetPriority);
|
||||
labelsToAdd.push(downgradedPriority);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce mutually exclusive priority labels
|
||||
const priorityLabelsToAdd = labelsToAdd.filter((l) =>
|
||||
l.startsWith('priority/'),
|
||||
labelsToRemove.push('status/need-triage');
|
||||
|
||||
if (
|
||||
labelsToAdd.includes('status/manual-triage') ||
|
||||
existingLabels.includes('status/manual-triage')
|
||||
) {
|
||||
labelsToRemove.push('status/bot-triaged');
|
||||
labelsToAdd = labelsToAdd.filter((l) => l !== 'status/bot-triaged');
|
||||
} else {
|
||||
labelsToAdd.push('status/bot-triaged');
|
||||
}
|
||||
|
||||
// Resolve internal conflicts (e.g., adding P1 and P2)
|
||||
// We already resolved these by putting Effort first in the combined list
|
||||
|
||||
// Resolve external conflicts with existing labels
|
||||
if (labelsToAdd.some((l) => l.startsWith('area/'))) {
|
||||
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('area/')));
|
||||
}
|
||||
if (labelsToAdd.some((l) => l.startsWith('priority/'))) {
|
||||
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('priority/')));
|
||||
}
|
||||
if (labelsToAdd.some((l) => l.startsWith('kind/'))) {
|
||||
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('kind/')));
|
||||
}
|
||||
|
||||
// Enforce mutual exclusivity in the TO-ADD list (Architect wins)
|
||||
const exclusivePrefixes = ['area/', 'priority/', 'kind/'];
|
||||
for (const prefix of exclusivePrefixes) {
|
||||
const filtered = labelsToAdd.filter(l => l.startsWith(prefix));
|
||||
if (filtered.length > 1) {
|
||||
const winner = filtered[0]; // First one wins
|
||||
core.info(`Issue #${issueNumber} has multiple ${prefix} labels suggested. Keeping "${winner}" and discarding others.`);
|
||||
labelsToAdd = labelsToAdd.filter(l => !l.startsWith(prefix) || l === winner);
|
||||
}
|
||||
}
|
||||
|
||||
// Final deduplication and cleanup
|
||||
labelsToRemove = [...new Set(labelsToRemove)].filter(
|
||||
(l) => !labelsToAdd.includes(l) && existingLabels.includes(l),
|
||||
);
|
||||
if (priorityLabelsToAdd.length > 1) {
|
||||
core.warning(
|
||||
`Issue #${issueNumber} has multiple priority labels to add: ${priorityLabelsToAdd.join(', ')}. Keeping only the first one.`,
|
||||
);
|
||||
const firstPriority = priorityLabelsToAdd[0];
|
||||
labelsToAdd = labelsToAdd.filter(
|
||||
(l) => !l.startsWith('priority/') || l === firstPriority,
|
||||
);
|
||||
}
|
||||
labelsToAdd = [...new Set(labelsToAdd)].filter((l) => !existingLabels.includes(l));
|
||||
|
||||
// Batch label operations
|
||||
if (labelsToAdd.length > 0) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
@@ -182,11 +184,7 @@ module.exports = async ({ github, context, core }) => {
|
||||
issue_number: issueNumber,
|
||||
labels: labelsToAdd,
|
||||
});
|
||||
|
||||
const explanation = entry.explanation ? ` - ${entry.explanation}` : '';
|
||||
core.info(
|
||||
`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}${explanation}`,
|
||||
);
|
||||
core.info(`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}`);
|
||||
}
|
||||
|
||||
if (labelsToRemove.length > 0) {
|
||||
@@ -199,46 +197,33 @@ module.exports = async ({ github, context, core }) => {
|
||||
name: label,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e.status !== 404) {
|
||||
core.warning(
|
||||
`Failed to remove label ${label} from #${issueNumber}: ${e.message}`,
|
||||
);
|
||||
}
|
||||
if (e.status !== 404) core.warning(`Failed to remove label ${label} from #${issueNumber}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
core.info(
|
||||
`Successfully removed labels for #${issueNumber}: ${labelsToRemove.join(', ')}`,
|
||||
);
|
||||
core.info(`Successfully removed labels for #${issueNumber}: ${labelsToRemove.join(', ')}`);
|
||||
}
|
||||
|
||||
if (
|
||||
(entry.explanation && process.env.SUPPRESS_COMMENT !== 'true') ||
|
||||
entry.effort_analysis
|
||||
) {
|
||||
// Post comment if needed
|
||||
const needsInfoAdded = labelsToAdd.includes('status/need-information') && !existingLabels.includes('status/need-information');
|
||||
const hasEffortAnalysis = !!entry.effort_analysis;
|
||||
|
||||
if (needsInfoAdded || hasEffortAnalysis) {
|
||||
let commentBody = '';
|
||||
if (entry.explanation && process.env.SUPPRESS_COMMENT !== 'true') {
|
||||
commentBody += entry.explanation;
|
||||
}
|
||||
if (entry.effort_analysis) {
|
||||
if (needsInfoAdded && entry.explanation) commentBody += entry.explanation;
|
||||
if (hasEffortAnalysis) {
|
||||
if (commentBody) commentBody += '\n\n';
|
||||
commentBody += `**Effort Analysis:**\n${entry.effort_analysis}`;
|
||||
}
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
body: commentBody,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
(!entry.labels_to_add || entry.labels_to_add.length === 0) &&
|
||||
(!entry.labels_to_remove || entry.labels_to_remove.length === 0)
|
||||
) {
|
||||
core.info(
|
||||
`No labels to add or remove for #${issueNumber}, leaving as is`,
|
||||
);
|
||||
if (commentBody) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
body: commentBody,
|
||||
});
|
||||
core.info(`Posted required comment for #${issueNumber}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -22,29 +22,53 @@ module.exports = async ({ github, context, core }) => {
|
||||
|
||||
for (const issue of issuesToCleanup) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
const { data: issueData } = await github.rest.issues.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
name: 'status/need-triage',
|
||||
});
|
||||
core.info(
|
||||
`Successfully removed status/need-triage from #${issue.number}`,
|
||||
|
||||
const labels = issueData.labels.map((l) =>
|
||||
typeof l === 'string' ? l : l.name,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
|
||||
if (
|
||||
labels.includes('status/bot-triaged') &&
|
||||
labels.includes('status/need-triage')
|
||||
) {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
name: 'status/need-triage',
|
||||
});
|
||||
core.info(
|
||||
`Label status/need-triage not found on #${issue.number}, skipping.`,
|
||||
);
|
||||
} else {
|
||||
core.warning(
|
||||
`Failed to remove label from #${issue.number}: ${error.message}`,
|
||||
`Successfully removed status/need-triage from #${issue.number}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
labels.includes('status/bot-triaged') &&
|
||||
labels.includes('status/manual-triage')
|
||||
) {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
name: 'status/bot-triaged',
|
||||
});
|
||||
core.info(
|
||||
`Successfully removed status/bot-triaged from #${issue.number} because it requires manual triage`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
core.warning(
|
||||
`Failed to clean up labels for #${issue.number}: ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
core.info(
|
||||
`Cleaned up status/need-triage from ${issuesToCleanup.length} issues.`,
|
||||
`Cleaned up conflicting labels from ${issuesToCleanup.length} issues.`,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
const fs = require('node:fs');
|
||||
|
||||
module.exports = async ({ github, context, core }) => {
|
||||
core.info('Fetching open issues to check for conflicting labels...');
|
||||
|
||||
const issues = await github.paginate(github.rest.issues.listForRepo, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
state: 'open',
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const conflictingLabelIssues = [];
|
||||
|
||||
for (const issue of issues) {
|
||||
if (issue.pull_request) continue;
|
||||
|
||||
const areaLabels = issue.labels
|
||||
.filter((l) => l.name && l.name.startsWith('area/'))
|
||||
.map((l) => l.name);
|
||||
|
||||
const priorityLabels = issue.labels
|
||||
.filter((l) => l.name && l.name.startsWith('priority/'))
|
||||
.map((l) => l.name);
|
||||
|
||||
if (areaLabels.length > 1 || priorityLabels.length > 1) {
|
||||
let message = `Issue #${issue.number} has conflicting labels:`;
|
||||
if (areaLabels.length > 1)
|
||||
message += ` multiple areas (${areaLabels.join(', ')}).`;
|
||||
if (priorityLabels.length > 1)
|
||||
message += ` multiple priorities (${priorityLabels.join(', ')}).`;
|
||||
|
||||
core.info(message);
|
||||
|
||||
conflictingLabelIssues.push({
|
||||
number: issue.number,
|
||||
title: issue.title,
|
||||
body: issue.body || '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Limit to 50 to avoid overwhelming the AI in a single run
|
||||
const issuesToProcess = conflictingLabelIssues.slice(0, 50);
|
||||
|
||||
fs.writeFileSync(
|
||||
'conflicting_labels_issues.json',
|
||||
JSON.stringify(issuesToProcess, null, 2),
|
||||
);
|
||||
|
||||
core.info(
|
||||
`Found ${conflictingLabelIssues.length} issues with conflicting labels. Wrote ${issuesToProcess.length} to conflicting_labels_issues.json`,
|
||||
);
|
||||
};
|
||||
@@ -16,6 +16,8 @@ module.exports = async ({ github, context, core }) => {
|
||||
const owner = context.repo.owner;
|
||||
const repo = context.repo.repo;
|
||||
|
||||
core.info(`Running in ${dryRun ? 'DRY RUN' : 'PRODUCTION'} mode.`);
|
||||
|
||||
const STALE_LABEL = 'stale';
|
||||
const NEED_INFO_LABEL = 'status/need-information';
|
||||
const EXEMPT_LABELS = [
|
||||
@@ -79,14 +81,16 @@ module.exports = async ({ github, context, core }) => {
|
||||
async function processItems(query, callback) {
|
||||
core.info(`Searching: ${query}`);
|
||||
try {
|
||||
const response = await github.rest.search.issuesAndPullRequests({
|
||||
q: query,
|
||||
per_page: 100,
|
||||
sort: 'updated',
|
||||
order: 'asc',
|
||||
});
|
||||
const items = response.data.items;
|
||||
core.info(`Found ${items.length} items (batch limited).`);
|
||||
let items = await github.paginate(
|
||||
github.rest.search.issuesAndPullRequests,
|
||||
{
|
||||
q: query,
|
||||
per_page: 100,
|
||||
sort: 'updated',
|
||||
order: 'asc',
|
||||
},
|
||||
);
|
||||
core.info(`Found ${items.length} items.`);
|
||||
for (const item of items) {
|
||||
try {
|
||||
await callback(item);
|
||||
@@ -114,16 +118,21 @@ module.exports = async ({ github, context, core }) => {
|
||||
per_page: 5,
|
||||
});
|
||||
|
||||
// Check if the last comment is from a non-maintainer
|
||||
// Check if the last comment is from a non-maintainer and not a bot
|
||||
const lastComment = comments[0];
|
||||
if (
|
||||
lastComment &&
|
||||
lastComment.user?.type !== 'Bot' &&
|
||||
!(await isMaintainer(lastComment.user, lastComment.author_association))
|
||||
) {
|
||||
core.info(
|
||||
`Removing ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
|
||||
);
|
||||
if (!dryRun) {
|
||||
if (dryRun) {
|
||||
core.info(
|
||||
`[DRY RUN] Would remove ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
|
||||
);
|
||||
} else {
|
||||
core.info(
|
||||
`Removing ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
|
||||
);
|
||||
await github.rest.issues
|
||||
.removeLabel({
|
||||
owner,
|
||||
@@ -141,10 +150,14 @@ module.exports = async ({ github, context, core }) => {
|
||||
await processItems(
|
||||
`repo:${owner}/${repo} is:open label:"${NEED_INFO_LABEL}" updated:<${noResponseThreshold.toISOString()}`,
|
||||
async (item) => {
|
||||
core.info(
|
||||
`Closing #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
|
||||
);
|
||||
if (!dryRun) {
|
||||
if (dryRun) {
|
||||
core.info(
|
||||
`[DRY RUN] Would close #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
|
||||
);
|
||||
} else {
|
||||
core.info(
|
||||
`Closing #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
|
||||
);
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
@@ -156,6 +169,7 @@ module.exports = async ({ github, context, core }) => {
|
||||
repo,
|
||||
issue_number: item.number,
|
||||
state: 'closed',
|
||||
state_reason: 'not_planned',
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -163,11 +177,21 @@ module.exports = async ({ github, context, core }) => {
|
||||
|
||||
// 2. Handle Stale Mark (60 days inactivity, no stale label)
|
||||
const exemptQuery = EXEMPT_LABELS.map((l) => `-label:"${l}"`).join(' ');
|
||||
|
||||
await processItems(
|
||||
`repo:${owner}/${repo} is:open -label:"${STALE_LABEL}" ${exemptQuery} updated:<${staleThreshold.toISOString()}`,
|
||||
async (item) => {
|
||||
core.info(`Marking #${item.number} as stale.`);
|
||||
if (!dryRun) {
|
||||
const isBug = item.labels.some((l) =>
|
||||
(typeof l === 'string' ? l : l.name).toLowerCase().includes('bug'),
|
||||
);
|
||||
const bodyText = isBug
|
||||
? `This bug report has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. Many issues are resolved in newer releases. Please verify if the issue persists in the latest Gemini CLI version. If it does, please leave a comment to keep this open. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`
|
||||
: `This item has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`;
|
||||
|
||||
if (dryRun) {
|
||||
core.info(`[DRY RUN] Would mark #${item.number} as stale.`);
|
||||
} else {
|
||||
core.info(`Marking #${item.number} as stale.`);
|
||||
await github.rest.issues.addLabels({
|
||||
owner,
|
||||
repo,
|
||||
@@ -178,18 +202,97 @@ module.exports = async ({ github, context, core }) => {
|
||||
owner,
|
||||
repo,
|
||||
issue_number: item.number,
|
||||
body: `This item has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`,
|
||||
body: bodyText,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 3. Handle Stale Close (14 days with stale label)
|
||||
// 3. Handle Stale Removal & Close
|
||||
await processItems(
|
||||
`repo:${owner}/${repo} is:open label:"${STALE_LABEL}" ${exemptQuery} updated:<${closeThreshold.toISOString()}`,
|
||||
`repo:${owner}/${repo} is:open label:"${STALE_LABEL}" ${exemptQuery}`,
|
||||
async (item) => {
|
||||
core.info(`Closing stale item #${item.number}.`);
|
||||
if (!dryRun) {
|
||||
// Fetch full timeline to see events and comments
|
||||
const timeline = await github.paginate(
|
||||
github.rest.issues.listEventsForTimeline,
|
||||
{
|
||||
owner,
|
||||
repo,
|
||||
issue_number: item.number,
|
||||
per_page: 100,
|
||||
},
|
||||
);
|
||||
|
||||
// Find exactly when the Stale label was added
|
||||
// We look for the last 'labeled' event for STALE_LABEL
|
||||
const staleEventIndex = timeline.findLastIndex(
|
||||
(e) =>
|
||||
e.event === 'labeled' &&
|
||||
e.label?.name?.toLowerCase() === STALE_LABEL.toLowerCase(),
|
||||
);
|
||||
|
||||
if (staleEventIndex === -1) return; // Fallback if no event found
|
||||
|
||||
const staleEvent = timeline[staleEventIndex];
|
||||
const eventsAfterStale = timeline.slice(staleEventIndex + 1);
|
||||
|
||||
// Check for meaningful activity after the Stale label was applied
|
||||
const meaningfulEvents = eventsAfterStale.filter((e) => {
|
||||
const actor = e.actor?.login || '';
|
||||
const isBot =
|
||||
actor.includes('[bot]') || actor.includes('github-actions');
|
||||
|
||||
if (isBot) return false;
|
||||
|
||||
// Explicit whitelist of meaningful events for humans
|
||||
if (
|
||||
[
|
||||
'commented',
|
||||
'cross-referenced',
|
||||
'connected',
|
||||
'reopened',
|
||||
'assigned',
|
||||
].includes(e.event)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
if (meaningfulEvents.length > 0) {
|
||||
// Activity detected, remove Stale label
|
||||
if (dryRun) {
|
||||
core.info(
|
||||
`[DRY RUN] Would remove ${STALE_LABEL} from #${item.number} due to meaningful activity (e.g., comment or PR).`,
|
||||
);
|
||||
} else {
|
||||
core.info(
|
||||
`Removing ${STALE_LABEL} from #${item.number} due to meaningful activity (e.g., comment or PR).`,
|
||||
);
|
||||
await github.rest.issues
|
||||
.removeLabel({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: item.number,
|
||||
name: STALE_LABEL,
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// No meaningful activity. Check if 14 days have passed.
|
||||
const labeledDate = new Date(staleEvent.created_at);
|
||||
if (labeledDate > closeThreshold) {
|
||||
// Has not been 14 days since it was ACTUALLY marked stale
|
||||
return;
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
core.info(`[DRY RUN] Would close stale item #${item.number}.`);
|
||||
} else {
|
||||
core.info(`Closing stale item #${item.number}.`);
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
@@ -201,6 +304,7 @@ module.exports = async ({ github, context, core }) => {
|
||||
repo,
|
||||
issue_number: item.number,
|
||||
state: 'closed',
|
||||
state_reason: 'not_planned',
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -222,8 +326,12 @@ module.exports = async ({ github, context, core }) => {
|
||||
async (pr) => {
|
||||
if (await isMaintainer(pr.user, pr.author_association)) return;
|
||||
|
||||
core.info(`Nudging PR #${pr.number} for contribution policy.`);
|
||||
if (!dryRun) {
|
||||
if (dryRun) {
|
||||
core.info(
|
||||
`[DRY RUN] Would nudge PR #${pr.number} for contribution policy.`,
|
||||
);
|
||||
} else {
|
||||
core.info(`Nudging PR #${pr.number} for contribution policy.`);
|
||||
await github.rest.issues.addLabels({
|
||||
owner,
|
||||
repo,
|
||||
@@ -246,10 +354,14 @@ module.exports = async ({ github, context, core }) => {
|
||||
async (pr) => {
|
||||
if (await isMaintainer(pr.user, pr.author_association)) return;
|
||||
|
||||
core.info(
|
||||
`Closing PR #${pr.number} per contribution policy (no 'help wanted').`,
|
||||
);
|
||||
if (!dryRun) {
|
||||
if (dryRun) {
|
||||
core.info(
|
||||
`[DRY RUN] Would close PR #${pr.number} per contribution policy (no 'help wanted').`,
|
||||
);
|
||||
} else {
|
||||
core.info(
|
||||
`Closing PR #${pr.number} per contribution policy (no 'help wanted').`,
|
||||
);
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
|
||||
@@ -68,6 +68,7 @@ jobs:
|
||||
ISSUE_NUMBER: '${{ github.event.issue.number }}'
|
||||
REPOSITORY: '${{ github.repository }}'
|
||||
FIRESTORE_PROJECT: '${{ vars.FIRESTORE_PROJECT }}'
|
||||
GEMINI_CLI_TRUST_WORKSPACE: 'true'
|
||||
with:
|
||||
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
|
||||
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
|
||||
|
||||
@@ -335,14 +335,41 @@ jobs:
|
||||
return;
|
||||
}
|
||||
|
||||
const newAreaLabel = labelsToAdd[0];
|
||||
|
||||
// Get current labels to resolve conflicts
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
});
|
||||
const currentLabelNames = currentLabels.map(l => l.name);
|
||||
const currentAreaLabels = currentLabelNames.filter(name => name.startsWith('area/'));
|
||||
|
||||
const labelsToRemove = currentAreaLabels.filter(name => name !== newAreaLabel);
|
||||
|
||||
for (const label of labelsToRemove) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: label
|
||||
});
|
||||
core.info(`Removed conflicting area label: ${label}`);
|
||||
} catch (e) {
|
||||
core.warning(`Failed to remove label ${label}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Set labels based on triage result
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: labelsToAdd
|
||||
labels: [newAreaLabel]
|
||||
});
|
||||
core.info(`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}`);
|
||||
core.info(`Successfully added labels for #${issueNumber}: ${newAreaLabel}`);
|
||||
|
||||
- name: 'Post Issue Analysis Failure Comment'
|
||||
if: |-
|
||||
|
||||
@@ -62,12 +62,20 @@ jobs:
|
||||
- name: 'Find Issues with Conflicting Labels'
|
||||
if: |-
|
||||
${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}
|
||||
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
|
||||
with:
|
||||
github-token: '${{ steps.generate_token.outputs.token }}'
|
||||
script: |-
|
||||
const findConflictingLabels = require('./.github/scripts/find-conflicting-labels.cjs');
|
||||
await findConflictingLabels({ github, context, core });
|
||||
env:
|
||||
GITHUB_TOKEN: '${{ steps.generate_token.outputs.token }}'
|
||||
GITHUB_REPOSITORY: '${{ github.repository }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
echo '🔍 Fetching open issues to find conflicts...'
|
||||
# Fetch up to 2000 open issues in one quick GraphQL-backed query
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" --search "is:issue is:open" --limit 2000 --json number,title,body,labels > all_open_issues.json
|
||||
|
||||
echo '🧹 Filtering issues with multiple area/ or priority/ labels...'
|
||||
jq -c '[ .[] | select( (.labels | map(select(.name | startswith("area/"))) | length) > 1 or (.labels | map(select(.name | startswith("priority/"))) | length) > 1 ) ] | .[0:50]' all_open_issues.json > conflicting_labels_issues.json
|
||||
|
||||
CONFLICT_COUNT=$(jq 'length' conflicting_labels_issues.json)
|
||||
echo "Found ${CONFLICT_COUNT} issues with conflicting labels (capped at 50 for processing)."
|
||||
|
||||
- name: 'Find untriaged issues'
|
||||
if: |-
|
||||
@@ -81,19 +89,19 @@ jobs:
|
||||
|
||||
echo '🔍 Finding issues missing area labels...'
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue -label:status/bot-triaged -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 50 --json number,title,body > no_area_issues.json
|
||||
--search 'is:open is:issue -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 50 --json number,title,body,labels > no_area_issues.json
|
||||
|
||||
echo '🔍 Finding issues missing kind labels...'
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue -label:status/bot-triaged -label:kind/bug -label:kind/enhancement -label:kind/customer-issue -label:kind/question' --limit 50 --json number,title,body > no_kind_issues.json
|
||||
--search 'is:open is:issue -label:kind/bug -label:kind/enhancement -label:kind/customer-issue -label:kind/question' --limit 50 --json number,title,body,labels > no_kind_issues.json
|
||||
|
||||
echo '🏷️ Finding issues missing priority labels...'
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue -label:priority/p0 -label:priority/p1 -label:priority/p2 -label:priority/p3 -label:priority/unknown' --limit 50 --json number,title,body > no_priority_issues.json
|
||||
--search 'is:open is:issue -label:priority/p0 -label:priority/p1 -label:priority/p2 -label:priority/p3 -label:priority/unknown' --limit 50 --json number,title,body,labels > no_priority_issues.json
|
||||
|
||||
echo '📏 Finding issues missing effort labels...'
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue -label:effort/small -label:effort/medium -label:effort/large label:area/core,area/extensions,area/site,area/non-interactive' --limit 5 --json number,title,body > no_effort_issues.json
|
||||
--search 'is:open is:issue -label:effort/small -label:effort/medium -label:effort/large label:area/core,area/extensions,area/site,area/non-interactive' --limit 20 --json number,title,body,labels > no_effort_issues.json
|
||||
|
||||
echo '🔄 Merging and deduplicating standard triage issues...'
|
||||
if [ ! -f conflicting_labels_issues.json ]; then echo "[]" > conflicting_labels_issues.json; fi
|
||||
@@ -158,6 +166,7 @@ jobs:
|
||||
GEMINI_CLI_TRUST_WORKSPACE: 'true'
|
||||
GEMINI_EXP: 'gemini_exp.json'
|
||||
GEMINI_STRICT_TELEMETRY_LIMITS: 'true'
|
||||
GEMINI_MODEL: 'gemini-3-flash-preview'
|
||||
with:
|
||||
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
|
||||
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
|
||||
@@ -174,7 +183,7 @@ jobs:
|
||||
"read_file"
|
||||
],
|
||||
"telemetry": {
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"target": "gcp"
|
||||
}
|
||||
}
|
||||
@@ -188,12 +197,12 @@ jobs:
|
||||
## Steps
|
||||
|
||||
1. You are only able to use the echo and read_file commands. Review the available labels in the environment variable: "${AVAILABLE_LABELS}".
|
||||
2. Use the read_file tool to read the file "standard_issues_to_triage.json" which contains the JSON array of issues to triage.
|
||||
3. Review the issue title, body and any comments provided in the JSON file.
|
||||
2. Use the read_file tool to read the file "standard_issues_to_triage.json" which contains the JSON array of issues to triage (including their current labels).
|
||||
3. Review the issue title, body, current labels, and any comments provided in the JSON file.
|
||||
4. Identify the most relevant labels from the existing labels, specifically focusing on area/*, kind/*, and priority/*.
|
||||
5. Label Policy:
|
||||
- If the issue already has a kind/ label, do not change it.
|
||||
- If the issue has exactly ONE priority/ label, do not change it.
|
||||
- If the issue has exactly ONE priority/ label, do not change it (unless you are explicitly re-evaluating an ambiguous priority).
|
||||
- If the issue is missing a priority/ label, OR if the issue currently has MULTIPLE priority/ labels, you must evaluate the issue's impact to determine exactly ONE priority level (priority/p0, priority/p1, priority/p2, priority/p3, or priority/unknown) based the guidelines. If you are fixing an issue with multiple priority/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`.
|
||||
- If the issue has exactly ONE area/ label, do not change it.
|
||||
- If the issue is missing an area/ label, OR if the issue currently has MULTIPLE area/ labels, select exactly ONE area/ label that best fits the issue. Issues MUST NOT have multiple area/ labels. If you are fixing an issue with multiple area/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`.
|
||||
@@ -213,11 +222,12 @@ jobs:
|
||||
]
|
||||
```
|
||||
If an issue cannot be classified, do not include it in the output array.
|
||||
9. For each issue please check if CLI version is present, this is usually in the output of the /about command and will look like 0.1.5
|
||||
- Anything more than 6 versions older than the most recent should add the status/need-retesting label
|
||||
10. If you see that the issue doesn't look like it has sufficient information recommend the status/need-information label and leave a comment politely requesting the relevant information, eg.. if repro steps are missing request for repro steps. if version information is missing request for version information into the explanation section below.
|
||||
11. If you think an issue might be a Priority/P0 do not apply the priority/p0 label. Instead apply a status/manual-triage label and include a note in your explanation.
|
||||
12. If you are uncertain about a category, use the area/unknown, kind/question, or priority/unknown labels as appropriate. If you are extremely uncertain, apply the status/manual-triage label.
|
||||
9. For each issue, carefully check if the CLI version is present. It is usually found under the "### Client information" header, as a bullet point (e.g., "• CLI Version: 0.33.1"), or in the output of the `/about` command.
|
||||
- If the version is provided but is more than 6 minor versions older than the most recent release, apply the status/need-information label and leave a comment politely asking the user to verify if the issue persists in the latest version.
|
||||
10. If the issue does not have sufficient information, recommend the status/need-information label and leave a comment politely requesting the missing details. For example, if repro steps are missing, ask for them; if the CLI version is completely missing, ask for the version information in the explanation section below. Do not ask for version info if it is already in the issue body.
|
||||
11. If you think an issue is a Priority/P0, you MUST apply the priority/p1 label AND the status/manual-triage label, and include a note in your explanation that it likely requires P0 escalation.
|
||||
12. If the issue is highly ambiguous, completely lacks a description, or you are torn between two lower priorities (like P2 vs P3), you MUST retain the existing priority label if one is already present. Do not toggle the priority if you do not have enough information to make a definitive change.
|
||||
13. If you are uncertain about a category, use the area/unknown, kind/question, or priority/unknown labels as appropriate. If you are extremely uncertain, apply the status/manual-triage label.
|
||||
|
||||
## Guidelines
|
||||
|
||||
@@ -230,12 +240,14 @@ jobs:
|
||||
- Identify exactly ONE area/ label. Do NOT assign multiple area/ labels to a single issue.
|
||||
- Identify only one kind/ label (Do not apply kind/duplicate or kind/parent-issue)
|
||||
- Identify exactly ONE priority/ label. Do NOT assign multiple priority/ labels to a single issue.
|
||||
- Once you categorize the issue if it needs information bump down the priority by 1 eg.. a p0 would become a p1 a p1 would become a p2. P2 and P3 can stay as is in this scenario.
|
||||
- **Do not manually downgrade the priority.** Always assign the true priority based on the guidelines. The system will handle downgrades programmatically if information is missing.
|
||||
- **NEVER mention label names, label removals, or label additions in your `explanation`.** The explanation must be purely written for the user (e.g., "Please provide your CLI version.") without exposing internal triage mechanics (e.g., do NOT say "Removing area/unknown to leave only area/core").
|
||||
|
||||
Categorization Guidelines (Priority):
|
||||
P0 - Urgent Blocking Issues:
|
||||
- DO NOT APPLY THE priority/p0 LABEL AUTOMATICALLY. Instead apply priority/p1 and status/manual-triage.
|
||||
- Definition: Critical failures breaking core functionality for a large portion of users. Examples: CLI fails to launch globally, core commands (gemini run) crash on valid input, unhandled promise rejections on boot, critical security vulnerability.
|
||||
- Note: You must apply status/manual-triage instead of priority/p0.
|
||||
- Note: You must apply priority/p1 and status/manual-triage instead of priority/p0.
|
||||
P1 - Critical but Workable:
|
||||
- Definition: Severe issues without a reasonable workaround, significantly degrading the developer experience but not globally blocking. Examples: Specific tools failing consistently (e.g., `web_search` returns 500s), persistent PTY streaming hangs, memory leaks leading to OOM after short use.
|
||||
P2 - Significant Issues:
|
||||
@@ -275,6 +287,7 @@ jobs:
|
||||
GEMINI_CLI_TRUST_WORKSPACE: 'true'
|
||||
GEMINI_EXP: 'gemini_exp.json'
|
||||
GEMINI_STRICT_TELEMETRY_LIMITS: 'true'
|
||||
GEMINI_MODEL: 'gemini-3-flash-preview'
|
||||
with:
|
||||
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
|
||||
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
|
||||
@@ -293,7 +306,7 @@ jobs:
|
||||
"read_file"
|
||||
],
|
||||
"telemetry": {
|
||||
"enabled": true,
|
||||
"enabled": false,
|
||||
"target": "gcp"
|
||||
}
|
||||
}
|
||||
@@ -379,30 +392,14 @@ jobs:
|
||||
- This product is designed to use different models eg.. using pro, downgrading to flash etc.
|
||||
- When users report that they dont expect the model to change those would be categorized as feature requests.
|
||||
|
||||
- name: 'Apply Standard Labels to Issues'
|
||||
- name: 'Apply Triaged Labels'
|
||||
if: |-
|
||||
${{ steps.gemini_standard_issue_analysis.outcome == 'success' &&
|
||||
steps.gemini_standard_issue_analysis.outputs.summary != '[]' &&
|
||||
steps.gemini_standard_issue_analysis.outputs.summary != '' }}
|
||||
always() &&
|
||||
( (steps.gemini_standard_issue_analysis.outcome == 'success' && steps.gemini_standard_issue_analysis.outputs.summary != '[]' && steps.gemini_standard_issue_analysis.outputs.summary != '') ||
|
||||
(steps.gemini_effort_issue_analysis.outcome == 'success' && steps.gemini_effort_issue_analysis.outputs.summary != '[]' && steps.gemini_effort_issue_analysis.outputs.summary != '') )
|
||||
env:
|
||||
REPOSITORY: '${{ github.repository }}'
|
||||
LABELS_OUTPUT: '${{ steps.gemini_standard_issue_analysis.outputs.summary }}'
|
||||
SUPPRESS_COMMENT: 'true'
|
||||
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
|
||||
with:
|
||||
github-token: '${{ steps.generate_token.outputs.token }}'
|
||||
script: |-
|
||||
const applyLabels = require('./.github/scripts/apply-issue-labels.cjs');
|
||||
await applyLabels({ github, context, core });
|
||||
|
||||
- name: 'Apply Effort Labels to Issues'
|
||||
if: |-
|
||||
${{ steps.gemini_effort_issue_analysis.outcome == 'success' &&
|
||||
steps.gemini_effort_issue_analysis.outputs.summary != '[]' &&
|
||||
steps.gemini_effort_issue_analysis.outputs.summary != '' }}
|
||||
env:
|
||||
REPOSITORY: '${{ github.repository }}'
|
||||
LABELS_OUTPUT: '${{ steps.gemini_effort_issue_analysis.outputs.summary }}'
|
||||
LABELS_OUTPUT_STANDARD: '${{ steps.gemini_standard_issue_analysis.outputs.summary }}'
|
||||
LABELS_OUTPUT_EFFORT: '${{ steps.gemini_effort_issue_analysis.outputs.summary }}'
|
||||
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
|
||||
with:
|
||||
github-token: '${{ steps.generate_token.outputs.token }}'
|
||||
@@ -428,9 +425,12 @@ jobs:
|
||||
GITHUB_REPOSITORY: '${{ github.repository }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
echo '🧹 Finding issues that have both bot-triaged and need-triage labels...'
|
||||
echo '🧹 Finding issues that have conflicting status labels...'
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue label:status/bot-triaged label:status/need-triage' --limit 50 --json number > issues_to_cleanup.json
|
||||
--search 'is:open is:issue label:status/bot-triaged label:status/need-triage' --limit 50 --json number > cleanup_1.json
|
||||
gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue label:status/bot-triaged label:status/manual-triage' --limit 50 --json number > cleanup_2.json
|
||||
jq -c -s 'add | unique_by(.number)' cleanup_1.json cleanup_2.json > issues_to_cleanup.json
|
||||
|
||||
- name: 'Clean Up Triage Labels'
|
||||
if: |-
|
||||
|
||||
@@ -29,10 +29,11 @@ You'll use Auto Memory when you want to:
|
||||
avoid them.
|
||||
- **Bootstrap a skills library** without writing every `SKILL.md` by hand.
|
||||
|
||||
Auto Memory complements direct memory-file editing. The agent can still persist
|
||||
explicit user instructions by editing the appropriate Markdown memory file; Auto
|
||||
Memory infers candidates from past sessions, writes reviewable patches or skill
|
||||
drafts, and never applies them without your approval.
|
||||
Auto Memory complements—but does not replace—the
|
||||
[`save_memory` tool](../tools/memory.md), which captures single facts into
|
||||
`GEMINI.md` when the agent explicitly calls it. Auto Memory infers candidates
|
||||
from past sessions, writes reviewable patches or skill drafts, and never applies
|
||||
them without your approval.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
|
||||
@@ -65,6 +65,8 @@ You can interact with the loaded context files by using the `/memory` command.
|
||||
being provided to the model.
|
||||
- **`/memory reload`**: Forces a re-scan and reload of all `GEMINI.md` files
|
||||
from all configured locations.
|
||||
- **`/memory add <text>`**: Appends your text to your global
|
||||
`~/.gemini/GEMINI.md` file. This lets you add persistent memories on the fly.
|
||||
|
||||
## Modularize context with imports
|
||||
|
||||
|
||||
@@ -138,6 +138,7 @@ These are the only allowed tools:
|
||||
[`replace`](../tools/file-system.md#6-replace-edit) only allowed for `.md`
|
||||
files in the `~/.gemini/tmp/<project>/<session-id>/plans/` directory or your
|
||||
[custom plans directory](#custom-plan-directory-and-policies).
|
||||
- **Memory:** [`save_memory`](../tools/memory.md)
|
||||
- **Skills:** [`activate_skill`](../cli/skills.md) (allows loading specialized
|
||||
instructions and resources in a read-only manner)
|
||||
|
||||
|
||||
+19
-19
@@ -40,7 +40,6 @@ they appear in the UI.
|
||||
| Enable Session Cleanup | `general.sessionRetention.enabled` | Enable automatic session cleanup | `true` |
|
||||
| Keep chat history | `general.sessionRetention.maxAge` | Automatically delete chats older than this time period (e.g., "30d", "7d", "24h", "1w") | `"30d"` |
|
||||
| Topic & Update Narration | `general.topicUpdateNarration` | Enable the Topic & Update communication model for reduced chattiness and structured progress reporting. | `true` |
|
||||
| Log RAG Snippets | `general.logRagSnippets` | Log full Code Customization (RAG) retrieved snippets to a local file for debugging. | `false` |
|
||||
|
||||
### Output
|
||||
|
||||
@@ -163,24 +162,25 @@ they appear in the UI.
|
||||
|
||||
### Experimental
|
||||
|
||||
| UI Label | Setting | Description | Default |
|
||||
| ---------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
|
||||
| Gemma Models | `experimental.gemma` | Enable access to Gemma 4 models via Gemini API. | `true` |
|
||||
| Voice Mode | `experimental.voiceMode` | Enable experimental voice dictation and commands (/voice, /voice model). | `false` |
|
||||
| Voice Activation Mode | `experimental.voice.activationMode` | How to trigger voice recording with the Space key. | `"push-to-talk"` |
|
||||
| Voice Transcription Backend | `experimental.voice.backend` | The backend to use for voice transcription. Note: When using the Gemini Live backend, voice recordings are sent to Google Cloud for transcription. | `"gemini-live"` |
|
||||
| Whisper Model | `experimental.voice.whisperModel` | The Whisper model to use for local transcription. | `"ggml-base.en.bin"` |
|
||||
| Voice Stop Grace Period (ms) | `experimental.voice.stopGracePeriodMs` | How long to wait for final transcription after stopping recording. | `4000` |
|
||||
| Enable Git Worktrees | `experimental.worktrees` | Enable automated Git worktree management for parallel work. | `false` |
|
||||
| Use OSC 52 Paste | `experimental.useOSC52Paste` | Use OSC 52 for pasting. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
|
||||
| Use OSC 52 Copy | `experimental.useOSC52Copy` | Use OSC 52 for copying. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
|
||||
| Model Steering | `experimental.modelSteering` | Enable model steering (user hints) to guide the model during tool execution. | `false` |
|
||||
| Direct Web Fetch | `experimental.directWebFetch` | Enable web fetch behavior that bypasses LLM summarization. | `false` |
|
||||
| Enable Gemma Model Router | `experimental.gemmaModelRouter.enabled` | Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim. | `false` |
|
||||
| Auto-start LiteRT Server | `experimental.gemmaModelRouter.autoStartServer` | Automatically start the LiteRT-LM server when Gemini CLI starts and the Gemma router is enabled. | `false` |
|
||||
| Auto Memory | `experimental.autoMemory` | Automatically extract memory patches and skills from past sessions in the background. Every change is written as a unified diff `.patch` file under `<projectMemoryDir>/.inbox/<kind>/` and held for review in /memory inbox; nothing is applied until you approve it. | `false` |
|
||||
| Use the generalist profile to manage agent contexts. | `experimental.generalistProfile` | Suitable for general coding and software development tasks. | `false` |
|
||||
| Enable Context Management | `experimental.contextManagement` | Enable logic for context management. | `false` |
|
||||
| UI Label | Setting | Description | Default |
|
||||
| ---------------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
|
||||
| Gemma Models | `experimental.gemma` | Enable access to Gemma 4 models via Gemini API. | `true` |
|
||||
| Voice Mode | `experimental.voiceMode` | Enable experimental voice dictation and commands (/voice, /voice model). | `false` |
|
||||
| Voice Activation Mode | `experimental.voice.activationMode` | How to trigger voice recording with the Space key. | `"push-to-talk"` |
|
||||
| Voice Transcription Backend | `experimental.voice.backend` | The backend to use for voice transcription. Note: When using the Gemini Live backend, voice recordings are sent to Google Cloud for transcription. | `"gemini-live"` |
|
||||
| Whisper Model | `experimental.voice.whisperModel` | The Whisper model to use for local transcription. | `"ggml-base.en.bin"` |
|
||||
| Voice Stop Grace Period (ms) | `experimental.voice.stopGracePeriodMs` | How long to wait for final transcription after stopping recording. | `4000` |
|
||||
| Enable Git Worktrees | `experimental.worktrees` | Enable automated Git worktree management for parallel work. | `false` |
|
||||
| Use OSC 52 Paste | `experimental.useOSC52Paste` | Use OSC 52 for pasting. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
|
||||
| Use OSC 52 Copy | `experimental.useOSC52Copy` | Use OSC 52 for copying. This may be more robust than the default system when using remote terminal sessions (if your terminal is configured to allow it). | `false` |
|
||||
| Model Steering | `experimental.modelSteering` | Enable model steering (user hints) to guide the model during tool execution. | `false` |
|
||||
| Direct Web Fetch | `experimental.directWebFetch` | Enable web fetch behavior that bypasses LLM summarization. | `false` |
|
||||
| Enable Gemma Model Router | `experimental.gemmaModelRouter.enabled` | Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim. | `false` |
|
||||
| Auto-start LiteRT Server | `experimental.gemmaModelRouter.autoStartServer` | Automatically start the LiteRT-LM server when Gemini CLI starts and the Gemma router is enabled. | `false` |
|
||||
| Memory v2 | `experimental.memoryV2` | Disable the built-in save_memory tool and let the main agent persist project context by editing markdown files directly with edit/write_file. Route facts across four tiers: team-shared conventions go to project GEMINI.md files, project-specific personal notes go to the per-project private memory folder (MEMORY.md as index + sibling .md files for detail), and cross-project personal preferences go to the global ~/.gemini/GEMINI.md (the only file under ~/.gemini/ that the agent can edit — settings, credentials, etc. remain off-limits). Set to false to fall back to the legacy save_memory tool. | `true` |
|
||||
| Auto Memory | `experimental.autoMemory` | Automatically extract memory patches and skills from past sessions in the background. Every change is written as a unified diff `.patch` file under `<projectMemoryDir>/.inbox/<kind>/` and held for review in /memory inbox; nothing is applied until you approve it. | `false` |
|
||||
| Use the generalist profile to manage agent contexts. | `experimental.generalistProfile` | Suitable for general coding and software development tasks. | `false` |
|
||||
| Enable Context Management | `experimental.contextManagement` | Enable logic for context management. | `false` |
|
||||
|
||||
### Skills
|
||||
|
||||
|
||||
@@ -71,8 +71,8 @@ Just tell the agent to remember something.
|
||||
|
||||
**Prompt:** `Remember that I prefer using 'const' over 'let' wherever possible.`
|
||||
|
||||
The agent will edit the appropriate memory Markdown file, so the fact is loaded
|
||||
in future sessions.
|
||||
The agent will use the `save_memory` tool to store this fact in your global
|
||||
memory file.
|
||||
|
||||
**Prompt:** `Save the fact that the staging server IP is 10.0.0.5.`
|
||||
|
||||
|
||||
@@ -210,22 +210,6 @@ To update an extension's settings:
|
||||
gemini extensions config <name> [setting] [--scope <scope>]
|
||||
```
|
||||
|
||||
#### Environment variable sanitization
|
||||
|
||||
For security reasons, sensitive environment variables are filtered out and not
|
||||
passed to extensions or MCP servers by default.
|
||||
|
||||
Extensions **will not** inherit the user's full shell environment variables.
|
||||
They will only have access to:
|
||||
|
||||
1. Standard safe variables (e.g., `HOME`, `PATH`, `TMPDIR`).
|
||||
2. Variables explicitly declared and requested in the `gemini-extension.json`
|
||||
manifest via the `settings` array (using the `envVar` property).
|
||||
|
||||
If your extension requires specific environment variables (like an API key,
|
||||
custom host, or config path), you **must** declare them in the `settings` array
|
||||
so the CLI can allowlist them for use within the extension.
|
||||
|
||||
### Custom commands
|
||||
|
||||
Provide [custom commands](../cli/custom-commands.md) by placing TOML files in a
|
||||
|
||||
@@ -159,13 +159,6 @@ When a user installs this extension, Gemini CLI will prompt them to enter the
|
||||
`sensitive` is true) and injected into the MCP server's process as the
|
||||
`MY_SERVICE_API_KEY` environment variable.
|
||||
|
||||
> **Important (Environment Variable Sanitization):** For security reasons,
|
||||
> sensitive environment variables are filtered out and not passed to extensions
|
||||
> or MCP servers by default. Extensions will _only_ have access to environment
|
||||
> variables that are explicitly declared in the `settings` array using the
|
||||
> `envVar` property, plus a few standard safe variables. Do not expect host
|
||||
> environment variables to be available otherwise.
|
||||
|
||||
## Step 4: Link your extension
|
||||
|
||||
Link your extension to your Gemini CLI installation for local development.
|
||||
|
||||
@@ -111,8 +111,8 @@ You can also run Gemini CLI using one of the following advanced methods:
|
||||
directly. This is useful for environments where you only have Docker and want
|
||||
to run the CLI.
|
||||
```bash
|
||||
# Run the published sandbox image for a specified CLI version
|
||||
docker run --rm -it us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.42.0-nightly.20260428.g59b2dea0e
|
||||
# Run the published sandbox image
|
||||
docker run --rm -it us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.1.1
|
||||
```
|
||||
- **Using the `--sandbox` flag:** If you have Gemini CLI installed locally
|
||||
(using the standard installation described above), you can instruct it to run
|
||||
|
||||
@@ -265,6 +265,9 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
- **Description:** Manage the AI's instructional context (hierarchical memory
|
||||
loaded from `GEMINI.md` files).
|
||||
- **Sub-commands:**
|
||||
- **`add`**:
|
||||
- **Description:** Adds the following text to the AI's memory. Usage:
|
||||
`/memory add <text to remember>`
|
||||
- **`list`**:
|
||||
- **Description:** Lists the paths of the GEMINI.md files in use for
|
||||
hierarchical memory.
|
||||
|
||||
@@ -203,11 +203,6 @@ their corresponding top-level category object in your `settings.json` file.
|
||||
chattiness and structured progress reporting.
|
||||
- **Default:** `true`
|
||||
|
||||
- **`general.logRagSnippets`** (boolean):
|
||||
- **Description:** Log full Code Customization (RAG) retrieved snippets to a
|
||||
local file for debugging.
|
||||
- **Default:** `false`
|
||||
|
||||
#### `output`
|
||||
|
||||
- **`output.format`** (enum):
|
||||
@@ -1872,6 +1867,13 @@ their corresponding top-level category object in your `settings.json` file.
|
||||
- **Default:** `false`
|
||||
- **Requires restart:** Yes
|
||||
|
||||
- **`experimental.jitContext`** (boolean):
|
||||
- **Description:** Enable Just-In-Time (JIT) context loading. Defaults to
|
||||
true; set to false to opt out and load all GEMINI.md files into the system
|
||||
instruction up-front.
|
||||
- **Default:** `true`
|
||||
- **Requires restart:** Yes
|
||||
|
||||
- **`experimental.useOSC52Paste`** (boolean):
|
||||
- **Description:** Use OSC 52 for pasting. This may be more robust than the
|
||||
default system when using remote terminal sessions (if your terminal is
|
||||
@@ -1934,6 +1936,19 @@ their corresponding top-level category object in your `settings.json` file.
|
||||
- **Default:** `"gemma3-1b-gpu-custom"`
|
||||
- **Requires restart:** Yes
|
||||
|
||||
- **`experimental.memoryV2`** (boolean):
|
||||
- **Description:** Disable the built-in save_memory tool and let the main
|
||||
agent persist project context by editing markdown files directly with
|
||||
edit/write_file. Route facts across four tiers: team-shared conventions go
|
||||
to project GEMINI.md files, project-specific personal notes go to the
|
||||
per-project private memory folder (MEMORY.md as index + sibling .md files
|
||||
for detail), and cross-project personal preferences go to the global
|
||||
~/.gemini/GEMINI.md (the only file under ~/.gemini/ that the agent can edit
|
||||
— settings, credentials, etc. remain off-limits). Set to false to fall back
|
||||
to the legacy save_memory tool.
|
||||
- **Default:** `true`
|
||||
- **Requires restart:** Yes
|
||||
|
||||
- **`experimental.stressTestProfile`** (boolean):
|
||||
- **Description:** Significantly lowers token limits to force early garbage
|
||||
collection and distillation for testing purposes.
|
||||
|
||||
@@ -120,6 +120,7 @@ each tool.
|
||||
| :----------------------------------------------- | :------ | :----------------------------------------------------------------------------------- |
|
||||
| [`activate_skill`](../tools/activate-skill.md) | `Other` | Loads specialized procedural expertise from the `.gemini/skills` directory. |
|
||||
| [`get_internal_docs`](../tools/internal-docs.md) | `Think` | Accesses Gemini CLI's own documentation for accurate answers about its capabilities. |
|
||||
| [`save_memory`](../tools/memory.md) | `Think` | Persists specific facts and project details to your `GEMINI.md` file. |
|
||||
|
||||
### Planning
|
||||
|
||||
@@ -172,6 +173,7 @@ representation of each tool's arguments.
|
||||
| `replace` | `file_path`, `old_string`, `new_string`, `instruction`, `allow_multiple` |
|
||||
| `ask_user` | `questions` (array of `question`, `header`, `type`, `options`) |
|
||||
| `write_todos` | `todos` (array of `description`, `status`) |
|
||||
| `save_memory` | `fact` |
|
||||
| `activate_skill` | `name` |
|
||||
| `get_internal_docs` | `path` |
|
||||
| `enter_plan_mode` | `reason` |
|
||||
|
||||
@@ -221,10 +221,8 @@ spawning MCP server processes.
|
||||
#### Automatic redaction
|
||||
|
||||
By default, the CLI redacts sensitive environment variables from the base
|
||||
environment (inherited from the host process). This prevents the accidental
|
||||
leakage of sensitive host environment variables (like AWS keys or GitHub tokens)
|
||||
to arbitrary third-party MCP servers that might execute malicious code or log
|
||||
your environment. This includes:
|
||||
environment (inherited from the host process) to prevent unintended exposure to
|
||||
third-party MCP servers. This includes:
|
||||
|
||||
- Core project keys: `GEMINI_API_KEY`, `GOOGLE_API_KEY`, etc.
|
||||
- Variables matching sensitive patterns: `*TOKEN*`, `*SECRET*`, `*PASSWORD*`,
|
||||
@@ -234,8 +232,7 @@ your environment. This includes:
|
||||
#### Explicit overrides
|
||||
|
||||
If an environment variable must be passed to an MCP server, you must explicitly
|
||||
state it in the `env` property of the server configuration in `settings.json`
|
||||
(or `mcp_config.json` if configuring standard MCP clients or remote skills).
|
||||
state it in the `env` property of the server configuration in `settings.json`.
|
||||
Explicitly defined variables (including those from extensions) are trusted and
|
||||
are **not** subjected to the automatic redaction process.
|
||||
|
||||
@@ -250,24 +247,6 @@ specific data with that server.
|
||||
> (for example, `"MY_KEY": "$MY_KEY"`) to securely pull the value from your host
|
||||
> environment at runtime.
|
||||
|
||||
**Example: Passing a GitHub Token securely to the
|
||||
[official GitHub MCP server](https://github.com/github/github-mcp-server) via
|
||||
`mcp_config.json`**
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"github": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@github/github-mcp-server"],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "$GITHUB_PERSONAL_ACCESS_TOKEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### OAuth support for remote MCP servers
|
||||
|
||||
Gemini CLI supports OAuth 2.0 authentication for remote MCP servers using SSE or
|
||||
|
||||
+13
-10
@@ -1,22 +1,25 @@
|
||||
# Memory files
|
||||
# Memory tool (`save_memory`)
|
||||
|
||||
Gemini CLI persists durable facts, user preferences, and project details by
|
||||
editing Markdown memory files directly.
|
||||
The `save_memory` tool allows the Gemini agent to persist specific facts, user
|
||||
preferences, and project details across sessions.
|
||||
|
||||
## Technical reference
|
||||
|
||||
The agent routes memories to the appropriate Markdown file: shared project
|
||||
instructions go in repository `GEMINI.md` files, private project notes go in the
|
||||
per-project private memory folder, and cross-project personal preferences go in
|
||||
the global `~/.gemini/GEMINI.md` file.
|
||||
This tool appends information to the `## Gemini Added Memories` section of your
|
||||
global `GEMINI.md` file (typically located at `~/.gemini/GEMINI.md`).
|
||||
|
||||
### Arguments
|
||||
|
||||
- `fact` (string, required): A clear, self-contained statement in natural
|
||||
language.
|
||||
|
||||
## Technical behavior
|
||||
|
||||
- **Storage:** Edits Markdown files with `write_file` or `replace`.
|
||||
- **Storage:** Appends to the global context file in the user's home directory.
|
||||
- **Loading:** The stored facts are automatically included in the hierarchical
|
||||
context system for all future sessions.
|
||||
- **Format:** Keeps durable instructions concise and avoids duplicating the same
|
||||
fact across multiple memory tiers.
|
||||
- **Format:** Saves data as a bulleted list item within a dedicated Markdown
|
||||
section.
|
||||
|
||||
## Use cases
|
||||
|
||||
|
||||
@@ -11,7 +11,11 @@ import {
|
||||
loadConversationRecord,
|
||||
SESSION_FILE_PREFIX,
|
||||
} from '@google/gemini-cli-core';
|
||||
import { evalTest, assertModelHasOutput } from './test-helper.js';
|
||||
import {
|
||||
evalTest,
|
||||
assertModelHasOutput,
|
||||
checkModelOutputContent,
|
||||
} from './test-helper.js';
|
||||
|
||||
function findDir(base: string, name: string): string | null {
|
||||
if (!fs.existsSync(base)) return null;
|
||||
@@ -73,13 +77,336 @@ async function waitForSessionScratchpad(
|
||||
return loadLatestSessionRecord(homeDir, sessionId);
|
||||
}
|
||||
|
||||
describe('memory persistence', () => {
|
||||
describe('save_memory', () => {
|
||||
const TEST_PREFIX = 'Save memory test: ';
|
||||
const rememberingFavoriteColor = "Agent remembers user's favorite color";
|
||||
evalTest('ALWAYS_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingFavoriteColor,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `remember that my favorite color is blue.
|
||||
|
||||
what is my favorite color? tell me that and surround it with $ symbol`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: 'blue',
|
||||
testName: `${TEST_PREFIX}${rememberingFavoriteColor}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
const rememberingCommandRestrictions = 'Agent remembers command restrictions';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingCommandRestrictions,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `I don't want you to ever run npm commands.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: [/not run npm commands|remember|ok/i],
|
||||
testName: `${TEST_PREFIX}${rememberingCommandRestrictions}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const rememberingWorkflow = 'Agent remembers workflow preferences';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingWorkflow,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `I want you to always lint after building.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: [/always|ok|remember|will do/i],
|
||||
testName: `${TEST_PREFIX}${rememberingWorkflow}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const ignoringTemporaryInformation =
|
||||
'Agent ignores temporary conversation details';
|
||||
evalTest('ALWAYS_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: ignoringTemporaryInformation,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `I'm going to get a coffee.`,
|
||||
assert: async (rig, result) => {
|
||||
await rig.waitForTelemetryReady();
|
||||
const wasToolCalled = rig
|
||||
.readToolLogs()
|
||||
.some((log) => log.toolRequest.name === 'save_memory');
|
||||
expect(
|
||||
wasToolCalled,
|
||||
'save_memory should not be called for temporary information',
|
||||
).toBe(false);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
testName: `${TEST_PREFIX}${ignoringTemporaryInformation}`,
|
||||
forbiddenContent: [/remember|will do/i],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const rememberingPetName = "Agent remembers user's pet's name";
|
||||
evalTest('ALWAYS_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingPetName,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `Please remember that my dog's name is Buddy.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: [/Buddy/i],
|
||||
testName: `${TEST_PREFIX}${rememberingPetName}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const rememberingCommandAlias = 'Agent remembers custom command aliases';
|
||||
evalTest('ALWAYS_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingCommandAlias,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `When I say 'start server', you should run 'npm run dev'.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: [/npm run dev|start server|ok|remember|will do/i],
|
||||
testName: `${TEST_PREFIX}${rememberingCommandAlias}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const savingDbSchemaLocationAsProjectMemory =
|
||||
'Agent saves workspace database schema location as project memory';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: savingDbSchemaLocationAsProjectMemory,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
prompt: `The database schema for this workspace is located in \`db/schema.sql\`.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall(
|
||||
'save_memory',
|
||||
undefined,
|
||||
(args) => {
|
||||
try {
|
||||
const params = JSON.parse(args);
|
||||
return params.scope === 'project';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
);
|
||||
expect(
|
||||
wasToolCalled,
|
||||
'Expected save_memory to be called with scope="project" for workspace-specific information',
|
||||
).toBe(true);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
},
|
||||
});
|
||||
|
||||
const rememberingCodingStyle =
|
||||
"Agent remembers user's coding style preference";
|
||||
evalTest('ALWAYS_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingCodingStyle,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `I prefer to use tabs instead of spaces for indentation.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: [/tabs instead of spaces|ok|remember|will do/i],
|
||||
testName: `${TEST_PREFIX}${rememberingCodingStyle}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const savingBuildArtifactLocationAsProjectMemory =
|
||||
'Agent saves workspace build artifact location as project memory';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: savingBuildArtifactLocationAsProjectMemory,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
prompt: `In this workspace, build artifacts are stored in the \`dist/artifacts\` directory.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall(
|
||||
'save_memory',
|
||||
undefined,
|
||||
(args) => {
|
||||
try {
|
||||
const params = JSON.parse(args);
|
||||
return params.scope === 'project';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
);
|
||||
expect(
|
||||
wasToolCalled,
|
||||
'Expected save_memory to be called with scope="project" for workspace-specific information',
|
||||
).toBe(true);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
},
|
||||
});
|
||||
|
||||
const savingMainEntryPointAsProjectMemory =
|
||||
'Agent saves workspace main entry point as project memory';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: savingMainEntryPointAsProjectMemory,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
prompt: `The main entry point for this workspace is \`src/index.js\`.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall(
|
||||
'save_memory',
|
||||
undefined,
|
||||
(args) => {
|
||||
try {
|
||||
const params = JSON.parse(args);
|
||||
return params.scope === 'project';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
);
|
||||
expect(
|
||||
wasToolCalled,
|
||||
'Expected save_memory to be called with scope="project" for workspace-specific information',
|
||||
).toBe(true);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
},
|
||||
});
|
||||
|
||||
const rememberingBirthday = "Agent remembers user's birthday";
|
||||
evalTest('ALWAYS_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: rememberingBirthday,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: false },
|
||||
},
|
||||
},
|
||||
|
||||
prompt: `My birthday is on June 15th.`,
|
||||
assert: async (rig, result) => {
|
||||
const wasToolCalled = await rig.waitForToolCall('save_memory');
|
||||
expect(wasToolCalled, 'Expected save_memory tool to be called').toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
assertModelHasOutput(result);
|
||||
checkModelOutputContent(result, {
|
||||
expectedContent: [/June 15th|ok|remember|will do/i],
|
||||
testName: `${TEST_PREFIX}${rememberingBirthday}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const proactiveMemoryFromLongSession =
|
||||
'Agent saves preference from earlier in conversation history';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: proactiveMemoryFromLongSession,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: true },
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: 'msg-1',
|
||||
@@ -135,9 +462,9 @@ describe('memory persistence', () => {
|
||||
prompt:
|
||||
'Please save any persistent preferences or facts about me from our conversation to memory.',
|
||||
assert: async (rig, result) => {
|
||||
// The agent persists memories by editing markdown files directly with
|
||||
// write_file or replace. The user said
|
||||
// "I always prefer Vitest over
|
||||
// Under experimental.memoryV2, the agent persists memories by
|
||||
// editing markdown files directly with write_file or replace — not via
|
||||
// a save_memory subagent. The user said "I always prefer Vitest over
|
||||
// Jest for testing in all my projects" — that matches the new
|
||||
// cross-project cue phrase ("across all my projects"), so under the
|
||||
// 4-tier model the correct destination is the global personal memory
|
||||
@@ -195,12 +522,17 @@ describe('memory persistence', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const memoryRoutesTeamConventionsToProjectGemini =
|
||||
const memoryV2RoutesTeamConventionsToProjectGemini =
|
||||
'Agent routes team-shared project conventions to ./GEMINI.md';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: memoryRoutesTeamConventionsToProjectGemini,
|
||||
name: memoryV2RoutesTeamConventionsToProjectGemini,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: true },
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: 'msg-1',
|
||||
@@ -241,11 +573,11 @@ describe('memory persistence', () => {
|
||||
],
|
||||
prompt: 'Please save the preferences I mentioned earlier to memory.',
|
||||
assert: async (rig, result) => {
|
||||
// The prompt enforces an explicit one-tier-per-fact rule: team-shared
|
||||
// project conventions (the team's test command, project-wide
|
||||
// indentation rules) belong in the committed project-root ./GEMINI.md
|
||||
// and must NOT be mirrored or cross-referenced into the private project
|
||||
// memory folder
|
||||
// Under experimental.memoryV2, the prompt enforces an explicit
|
||||
// one-tier-per-fact rule: team-shared project conventions (the team's
|
||||
// test command, project-wide indentation rules) belong in the
|
||||
// committed project-root ./GEMINI.md and must NOT be mirrored or
|
||||
// cross-referenced into the private project memory folder
|
||||
// (~/.gemini/tmp/<hash>/memory/). The global ~/.gemini/GEMINI.md must
|
||||
// never be touched in this mode either.
|
||||
await rig.waitForToolCall('write_file').catch(() => {});
|
||||
@@ -303,13 +635,18 @@ describe('memory persistence', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const memorySessionScratchpad =
|
||||
const memoryV2SessionScratchpad =
|
||||
'Session summary persists memory scratchpad for memory-saving sessions';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: memorySessionScratchpad,
|
||||
name: memoryV2SessionScratchpad,
|
||||
sessionId: 'memory-scratchpad-eval',
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: true },
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: 'msg-1',
|
||||
@@ -358,7 +695,7 @@ describe('memory persistence', () => {
|
||||
|
||||
expect(
|
||||
writeCalls.length,
|
||||
'Expected memory save flow to edit a markdown memory file',
|
||||
'Expected memoryV2 save flow to edit a markdown memory file',
|
||||
).toBeGreaterThan(0);
|
||||
|
||||
await rig.run({
|
||||
@@ -395,12 +732,17 @@ describe('memory persistence', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const memoryRoutesUserProject =
|
||||
const memoryV2RoutesUserProject =
|
||||
'Agent routes personal-to-user project notes to user-project memory';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: memoryRoutesUserProject,
|
||||
name: memoryV2RoutesUserProject,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: true },
|
||||
},
|
||||
},
|
||||
prompt: `Please remember my personal local dev setup for THIS project's Postgres database. This is private to my machine — do NOT commit it to the repo.
|
||||
|
||||
Connection details:
|
||||
@@ -419,11 +761,11 @@ Quirks to remember:
|
||||
- The migrations runner sometimes hangs on my machine if I forget step 1; kill it with Ctrl+C and rerun.
|
||||
- I keep an extra \`scratch\` schema for ad-hoc experiments — never reference it from project code.`,
|
||||
assert: async (rig, result) => {
|
||||
// With the Private Project Memory bullet surfaced in the prompt, a fact
|
||||
// that is project-specific AND personal-to-the-user (must not be
|
||||
// committed) should land in the private project memory folder under
|
||||
// ~/.gemini/tmp/<hash>/memory/. The detailed note should be written to a
|
||||
// sibling markdown file, with
|
||||
// Under experimental.memoryV2 with the Private Project Memory bullet
|
||||
// surfaced in the prompt, a fact that is project-specific AND
|
||||
// personal-to-the-user (must not be committed) should land in the
|
||||
// private project memory folder under ~/.gemini/tmp/<hash>/memory/. The
|
||||
// detailed note should be written to a sibling markdown file, with
|
||||
// MEMORY.md updated as the index. It must NOT go to committed
|
||||
// ./GEMINI.md or the global ~/.gemini/GEMINI.md.
|
||||
await rig.waitForToolCall('write_file').catch(() => {});
|
||||
@@ -486,19 +828,24 @@ Quirks to remember:
|
||||
},
|
||||
});
|
||||
|
||||
const memoryRoutesCrossProjectToGlobal =
|
||||
const memoryV2RoutesCrossProjectToGlobal =
|
||||
'Agent routes cross-project personal preferences to ~/.gemini/GEMINI.md';
|
||||
evalTest('USUALLY_PASSES', {
|
||||
suiteName: 'default',
|
||||
suiteType: 'behavioral',
|
||||
name: memoryRoutesCrossProjectToGlobal,
|
||||
name: memoryV2RoutesCrossProjectToGlobal,
|
||||
params: {
|
||||
settings: {
|
||||
experimental: { memoryV2: true },
|
||||
},
|
||||
},
|
||||
prompt:
|
||||
'Please remember this about me in general: across all my projects I always prefer Prettier with single quotes and trailing commas, and I always prefer tabs over spaces for indentation. These are my personal coding-style defaults that follow me into every workspace.',
|
||||
assert: async (rig, result) => {
|
||||
// With the Global Personal Memory tier surfaced in the prompt, a fact
|
||||
// that explicitly applies to the user "across all my projects" / "in
|
||||
// every workspace" must land in the global ~/.gemini/GEMINI.md (the
|
||||
// cross-project tier). It must
|
||||
// Under experimental.memoryV2 with the Global Personal Memory
|
||||
// tier surfaced in the prompt, a fact that explicitly applies to the
|
||||
// user "across all my projects" / "in every workspace" must land in
|
||||
// the global ~/.gemini/GEMINI.md (the cross-project tier). It must
|
||||
// NOT be mirrored into a committed project-root ./GEMINI.md (that
|
||||
// tier is for team-shared conventions) or into the per-project
|
||||
// private memory folder (that tier is for project-specific personal
|
||||
@@ -32,7 +32,7 @@ export const EVAL_MODEL =
|
||||
// Indicates the consistency expectation for this test.
|
||||
// - ALWAYS_PASSES - Means that the test is expected to pass 100% of the time. These
|
||||
// These tests are typically trivial and test basic functionality with unambiguous
|
||||
// prompts. For example: "remember foo" should be fairly reliable.
|
||||
// prompts. For example: "call save_memory to remember foo" should be fairly reliable.
|
||||
// These are the first line of defense against regressions in key behaviors and run in
|
||||
// every CI. You can run these locally with 'npm run test:always_passing_evals'.
|
||||
//
|
||||
|
||||
@@ -12,7 +12,7 @@ if (process.env['NO_COLOR'] !== undefined) {
|
||||
import { mkdir, readdir, rm, readFile } from 'node:fs/promises';
|
||||
import { join, dirname, extname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveRipgrepPath } from '../packages/core/src/tools/ripGrep.js';
|
||||
import { canUseRipgrep } from '../packages/core/src/tools/ripGrep.js';
|
||||
import { disableMouseTracking } from '@google/gemini-cli-core';
|
||||
import { isolateTestEnv } from '../packages/test-utils/src/env-setup.js';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
@@ -93,7 +93,7 @@ export async function setup() {
|
||||
isolateTestEnv(runDir);
|
||||
|
||||
// Download ripgrep to avoid race conditions in parallel tests
|
||||
const available = await resolveRipgrepPath();
|
||||
const available = await canUseRipgrep();
|
||||
if (!available) {
|
||||
throw new Error('Failed to download ripgrep binary');
|
||||
}
|
||||
|
||||
@@ -8,10 +8,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import * as path from 'node:path';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as os from 'node:os';
|
||||
import {
|
||||
RipGrepTool,
|
||||
resolveRipgrepPath,
|
||||
} from '../packages/core/src/tools/ripGrep.js';
|
||||
import { RipGrepTool } from '../packages/core/src/tools/ripGrep.js';
|
||||
import { Config } from '../packages/core/src/config/config.js';
|
||||
import { WorkspaceContext } from '../packages/core/src/utils/workspaceContext.js';
|
||||
import { createMockMessageBus } from '../packages/core/src/test-utils/mock-message-bus.js';
|
||||
@@ -51,10 +48,6 @@ class MockConfig {
|
||||
validatePathAccess() {
|
||||
return null;
|
||||
}
|
||||
|
||||
async getRipgrepPath() {
|
||||
return resolveRipgrepPath();
|
||||
}
|
||||
}
|
||||
|
||||
describe('ripgrep-real-direct', () => {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { mkdir, readdir, rm } from 'node:fs/promises';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveRipgrepPath } from '../packages/core/src/tools/ripGrep.js';
|
||||
import { canUseRipgrep } from '../packages/core/src/tools/ripGrep.js';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = join(__dirname, '..');
|
||||
@@ -27,7 +27,7 @@ export async function setup() {
|
||||
process.env['GEMINI_CONFIG_DIR'] = join(runDir, '.gemini');
|
||||
|
||||
// Download ripgrep to avoid race conditions
|
||||
const available = await resolveRipgrepPath();
|
||||
const available = await canUseRipgrep();
|
||||
if (!available) {
|
||||
throw new Error('Failed to download ripgrep binary');
|
||||
}
|
||||
|
||||
Generated
+348
-364
File diff suppressed because it is too large
Load Diff
@@ -418,7 +418,7 @@ confirmations for tool calls (like executing a shell command), will be sent as
|
||||
```proto
|
||||
// Request to execute a specific slash command.
|
||||
message ExecuteSlashCommandRequest {
|
||||
// The path to the command, e.g., ["memory", "list"] for /memory list
|
||||
// The path to the command, e.g., ["memory", "add"] for /memory add
|
||||
repeated string command_path = 1;
|
||||
// The arguments for the command as a single string.
|
||||
string args = 2;
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"@a2a-js/sdk": "0.3.11",
|
||||
"@google-cloud/storage": "^7.19.0",
|
||||
"@google-cloud/storage": "^7.16.0",
|
||||
"@google/gemini-cli-core": "file:../core",
|
||||
"express": "^5.1.0",
|
||||
"fs-extra": "^11.3.0",
|
||||
|
||||
@@ -5,13 +5,17 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
addMemory,
|
||||
listMemoryFiles,
|
||||
refreshMemory,
|
||||
showMemory,
|
||||
type AnyDeclarativeTool,
|
||||
type Config,
|
||||
type ToolRegistry,
|
||||
} from '@google/gemini-cli-core';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
AddMemoryCommand,
|
||||
ListMemoryCommand,
|
||||
MemoryCommand,
|
||||
RefreshMemoryCommand,
|
||||
@@ -28,23 +32,44 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
showMemory: vi.fn(),
|
||||
refreshMemory: vi.fn(),
|
||||
listMemoryFiles: vi.fn(),
|
||||
addMemory: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const mockShowMemory = vi.mocked(showMemory);
|
||||
const mockRefreshMemory = vi.mocked(refreshMemory);
|
||||
const mockListMemoryFiles = vi.mocked(listMemoryFiles);
|
||||
const mockAddMemory = vi.mocked(addMemory);
|
||||
|
||||
describe('a2a-server memory commands', () => {
|
||||
let mockContext: CommandContext;
|
||||
let mockConfig: Config;
|
||||
let mockToolRegistry: ToolRegistry;
|
||||
let mockSaveMemoryTool: AnyDeclarativeTool;
|
||||
|
||||
beforeEach(() => {
|
||||
mockConfig = {} as unknown as Config;
|
||||
mockSaveMemoryTool = {
|
||||
name: 'save_memory',
|
||||
description: 'Saves memory',
|
||||
buildAndExecute: vi.fn().mockResolvedValue(undefined),
|
||||
} as unknown as AnyDeclarativeTool;
|
||||
|
||||
mockToolRegistry = {
|
||||
getTool: vi.fn(),
|
||||
} as unknown as ToolRegistry;
|
||||
|
||||
mockConfig = {
|
||||
get toolRegistry() {
|
||||
return mockToolRegistry;
|
||||
},
|
||||
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
|
||||
} as unknown as Config;
|
||||
|
||||
mockContext = {
|
||||
config: mockConfig,
|
||||
};
|
||||
|
||||
vi.mocked(mockToolRegistry.getTool).mockReturnValue(mockSaveMemoryTool);
|
||||
});
|
||||
|
||||
describe('MemoryCommand', () => {
|
||||
@@ -111,4 +136,76 @@ describe('a2a-server memory commands', () => {
|
||||
expect(response.data).toBe('file1.md\nfile2.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AddMemoryCommand', () => {
|
||||
it('returns message content if addMemory returns a message', async () => {
|
||||
const command = new AddMemoryCommand();
|
||||
mockAddMemory.mockReturnValue({
|
||||
type: 'message',
|
||||
messageType: 'error',
|
||||
content: 'error message',
|
||||
});
|
||||
|
||||
const response = await command.execute(mockContext, []);
|
||||
|
||||
expect(mockAddMemory).toHaveBeenCalledWith('');
|
||||
expect(response.name).toBe('memory add');
|
||||
expect(response.data).toBe('error message');
|
||||
});
|
||||
|
||||
it('executes the save_memory tool if found', async () => {
|
||||
const command = new AddMemoryCommand();
|
||||
const fact = 'this is a new fact';
|
||||
mockAddMemory.mockReturnValue({
|
||||
type: 'tool',
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact },
|
||||
});
|
||||
|
||||
const response = await command.execute(mockContext, [
|
||||
'this',
|
||||
'is',
|
||||
'a',
|
||||
'new',
|
||||
'fact',
|
||||
]);
|
||||
|
||||
expect(mockAddMemory).toHaveBeenCalledWith(fact);
|
||||
expect(mockToolRegistry.getTool).toHaveBeenCalledWith('save_memory');
|
||||
expect(mockSaveMemoryTool.buildAndExecute).toHaveBeenCalledWith(
|
||||
{ fact },
|
||||
expect.any(AbortSignal),
|
||||
undefined,
|
||||
{
|
||||
shellExecutionConfig: {
|
||||
sanitizationConfig: {
|
||||
allowedEnvironmentVariables: [],
|
||||
blockedEnvironmentVariables: [],
|
||||
enableEnvironmentVariableRedaction: false,
|
||||
},
|
||||
sandboxManager: undefined,
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(mockRefreshMemory).toHaveBeenCalledWith(mockContext.config);
|
||||
expect(response.name).toBe('memory add');
|
||||
expect(response.data).toBe(`Added memory: "${fact}"`);
|
||||
});
|
||||
|
||||
it('returns an error if the tool is not found', async () => {
|
||||
const command = new AddMemoryCommand();
|
||||
const fact = 'another fact';
|
||||
mockAddMemory.mockReturnValue({
|
||||
type: 'tool',
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact },
|
||||
});
|
||||
vi.mocked(mockToolRegistry.getTool).mockReturnValue(undefined);
|
||||
|
||||
const response = await command.execute(mockContext, ['another', 'fact']);
|
||||
|
||||
expect(response.name).toBe('memory add');
|
||||
expect(response.data).toBe('Error: Tool save_memory not found.');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
addMemory,
|
||||
listMemoryFiles,
|
||||
refreshMemory,
|
||||
showMemory,
|
||||
@@ -14,6 +15,13 @@ import type {
|
||||
CommandContext,
|
||||
CommandExecutionResponse,
|
||||
} from './types.js';
|
||||
import type { AgentLoopContext } from '@google/gemini-cli-core';
|
||||
|
||||
const DEFAULT_SANITIZATION_CONFIG = {
|
||||
allowedEnvironmentVariables: [],
|
||||
blockedEnvironmentVariables: [],
|
||||
enableEnvironmentVariableRedaction: false,
|
||||
};
|
||||
|
||||
export class MemoryCommand implements Command {
|
||||
readonly name = 'memory';
|
||||
@@ -22,6 +30,7 @@ export class MemoryCommand implements Command {
|
||||
new ShowMemoryCommand(),
|
||||
new RefreshMemoryCommand(),
|
||||
new ListMemoryCommand(),
|
||||
new AddMemoryCommand(),
|
||||
];
|
||||
readonly topLevel = true;
|
||||
readonly requiresWorkspace = true;
|
||||
@@ -72,3 +81,43 @@ export class ListMemoryCommand implements Command {
|
||||
return { name: this.name, data: result.content };
|
||||
}
|
||||
}
|
||||
|
||||
export class AddMemoryCommand implements Command {
|
||||
readonly name = 'memory add';
|
||||
readonly description = 'Add content to the memory.';
|
||||
|
||||
async execute(
|
||||
context: CommandContext,
|
||||
args: string[],
|
||||
): Promise<CommandExecutionResponse> {
|
||||
const textToAdd = args.join(' ').trim();
|
||||
const result = addMemory(textToAdd);
|
||||
if (result.type === 'message') {
|
||||
return { name: this.name, data: result.content };
|
||||
}
|
||||
|
||||
const loopContext: AgentLoopContext = context.config;
|
||||
const toolRegistry = loopContext.toolRegistry;
|
||||
const tool = toolRegistry.getTool(result.toolName);
|
||||
if (tool) {
|
||||
const abortController = new AbortController();
|
||||
const abortSignal = abortController.signal;
|
||||
await tool.buildAndExecute(result.toolArgs, abortSignal, undefined, {
|
||||
shellExecutionConfig: {
|
||||
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
|
||||
sandboxManager: loopContext.sandboxManager,
|
||||
},
|
||||
});
|
||||
await refreshMemory(context.config);
|
||||
return {
|
||||
name: this.name,
|
||||
data: `Added memory: "${textToAdd}"`,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
name: this.name,
|
||||
data: `Error: Tool ${result.toolName} not found.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { loadConfig } from './config.js';
|
||||
import type { Settings } from './settings.js';
|
||||
import {
|
||||
type ExtensionLoader,
|
||||
FileDiscoveryService,
|
||||
getCodeAssistServer,
|
||||
Config,
|
||||
ExperimentFlags,
|
||||
@@ -47,10 +48,16 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
};
|
||||
return mockConfig;
|
||||
}),
|
||||
loadServerHierarchicalMemory: vi.fn().mockResolvedValue({
|
||||
memoryContent: { global: '', extension: '', project: '' },
|
||||
fileCount: 0,
|
||||
filePaths: [],
|
||||
}),
|
||||
startupProfiler: {
|
||||
flush: vi.fn(),
|
||||
},
|
||||
isHeadlessMode: vi.fn().mockReturnValue(false),
|
||||
FileDiscoveryService: vi.fn(),
|
||||
getCodeAssistServer: vi.fn(),
|
||||
fetchAdminControlsOnce: vi.fn(),
|
||||
coreEvents: {
|
||||
@@ -261,6 +268,24 @@ describe('loadConfig', () => {
|
||||
expect((config as any).fileFiltering.customIgnoreFilePaths).toEqual([]);
|
||||
});
|
||||
|
||||
it('should initialize FileDiscoveryService with correct options', async () => {
|
||||
const testPath = '/tmp/ignore';
|
||||
vi.stubEnv('CUSTOM_IGNORE_FILE_PATHS', testPath);
|
||||
const settings: Settings = {
|
||||
fileFiltering: {
|
||||
respectGitIgnore: false,
|
||||
},
|
||||
};
|
||||
|
||||
await loadConfig(settings, mockExtensionLoader, taskId);
|
||||
|
||||
expect(FileDiscoveryService).toHaveBeenCalledWith(expect.any(String), {
|
||||
respectGitIgnore: false,
|
||||
respectGeminiIgnore: undefined,
|
||||
customIgnoreFilePaths: [testPath],
|
||||
});
|
||||
});
|
||||
|
||||
describe('tool configuration', () => {
|
||||
it('should pass V1 allowedTools to Config properly', async () => {
|
||||
const settings: Settings = {
|
||||
|
||||
@@ -11,7 +11,9 @@ import * as dotenv from 'dotenv';
|
||||
import {
|
||||
AuthType,
|
||||
Config,
|
||||
FileDiscoveryService,
|
||||
ApprovalMode,
|
||||
loadServerHierarchicalMemory,
|
||||
GEMINI_DIR,
|
||||
DEFAULT_GEMINI_EMBEDDING_MODEL,
|
||||
startupProfiler,
|
||||
@@ -127,6 +129,23 @@ export async function loadConfig(
|
||||
enableAgents: settings.experimental?.enableAgents ?? true,
|
||||
};
|
||||
|
||||
const fileService = new FileDiscoveryService(workspaceDir, {
|
||||
respectGitIgnore: configParams?.fileFiltering?.respectGitIgnore,
|
||||
respectGeminiIgnore: configParams?.fileFiltering?.respectGeminiIgnore,
|
||||
customIgnoreFilePaths: configParams?.fileFiltering?.customIgnoreFilePaths,
|
||||
});
|
||||
const { memoryContent, fileCount, filePaths } =
|
||||
await loadServerHierarchicalMemory(
|
||||
workspaceDir,
|
||||
[workspaceDir],
|
||||
fileService,
|
||||
extensionLoader,
|
||||
folderTrust,
|
||||
);
|
||||
configParams.userMemory = memoryContent;
|
||||
configParams.geminiMdFileCount = fileCount;
|
||||
configParams.geminiMdFilePaths = filePaths;
|
||||
|
||||
// Set an initial config to use to get a code assist server.
|
||||
// This is needed to fetch admin controls.
|
||||
const initialConfig = new Config({
|
||||
|
||||
@@ -17,8 +17,9 @@ describe('CommandHandler', () => {
|
||||
expect(memShow.commandToExecute?.name).toBe('memory show');
|
||||
expect(memShow.args).toBe('');
|
||||
|
||||
const memList = parse('/memory list');
|
||||
expect(memList.commandToExecute?.name).toBe('memory list');
|
||||
const memAdd = parse('/memory add hello world');
|
||||
expect(memAdd.commandToExecute?.name).toBe('memory add');
|
||||
expect(memAdd.args).toBe('hello world');
|
||||
|
||||
const extList = parse('/extensions list');
|
||||
expect(extList.commandToExecute?.name).toBe('extensions list');
|
||||
|
||||
@@ -69,10 +69,7 @@ export class AcpSessionManager {
|
||||
);
|
||||
|
||||
const authType =
|
||||
loadedSettings.merged.security.auth.selectedType ||
|
||||
(authDetails.baseUrl || process.env['GOOGLE_GEMINI_BASE_URL']
|
||||
? AuthType.GATEWAY
|
||||
: AuthType.USE_GEMINI);
|
||||
loadedSettings.merged.security.auth.selectedType || AuthType.USE_GEMINI;
|
||||
|
||||
let isAuthenticated = false;
|
||||
let authErrorMessage = '';
|
||||
@@ -234,12 +231,7 @@ export class AcpSessionManager {
|
||||
mcpServers: acp.McpServer[],
|
||||
authDetails: AuthDetails,
|
||||
): Promise<Config> {
|
||||
const selectedAuthType =
|
||||
this.settings.merged.security.auth.selectedType ||
|
||||
(authDetails.baseUrl || process.env['GOOGLE_GEMINI_BASE_URL']
|
||||
? AuthType.GATEWAY
|
||||
: undefined);
|
||||
|
||||
const selectedAuthType = this.settings.merged.security.auth.selectedType;
|
||||
if (!selectedAuthType) {
|
||||
throw acp.RequestError.authRequired();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
addMemory,
|
||||
listInboxMemoryPatches,
|
||||
listInboxSkills,
|
||||
listInboxPatches,
|
||||
@@ -18,6 +19,12 @@ import type {
|
||||
CommandExecutionResponse,
|
||||
} from './types.js';
|
||||
|
||||
const DEFAULT_SANITIZATION_CONFIG = {
|
||||
allowedEnvironmentVariables: [],
|
||||
blockedEnvironmentVariables: [],
|
||||
enableEnvironmentVariableRedaction: false,
|
||||
};
|
||||
|
||||
export class MemoryCommand implements Command {
|
||||
readonly name = 'memory';
|
||||
readonly description = 'Manage memory.';
|
||||
@@ -25,6 +32,7 @@ export class MemoryCommand implements Command {
|
||||
new ShowMemoryCommand(),
|
||||
new RefreshMemoryCommand(),
|
||||
new ListMemoryCommand(),
|
||||
new AddMemoryCommand(),
|
||||
new InboxMemoryCommand(),
|
||||
];
|
||||
readonly requiresWorkspace = true;
|
||||
@@ -77,6 +85,48 @@ export class ListMemoryCommand implements Command {
|
||||
}
|
||||
}
|
||||
|
||||
export class AddMemoryCommand implements Command {
|
||||
readonly name = 'memory add';
|
||||
readonly description = 'Add content to the memory.';
|
||||
|
||||
async execute(
|
||||
context: CommandContext,
|
||||
args: string[],
|
||||
): Promise<CommandExecutionResponse> {
|
||||
const textToAdd = args.join(' ').trim();
|
||||
const result = addMemory(textToAdd);
|
||||
if (result.type === 'message') {
|
||||
return { name: this.name, data: result.content };
|
||||
}
|
||||
|
||||
const toolRegistry = context.agentContext.toolRegistry;
|
||||
const tool = toolRegistry.getTool(result.toolName);
|
||||
if (tool) {
|
||||
const abortController = new AbortController();
|
||||
const signal = abortController.signal;
|
||||
|
||||
await context.sendMessage(`Saving memory via ${result.toolName}...`);
|
||||
|
||||
await tool.buildAndExecute(result.toolArgs, signal, undefined, {
|
||||
shellExecutionConfig: {
|
||||
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
|
||||
sandboxManager: context.agentContext.sandboxManager,
|
||||
},
|
||||
});
|
||||
await refreshMemory(context.agentContext.config);
|
||||
return {
|
||||
name: this.name,
|
||||
data: `Added memory: "${textToAdd}"`,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
name: this.name,
|
||||
data: `Error: Tool ${result.toolName} not found.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class InboxMemoryCommand implements Command {
|
||||
readonly name = 'memory inbox';
|
||||
readonly description =
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
EDIT_TOOL_NAME,
|
||||
WEB_FETCH_TOOL_NAME,
|
||||
ASK_USER_TOOL_NAME,
|
||||
type ExtensionLoader,
|
||||
debugLogger,
|
||||
ApprovalMode,
|
||||
type MCPServerConfig,
|
||||
@@ -111,6 +112,27 @@ vi.mock('@google/gemini-cli-core', async () => {
|
||||
}),
|
||||
},
|
||||
loadEnvironment: vi.fn(),
|
||||
loadServerHierarchicalMemory: vi.fn(
|
||||
(
|
||||
cwd,
|
||||
dirs,
|
||||
fileService,
|
||||
extensionLoader: ExtensionLoader,
|
||||
_folderTrust,
|
||||
_importFormat,
|
||||
_fileFilteringOptions,
|
||||
_maxDirs,
|
||||
) => {
|
||||
const extensionPaths =
|
||||
extensionLoader?.getExtensions?.()?.flatMap((e) => e.contextFiles) ||
|
||||
[];
|
||||
return Promise.resolve({
|
||||
memoryContent: extensionPaths.join(',') || '',
|
||||
fileCount: extensionPaths?.length || 0,
|
||||
filePaths: extensionPaths,
|
||||
});
|
||||
},
|
||||
),
|
||||
DEFAULT_MEMORY_FILE_FILTERING_OPTIONS: {
|
||||
respectGitIgnore: false,
|
||||
respectGeminiIgnore: true,
|
||||
@@ -1045,6 +1067,151 @@ describe('loadCliConfig', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.stubEnv('GEMINI_CLI_IDE_WORKSPACE_PATH', '');
|
||||
// Restore ExtensionManager mocks that were reset
|
||||
ExtensionManager.prototype.getExtensions = vi.fn().mockReturnValue([]);
|
||||
ExtensionManager.prototype.loadExtensions = vi
|
||||
.fn()
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
// Other common mocks would be reset here.
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should pass extension context file paths to loadServerHierarchicalMemory', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const settings = createTestMergedSettings({
|
||||
experimental: { jitContext: false },
|
||||
});
|
||||
vi.spyOn(ExtensionManager.prototype, 'getExtensions').mockReturnValue([
|
||||
{
|
||||
path: '/path/to/ext1',
|
||||
name: 'ext1',
|
||||
id: 'ext1-id',
|
||||
version: '1.0.0',
|
||||
contextFiles: ['/path/to/ext1/GEMINI.md'],
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
path: '/path/to/ext2',
|
||||
name: 'ext2',
|
||||
id: 'ext2-id',
|
||||
version: '1.0.0',
|
||||
contextFiles: [],
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
path: '/path/to/ext3',
|
||||
name: 'ext3',
|
||||
id: 'ext3-id',
|
||||
version: '1.0.0',
|
||||
contextFiles: [
|
||||
'/path/to/ext3/context1.md',
|
||||
'/path/to/ext3/context2.md',
|
||||
],
|
||||
isActive: true,
|
||||
},
|
||||
]);
|
||||
const argv = await parseArguments(createTestMergedSettings());
|
||||
await loadCliConfig(settings, 'session-id', argv);
|
||||
expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
[],
|
||||
expect.any(Object),
|
||||
expect.any(ExtensionManager),
|
||||
true,
|
||||
'tree',
|
||||
expect.objectContaining({
|
||||
respectGitIgnore: true,
|
||||
respectGeminiIgnore: true,
|
||||
}),
|
||||
200, // maxDirs
|
||||
['.git'], // boundaryMarkers
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass includeDirectories to loadServerHierarchicalMemory when loadMemoryFromIncludeDirectories is true', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const includeDir = path.resolve(path.sep, 'path', 'to', 'include');
|
||||
const settings = createTestMergedSettings({
|
||||
experimental: { jitContext: false },
|
||||
context: {
|
||||
includeDirectories: [includeDir],
|
||||
loadMemoryFromIncludeDirectories: true,
|
||||
},
|
||||
});
|
||||
|
||||
const argv = await parseArguments(settings);
|
||||
await loadCliConfig(settings, 'session-id', argv);
|
||||
|
||||
expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
[includeDir],
|
||||
expect.any(Object),
|
||||
expect.any(ExtensionManager),
|
||||
true,
|
||||
'tree',
|
||||
expect.objectContaining({
|
||||
respectGitIgnore: true,
|
||||
respectGeminiIgnore: true,
|
||||
}),
|
||||
200,
|
||||
['.git'], // boundaryMarkers
|
||||
);
|
||||
});
|
||||
|
||||
it('should NOT pass includeDirectories to loadServerHierarchicalMemory when loadMemoryFromIncludeDirectories is false', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const settings = createTestMergedSettings({
|
||||
experimental: { jitContext: false },
|
||||
context: {
|
||||
includeDirectories: ['/path/to/include'],
|
||||
loadMemoryFromIncludeDirectories: false,
|
||||
},
|
||||
});
|
||||
|
||||
const argv = await parseArguments(settings);
|
||||
await loadCliConfig(settings, 'session-id', argv);
|
||||
|
||||
expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
[],
|
||||
expect.any(Object),
|
||||
expect.any(ExtensionManager),
|
||||
true,
|
||||
'tree',
|
||||
expect.objectContaining({
|
||||
respectGitIgnore: true,
|
||||
respectGeminiIgnore: true,
|
||||
}),
|
||||
200,
|
||||
['.git'], // boundaryMarkers
|
||||
);
|
||||
});
|
||||
|
||||
it('should NOT call loadServerHierarchicalMemory when skipMemoryLoad is true', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const settings = createTestMergedSettings({
|
||||
experimental: { jitContext: false },
|
||||
});
|
||||
|
||||
const argv = await parseArguments(settings);
|
||||
await loadCliConfig(settings, 'session-id', argv, {
|
||||
skipMemoryLoad: true,
|
||||
});
|
||||
|
||||
expect(ServerConfig.loadServerHierarchicalMemory).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeMcpServers', () => {
|
||||
it('should not modify the original settings object', async () => {
|
||||
const settings = createTestMergedSettings({
|
||||
|
||||
@@ -16,19 +16,21 @@ import { hooksCommand } from '../commands/hooks.js';
|
||||
import { gemmaCommand } from '../commands/gemma.js';
|
||||
import {
|
||||
setGeminiMdFilename as setServerGeminiMdFilename,
|
||||
resetGeminiMdFilename,
|
||||
DEFAULT_CONTEXT_FILENAME,
|
||||
getCurrentGeminiMdFilename,
|
||||
ApprovalMode,
|
||||
DEFAULT_GEMINI_EMBEDDING_MODEL,
|
||||
DEFAULT_FILE_FILTERING_OPTIONS,
|
||||
DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
|
||||
FileDiscoveryService,
|
||||
resolveTelemetrySettings,
|
||||
FatalConfigError,
|
||||
getErrorMessage,
|
||||
getPty,
|
||||
debugLogger,
|
||||
loadServerHierarchicalMemory,
|
||||
ASK_USER_TOOL_NAME,
|
||||
getVersion,
|
||||
type HierarchicalMemory,
|
||||
coreEvents,
|
||||
GEMINI_MODEL_ALIAS_AUTO,
|
||||
getAdminErrorMessage,
|
||||
@@ -569,6 +571,7 @@ export interface LoadCliConfigOptions {
|
||||
};
|
||||
worktreeSettings?: WorktreeSettings;
|
||||
skipExtensions?: boolean;
|
||||
skipMemoryLoad?: boolean;
|
||||
}
|
||||
|
||||
export async function loadCliConfig(
|
||||
@@ -577,7 +580,12 @@ export async function loadCliConfig(
|
||||
argv: CliArgs,
|
||||
options: LoadCliConfigOptions = {},
|
||||
): Promise<Config> {
|
||||
const { cwd = process.cwd(), projectHooks, skipExtensions = false } = options;
|
||||
const {
|
||||
cwd = process.cwd(),
|
||||
projectHooks,
|
||||
skipExtensions = false,
|
||||
skipMemoryLoad = false,
|
||||
} = options;
|
||||
const debugMode = isDebugMode(argv);
|
||||
|
||||
const worktreeSettings =
|
||||
@@ -587,6 +595,7 @@ export async function loadCliConfig(
|
||||
process.env['GEMINI_SANDBOX'] = 'true';
|
||||
}
|
||||
|
||||
const memoryImportFormat = settings.context?.importFormat || 'tree';
|
||||
const includeDirectoryTree = settings.context?.includeDirectoryTree ?? true;
|
||||
|
||||
const ideMode = settings.ide?.enabled ?? false;
|
||||
@@ -602,7 +611,7 @@ export async function loadCliConfig(
|
||||
query: argv.query,
|
||||
})?.isTrusted ?? false;
|
||||
|
||||
// Set the context filename in the server's memory file helpers before loading memory
|
||||
// Set the context filename in the server's memoryTool module BEFORE loading memory
|
||||
// TODO(b/343434939): This is a bit of a hack. The contextFileName should ideally be passed
|
||||
// directly to the Config constructor in core, and have core handle setGeminiMdFilename.
|
||||
// However, loadHierarchicalGeminiMemory is called *before* createServerConfig.
|
||||
@@ -610,11 +619,16 @@ export async function loadCliConfig(
|
||||
setServerGeminiMdFilename(settings.context.fileName);
|
||||
} else {
|
||||
// Reset to default if not provided in settings.
|
||||
resetGeminiMdFilename(DEFAULT_CONTEXT_FILENAME);
|
||||
setServerGeminiMdFilename(getCurrentGeminiMdFilename());
|
||||
}
|
||||
|
||||
const fileService = new FileDiscoveryService(cwd);
|
||||
|
||||
const memoryFileFiltering = {
|
||||
...DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
|
||||
...settings.context?.fileFiltering,
|
||||
};
|
||||
|
||||
const fileFiltering = {
|
||||
...DEFAULT_FILE_FILTERING_OPTIONS,
|
||||
...settings.context?.fileFiltering,
|
||||
@@ -665,6 +679,8 @@ export async function loadCliConfig(
|
||||
?.getExtensions()
|
||||
?.find((ext) => ext.isActive && ext.plan?.directory)?.plan;
|
||||
|
||||
const experimentalJitContext = settings.experimental.jitContext ?? true;
|
||||
|
||||
let extensionRegistryURI =
|
||||
process.env['GEMINI_CLI_EXTENSION_REGISTRY_URI'] ??
|
||||
(trustedFolder ? settings.experimental?.extensionRegistryURI : undefined);
|
||||
@@ -675,9 +691,33 @@ export async function loadCliConfig(
|
||||
);
|
||||
}
|
||||
|
||||
let memoryContent: string | HierarchicalMemory = '';
|
||||
let fileCount = 0;
|
||||
let filePaths: string[] = [];
|
||||
|
||||
const finalExtensionLoader =
|
||||
extensionManager ?? new SimpleExtensionLoader([]);
|
||||
|
||||
if (!experimentalJitContext && !skipMemoryLoad) {
|
||||
// Call the (now wrapper) loadHierarchicalGeminiMemory which calls the server's version
|
||||
const result = await loadServerHierarchicalMemory(
|
||||
cwd,
|
||||
settings.context?.loadMemoryFromIncludeDirectories || false
|
||||
? includeDirectories
|
||||
: [],
|
||||
fileService,
|
||||
finalExtensionLoader,
|
||||
trustedFolder,
|
||||
memoryImportFormat,
|
||||
memoryFileFiltering,
|
||||
settings.context?.discoveryMaxDirs,
|
||||
settings.context?.memoryBoundaryMarkers,
|
||||
);
|
||||
memoryContent = result.memoryContent;
|
||||
fileCount = result.fileCount;
|
||||
filePaths = result.filePaths;
|
||||
}
|
||||
|
||||
const question = argv.promptInteractive || argv.prompt || '';
|
||||
|
||||
// Determine approval mode with backward compatibility
|
||||
@@ -989,6 +1029,9 @@ export async function loadCliConfig(
|
||||
settings.security?.environmentVariableRedaction?.allowed,
|
||||
enableEnvironmentVariableRedaction:
|
||||
settings.security?.environmentVariableRedaction?.enabled,
|
||||
userMemory: memoryContent,
|
||||
geminiMdFileCount: fileCount,
|
||||
geminiMdFilePaths: filePaths,
|
||||
approvalMode,
|
||||
disableYoloMode:
|
||||
settings.security?.disableYoloMode || settings.admin?.secureModeEnabled,
|
||||
@@ -1033,6 +1076,8 @@ export async function loadCliConfig(
|
||||
enableEventDrivenScheduler: true,
|
||||
skillsSupport: settings.skills?.enabled ?? true,
|
||||
disabledSkills: settings.skills?.disabled,
|
||||
experimentalJitContext,
|
||||
experimentalMemoryV2: settings.experimental?.memoryV2,
|
||||
experimentalAutoMemory: settings.experimental?.autoMemory,
|
||||
experimentalGemma: settings.experimental?.gemma,
|
||||
contextManagement,
|
||||
|
||||
@@ -109,7 +109,6 @@ describe('ExtensionManager theme loading', () => {
|
||||
getFileExclusions: () => ({
|
||||
isIgnored: () => false,
|
||||
}),
|
||||
getMemoryContextManager: () => undefined,
|
||||
getGeminiMdFilePaths: () => [],
|
||||
getMcpServers: () => ({}),
|
||||
getAllowedMcpServers: () => [],
|
||||
@@ -186,7 +185,6 @@ describe('ExtensionManager theme loading', () => {
|
||||
getWorkspaceContext: () => ({
|
||||
getDirectories: () => [],
|
||||
}),
|
||||
getMemoryContextManager: () => undefined,
|
||||
getDebugMode: () => false,
|
||||
getFileService: () => ({
|
||||
findFiles: async () => [],
|
||||
|
||||
@@ -429,16 +429,6 @@ const SETTINGS_SCHEMA = {
|
||||
'Enable the Topic & Update communication model for reduced chattiness and structured progress reporting.',
|
||||
showInDialog: true,
|
||||
},
|
||||
logRagSnippets: {
|
||||
type: 'boolean',
|
||||
label: 'Log RAG Snippets',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description:
|
||||
'Log full Code Customization (RAG) retrieved snippets to a local file for debugging.',
|
||||
showInDialog: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
output: {
|
||||
@@ -2262,6 +2252,16 @@ const SETTINGS_SCHEMA = {
|
||||
'Enables extension loading/unloading within the CLI session.',
|
||||
showInDialog: false,
|
||||
},
|
||||
jitContext: {
|
||||
type: 'boolean',
|
||||
label: 'JIT Context Loading',
|
||||
category: 'Experimental',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
description:
|
||||
'Enable Just-In-Time (JIT) context loading. Defaults to true; set to false to opt out and load all GEMINI.md files into the system instruction up-front.',
|
||||
showInDialog: false,
|
||||
},
|
||||
useOSC52Paste: {
|
||||
type: 'boolean',
|
||||
label: 'Use OSC 52 Paste',
|
||||
@@ -2392,6 +2392,16 @@ const SETTINGS_SCHEMA = {
|
||||
},
|
||||
},
|
||||
},
|
||||
memoryV2: {
|
||||
type: 'boolean',
|
||||
label: 'Memory v2',
|
||||
category: 'Experimental',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
description:
|
||||
'Disable the built-in save_memory tool and let the main agent persist project context by editing markdown files directly with edit/write_file. Route facts across four tiers: team-shared conventions go to project GEMINI.md files, project-specific personal notes go to the per-project private memory folder (MEMORY.md as index + sibling .md files for detail), and cross-project personal preferences go to the global ~/.gemini/GEMINI.md (the only file under ~/.gemini/ that the agent can edit — settings, credentials, etc. remain off-limits). Set to false to fall back to the legacy save_memory tool.',
|
||||
showInDialog: true,
|
||||
},
|
||||
stressTestProfile: {
|
||||
type: 'boolean',
|
||||
label:
|
||||
|
||||
@@ -26,6 +26,11 @@ vi.mock('@google/gemini-cli-core', async () => {
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
loadServerHierarchicalMemory: vi.fn().mockResolvedValue({
|
||||
memoryContent: '',
|
||||
fileCount: 0,
|
||||
filePaths: [],
|
||||
}),
|
||||
createPolicyEngineConfig: vi.fn().mockResolvedValue({
|
||||
rules: [],
|
||||
checkers: [],
|
||||
|
||||
@@ -499,6 +499,7 @@ export async function main() {
|
||||
const partialConfig = await loadCliConfig(settings.merged, sessionId, argv, {
|
||||
projectHooks: settings.workspace.settings.hooks,
|
||||
skipExtensions: true,
|
||||
skipMemoryLoad: true,
|
||||
});
|
||||
|
||||
adminControlsListner.setConfig(partialConfig);
|
||||
|
||||
@@ -38,6 +38,7 @@ export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
|
||||
fireSessionEndEvent: vi.fn().mockResolvedValue(undefined),
|
||||
fireSessionStartEvent: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
isMemoryV2Enabled: vi.fn(() => false),
|
||||
isAutoMemoryEnabled: vi.fn(() => false),
|
||||
getListExtensions: vi.fn(() => false),
|
||||
getExtensions: vi.fn(() => []),
|
||||
@@ -165,6 +166,7 @@ export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
|
||||
getEnableEventDrivenScheduler: vi.fn().mockReturnValue(false),
|
||||
getAdminSkillsEnabled: vi.fn().mockReturnValue(false),
|
||||
getDisabledSkills: vi.fn().mockReturnValue([]),
|
||||
getExperimentalJitContext: vi.fn().mockReturnValue(false),
|
||||
getExperimentalGemma: vi.fn().mockReturnValue(false),
|
||||
getMemoryBoundaryMarkers: vi.fn().mockReturnValue(['.git']),
|
||||
getTerminalBackground: vi.fn().mockReturnValue(undefined),
|
||||
|
||||
@@ -70,6 +70,7 @@ import {
|
||||
debugLogger,
|
||||
coreEvents,
|
||||
CoreEvent,
|
||||
refreshServerHierarchicalMemory,
|
||||
flattenMemory,
|
||||
type MemoryChangedPayload,
|
||||
writeToStdout,
|
||||
@@ -1074,10 +1075,19 @@ Logging in with Google... Restarting Gemini CLI to continue.
|
||||
Date.now(),
|
||||
);
|
||||
try {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
config.updateSystemInstructionIfInitialized();
|
||||
const flattenedMemory = flattenMemory(config.getUserMemory());
|
||||
const fileCount = config.getGeminiMdFileCount();
|
||||
let flattenedMemory: string;
|
||||
let fileCount: number;
|
||||
|
||||
if (config.isJitContextEnabled()) {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
config.updateSystemInstructionIfInitialized();
|
||||
flattenedMemory = flattenMemory(config.getUserMemory());
|
||||
fileCount = config.getGeminiMdFileCount();
|
||||
} else {
|
||||
const result = await refreshServerHierarchicalMemory(config);
|
||||
flattenedMemory = flattenMemory(result.memoryContent);
|
||||
fileCount = result.fileCount;
|
||||
}
|
||||
|
||||
historyManager.addItem(
|
||||
{
|
||||
|
||||
@@ -80,7 +80,6 @@ describe('directoryCommand', () => {
|
||||
}),
|
||||
getWorkingDir: () => path.resolve('/test/dir'),
|
||||
shouldLoadMemoryFromIncludeDirectories: () => false,
|
||||
getMemoryContextManager: vi.fn(),
|
||||
getDebugMode: () => false,
|
||||
getFileService: () => ({}),
|
||||
getFileFilteringOptions: () => ({ ignore: [], include: [] }),
|
||||
|
||||
@@ -15,7 +15,10 @@ import {
|
||||
type CommandContext,
|
||||
} from './types.js';
|
||||
import { MessageType, type HistoryItem } from '../types.js';
|
||||
import { type Config } from '@google/gemini-cli-core';
|
||||
import {
|
||||
refreshServerHierarchicalMemory,
|
||||
type Config,
|
||||
} from '@google/gemini-cli-core';
|
||||
import {
|
||||
expandHomeDir,
|
||||
getDirectorySuggestions,
|
||||
@@ -44,7 +47,7 @@ async function finishAddingDirectories(
|
||||
if (added.length > 0) {
|
||||
try {
|
||||
if (config.shouldLoadMemoryFromIncludeDirectories()) {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
await refreshServerHierarchicalMemory(config);
|
||||
}
|
||||
addItem({
|
||||
type: MessageType.INFO,
|
||||
|
||||
@@ -11,10 +11,13 @@ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js
|
||||
import { MessageType } from '../types.js';
|
||||
import type { LoadedSettings } from '../../config/settings.js';
|
||||
import {
|
||||
type Config,
|
||||
refreshMemory,
|
||||
refreshServerHierarchicalMemory,
|
||||
SimpleExtensionLoader,
|
||||
type FileDiscoveryService,
|
||||
showMemory,
|
||||
addMemory,
|
||||
listMemoryFiles,
|
||||
flattenMemory,
|
||||
} from '@google/gemini-cli-core';
|
||||
@@ -29,28 +32,46 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
return String(error);
|
||||
}),
|
||||
refreshMemory: vi.fn(async (config) => {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
const memoryContent = original.flattenMemory(config.getUserMemory());
|
||||
const fileCount = config.getGeminiMdFileCount() || 0;
|
||||
if (config.isJitContextEnabled()) {
|
||||
await config.getContextManager()?.refresh();
|
||||
const memoryContent = original.flattenMemory(config.getUserMemory());
|
||||
const fileCount = config.getGeminiMdFileCount() || 0;
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: `Memory reloaded successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: `Memory reloaded successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`,
|
||||
content: 'Memory reloaded successfully.',
|
||||
};
|
||||
}),
|
||||
showMemory: vi.fn(),
|
||||
addMemory: vi.fn(),
|
||||
listMemoryFiles: vi.fn(),
|
||||
refreshServerHierarchicalMemory: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const mockRefreshMemory = refreshMemory as Mock;
|
||||
const mockRefreshServerHierarchicalMemory =
|
||||
refreshServerHierarchicalMemory as Mock;
|
||||
|
||||
describe('memoryCommand', () => {
|
||||
let mockContext: CommandContext;
|
||||
|
||||
const buildMemoryCommand = (): SlashCommand => memoryCommand(null);
|
||||
const buildMemoryCommand = (isMemoryV2 = false): SlashCommand => {
|
||||
const config: Pick<Config, 'isMemoryV2Enabled'> = {
|
||||
isMemoryV2Enabled: () => isMemoryV2,
|
||||
};
|
||||
return memoryCommand(config as Config);
|
||||
};
|
||||
|
||||
const getSubCommand = (name: 'show' | 'reload' | 'list'): SlashCommand => {
|
||||
const getSubCommand = (
|
||||
name: 'show' | 'add' | 'reload' | 'list',
|
||||
): SlashCommand => {
|
||||
const subCommand = buildMemoryCommand().subCommands?.find(
|
||||
(cmd) => cmd.name === name,
|
||||
);
|
||||
@@ -60,11 +81,23 @@ describe('memoryCommand', () => {
|
||||
return subCommand;
|
||||
};
|
||||
|
||||
describe('subcommands', () => {
|
||||
it('does not include the legacy add subcommand', () => {
|
||||
const command = buildMemoryCommand();
|
||||
describe('Memory v2', () => {
|
||||
it('omits the /memory add subcommand when memoryV2 is enabled', () => {
|
||||
const command = buildMemoryCommand(true);
|
||||
const names = command.subCommands?.map((cmd) => cmd.name) ?? [];
|
||||
expect(names).toEqual(['show', 'reload', 'list', 'inbox']);
|
||||
expect(names).not.toContain('add');
|
||||
});
|
||||
|
||||
it('includes the /memory add subcommand by default', () => {
|
||||
const command = buildMemoryCommand(false);
|
||||
const names = command.subCommands?.map((cmd) => cmd.name) ?? [];
|
||||
expect(names).toContain('add');
|
||||
});
|
||||
|
||||
it('includes the /memory add subcommand when no config is provided', () => {
|
||||
const command = memoryCommand(null);
|
||||
const names = command.subCommands?.map((cmd) => cmd.name) ?? [];
|
||||
expect(names).toContain('add');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -145,6 +178,63 @@ describe('memoryCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('/memory add', () => {
|
||||
let addCommand: SlashCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
addCommand = getSubCommand('add');
|
||||
vi.mocked(addMemory).mockImplementation((args) => {
|
||||
if (!args || args.trim() === '') {
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'error',
|
||||
content: 'Usage: /memory add <text to remember>',
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'tool',
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact: args.trim() },
|
||||
};
|
||||
});
|
||||
mockContext = createMockCommandContext();
|
||||
});
|
||||
|
||||
it('should return an error message if no arguments are provided', () => {
|
||||
if (!addCommand.action) throw new Error('Command has no action');
|
||||
|
||||
const result = addCommand.action(mockContext, ' ');
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
messageType: 'error',
|
||||
content: 'Usage: /memory add <text to remember>',
|
||||
});
|
||||
|
||||
expect(mockContext.ui.addItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return a tool action and add an info message when arguments are provided', () => {
|
||||
if (!addCommand.action) throw new Error('Command has no action');
|
||||
|
||||
const fact = 'remember this';
|
||||
const result = addCommand.action(mockContext, ` ${fact} `);
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: `Attempting to save to memory: "${fact}"`,
|
||||
},
|
||||
expect.any(Number),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
type: 'tool',
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('/memory reload', () => {
|
||||
let reloadCommand: SlashCommand;
|
||||
let mockSetUserMemory: Mock;
|
||||
@@ -180,7 +270,8 @@ describe('memoryCommand', () => {
|
||||
updateSystemInstructionIfInitialized: vi
|
||||
.fn()
|
||||
.mockResolvedValue(undefined),
|
||||
getMemoryContextManager: vi.fn().mockReturnValue({
|
||||
isJitContextEnabled: vi.fn().mockReturnValue(false),
|
||||
getContextManager: vi.fn().mockReturnValue({
|
||||
refresh: mockContextManagerRefresh,
|
||||
}),
|
||||
getUserMemory: vi.fn().mockReturnValue(''),
|
||||
@@ -203,18 +294,21 @@ describe('memoryCommand', () => {
|
||||
mockRefreshMemory.mockClear();
|
||||
});
|
||||
|
||||
it('should use MemoryContextManager.refresh', async () => {
|
||||
it('should use ContextManager.refresh when JIT is enabled', async () => {
|
||||
if (!reloadCommand.action) throw new Error('Command has no action');
|
||||
|
||||
// Enable JIT in mock config
|
||||
const config = mockContext.services.agentContext?.config;
|
||||
if (!config) throw new Error('Config is undefined');
|
||||
|
||||
vi.mocked(config.isJitContextEnabled).mockReturnValue(true);
|
||||
vi.mocked(config.getUserMemory).mockReturnValue('JIT Memory Content');
|
||||
vi.mocked(config.getGeminiMdFileCount).mockReturnValue(3);
|
||||
|
||||
await reloadCommand.action(mockContext, '');
|
||||
|
||||
expect(mockContextManagerRefresh).toHaveBeenCalledOnce();
|
||||
expect(mockRefreshServerHierarchicalMemory).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
|
||||
{
|
||||
@@ -225,7 +319,7 @@ describe('memoryCommand', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should display success message when memory is reloaded with content', async () => {
|
||||
it('should display success message when memory is reloaded with content (Legacy)', async () => {
|
||||
if (!reloadCommand.action) throw new Error('Command has no action');
|
||||
|
||||
const successMessage = {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
addMemory,
|
||||
type Config,
|
||||
listMemoryFiles,
|
||||
refreshMemory,
|
||||
@@ -40,6 +41,30 @@ const showSubCommand: SlashCommand = {
|
||||
},
|
||||
};
|
||||
|
||||
const addSubCommand: SlashCommand = {
|
||||
name: 'add',
|
||||
description: 'Add content to the memory',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
autoExecute: false,
|
||||
action: (context, args): SlashCommandActionReturn | void => {
|
||||
const result = addMemory(args);
|
||||
|
||||
if (result.type === 'message') {
|
||||
return result;
|
||||
}
|
||||
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: `Attempting to save to memory: "${args.trim()}"`,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
const reloadSubCommand: SlashCommand = {
|
||||
name: 'reload',
|
||||
altNames: ['refresh'],
|
||||
@@ -145,9 +170,14 @@ const inboxSubCommand: SlashCommand = {
|
||||
},
|
||||
};
|
||||
|
||||
export const memoryCommand = (_config: Config | null): SlashCommand => {
|
||||
export const memoryCommand = (config: Config | null): SlashCommand => {
|
||||
// The `add` subcommand depends on the `save_memory` tool, which is not
|
||||
// registered when Memory v2 is enabled. Omit it in that case.
|
||||
const isMemoryV2 = config?.isMemoryV2Enabled() ?? false;
|
||||
|
||||
const subCommands: SlashCommand[] = [
|
||||
showSubCommand,
|
||||
...(isMemoryV2 ? [] : [addSubCommand]),
|
||||
reloadSubCommand,
|
||||
listSubCommand,
|
||||
inboxSubCommand,
|
||||
|
||||
@@ -1962,8 +1962,8 @@ describe('InputPrompt', () => {
|
||||
},
|
||||
{
|
||||
name: 'should NOT trigger completion when cursor is after space following /',
|
||||
text: '/memory list',
|
||||
cursor: [0, 12],
|
||||
text: '/memory add',
|
||||
cursor: [0, 11],
|
||||
showSuggestions: false,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -174,6 +174,27 @@ exports[`InputPrompt > mouse interaction > should toggle paste expansion on doub
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`InputPrompt > mouse interaction > should toggle paste expansion on double-click 4`] = `
|
||||
"▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
|
||||
> [Pasted Text: 10 lines]
|
||||
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`InputPrompt > mouse interaction > should toggle paste expansion on double-click 5`] = `
|
||||
"▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
|
||||
> [Pasted Text: 10 lines]
|
||||
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`InputPrompt > mouse interaction > should toggle paste expansion on double-click 6`] = `
|
||||
"▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
|
||||
> [Pasted Text: 10 lines]
|
||||
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`InputPrompt > multiline rendering > should correctly render multiline input including blank lines 1`] = `
|
||||
"────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
> hello
|
||||
|
||||
@@ -144,6 +144,7 @@ export const INFORMATIVE_TIPS = [
|
||||
'Authenticate with an OAuth-enabled MCP server with /mcp auth',
|
||||
'Reload MCP servers with /mcp reload',
|
||||
'See the current instructional context with /memory show',
|
||||
'Add content to the instructional memory with /memory add',
|
||||
'Reload instructional context from GEMINI.md files with /memory reload',
|
||||
'List the paths of the GEMINI.md files in use with /memory list',
|
||||
'Choose your Gemini model with /model',
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
type Mock,
|
||||
} from 'vitest';
|
||||
import {
|
||||
checkPermissions,
|
||||
handleAtCommand,
|
||||
escapeAtSymbols,
|
||||
unescapeLiteralAt,
|
||||
@@ -36,7 +35,6 @@ import {
|
||||
import * as core from '@google/gemini-cli-core';
|
||||
import * as os from 'node:os';
|
||||
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
|
||||
import * as fs from 'node:fs';
|
||||
import * as fsPromises from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
|
||||
@@ -96,7 +94,6 @@ describe('handleAtCommand', () => {
|
||||
p.startsWith(testRootDir) || p.startsWith('/private' + testRootDir),
|
||||
getDirectories: () => [testRootDir],
|
||||
}),
|
||||
getMemoryContextManager: () => undefined,
|
||||
storage: {
|
||||
getProjectTempDir: () => path.join(os.tmpdir(), 'gemini-cli-temp'),
|
||||
},
|
||||
@@ -1543,57 +1540,3 @@ describe('unescapeLiteralAt', () => {
|
||||
expect(unescapeLiteralAt(escapeAtSymbols(input))).toBe(input);
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkPermissions', () => {
|
||||
let testRootDir: string;
|
||||
let mockConfig: Config;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
testRootDir = await fsPromises.mkdtemp(
|
||||
path.join(os.tmpdir(), 'check-permissions-test-'),
|
||||
);
|
||||
|
||||
mockConfig = {
|
||||
getTargetDir: () => testRootDir,
|
||||
getAgentRegistry: () => ({
|
||||
getDefinition: () => undefined,
|
||||
}),
|
||||
getResourceRegistry: () => ({
|
||||
findResourceByUri: () => undefined,
|
||||
getAllResources: () => [],
|
||||
}),
|
||||
validatePathAccess: () => null,
|
||||
} as unknown as Config;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fsPromises.rm(testRootDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Regression for #22029 (and related #25910 / #25923): when a user pastes
|
||||
// a JSON-like blob after an @, the @-command regex greedily captures it.
|
||||
// The resolved string is longer than NAME_MAX, so fs.realpathSync throws
|
||||
// ENAMETOOLONG. Previously this bubbled up as an unhandled rejection and
|
||||
// crashed the CLI.
|
||||
it('skips @-mentions whose path is too long to be a real filesystem entry', async () => {
|
||||
const longSegment = 'a'.repeat(8192);
|
||||
const query = `@${longSegment}`;
|
||||
await expect(checkPermissions(query, mockConfig)).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it('still surfaces real @-mentioned files when a sibling @-mention is unresolvable', async () => {
|
||||
// A real file alongside a giant pasted-blob mention: the bogus mention
|
||||
// should be skipped, the real one should still appear in the result.
|
||||
const realFile = path.join(testRootDir, 'real.txt');
|
||||
await fsPromises.writeFile(realFile, 'hello');
|
||||
const resolvedRealFile = fs.realpathSync(realFile);
|
||||
mockConfig.validatePathAccess = () =>
|
||||
'permission required' as unknown as null;
|
||||
const longSegment = 'b'.repeat(8192);
|
||||
const query = `@real.txt and @${longSegment}`;
|
||||
await expect(checkPermissions(query, mockConfig)).resolves.toEqual([
|
||||
resolvedRealFile,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -188,15 +188,9 @@ export async function checkPermissions(
|
||||
const pathName = part.content.substring(1);
|
||||
if (!pathName) continue;
|
||||
|
||||
let resolvedPathName: string;
|
||||
try {
|
||||
resolvedPathName = resolveToRealPath(
|
||||
path.resolve(config.getTargetDir(), pathName),
|
||||
);
|
||||
} catch {
|
||||
// skip if resolveToRealPath errors out
|
||||
continue;
|
||||
}
|
||||
const resolvedPathName = resolveToRealPath(
|
||||
path.resolve(config.getTargetDir(), pathName),
|
||||
);
|
||||
|
||||
if (config.validatePathAccess(resolvedPathName, 'read')) {
|
||||
if (await fileExists(resolvedPathName)) {
|
||||
|
||||
@@ -352,6 +352,7 @@ describe('useGeminiStream', () => {
|
||||
isInteractive: () => false,
|
||||
getExperiments: () => {},
|
||||
getMaxSessionTurns: vi.fn(() => 100),
|
||||
isJitContextEnabled: vi.fn(() => false),
|
||||
getGlobalMemory: vi.fn(() => ''),
|
||||
getUserMemory: vi.fn(() => ''),
|
||||
getMessageBus: vi.fn(() => mockMessageBus),
|
||||
@@ -1950,23 +1951,23 @@ describe('useGeminiStream', () => {
|
||||
it('should schedule a tool call when the command processor returns a schedule_tool action', async () => {
|
||||
const clientToolRequest: SlashCommandProcessorResult = {
|
||||
type: 'schedule_tool',
|
||||
toolName: 'activate_skill',
|
||||
toolArgs: { name: 'test-skill' },
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact: 'test fact' },
|
||||
};
|
||||
mockHandleSlashCommand.mockResolvedValue(clientToolRequest);
|
||||
|
||||
const { result } = await renderTestHook();
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitQuery('/memory show');
|
||||
await result.current.submitQuery('/memory add "test fact"');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockScheduleToolCalls).toHaveBeenCalledWith(
|
||||
[
|
||||
expect.objectContaining({
|
||||
name: 'activate_skill',
|
||||
args: { name: 'test-skill' },
|
||||
name: 'save_memory',
|
||||
args: { fact: 'test fact' },
|
||||
isClientInitiated: true,
|
||||
}),
|
||||
],
|
||||
@@ -2194,25 +2195,25 @@ describe('useGeminiStream', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should NOT record other client-initiated tool calls in history', async () => {
|
||||
it('should NOT record other client-initiated tool calls (like save_memory) in history', async () => {
|
||||
const { result, client: mockGeminiClient } = await renderTestHook();
|
||||
|
||||
mockHandleSlashCommand.mockResolvedValue({
|
||||
type: 'schedule_tool',
|
||||
toolName: 'write_todos',
|
||||
toolArgs: { todos: [] },
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact: 'test fact' },
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitQuery('/todos');
|
||||
await result.current.submitQuery('/memory add "test fact"');
|
||||
});
|
||||
|
||||
// Simulate tool completion
|
||||
const completedTool = {
|
||||
request: {
|
||||
callId: 'test-call-id',
|
||||
name: 'write_todos',
|
||||
args: { todos: [] },
|
||||
name: 'save_memory',
|
||||
args: { fact: 'test fact' },
|
||||
isClientInitiated: true,
|
||||
},
|
||||
status: CoreToolCallStatus.Success,
|
||||
@@ -2226,7 +2227,7 @@ describe('useGeminiStream', () => {
|
||||
responseParts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'write_todos',
|
||||
name: 'save_memory',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
@@ -2245,6 +2246,91 @@ describe('useGeminiStream', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Memory Refresh on save_memory', () => {
|
||||
it('should call performMemoryRefresh when a save_memory tool call completes successfully', async () => {
|
||||
const mockPerformMemoryRefresh = vi.fn();
|
||||
const completedToolCall: TrackedCompletedToolCall = {
|
||||
request: {
|
||||
callId: 'save-mem-call-1',
|
||||
name: 'save_memory',
|
||||
args: { fact: 'test' },
|
||||
isClientInitiated: true,
|
||||
prompt_id: 'prompt-id-6',
|
||||
},
|
||||
status: CoreToolCallStatus.Success,
|
||||
responseSubmittedToGemini: false,
|
||||
response: {
|
||||
callId: 'save-mem-call-1',
|
||||
responseParts: [{ text: 'Memory saved' }],
|
||||
resultDisplay: 'Success: Memory saved',
|
||||
error: undefined,
|
||||
errorType: undefined, // FIX: Added missing property
|
||||
},
|
||||
tool: {
|
||||
name: 'save_memory',
|
||||
displayName: 'save_memory',
|
||||
description: 'Saves memory',
|
||||
build: vi.fn(),
|
||||
} as unknown as AnyDeclarativeTool,
|
||||
invocation: {
|
||||
getDescription: () => `Mock description`,
|
||||
} as unknown as AnyToolInvocation,
|
||||
};
|
||||
|
||||
// Capture the onComplete callback
|
||||
let capturedOnComplete:
|
||||
| ((completedTools: TrackedToolCall[]) => Promise<void>)
|
||||
| null = null;
|
||||
|
||||
mockUseToolScheduler.mockImplementation((onComplete) => {
|
||||
capturedOnComplete = onComplete;
|
||||
return [
|
||||
[],
|
||||
mockScheduleToolCalls,
|
||||
mockMarkToolsAsSubmitted,
|
||||
vi.fn(),
|
||||
mockCancelAllToolCalls,
|
||||
0,
|
||||
];
|
||||
});
|
||||
|
||||
await renderHookWithProviders(() =>
|
||||
useGeminiStream(
|
||||
new MockedGeminiClientClass(mockConfig),
|
||||
[],
|
||||
mockAddItem,
|
||||
mockConfig,
|
||||
mockLoadedSettings,
|
||||
mockOnDebugMessage,
|
||||
mockHandleSlashCommand,
|
||||
false,
|
||||
() => 'vscode' as EditorType,
|
||||
() => {},
|
||||
mockPerformMemoryRefresh,
|
||||
false,
|
||||
() => {},
|
||||
() => {},
|
||||
() => {},
|
||||
80,
|
||||
24,
|
||||
),
|
||||
);
|
||||
|
||||
// Trigger the onComplete callback with the completed save_memory tool
|
||||
await act(async () => {
|
||||
if (capturedOnComplete) {
|
||||
// Wait a tick for refs to be set up
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await capturedOnComplete([completedToolCall]);
|
||||
}
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPerformMemoryRefresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should call parseAndFormatApiError with the correct authType on stream initialization failure', async () => {
|
||||
// 1. Setup
|
||||
|
||||
@@ -226,7 +226,7 @@ export const useGeminiStream = (
|
||||
shellModeActive: boolean,
|
||||
getPreferredEditor: () => EditorType | undefined,
|
||||
onAuthError: (error: string) => void,
|
||||
_performMemoryRefresh: () => Promise<void>,
|
||||
performMemoryRefresh: () => Promise<void>,
|
||||
modelSwitchedFromQuotaError: boolean,
|
||||
setModelSwitchedFromQuotaError: React.Dispatch<React.SetStateAction<boolean>>,
|
||||
onCancelSubmit: (
|
||||
@@ -266,6 +266,7 @@ export const useGeminiStream = (
|
||||
useStateAndRef<Set<string>>(new Set());
|
||||
const [_isFirstToolInGroup, isFirstToolInGroupRef, setIsFirstToolInGroup] =
|
||||
useStateAndRef<boolean>(true);
|
||||
const processedMemoryToolsRef = useRef<Set<string>>(new Set());
|
||||
const { startNewPrompt, getPromptCount } = useSessionStats();
|
||||
const logger = useLogger(config);
|
||||
const gitService = useMemo(() => {
|
||||
@@ -1896,8 +1897,8 @@ export const useGeminiStream = (
|
||||
if (geminiClient) {
|
||||
for (const tool of clientTools) {
|
||||
// Only manually record skill activations in the chat history.
|
||||
// Other client-initiated tools update context and don't strictly
|
||||
// need to be in the history.
|
||||
// Other client-initiated tools (like save_memory) update the system
|
||||
// prompt/context and don't strictly need to be in the history.
|
||||
if (tool.request.name !== ACTIVATE_SKILL_TOOL_NAME) {
|
||||
continue;
|
||||
}
|
||||
@@ -1924,6 +1925,14 @@ export const useGeminiStream = (
|
||||
}
|
||||
}
|
||||
|
||||
// Identify new, successful save_memory calls that we haven't processed yet.
|
||||
const newSuccessfulMemorySaves = completedAndReadyToSubmitTools.filter(
|
||||
(t) =>
|
||||
t.request.name === 'save_memory' &&
|
||||
t.status === 'success' &&
|
||||
!processedMemoryToolsRef.current.has(t.request.callId),
|
||||
);
|
||||
|
||||
for (const toolCall of completedAndReadyToSubmitTools) {
|
||||
const backgroundedTool = getBackgroundedToolInfo(toolCall);
|
||||
if (backgroundedTool) {
|
||||
@@ -1935,6 +1944,15 @@ export const useGeminiStream = (
|
||||
}
|
||||
}
|
||||
|
||||
if (newSuccessfulMemorySaves.length > 0) {
|
||||
// Perform the refresh only if there are new ones.
|
||||
void performMemoryRefresh();
|
||||
// Mark them as processed so we don't do this again on the next render.
|
||||
newSuccessfulMemorySaves.forEach((t) =>
|
||||
processedMemoryToolsRef.current.add(t.request.callId),
|
||||
);
|
||||
}
|
||||
|
||||
const geminiTools = completedAndReadyToSubmitTools.filter(
|
||||
(t) => !t.request.isClientInitiated,
|
||||
);
|
||||
@@ -2058,6 +2076,7 @@ export const useGeminiStream = (
|
||||
submitQuery,
|
||||
markToolsAsSubmitted,
|
||||
geminiClient,
|
||||
performMemoryRefresh,
|
||||
modelSwitchedFromQuotaError,
|
||||
addItem,
|
||||
registerBackgroundTask,
|
||||
|
||||
@@ -80,8 +80,6 @@ describe('useIncludeDirsTrust', () => {
|
||||
clearPendingIncludeDirectories: vi.fn(),
|
||||
getFolderTrust: vi.fn().mockReturnValue(true),
|
||||
getWorkspaceContext: () => mockWorkspaceContext,
|
||||
shouldLoadMemoryFromIncludeDirectories: vi.fn().mockReturnValue(false),
|
||||
getMemoryContextManager: vi.fn(),
|
||||
getGeminiClient: vi
|
||||
.fn()
|
||||
.mockReturnValue({ addDirectoryContext: vi.fn() }),
|
||||
|
||||
@@ -8,7 +8,10 @@ import { useEffect } from 'react';
|
||||
import { type Config } from '@google/gemini-cli-core';
|
||||
import { loadTrustedFolders } from '../../config/trustedFolders.js';
|
||||
import { expandHomeDir, batchAddDirectories } from '../utils/directoryUtils.js';
|
||||
import { debugLogger } from '@google/gemini-cli-core';
|
||||
import {
|
||||
debugLogger,
|
||||
refreshServerHierarchicalMemory,
|
||||
} from '@google/gemini-cli-core';
|
||||
import { MultiFolderTrustDialog } from '../components/MultiFolderTrustDialog.js';
|
||||
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
|
||||
import { MessageType, type HistoryItem } from '../types.js';
|
||||
@@ -32,7 +35,7 @@ async function finishAddingDirectories(
|
||||
|
||||
try {
|
||||
if (config.shouldLoadMemoryFromIncludeDirectories()) {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
await refreshServerHierarchicalMemory(config);
|
||||
}
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
|
||||
@@ -17,6 +17,11 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
return {
|
||||
...original,
|
||||
homedir: () => mockHomeDir,
|
||||
loadServerHierarchicalMemory: vi.fn().mockResolvedValue({
|
||||
memoryContent: 'mock memory',
|
||||
fileCount: 10,
|
||||
filePaths: ['/a/b/c.md'],
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ const mockCommands: readonly SlashCommand[] = [
|
||||
altNames: ['mem'],
|
||||
subCommands: [
|
||||
{
|
||||
name: 'list',
|
||||
description: 'List memory files',
|
||||
name: 'add',
|
||||
description: 'Add to memory',
|
||||
action: async () => {},
|
||||
kind: CommandKind.BUILT_IN,
|
||||
},
|
||||
@@ -64,27 +64,27 @@ describe('parseSlashCommand', () => {
|
||||
});
|
||||
|
||||
it('should parse a subcommand', () => {
|
||||
const result = parseSlashCommand('/memory list', mockCommands);
|
||||
expect(result.commandToExecute?.name).toBe('list');
|
||||
const result = parseSlashCommand('/memory add', mockCommands);
|
||||
expect(result.commandToExecute?.name).toBe('add');
|
||||
expect(result.args).toBe('');
|
||||
expect(result.canonicalPath).toEqual(['memory', 'list']);
|
||||
expect(result.canonicalPath).toEqual(['memory', 'add']);
|
||||
});
|
||||
|
||||
it('should parse a subcommand with arguments', () => {
|
||||
const result = parseSlashCommand(
|
||||
'/memory list some important data',
|
||||
'/memory add some important data',
|
||||
mockCommands,
|
||||
);
|
||||
expect(result.commandToExecute?.name).toBe('list');
|
||||
expect(result.commandToExecute?.name).toBe('add');
|
||||
expect(result.args).toBe('some important data');
|
||||
expect(result.canonicalPath).toEqual(['memory', 'list']);
|
||||
expect(result.canonicalPath).toEqual(['memory', 'add']);
|
||||
});
|
||||
|
||||
it('should handle a command alias', () => {
|
||||
const result = parseSlashCommand('/mem list some data', mockCommands);
|
||||
expect(result.commandToExecute?.name).toBe('list');
|
||||
const result = parseSlashCommand('/mem add some data', mockCommands);
|
||||
expect(result.commandToExecute?.name).toBe('add');
|
||||
expect(result.args).toBe('some data');
|
||||
expect(result.canonicalPath).toEqual(['memory', 'list']);
|
||||
expect(result.canonicalPath).toEqual(['memory', 'add']);
|
||||
});
|
||||
|
||||
it('should handle a subcommand alias', () => {
|
||||
@@ -113,12 +113,12 @@ describe('parseSlashCommand', () => {
|
||||
|
||||
it('should handle extra whitespace', () => {
|
||||
const result = parseSlashCommand(
|
||||
' /memory list some data ',
|
||||
' /memory add some data ',
|
||||
mockCommands,
|
||||
);
|
||||
expect(result.commandToExecute?.name).toBe('list');
|
||||
expect(result.commandToExecute?.name).toBe('add');
|
||||
expect(result.args).toBe('some data');
|
||||
expect(result.canonicalPath).toEqual(['memory', 'list']);
|
||||
expect(result.canonicalPath).toEqual(['memory', 'add']);
|
||||
});
|
||||
|
||||
it('should return undefined if query does not start with a slash', () => {
|
||||
|
||||
@@ -16,7 +16,7 @@ export type ParsedSlashCommand = {
|
||||
* Parses a raw slash command string into its command, arguments, and canonical path.
|
||||
* If no valid command is found, the `commandToExecute` property will be `undefined`.
|
||||
*
|
||||
* @param query The raw input string, e.g., "/memory show" or "/help".
|
||||
* @param query The raw input string, e.g., "/memory add some data" or "/help".
|
||||
* @param commands The list of available top-level slash commands.
|
||||
* @returns An object containing the resolved command, its arguments, and its canonical path.
|
||||
*/
|
||||
|
||||
@@ -336,14 +336,7 @@ describe('sandbox', () => {
|
||||
await expect(promise).resolves.toBe(0);
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'docker',
|
||||
expect.arrayContaining([
|
||||
'run',
|
||||
'-i',
|
||||
'--rm',
|
||||
'--init',
|
||||
'--entrypoint',
|
||||
'',
|
||||
]),
|
||||
expect.arrayContaining(['run', '-i', '--rm', '--init']),
|
||||
expect.objectContaining({ stdio: 'inherit' }),
|
||||
);
|
||||
|
||||
@@ -794,67 +787,12 @@ describe('sandbox', () => {
|
||||
expect.arrayContaining(['--user', 'root', '--env', 'HOME=/home/user']),
|
||||
expect.any(Object),
|
||||
);
|
||||
// Check that the entrypoint command includes the defensive useradd check
|
||||
// Check that the entrypoint command includes useradd/groupadd
|
||||
const args = vi.mocked(spawn).mock.calls[1][1] as string[];
|
||||
const entrypointCmd = args[args.length - 1];
|
||||
expect(entrypointCmd).toContain('if command -v useradd');
|
||||
expect(entrypointCmd).toContain('groupadd -g 1000 -o gemini');
|
||||
expect(entrypointCmd).toContain('id 1000');
|
||||
expect(entrypointCmd).toContain('useradd -o -u 1000');
|
||||
expect(entrypointCmd).toContain('USER_NAME=$(id -nu 1000 2>/dev/null);');
|
||||
expect(entrypointCmd).toContain('if [ -n "$USER_NAME" ]; then');
|
||||
expect(entrypointCmd).toContain('su -p "$USER_NAME"');
|
||||
expect(entrypointCmd).toContain('else');
|
||||
expect(entrypointCmd).toContain('Error: Failed to map host UID 1000');
|
||||
expect(entrypointCmd).toContain('exit 1');
|
||||
expect(entrypointCmd).toContain("Error: 'useradd' not found");
|
||||
});
|
||||
|
||||
it('should correctly escape home directory with spaces and special characters', async () => {
|
||||
const config: SandboxConfig = createMockSandboxConfig({
|
||||
command: 'docker',
|
||||
image: 'gemini-cli-sandbox',
|
||||
});
|
||||
process.env['SANDBOX_SET_UID_GID'] = 'true';
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
|
||||
const specialHome = '/home/user name `$(id)`';
|
||||
mockedHomedir.mockReturnValue(specialHome);
|
||||
mockedGetContainerPath.mockImplementation((p: string) => p);
|
||||
|
||||
// Mock image check to return true
|
||||
interface MockProcessWithStdout extends EventEmitter {
|
||||
stdout: EventEmitter;
|
||||
}
|
||||
const mockImageCheckProcess = new EventEmitter() as MockProcessWithStdout;
|
||||
mockImageCheckProcess.stdout = new EventEmitter();
|
||||
vi.mocked(spawn).mockImplementationOnce(() => {
|
||||
setTimeout(() => {
|
||||
mockImageCheckProcess.stdout.emit('data', Buffer.from('image-id'));
|
||||
mockImageCheckProcess.emit('close', 0);
|
||||
}, 1);
|
||||
return mockImageCheckProcess as unknown as ReturnType<typeof spawn>;
|
||||
});
|
||||
|
||||
const mockSpawnProcess = new EventEmitter() as unknown as ReturnType<
|
||||
typeof spawn
|
||||
>;
|
||||
mockSpawnProcess.on = vi.fn().mockImplementation((event, cb) => {
|
||||
if (event === 'close') {
|
||||
setTimeout(() => cb(0), 10);
|
||||
}
|
||||
return mockSpawnProcess;
|
||||
});
|
||||
vi.mocked(spawn).mockImplementationOnce(() => mockSpawnProcess);
|
||||
|
||||
await start_sandbox(config);
|
||||
|
||||
const args = vi.mocked(spawn).mock.calls[1][1] as string[];
|
||||
const entrypointCmd = args[args.length - 1];
|
||||
|
||||
// Verify that the special home directory is properly quoted/escaped
|
||||
// The quote tool should handle spaces and backticks
|
||||
expect(entrypointCmd).toContain("'/home/user name `$(id)`'");
|
||||
expect(entrypointCmd).toContain('groupadd');
|
||||
expect(entrypointCmd).toContain('useradd');
|
||||
expect(entrypointCmd).toContain('su -p gemini');
|
||||
});
|
||||
|
||||
it('should register and unregister proxy exit handlers', async () => {
|
||||
|
||||
@@ -314,10 +314,6 @@ export async function start_sandbox(
|
||||
// run init binary inside container to forward signals & reap zombies
|
||||
const args = ['run', '-i', '--rm', '--init', '--workdir', containerWorkdir];
|
||||
|
||||
// explicitly clear the entrypoint to prevent the container's default
|
||||
// entrypoint from interfering with the CLI's spawn command.
|
||||
args.push('--entrypoint', '');
|
||||
|
||||
// add runsc runtime if using runsc
|
||||
if (config.command === 'runsc') {
|
||||
args.push('--runtime=runsc');
|
||||
@@ -680,34 +676,22 @@ export async function start_sandbox(
|
||||
// container's /etc/passwd file, which is required by os.userInfo().
|
||||
const username = 'gemini';
|
||||
const homeDir = getContainerPath(homedir());
|
||||
const quotedHomeDir = quote([homeDir]);
|
||||
|
||||
const setupUserCommands = [
|
||||
// Use -f with groupadd to avoid errors if the group already exists.
|
||||
`groupadd -f -g ${gid} ${username}`,
|
||||
// Create user only if it doesn't exist. Use -o for non-unique UID.
|
||||
`id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`,
|
||||
].join(' && ');
|
||||
|
||||
const originalCommand = finalEntrypoint[2];
|
||||
const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
|
||||
|
||||
// Use defensive entrypoint logic that checks for useradd availability.
|
||||
// This ensures we can support UID/GID mapping on distros that have these
|
||||
// tools. If useradd is missing (e.g. on minimal images), we fail explicitly
|
||||
// to avoid insecurely falling back to root execution with host mounts.
|
||||
const defensiveEntrypoint = [
|
||||
`if command -v useradd >/dev/null 2>&1; then`,
|
||||
` (groupadd -g ${gid} -o ${username} 2>/dev/null || true) &&`,
|
||||
` (id ${uid} >/dev/null 2>&1 || useradd -o -u ${uid} -g ${gid} -d ${quotedHomeDir} -s /bin/bash ${username} 2>/dev/null || true) &&`,
|
||||
` USER_NAME=$(id -nu ${uid} 2>/dev/null);`,
|
||||
` if [ -n "$USER_NAME" ]; then`,
|
||||
` su -p "$USER_NAME" -c '${escapedOriginalCommand}';`,
|
||||
` else`,
|
||||
` echo "Error: Failed to map host UID ${uid} to a user in the container." >&2;`,
|
||||
` exit 1;`,
|
||||
` fi`,
|
||||
`else`,
|
||||
` echo "Error: 'useradd' not found in container. UID/GID mapping is required for Linux distros like NixOS/Arch to avoid permission issues. Please use a container image that includes standard user management tools (like 'ubuntu' or 'debian')." >&2;`,
|
||||
` exit 1;`,
|
||||
`fi`,
|
||||
].join('\n');
|
||||
// Use `su -p` to preserve the environment.
|
||||
const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`;
|
||||
|
||||
// The entrypoint is always `['bash', '-c', '<command>']`, so we modify the command part.
|
||||
finalEntrypoint[2] = defensiveEntrypoint;
|
||||
finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`;
|
||||
|
||||
// We still need userFlag for the simpler proxy container, which does not have this issue.
|
||||
userFlag = `--user ${uid}:${gid}`;
|
||||
@@ -732,8 +716,6 @@ export async function start_sandbox(
|
||||
'run',
|
||||
'--rm',
|
||||
'--init',
|
||||
'--entrypoint',
|
||||
'',
|
||||
...(userFlag ? userFlag.split(' ') : []),
|
||||
'--name',
|
||||
SANDBOX_PROXY_NAME,
|
||||
|
||||
@@ -143,95 +143,6 @@ describe('sandboxUtils', () => {
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true on NixOS', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue('ID=nixos\n');
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true on NixOS with quotes', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue('ID="nixos"\n');
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true on Ubuntu with single quotes', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue("ID='ubuntu'\n");
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true on Arch Linux', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue('ID=arch\n');
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false on unrecognized Linux and warn on UID mismatch', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue('ID=unknown\n');
|
||||
vi.mocked(os.userInfo).mockReturnValue({
|
||||
uid: 1234,
|
||||
username: 'test',
|
||||
gid: 1234,
|
||||
shell: '/bin/bash',
|
||||
homedir: '/home/test',
|
||||
});
|
||||
|
||||
const { debugLogger } = await import('@google/gemini-cli-core');
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(false);
|
||||
expect(debugLogger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'Host UID mismatch detected (current UID: 1234)',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return true on Pop!_OS (via ID_LIKE)', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue(
|
||||
'ID=pop\nID_LIKE="ubuntu debian"\n',
|
||||
);
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false and NOT warn for host root user (UID 0)', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockResolvedValue('ID=unknown\n');
|
||||
vi.mocked(os.userInfo).mockReturnValue({
|
||||
uid: 0,
|
||||
username: 'root',
|
||||
gid: 0,
|
||||
shell: '/bin/bash',
|
||||
homedir: '/root',
|
||||
});
|
||||
|
||||
const { debugLogger } = await import('@google/gemini-cli-core');
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(false);
|
||||
expect(debugLogger.warn).not.toHaveBeenCalledWith(
|
||||
expect.stringContaining('Host UID mismatch detected'),
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn and return false if /etc/os-release is unreadable', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('linux');
|
||||
vi.mocked(readFile).mockRejectedValue(new Error('EACCES'));
|
||||
|
||||
const { debugLogger } = await import('@google/gemini-cli-core');
|
||||
expect(await shouldUseCurrentUserInSandbox()).toBe(false);
|
||||
expect(debugLogger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Could not read /etc/os-release'),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return false on non-Linux', async () => {
|
||||
delete process.env['SANDBOX_SET_UID_GID'];
|
||||
vi.mocked(os.platform).mockReturnValue('darwin');
|
||||
|
||||
@@ -49,35 +49,22 @@ export async function shouldUseCurrentUserInSandbox(): Promise<boolean> {
|
||||
if (os.platform() === 'linux') {
|
||||
try {
|
||||
const osReleaseContent = await readFile('/etc/os-release', 'utf8');
|
||||
const isSupportedDistro =
|
||||
osReleaseContent.match(
|
||||
/^ID=["']?(?:debian|ubuntu|nixos|arch|fedora|suse|opensuse)/m,
|
||||
) ||
|
||||
osReleaseContent.match(
|
||||
/^ID_LIKE=["']?.*(?:debian|ubuntu|arch|fedora|suse).*/m,
|
||||
);
|
||||
|
||||
if (isSupportedDistro) {
|
||||
if (
|
||||
osReleaseContent.includes('ID=debian') ||
|
||||
osReleaseContent.includes('ID=ubuntu') ||
|
||||
osReleaseContent.match(/^ID_LIKE=.*debian.*/m) || // Covers derivatives
|
||||
osReleaseContent.match(/^ID_LIKE=.*ubuntu.*/m) // Covers derivatives
|
||||
) {
|
||||
debugLogger.log(
|
||||
'Defaulting to use current user UID/GID for supported Linux distribution.',
|
||||
'Defaulting to use current user UID/GID for Debian/Ubuntu-based Linux.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// If we're on Linux but the distro is unrecognized, check for a UID mismatch
|
||||
// that might cause permission issues in the sandbox.
|
||||
const uid = os.userInfo().uid;
|
||||
if (uid !== 1000 && uid !== 0) {
|
||||
debugLogger.warn(
|
||||
`Warning: Host UID mismatch detected (current UID: ${uid}). ` +
|
||||
'If you encounter permission errors in the sandbox, try setting SANDBOX_SET_UID_GID=true.',
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore if /etc/os-release is not found or unreadable.
|
||||
// The default (false) will be applied in this case.
|
||||
debugLogger.warn(
|
||||
'Warning: Could not read /etc/os-release to auto-detect Linux distribution for UID/GID default.',
|
||||
'Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+16
-17
@@ -33,22 +33,22 @@
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@modelcontextprotocol/sdk": "^1.23.0",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/api-logs": "^0.218.0",
|
||||
"@opentelemetry/core": "^2.7.1",
|
||||
"@opentelemetry/exporter-logs-otlp-grpc": "^0.218.0",
|
||||
"@opentelemetry/exporter-logs-otlp-http": "^0.218.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.218.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "^0.218.0",
|
||||
"@opentelemetry/exporter-trace-otlp-grpc": "^0.218.0",
|
||||
"@opentelemetry/exporter-trace-otlp-http": "^0.218.0",
|
||||
"@opentelemetry/instrumentation-http": "^0.218.0",
|
||||
"@opentelemetry/otlp-exporter-base": "^0.218.0",
|
||||
"@opentelemetry/resources": "^2.7.1",
|
||||
"@opentelemetry/sdk-logs": "^0.218.0",
|
||||
"@opentelemetry/sdk-metrics": "^2.7.1",
|
||||
"@opentelemetry/sdk-node": "^0.218.0",
|
||||
"@opentelemetry/sdk-trace-base": "^2.7.1",
|
||||
"@opentelemetry/sdk-trace-node": "^2.7.1",
|
||||
"@opentelemetry/api-logs": "^0.211.0",
|
||||
"@opentelemetry/core": "^2.5.0",
|
||||
"@opentelemetry/exporter-logs-otlp-grpc": "^0.211.0",
|
||||
"@opentelemetry/exporter-logs-otlp-http": "^0.211.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.211.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "^0.211.0",
|
||||
"@opentelemetry/exporter-trace-otlp-grpc": "^0.211.0",
|
||||
"@opentelemetry/exporter-trace-otlp-http": "^0.211.0",
|
||||
"@opentelemetry/instrumentation-http": "^0.211.0",
|
||||
"@opentelemetry/otlp-exporter-base": "^0.211.0",
|
||||
"@opentelemetry/resources": "^2.5.0",
|
||||
"@opentelemetry/sdk-logs": "^0.211.0",
|
||||
"@opentelemetry/sdk-metrics": "^2.5.0",
|
||||
"@opentelemetry/sdk-node": "^0.211.0",
|
||||
"@opentelemetry/sdk-trace-base": "^2.5.0",
|
||||
"@opentelemetry/sdk-trace-node": "^2.5.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.39.0",
|
||||
"@types/html-to-text": "^9.0.4",
|
||||
"@xterm/headless": "5.5.0",
|
||||
@@ -67,7 +67,6 @@
|
||||
"glob": "^12.0.0",
|
||||
"google-auth-library": "^9.11.0",
|
||||
"html-to-text": "^9.0.5",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"ignore": "^7.0.0",
|
||||
"ipaddr.js": "^1.9.1",
|
||||
|
||||
@@ -4132,7 +4132,40 @@ describe('LocalAgentExecutor', () => {
|
||||
expect(systemInstruction).toContain('<loaded_context>');
|
||||
});
|
||||
|
||||
it('should inject session memory into the first message', async () => {
|
||||
it('should inject environment memory into the first message when JIT is disabled', async () => {
|
||||
const definition = createTestDefinition();
|
||||
const executor = await LocalAgentExecutor.create(
|
||||
definition,
|
||||
mockConfig,
|
||||
onActivity,
|
||||
);
|
||||
|
||||
const mockMemory = 'Project memory rule';
|
||||
vi.spyOn(mockConfig, 'getEnvironmentMemory').mockReturnValue(
|
||||
mockMemory,
|
||||
);
|
||||
vi.spyOn(mockConfig, 'isJitContextEnabled').mockReturnValue(false);
|
||||
|
||||
mockModelResponse([
|
||||
{
|
||||
name: COMPLETE_TASK_TOOL_NAME,
|
||||
args: { finalResult: 'done' },
|
||||
id: 'call1',
|
||||
},
|
||||
]);
|
||||
|
||||
await executor.run({ goal: 'test' }, signal);
|
||||
|
||||
const { message } = getMockMessageParams(0);
|
||||
const parts = message as Part[];
|
||||
|
||||
expect(parts).toBeDefined();
|
||||
const memoryPart = parts.find((p) => p.text?.includes(mockMemory));
|
||||
expect(memoryPart).toBeDefined();
|
||||
expect(memoryPart?.text).toBe(mockMemory);
|
||||
});
|
||||
|
||||
it('should inject session memory into the first message when JIT is enabled', async () => {
|
||||
const definition = createTestDefinition();
|
||||
const executor = await LocalAgentExecutor.create(
|
||||
definition,
|
||||
@@ -4143,6 +4176,7 @@ describe('LocalAgentExecutor', () => {
|
||||
const mockMemory =
|
||||
'<loaded_context>\nExtension memory rule\n</loaded_context>';
|
||||
vi.spyOn(mockConfig, 'getSessionMemory').mockReturnValue(mockMemory);
|
||||
vi.spyOn(mockConfig, 'isJitContextEnabled').mockReturnValue(true);
|
||||
|
||||
mockModelResponse([
|
||||
{
|
||||
@@ -4182,6 +4216,7 @@ describe('LocalAgentExecutor', () => {
|
||||
? '<loaded_context>\n<project_context>\nProject memory rule\n</project_context>\n</loaded_context>'
|
||||
: '<loaded_context>\n<extension_context>\nExtension memory rule\n</extension_context>\n<project_context>\nProject memory rule\n</project_context>\n</loaded_context>',
|
||||
);
|
||||
vi.spyOn(mockConfig, 'isJitContextEnabled').mockReturnValue(true);
|
||||
|
||||
mockModelResponse([
|
||||
{
|
||||
|
||||
@@ -643,12 +643,17 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
|
||||
|
||||
// Inject loaded memory files. Some background agents opt out of
|
||||
// extension memory while still retaining project session context.
|
||||
const environmentMemory =
|
||||
this.definition.includeExtensionContext === false
|
||||
? this.context.config.getSessionMemory({
|
||||
includeExtensionContext: false,
|
||||
})
|
||||
: this.context.config.getSessionMemory();
|
||||
let environmentMemory: string;
|
||||
if (this.context.config.isJitContextEnabled?.()) {
|
||||
environmentMemory =
|
||||
this.definition.includeExtensionContext === false
|
||||
? this.context.config.getSessionMemory({
|
||||
includeExtensionContext: false,
|
||||
})
|
||||
: this.context.config.getSessionMemory();
|
||||
} else {
|
||||
environmentMemory = this.context.config.getEnvironmentMemory();
|
||||
}
|
||||
|
||||
const initialParts: Part[] = [];
|
||||
if (environmentMemory) {
|
||||
|
||||
@@ -29,9 +29,6 @@ describe('Auto Routing Fallback Integration', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(Config.prototype, 'getHasAccessToPreviewModel').mockReturnValue(
|
||||
true,
|
||||
);
|
||||
|
||||
// Mock fs to avoid real file system access
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
|
||||
@@ -28,7 +28,6 @@ describe('Fallback Integration', () => {
|
||||
getActiveModel: () => PREVIEW_GEMINI_MODEL_AUTO,
|
||||
setActiveModel: vi.fn(),
|
||||
getUserTier: () => undefined,
|
||||
getHasAccessToPreviewModel: () => true,
|
||||
getModelAvailabilityService: () => availabilityService,
|
||||
modelConfigService: undefined as unknown as ModelConfigService,
|
||||
} as unknown as Config;
|
||||
|
||||
@@ -55,10 +55,7 @@ export function resolvePolicyChain(
|
||||
const useGemini31FlashLite =
|
||||
config.getGemini31FlashLiteLaunchedSync?.() ?? false;
|
||||
const useCustomToolModel = config.getUseCustomToolModelSync?.() ?? false;
|
||||
const hasAccessToPreview = config.getHasAccessToPreviewModel?.() ?? false;
|
||||
|
||||
// Capture the original family intent before any normalization or early downgrade.
|
||||
const isOriginallyGemini3 = isGemini3Model(modelFromConfig, config);
|
||||
const hasAccessToPreview = config.getHasAccessToPreviewModel?.() ?? true;
|
||||
|
||||
const resolvedModel = normalizeModelId(
|
||||
resolveModel(
|
||||
@@ -78,7 +75,10 @@ export function resolvePolicyChain(
|
||||
// We always wrap around for Gemini 3 chains to ensure maximum availability
|
||||
// between models in the same family (e.g. fallback to Pro if Flash is exhausted).
|
||||
const effectiveWrapsAround =
|
||||
wrapsAround || isAutoPreferred || isAutoConfigured || isOriginallyGemini3;
|
||||
wrapsAround ||
|
||||
isAutoPreferred ||
|
||||
isAutoConfigured ||
|
||||
isGemini3Model(resolvedModel, config);
|
||||
|
||||
// --- DYNAMIC PATH ---
|
||||
if (config.getExperimentalDynamicModelConfiguration?.() === true) {
|
||||
@@ -91,7 +91,11 @@ export function resolvePolicyChain(
|
||||
|
||||
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
|
||||
chain = config.modelConfigService.resolveChain('lite', context);
|
||||
} else if (isOriginallyGemini3 || isAutoPreferred || isAutoConfigured) {
|
||||
} else if (
|
||||
isGemini3Model(normalizeModelId(resolvedModel), config) ||
|
||||
isAutoPreferred ||
|
||||
isAutoConfigured
|
||||
) {
|
||||
// 1. Try to find a chain specifically for the current configured alias
|
||||
if (
|
||||
isAutoConfigured &&
|
||||
@@ -128,11 +132,15 @@ export function resolvePolicyChain(
|
||||
|
||||
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
|
||||
chain = getFlashLitePolicyChain();
|
||||
} else if (isOriginallyGemini3 || isAutoPreferred || isAutoConfigured) {
|
||||
} else if (
|
||||
isGemini3Model(resolvedModel, config) ||
|
||||
isAutoPreferred ||
|
||||
isAutoConfigured
|
||||
) {
|
||||
const isAutoSelection = isAutoPreferred || isAutoConfigured;
|
||||
if (hasAccessToPreview) {
|
||||
const previewEnabled =
|
||||
isOriginallyGemini3 ||
|
||||
isGemini3Model(resolvedModel, config) ||
|
||||
normalizedPreferredModel === PREVIEW_GEMINI_MODEL_AUTO ||
|
||||
configuredModel === PREVIEW_GEMINI_MODEL_AUTO;
|
||||
chain = getModelPolicyChain({
|
||||
|
||||
@@ -87,9 +87,7 @@ export function sanitizeAdminSettings(
|
||||
mcpSetting: {
|
||||
mcpEnabled: sanitized.mcpSetting?.mcpEnabled ?? false,
|
||||
mcpConfig: mcpConfig ?? {},
|
||||
...(mcpConfig?.requiredMcpServers && {
|
||||
requiredMcpConfig: mcpConfig.requiredMcpServers,
|
||||
}),
|
||||
requiredMcpConfig: mcpConfig?.requiredMcpServers,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -228,7 +228,6 @@ describe('setupUser', () => {
|
||||
});
|
||||
|
||||
it('should throw InvalidNumericProjectIdError when GOOGLE_CLOUD_PROJECT_ID is numeric', async () => {
|
||||
vi.stubEnv('GOOGLE_CLOUD_PROJECT', '');
|
||||
vi.stubEnv('GOOGLE_CLOUD_PROJECT_ID', '1234567890');
|
||||
await expect(setupUser({} as OAuth2Client, mockConfig)).rejects.toThrow(
|
||||
InvalidNumericProjectIdError,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import type { Config } from '../config/config.js';
|
||||
import { Storage } from '../config/storage.js';
|
||||
import {
|
||||
addMemory,
|
||||
applyInboxMemoryPatch,
|
||||
dismissInboxSkill,
|
||||
dismissInboxMemoryPatch,
|
||||
@@ -24,6 +25,11 @@ import {
|
||||
refreshMemory,
|
||||
showMemory,
|
||||
} from './memory.js';
|
||||
import * as memoryDiscovery from '../utils/memoryDiscovery.js';
|
||||
|
||||
vi.mock('../utils/memoryDiscovery.js', () => ({
|
||||
refreshServerHierarchicalMemory: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../config/storage.js', () => ({
|
||||
Storage: {
|
||||
@@ -32,19 +38,17 @@ vi.mock('../config/storage.js', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const mockRefresh = vi.mocked(memoryDiscovery.refreshServerHierarchicalMemory);
|
||||
|
||||
describe('memory commands', () => {
|
||||
let mockConfig: Config;
|
||||
let mockMemoryContextRefresh: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockMemoryContextRefresh = vi.fn().mockResolvedValue(undefined);
|
||||
mockConfig = {
|
||||
getUserMemory: vi.fn(),
|
||||
getGeminiMdFileCount: vi.fn(),
|
||||
getGeminiMdFilePaths: vi.fn(),
|
||||
getMemoryContextManager: vi.fn().mockReturnValue({
|
||||
refresh: mockMemoryContextRefresh,
|
||||
}),
|
||||
isJitContextEnabled: vi.fn(),
|
||||
updateSystemInstructionIfInitialized: vi
|
||||
.fn()
|
||||
.mockResolvedValue(undefined),
|
||||
@@ -88,16 +92,63 @@ describe('memory commands', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('addMemory', () => {
|
||||
it('should return a tool action to save memory', () => {
|
||||
const result = addMemory('new memory');
|
||||
expect(result.type).toBe('tool');
|
||||
if (result.type === 'tool') {
|
||||
expect(result.toolName).toBe('save_memory');
|
||||
expect(result.toolArgs).toEqual({ fact: 'new memory' });
|
||||
}
|
||||
});
|
||||
|
||||
it('should trim the arguments', () => {
|
||||
const result = addMemory(' new memory ');
|
||||
expect(result.type).toBe('tool');
|
||||
if (result.type === 'tool') {
|
||||
expect(result.toolArgs).toEqual({ fact: 'new memory' });
|
||||
}
|
||||
});
|
||||
|
||||
it('should return an error if args are empty', () => {
|
||||
const result = addMemory('');
|
||||
expect(result.type).toBe('message');
|
||||
if (result.type === 'message') {
|
||||
expect(result.messageType).toBe('error');
|
||||
expect(result.content).toBe('Usage: /memory add <text to remember>');
|
||||
}
|
||||
});
|
||||
|
||||
it('should return an error if args are just whitespace', () => {
|
||||
const result = addMemory(' ');
|
||||
expect(result.type).toBe('message');
|
||||
if (result.type === 'message') {
|
||||
expect(result.messageType).toBe('error');
|
||||
expect(result.content).toBe('Usage: /memory add <text to remember>');
|
||||
}
|
||||
});
|
||||
|
||||
it('should return an error if args are undefined', () => {
|
||||
const result = addMemory(undefined);
|
||||
expect(result.type).toBe('message');
|
||||
if (result.type === 'message') {
|
||||
expect(result.messageType).toBe('error');
|
||||
expect(result.content).toBe('Usage: /memory add <text to remember>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('refreshMemory', () => {
|
||||
it('should refresh memory and show success message', async () => {
|
||||
vi.mocked(mockConfig.getUserMemory).mockReturnValue({
|
||||
project: 'refreshed content',
|
||||
mockRefresh.mockResolvedValue({
|
||||
memoryContent: { project: 'refreshed content' },
|
||||
fileCount: 2,
|
||||
filePaths: [],
|
||||
});
|
||||
vi.mocked(mockConfig.getGeminiMdFileCount).mockReturnValue(2);
|
||||
|
||||
const result = await refreshMemory(mockConfig);
|
||||
|
||||
expect(mockMemoryContextRefresh).toHaveBeenCalled();
|
||||
expect(mockRefresh).toHaveBeenCalledWith(mockConfig);
|
||||
expect(
|
||||
mockConfig.updateSystemInstructionIfInitialized,
|
||||
).toHaveBeenCalled();
|
||||
@@ -111,8 +162,11 @@ describe('memory commands', () => {
|
||||
});
|
||||
|
||||
it('should show a message if no memory content is found after refresh', async () => {
|
||||
vi.mocked(mockConfig.getUserMemory).mockReturnValue({ project: '' });
|
||||
vi.mocked(mockConfig.getGeminiMdFileCount).mockReturnValue(0);
|
||||
mockRefresh.mockResolvedValue({
|
||||
memoryContent: { project: '' },
|
||||
fileCount: 0,
|
||||
filePaths: [],
|
||||
});
|
||||
|
||||
const result = await refreshMemory(mockConfig);
|
||||
expect(result.type).toBe('message');
|
||||
|
||||
@@ -31,7 +31,8 @@ import {
|
||||
validateParsedSkillPatchHeaders,
|
||||
} from '../services/memoryPatchUtils.js';
|
||||
import { readExtractionState } from '../services/memoryService.js';
|
||||
import type { MessageActionReturn } from './types.js';
|
||||
import { refreshServerHierarchicalMemory } from '../utils/memoryDiscovery.js';
|
||||
import type { MessageActionReturn, ToolActionReturn } from './types.js';
|
||||
|
||||
export type { InboxMemoryPatchKind } from '../services/memoryPatchUtils.js';
|
||||
export { getAllowedMemoryPatchRoots } from '../services/memoryPatchUtils.js';
|
||||
@@ -54,12 +55,38 @@ export function showMemory(config: Config): MessageActionReturn {
|
||||
};
|
||||
}
|
||||
|
||||
export function addMemory(
|
||||
args?: string,
|
||||
): MessageActionReturn | ToolActionReturn {
|
||||
if (!args || args.trim() === '') {
|
||||
return {
|
||||
type: 'message',
|
||||
messageType: 'error',
|
||||
content: 'Usage: /memory add <text to remember>',
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'tool',
|
||||
toolName: 'save_memory',
|
||||
toolArgs: { fact: args.trim() },
|
||||
};
|
||||
}
|
||||
|
||||
export async function refreshMemory(
|
||||
config: Config,
|
||||
): Promise<MessageActionReturn> {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
const memoryContent = flattenMemory(config.getUserMemory());
|
||||
const fileCount = config.getGeminiMdFileCount();
|
||||
let memoryContent = '';
|
||||
let fileCount = 0;
|
||||
|
||||
if (config.isJitContextEnabled()) {
|
||||
await config.getMemoryContextManager()?.refresh();
|
||||
memoryContent = flattenMemory(config.getUserMemory());
|
||||
fileCount = config.getGeminiMdFileCount();
|
||||
} else {
|
||||
const result = await refreshServerHierarchicalMemory(config);
|
||||
memoryContent = flattenMemory(result.memoryContent);
|
||||
fileCount = result.fileCount;
|
||||
}
|
||||
|
||||
config.updateSystemInstructionIfInitialized();
|
||||
let content: string;
|
||||
|
||||
@@ -52,7 +52,7 @@ import { ShellTool } from '../tools/shell.js';
|
||||
import { AgentTool } from '../agents/agent-tool.js';
|
||||
import { ReadFileTool } from '../tools/read-file.js';
|
||||
import { GrepTool } from '../tools/grep.js';
|
||||
import { RipGrepTool, resolveRipgrepPath } from '../tools/ripGrep.js';
|
||||
import { RipGrepTool, canUseRipgrep } from '../tools/ripGrep.js';
|
||||
import {
|
||||
logRipgrepFallback,
|
||||
logApprovalModeDuration,
|
||||
@@ -89,22 +89,6 @@ vi.mock('fs', async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../utils/paths.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../utils/paths.js')>();
|
||||
return {
|
||||
...actual,
|
||||
resolveToRealPath: vi.fn((p) => p),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../utils/fileUtils.js', () => ({
|
||||
fileExists: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../utils/shell-utils.js', () => ({
|
||||
resolveExecutable: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock dependencies that might be called during Config construction or createServerConfig
|
||||
vi.mock('../tools/tool-registry', () => {
|
||||
const ToolRegistryMock = vi.fn();
|
||||
@@ -127,12 +111,16 @@ vi.mock('../tools/mcp-client-manager.js', () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('../utils/memoryDiscovery.js', () => ({
|
||||
loadServerHierarchicalMemory: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock individual tools if their constructors are complex or have side effects
|
||||
vi.mock('../tools/ls');
|
||||
vi.mock('../tools/read-file');
|
||||
vi.mock('../tools/grep.js');
|
||||
vi.mock('../tools/ripGrep.js', () => ({
|
||||
resolveRipgrepPath: vi.fn(),
|
||||
canUseRipgrep: vi.fn(),
|
||||
RipGrepTool: class MockRipGrepTool {},
|
||||
}));
|
||||
vi.mock('../tools/glob');
|
||||
@@ -141,15 +129,13 @@ vi.mock('../tools/shell');
|
||||
vi.mock('../tools/write-file');
|
||||
vi.mock('../tools/web-fetch');
|
||||
vi.mock('../tools/read-many-files');
|
||||
vi.mock('../tools/memoryTool', async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import('../tools/memoryTool.js')>();
|
||||
return {
|
||||
...actual,
|
||||
setGeminiMdFilename: vi.fn(),
|
||||
getCurrentGeminiMdFilename: vi.fn(() => 'GEMINI.md'),
|
||||
};
|
||||
});
|
||||
vi.mock('../tools/memoryTool', () => ({
|
||||
MemoryTool: vi.fn(),
|
||||
setGeminiMdFilename: vi.fn(),
|
||||
getCurrentGeminiMdFilename: vi.fn(() => 'GEMINI.md'), // Mock the original filename
|
||||
DEFAULT_CONTEXT_FILENAME: 'GEMINI.md',
|
||||
GEMINI_DIR: '.gemini',
|
||||
}));
|
||||
|
||||
vi.mock('../core/contentGenerator.js');
|
||||
|
||||
@@ -324,38 +310,6 @@ describe('Server Config (config.ts)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('model fallback', () => {
|
||||
it('should fallback to default model when an obsolete model is provided', () => {
|
||||
const config = new Config({
|
||||
...baseParams,
|
||||
model: 'gemini-pro-latest',
|
||||
});
|
||||
expect(config.getModel()).toBe(DEFAULT_GEMINI_MODEL);
|
||||
});
|
||||
|
||||
it('should fallback to default model when an invalid gemini model is provided', () => {
|
||||
const config = new Config({
|
||||
...baseParams,
|
||||
model: 'gemini-invalid-model',
|
||||
});
|
||||
expect(config.getModel()).toBe(DEFAULT_GEMINI_MODEL);
|
||||
});
|
||||
|
||||
it('should fallback to default model when setModel is called with an invalid gemini model', () => {
|
||||
const config = new Config(baseParams);
|
||||
config.setModel('gemini-invalid-model');
|
||||
expect(config.getModel()).toBe(DEFAULT_GEMINI_MODEL);
|
||||
});
|
||||
|
||||
it('should allow custom models (non-gemini prefixed)', () => {
|
||||
const config = new Config({
|
||||
...baseParams,
|
||||
model: 'custom-model',
|
||||
});
|
||||
expect(config.getModel()).toBe('custom-model');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setShellExecutionConfig', () => {
|
||||
it('should preserve existing shell execution fields that are not being updated', () => {
|
||||
const config = new Config({
|
||||
@@ -2334,7 +2288,7 @@ describe('setApprovalMode with folder trust', () => {
|
||||
});
|
||||
|
||||
it('should register RipGrepTool when useRipgrep is true and it is available', async () => {
|
||||
vi.mocked(resolveRipgrepPath).mockResolvedValue('/mock/rg');
|
||||
vi.mocked(canUseRipgrep).mockResolvedValue(true);
|
||||
const config = new Config({ ...baseParams, useRipgrep: true });
|
||||
await config.initialize();
|
||||
|
||||
@@ -2352,7 +2306,7 @@ describe('setApprovalMode with folder trust', () => {
|
||||
});
|
||||
|
||||
it('should register GrepTool as a fallback when useRipgrep is true but it is not available', async () => {
|
||||
vi.mocked(resolveRipgrepPath).mockResolvedValue(null);
|
||||
vi.mocked(canUseRipgrep).mockResolvedValue(false);
|
||||
const config = new Config({ ...baseParams, useRipgrep: true });
|
||||
await config.initialize();
|
||||
|
||||
@@ -2376,7 +2330,7 @@ describe('setApprovalMode with folder trust', () => {
|
||||
|
||||
it('should register GrepTool as a fallback when canUseRipgrep throws an error', async () => {
|
||||
const error = new Error('ripGrep check failed');
|
||||
vi.mocked(resolveRipgrepPath).mockRejectedValue(error);
|
||||
vi.mocked(canUseRipgrep).mockRejectedValue(error);
|
||||
const config = new Config({ ...baseParams, useRipgrep: true });
|
||||
await config.initialize();
|
||||
|
||||
@@ -2412,7 +2366,7 @@ describe('setApprovalMode with folder trust', () => {
|
||||
|
||||
expect(wasRipGrepRegistered).toBe(false);
|
||||
expect(wasGrepRegistered).toBe(true);
|
||||
expect(resolveRipgrepPath).not.toHaveBeenCalled();
|
||||
expect(canUseRipgrep).not.toHaveBeenCalled();
|
||||
expect(logRipgrepFallback).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2645,7 +2599,7 @@ describe('Config getHooks', () => {
|
||||
targetDir: '/path/to/target',
|
||||
debugMode: false,
|
||||
sessionId: 'test-session-id',
|
||||
model: 'gemini-2.5-flash',
|
||||
model: 'gemini-pro',
|
||||
usageStatisticsEnabled: false,
|
||||
};
|
||||
|
||||
@@ -2894,7 +2848,7 @@ describe('Config getExperiments', () => {
|
||||
targetDir: '/path/to/target',
|
||||
debugMode: false,
|
||||
sessionId: 'test-session-id',
|
||||
model: 'gemini-2.5-flash',
|
||||
model: 'gemini-pro',
|
||||
usageStatisticsEnabled: false,
|
||||
};
|
||||
|
||||
@@ -2939,7 +2893,7 @@ describe('Config setExperiments logging', () => {
|
||||
targetDir: '/path/to/target',
|
||||
debugMode: false,
|
||||
sessionId: 'test-session-id',
|
||||
model: 'gemini-2.5-flash',
|
||||
model: 'gemini-pro',
|
||||
usageStatisticsEnabled: false,
|
||||
};
|
||||
|
||||
@@ -3283,8 +3237,8 @@ describe('Config Quota & Preview Model Access', () => {
|
||||
vi.mocked(getCodeAssistServer).mockReturnValue(undefined);
|
||||
const result = await config.refreshUserQuota();
|
||||
expect(result).toBeUndefined();
|
||||
// Never set => stays null (unknown); getter returns false by default
|
||||
expect(config.getHasAccessToPreviewModel()).toBe(false);
|
||||
// Never set => stays null (unknown); getter returns true so UI shows preview
|
||||
expect(config.getHasAccessToPreviewModel()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return undefined if retrieveUserQuota fails', async () => {
|
||||
@@ -3293,8 +3247,8 @@ describe('Config Quota & Preview Model Access', () => {
|
||||
);
|
||||
const result = await config.refreshUserQuota();
|
||||
expect(result).toBeUndefined();
|
||||
// Never set => stays null (unknown); getter returns false by default
|
||||
expect(config.getHasAccessToPreviewModel()).toBe(false);
|
||||
// Never set => stays null (unknown); getter returns true so UI shows preview
|
||||
expect(config.getHasAccessToPreviewModel()).toBe(true);
|
||||
});
|
||||
it('should derive quota from remainingFraction when remainingAmount is missing', async () => {
|
||||
mockCodeAssistServer.retrieveUserQuota.mockResolvedValue({
|
||||
@@ -3533,12 +3487,13 @@ describe('Config JIT Initialization', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should initialize MemoryContextManager, load memory, and delegate to it', async () => {
|
||||
it('should initialize MemoryContextManager, load memory, and delegate to it when experimentalJitContext is enabled', async () => {
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
experimentalJitContext: true,
|
||||
userMemory: 'Initial Memory',
|
||||
cwd: '/tmp/test',
|
||||
};
|
||||
@@ -3585,11 +3540,26 @@ describe('Config JIT Initialization', () => {
|
||||
expect(config.getGeminiMdFilePaths()).toEqual(['/path/to/GEMINI.md']);
|
||||
});
|
||||
|
||||
describe('memory path access', () => {
|
||||
it('should NOT add the global ~/.gemini directory to the workspace', async () => {
|
||||
// Memory does not broaden the workspace to include the global ~/.gemini/
|
||||
// directory. Cross-project personal preferences are routed to
|
||||
// ~/.gemini/GEMINI.md via the surgical isPathAllowed allowlist instead.
|
||||
it('should NOT initialize MemoryContextManager when experimentalJitContext is disabled', async () => {
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
experimentalJitContext: false,
|
||||
userMemory: 'Initial Memory',
|
||||
cwd: '/tmp/test',
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
await config.initialize();
|
||||
|
||||
expect(MemoryContextManager).not.toHaveBeenCalled();
|
||||
expect(config.getUserMemory()).toBe('Initial Memory');
|
||||
});
|
||||
|
||||
describe('isMemoryV2Enabled', () => {
|
||||
it('should default to true', () => {
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
@@ -3598,6 +3568,52 @@ describe('Config JIT Initialization', () => {
|
||||
cwd: '/tmp/test',
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
expect(config.isMemoryV2Enabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when experimentalMemoryV2 is explicitly false', () => {
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
cwd: '/tmp/test',
|
||||
experimentalMemoryV2: false,
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
expect(config.isMemoryV2Enabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when experimentalMemoryV2 is true', () => {
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
cwd: '/tmp/test',
|
||||
experimentalMemoryV2: true,
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
expect(config.isMemoryV2Enabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT add the global ~/.gemini directory to the workspace when enabled', async () => {
|
||||
// The prompt-driven memoryV2 mode does not broaden the workspace
|
||||
// to include the global ~/.gemini/ directory. Cross-project personal
|
||||
// preferences are routed to ~/.gemini/GEMINI.md via the surgical
|
||||
// isPathAllowed allowlist instead — see the next two tests.
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
cwd: '/tmp/test',
|
||||
experimentalMemoryV2: true,
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
await config.initialize();
|
||||
|
||||
@@ -3606,15 +3622,16 @@ describe('Config JIT Initialization', () => {
|
||||
});
|
||||
|
||||
it('should allow isPathAllowed to write the global ~/.gemini/GEMINI.md file', async () => {
|
||||
// Surgical allowlist: the prompt routes cross-project personal
|
||||
// preferences to ~/.gemini/GEMINI.md, so the agent must be able to edit
|
||||
// that exact file via edit/write_file.
|
||||
// Surgical allowlist: when memoryV2 is on, the prompt routes
|
||||
// cross-project personal preferences to ~/.gemini/GEMINI.md, so the
|
||||
// agent must be able to edit that exact file via edit/write_file.
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
cwd: '/tmp/test',
|
||||
experimentalMemoryV2: true,
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
@@ -3636,6 +3653,7 @@ describe('Config JIT Initialization', () => {
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
cwd: '/tmp/test',
|
||||
experimentalMemoryV2: true,
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
@@ -3927,16 +3945,18 @@ describe('Config JIT Initialization', () => {
|
||||
expect(config.getExperimentalGemma()).toBe(true);
|
||||
});
|
||||
|
||||
it('should default to disabled', () => {
|
||||
it('should be independent of experimentalMemoryV2', () => {
|
||||
const params: ConfigParameters = {
|
||||
sessionId: 'test-session',
|
||||
targetDir: '/tmp/test',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
cwd: '/tmp/test',
|
||||
experimentalMemoryV2: true,
|
||||
};
|
||||
|
||||
config = new Config(params);
|
||||
expect(config.isMemoryV2Enabled()).toBe(true);
|
||||
expect(config.isAutoMemoryEnabled()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ import { ReadFileTool } from '../tools/read-file.js';
|
||||
import { ReadMcpResourceTool } from '../tools/read-mcp-resource.js';
|
||||
import { ListMcpResourcesTool } from '../tools/list-mcp-resources.js';
|
||||
import { GrepTool } from '../tools/grep.js';
|
||||
import { RipGrepTool, resolveRipgrepPath } from '../tools/ripGrep.js';
|
||||
import { canUseRipgrep, RipGrepTool } from '../tools/ripGrep.js';
|
||||
import { GlobTool } from '../tools/glob.js';
|
||||
import { ActivateSkillTool } from '../tools/activate-skill.js';
|
||||
import { EditTool } from '../tools/edit.js';
|
||||
@@ -42,6 +42,7 @@ import { ShellTool } from '../tools/shell.js';
|
||||
import { WriteFileTool } from '../tools/write-file.js';
|
||||
import { WebFetchTool } from '../tools/web-fetch.js';
|
||||
import {
|
||||
MemoryTool,
|
||||
setGeminiMdFilename,
|
||||
getCurrentGeminiMdFilename,
|
||||
} from '../tools/memoryTool.js';
|
||||
@@ -80,12 +81,10 @@ import { tokenLimit } from '../core/tokenLimits.js';
|
||||
import {
|
||||
DEFAULT_GEMINI_EMBEDDING_MODEL,
|
||||
DEFAULT_GEMINI_FLASH_MODEL,
|
||||
DEFAULT_GEMINI_MODEL,
|
||||
DEFAULT_GEMINI_MODEL_AUTO,
|
||||
isAutoModel,
|
||||
isPreviewModel,
|
||||
isGemini2Model,
|
||||
isValidModel,
|
||||
PREVIEW_GEMINI_FLASH_MODEL,
|
||||
resolveModel,
|
||||
} from './models.js';
|
||||
@@ -173,7 +172,6 @@ import { AcknowledgedAgentsService } from '../agents/acknowledgedAgents.js';
|
||||
import { setGlobalProxy, updateGlobalFetchTimeouts } from '../utils/fetch.js';
|
||||
import { ExperimentFlags } from '../code_assist/experiments/flagNames.js';
|
||||
import { debugLogger } from '../utils/debugLogger.js';
|
||||
import { ragLogger } from '../utils/ragLogger.js';
|
||||
import { SkillManager, type SkillDefinition } from '../skills/skillManager.js';
|
||||
import { startupProfiler } from '../telemetry/startupProfiler.js';
|
||||
import type { AgentDefinition } from '../agents/types.js';
|
||||
@@ -711,7 +709,9 @@ export interface ConfigParameters {
|
||||
skillsSupport?: boolean;
|
||||
disabledSkills?: string[];
|
||||
adminSkillsEnabled?: boolean;
|
||||
experimentalJitContext?: boolean;
|
||||
autoDistillation?: boolean;
|
||||
experimentalMemoryV2?: boolean;
|
||||
experimentalAutoMemory?: boolean;
|
||||
experimentalGemma?: boolean;
|
||||
experimentalContextManagementConfig?: string;
|
||||
@@ -742,7 +742,6 @@ export interface ConfigParameters {
|
||||
overageStrategy?: OverageStrategy;
|
||||
};
|
||||
vertexAiRouting?: VertexAiRoutingConfig;
|
||||
logRagSnippets?: boolean;
|
||||
}
|
||||
|
||||
export class Config implements McpContext, AgentLoopContext {
|
||||
@@ -773,7 +772,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
private readonly sandbox: SandboxConfig | undefined;
|
||||
private _sandboxForbiddenPaths: string[] | undefined;
|
||||
private readonly targetDir: string;
|
||||
private _ripgrepPathPromise?: Promise<string | null>;
|
||||
private workspaceContext: WorkspaceContext;
|
||||
private readonly debugMode: boolean;
|
||||
private readonly question: string | undefined;
|
||||
@@ -797,7 +795,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
private geminiMdFileCount: number;
|
||||
private geminiMdFilePaths: string[];
|
||||
private readonly showMemoryUsage: boolean;
|
||||
private readonly logRagSnippets: boolean;
|
||||
private readonly accessibility: AccessibilitySettings;
|
||||
private readonly telemetrySettings: TelemetrySettings;
|
||||
private readonly usageStatisticsEnabled: boolean;
|
||||
@@ -959,6 +956,8 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
private readonly skillsSupport: boolean;
|
||||
private disabledSkills: string[];
|
||||
private readonly adminSkillsEnabled: boolean;
|
||||
private readonly experimentalJitContext: boolean;
|
||||
private readonly experimentalMemoryV2: boolean;
|
||||
private readonly experimentalAutoMemory: boolean;
|
||||
private readonly experimentalGemma: boolean;
|
||||
private readonly experimentalContextManagementConfig?: string;
|
||||
@@ -1072,7 +1071,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
this.geminiMdFileCount = params.geminiMdFileCount ?? 0;
|
||||
this.geminiMdFilePaths = params.geminiMdFilePaths ?? [];
|
||||
this.showMemoryUsage = params.showMemoryUsage ?? false;
|
||||
this.logRagSnippets = params.logRagSnippets ?? false;
|
||||
this.accessibility = params.accessibility ?? {};
|
||||
this.telemetrySettings = {
|
||||
enabled: params.telemetry?.enabled ?? false,
|
||||
@@ -1116,11 +1114,9 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
this.cwd = params.cwd ?? process.cwd();
|
||||
this.fileDiscoveryService = params.fileDiscoveryService ?? null;
|
||||
this.bugCommand = params.bugCommand;
|
||||
this.model = isValidModel(params.model)
|
||||
? params.model
|
||||
: DEFAULT_GEMINI_MODEL;
|
||||
this.model = params.model;
|
||||
this.disableLoopDetection = params.disableLoopDetection ?? false;
|
||||
this._activeModel = this.model;
|
||||
this._activeModel = params.model;
|
||||
this.enableAgents = params.enableAgents ?? true;
|
||||
this.agents = params.agents ?? {};
|
||||
this.disableLLMCorrection = params.disableLLMCorrection ?? true;
|
||||
@@ -1182,6 +1178,8 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
modelConfigServiceConfig ?? DEFAULT_MODEL_CONFIGS,
|
||||
);
|
||||
|
||||
this.experimentalJitContext = params.experimentalJitContext ?? true;
|
||||
this.experimentalMemoryV2 = params.experimentalMemoryV2 ?? true;
|
||||
this.experimentalAutoMemory = params.experimentalAutoMemory ?? false;
|
||||
this.experimentalGemma = params.experimentalGemma ?? true;
|
||||
this.experimentalContextManagementConfig =
|
||||
@@ -1438,7 +1436,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
|
||||
private async _initialize(): Promise<void> {
|
||||
await this.storage.initialize();
|
||||
ragLogger.initialize(this.storage.getProjectTempLogsDir());
|
||||
|
||||
// Add pending directories to workspace context
|
||||
for (const dir of this.pendingIncludeDirectories) {
|
||||
@@ -1545,8 +1542,10 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
await this.hookSystem.initialize();
|
||||
}
|
||||
|
||||
this.memoryContextManager = new MemoryContextManager(this);
|
||||
await this.memoryContextManager.refresh();
|
||||
if (this.experimentalJitContext) {
|
||||
this.memoryContextManager = new MemoryContextManager(this);
|
||||
await this.memoryContextManager.refresh();
|
||||
}
|
||||
|
||||
await this._geminiClient.initialize();
|
||||
this.initialized = true;
|
||||
@@ -1906,20 +1905,17 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
}
|
||||
|
||||
setModel(newModel: string, isTemporary: boolean = true): void {
|
||||
const validatedModel = isValidModel(newModel)
|
||||
? newModel
|
||||
: DEFAULT_GEMINI_MODEL;
|
||||
if (this.model !== validatedModel || this._activeModel !== validatedModel) {
|
||||
this.model = validatedModel;
|
||||
if (this.model !== newModel || this._activeModel !== newModel) {
|
||||
this.model = newModel;
|
||||
// When the user explicitly sets a model, that becomes the active model.
|
||||
this._activeModel = validatedModel;
|
||||
coreEvents.emitModelChanged(validatedModel);
|
||||
this._activeModel = newModel;
|
||||
coreEvents.emitModelChanged(newModel);
|
||||
this.lastEmittedQuotaRemaining = undefined;
|
||||
this.lastEmittedQuotaLimit = undefined;
|
||||
this.emitQuotaChangedEvent();
|
||||
}
|
||||
if (this.onModelChange && !isTemporary) {
|
||||
this.onModelChange(validatedModel);
|
||||
this.onModelChange(newModel);
|
||||
}
|
||||
this.modelAvailabilityService.reset();
|
||||
}
|
||||
@@ -2145,32 +2141,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
return this.targetDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path to the ripgrep binary, or null if not found or unsafe.
|
||||
* Uses Promise-based caching to prevent race conditions and redundant I/O.
|
||||
*/
|
||||
async getRipgrepPath(): Promise<string | null> {
|
||||
if (!this._ripgrepPathPromise) {
|
||||
this._ripgrepPathPromise = resolveRipgrepPath();
|
||||
}
|
||||
return this._ripgrepPathPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if ripgrep is available.
|
||||
*/
|
||||
async canUseRipgrep(): Promise<boolean> {
|
||||
return (await this.getRipgrepPath()) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the cached ripgrep path. Used for testing.
|
||||
* @internal
|
||||
*/
|
||||
__resetRipgrepPathCache(): void {
|
||||
this._ripgrepPathPromise = undefined;
|
||||
}
|
||||
|
||||
getWorkspaceContext(): WorkspaceContext {
|
||||
return getWorkspaceContextOverride() ?? this.workspaceContext;
|
||||
}
|
||||
@@ -2239,7 +2209,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
}
|
||||
|
||||
getHasAccessToPreviewModel(): boolean {
|
||||
return this.hasAccessToPreviewModel ?? false;
|
||||
return this.hasAccessToPreviewModel !== false;
|
||||
}
|
||||
|
||||
setHasAccessToPreviewModel(hasAccess: boolean | null): void {
|
||||
@@ -2301,6 +2271,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
});
|
||||
}
|
||||
}
|
||||
this.emitQuotaChangedEvent();
|
||||
}
|
||||
|
||||
const hasAccess =
|
||||
@@ -2308,11 +2279,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
(b) => b.modelId && isPreviewModel(b.modelId, this),
|
||||
) ?? false;
|
||||
this.setHasAccessToPreviewModel(hasAccess);
|
||||
|
||||
if (quota.buckets) {
|
||||
this.emitQuotaChangedEvent();
|
||||
}
|
||||
|
||||
return quota;
|
||||
} catch (e) {
|
||||
debugLogger.debug('Failed to retrieve user quota', e);
|
||||
@@ -2493,7 +2459,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
}
|
||||
|
||||
getUserMemory(): string | HierarchicalMemory {
|
||||
if (this.memoryContextManager) {
|
||||
if (this.experimentalJitContext && this.memoryContextManager) {
|
||||
return {
|
||||
global: this.memoryContextManager.getGlobalMemory(),
|
||||
extension: this.memoryContextManager.getExtensionMemory(),
|
||||
@@ -2508,7 +2474,14 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
* Refreshes the MCP context, including memory, tools, and system instructions.
|
||||
*/
|
||||
async refreshMcpContext(): Promise<void> {
|
||||
await this.memoryContextManager?.refresh();
|
||||
if (this.experimentalJitContext && this.memoryContextManager) {
|
||||
await this.memoryContextManager.refresh();
|
||||
} else {
|
||||
const { refreshServerHierarchicalMemory } = await import(
|
||||
'../utils/memoryDiscovery.js'
|
||||
);
|
||||
await refreshServerHierarchicalMemory(this);
|
||||
}
|
||||
if (this._geminiClient?.isInitialized()) {
|
||||
await this._geminiClient.setTools();
|
||||
this._geminiClient.updateSystemInstruction();
|
||||
@@ -2520,14 +2493,15 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Tier 1 memory for the system instruction. Global memory and user
|
||||
* project memory go in the system instruction; extension and project memory
|
||||
* are placed in the first user message instead, per the tiered context model.
|
||||
* User project memory is in Tier 1 so mid-session saves are reflected via
|
||||
* system instruction updates.
|
||||
* Returns memory for the system instruction.
|
||||
* When JIT is enabled, global memory and user project memory (Tier 1) go
|
||||
* in the system instruction. Extension and project memory (Tier 2) are
|
||||
* placed in the first user message instead, per the tiered context model.
|
||||
* User project memory is in Tier 1 so mid-session saves are reflected
|
||||
* via system instruction updates.
|
||||
*/
|
||||
getSystemInstructionMemory(): string | HierarchicalMemory {
|
||||
if (this.memoryContextManager) {
|
||||
if (this.experimentalJitContext && this.memoryContextManager) {
|
||||
const global = this.memoryContextManager.getGlobalMemory();
|
||||
const userProjectMemory =
|
||||
this.memoryContextManager.getUserProjectMemory();
|
||||
@@ -2541,10 +2515,11 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
|
||||
/**
|
||||
* Returns Tier 2 memory (extension + project) for injection into the first
|
||||
* user message.
|
||||
* user message when JIT is enabled. Returns empty string when JIT is
|
||||
* disabled (Tier 2 memory is already in the system instruction).
|
||||
*/
|
||||
getSessionMemory(options?: { includeExtensionContext?: boolean }): string {
|
||||
if (!this.memoryContextManager) {
|
||||
if (!this.experimentalJitContext || !this.memoryContextManager) {
|
||||
return '';
|
||||
}
|
||||
const sections: string[] = [];
|
||||
@@ -2577,6 +2552,10 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
return this.memoryContextManager;
|
||||
}
|
||||
|
||||
isJitContextEnabled(): boolean {
|
||||
return this.experimentalJitContext;
|
||||
}
|
||||
|
||||
isContextManagementEnabled(): boolean {
|
||||
return this.contextManagement.enabled;
|
||||
}
|
||||
@@ -2585,6 +2564,10 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
return this.memoryBoundaryMarkers;
|
||||
}
|
||||
|
||||
isMemoryV2Enabled(): boolean {
|
||||
return this.experimentalMemoryV2;
|
||||
}
|
||||
|
||||
isAutoMemoryEnabled(): boolean {
|
||||
return this.experimentalAutoMemory;
|
||||
}
|
||||
@@ -2659,7 +2642,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
}
|
||||
|
||||
getGeminiMdFileCount(): number {
|
||||
if (this.memoryContextManager) {
|
||||
if (this.experimentalJitContext && this.memoryContextManager) {
|
||||
return this.memoryContextManager.getLoadedPaths().size;
|
||||
}
|
||||
return this.geminiMdFileCount;
|
||||
@@ -2670,7 +2653,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
}
|
||||
|
||||
getGeminiMdFilePaths(): string[] {
|
||||
if (this.memoryContextManager) {
|
||||
if (this.experimentalJitContext && this.memoryContextManager) {
|
||||
return Array.from(this.memoryContextManager.getLoadedPaths());
|
||||
}
|
||||
return this.geminiMdFilePaths;
|
||||
@@ -2825,10 +2808,6 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
return this.accessibility;
|
||||
}
|
||||
|
||||
getLogRagSnippets(): boolean {
|
||||
return this.logRagSnippets;
|
||||
}
|
||||
|
||||
getTelemetryEnabled(): boolean {
|
||||
return this.telemetrySettings.enabled ?? false;
|
||||
}
|
||||
@@ -3905,7 +3884,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
let useRipgrep = false;
|
||||
let errorString: undefined | string = undefined;
|
||||
try {
|
||||
useRipgrep = await this.canUseRipgrep();
|
||||
useRipgrep = await canUseRipgrep();
|
||||
} catch (error: unknown) {
|
||||
errorString = String(error);
|
||||
}
|
||||
@@ -3960,6 +3939,11 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
new ReadBackgroundOutputTool(this, this.messageBus),
|
||||
),
|
||||
);
|
||||
if (!this.isMemoryV2Enabled()) {
|
||||
maybeRegister(MemoryTool, () =>
|
||||
registry.registerTool(new MemoryTool(this.messageBus, this.storage)),
|
||||
);
|
||||
}
|
||||
maybeRegister(WebSearchTool, () =>
|
||||
registry.registerTool(new WebSearchTool(this, this.messageBus)),
|
||||
);
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { normalizeModelId } from '../utils/modelUtils.js';
|
||||
|
||||
export interface ModelResolutionContext {
|
||||
useGemini3_1?: boolean;
|
||||
useGemini3_1FlashLite?: boolean;
|
||||
@@ -112,20 +110,6 @@ export function getAutoModelDescription(
|
||||
return `Let Gemini CLI decide the best model for the task: ${proModel}, ${flashModel}`;
|
||||
}
|
||||
|
||||
export function isValidModel(model: string): boolean {
|
||||
const normalized = normalizeModelId(model);
|
||||
return (
|
||||
VALID_GEMINI_MODELS.has(normalized) ||
|
||||
normalized === GEMINI_MODEL_ALIAS_AUTO ||
|
||||
normalized === GEMINI_MODEL_ALIAS_PRO ||
|
||||
normalized === GEMINI_MODEL_ALIAS_FLASH ||
|
||||
normalized === GEMINI_MODEL_ALIAS_FLASH_LITE ||
|
||||
normalized === PREVIEW_GEMINI_MODEL_AUTO ||
|
||||
normalized === DEFAULT_GEMINI_MODEL_AUTO ||
|
||||
!normalized.startsWith('gemini-')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the requested model alias (e.g., 'auto', 'pro', 'flash', 'flash-lite')
|
||||
* to a concrete model name.
|
||||
@@ -212,12 +196,7 @@ export function resolveModel(
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
if (!isValidModel(normalizedModel)) {
|
||||
// Fallback to stable default for unknown/obsolete models.
|
||||
resolved = DEFAULT_GEMINI_MODEL;
|
||||
} else {
|
||||
resolved = normalizedModel;
|
||||
}
|
||||
resolved = normalizedModel;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { ContextEnvironment } from '../pipeline/environment.js';
|
||||
import { sanitizeFilenamePart } from '../../utils/fileUtils.js';
|
||||
import {
|
||||
ACTIVATE_SKILL_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
ASK_USER_TOOL_NAME,
|
||||
ENTER_PLAN_MODE_TOOL_NAME,
|
||||
EXIT_PLAN_MODE_TOOL_NAME,
|
||||
@@ -38,6 +39,7 @@ export const ToolMaskingProcessorOptionsSchema: JSONSchemaType<ToolMaskingProces
|
||||
|
||||
const UNMASKABLE_TOOLS = new Set([
|
||||
ACTIVATE_SKILL_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
ASK_USER_TOOL_NAME,
|
||||
ENTER_PLAN_MODE_TOOL_NAME,
|
||||
EXIT_PLAN_MODE_TOOL_NAME,
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import {
|
||||
SHELL_TOOL_NAME,
|
||||
ACTIVATE_SKILL_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
} from '../tools/tool-names.js';
|
||||
import { estimateTokenCountSync } from '../utils/tokenCalculation.js';
|
||||
import type { Config } from '../config/config.js';
|
||||
@@ -565,6 +566,17 @@ describe('ToolOutputMaskingService', () => {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: MEMORY_TOOL_NAME,
|
||||
response: { output: 'Important user preference' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
@@ -601,6 +613,7 @@ describe('ToolOutputMaskingService', () => {
|
||||
|
||||
const name = parts[0].functionResponse?.name;
|
||||
if (name === ACTIVATE_SKILL_TOOL_NAME) return 1000;
|
||||
if (name === MEMORY_TOOL_NAME) return 500;
|
||||
if (name === 'bulky_tool') return 60000;
|
||||
if (name === 'padding') return 60000;
|
||||
return 10;
|
||||
@@ -609,8 +622,8 @@ describe('ToolOutputMaskingService', () => {
|
||||
const result = await service.mask(history, mockConfig);
|
||||
|
||||
// Both 'bulky_tool' and 'padding' should be masked.
|
||||
// 'padding' crosses the 50k protection boundary immediately.
|
||||
// ACTIVATE_SKILL is exempt.
|
||||
// 'padding' (Index 3) crosses the 50k protection boundary immediately.
|
||||
// ACTIVATE_SKILL and MEMORY are exempt.
|
||||
expect(result.maskedCount).toBe(2);
|
||||
expect(result.newHistory[0].parts?.[0].functionResponse?.name).toBe(
|
||||
ACTIVATE_SKILL_TOOL_NAME,
|
||||
@@ -625,7 +638,7 @@ describe('ToolOutputMaskingService', () => {
|
||||
).toBe('High value instructions for skill');
|
||||
|
||||
expect(result.newHistory[1].parts?.[0].functionResponse?.name).toBe(
|
||||
'bulky_tool',
|
||||
MEMORY_TOOL_NAME,
|
||||
);
|
||||
expect(
|
||||
(
|
||||
@@ -634,6 +647,18 @@ describe('ToolOutputMaskingService', () => {
|
||||
unknown
|
||||
>
|
||||
)['output'],
|
||||
).toBe('Important user preference');
|
||||
|
||||
expect(result.newHistory[2].parts?.[0].functionResponse?.name).toBe(
|
||||
'bulky_tool',
|
||||
);
|
||||
expect(
|
||||
(
|
||||
result.newHistory[2].parts?.[0].functionResponse?.response as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
)['output'],
|
||||
).toContain(MASKING_INDICATOR_TAG);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import { logToolOutputMasking } from '../telemetry/loggers.js';
|
||||
import {
|
||||
SHELL_TOOL_NAME,
|
||||
ACTIVATE_SKILL_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
ASK_USER_TOOL_NAME,
|
||||
ENTER_PLAN_MODE_TOOL_NAME,
|
||||
EXIT_PLAN_MODE_TOOL_NAME,
|
||||
@@ -35,6 +36,7 @@ export const TOOL_OUTPUTS_DIR = 'tool-outputs';
|
||||
*/
|
||||
const EXEMPT_TOOLS = new Set([
|
||||
ACTIVATE_SKILL_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
ASK_USER_TOOL_NAME,
|
||||
ENTER_PLAN_MODE_TOOL_NAME,
|
||||
EXIT_PLAN_MODE_TOOL_NAME,
|
||||
|
||||
@@ -169,19 +169,10 @@ ONLY use the built-in \`exit_plan_mode\` tool to present the plan for formal app
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -364,19 +355,10 @@ An approved plan is available for this task at \`../plans/feature-x.md\`.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -485,11 +467,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -672,19 +650,10 @@ ONLY use the built-in \`exit_plan_mode\` tool to present the plan for formal app
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -845,19 +814,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1004,19 +964,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim).
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1146,19 +1097,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim).
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1267,11 +1209,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1386,11 +1324,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1514,11 +1448,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1646,11 +1576,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -1830,19 +1756,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -2003,19 +1920,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -2180,19 +2088,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -2357,19 +2256,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -2530,19 +2420,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -2697,19 +2578,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -2838,19 +2710,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3011,19 +2874,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3145,11 +2999,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3329,19 +3179,10 @@ You are operating with a persistent file-based task tracking system located at \
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3450,11 +3291,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3570,11 +3407,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3755,19 +3588,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -3928,19 +3752,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -4048,11 +3863,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim).
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information.
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
@@ -4219,19 +4030,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -4392,19 +4194,10 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true. If unsure, ask the user.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with \`replace\` or \`write_file\`. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
- **Global Personal Memory** (\`/tmp/test-home/.gemini/GEMINI.md\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.
|
||||
**Routing rules — pick exactly one tier per fact:**
|
||||
- When the user states a **team-shared convention, architecture rule, or repo-wide workflow** ("our project uses X", "the team always Y", "for this repo, always Z"), update the relevant \`GEMINI.md\` file. Do **not** also write it into the private memory folder or the global personal memory file.
|
||||
- When the user states a **personal-to-them local setup, machine-specific note, or private workflow** for this codebase ("on my machine", "my local setup", "do not commit this"), save it under the private project memory folder. Do **not** also write it into a \`GEMINI.md\` file or the global personal memory file.
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.
|
||||
- If a fact could plausibly belong to more than one tier, **ask the user** which tier they want before writing.
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Memory Tool:** Use \`save_memory\` to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task. If unsure whether a fact is global or project-specific, ask the user.
|
||||
- **Confirmation Protocol:** If a tool call is declined or cancelled, respect the decision immediately. Do not re-attempt the action or "negotiate" for the same tool call unless the user explicitly directs you to. Offer an alternative technical path if possible.
|
||||
|
||||
## Interaction Details
|
||||
@@ -4513,11 +4306,7 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
|
||||
- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
- **Background Processes:** To run a command in the background, set the \`is_background\` parameter to true.
|
||||
- **Interactive Commands:** Always prefer non-interactive commands (e.g., using 'run once' or 'CI' flags for test runners to avoid persistent watch modes or 'git --no-pager') unless a persistent process is specifically required; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`tab\` to focus into the shell to provide input.
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with 'replace' or 'write_file'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.
|
||||
- **Private Project Memory** (\`/tmp/project-temp/memory/MEMORY.md\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.
|
||||
- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
|
||||
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||
|
||||
## Interaction Details
|
||||
|
||||
@@ -223,6 +223,7 @@ describe('Gemini Client (client.ts)', () => {
|
||||
getEnvironmentMemory: vi.fn().mockReturnValue(''),
|
||||
getSystemInstructionMemory: vi.fn().mockReturnValue(''),
|
||||
getSessionMemory: vi.fn().mockReturnValue(''),
|
||||
isJitContextEnabled: vi.fn().mockReturnValue(false),
|
||||
getMemoryContextManager: vi.fn().mockReturnValue(undefined),
|
||||
getDisableLoopDetection: vi.fn().mockReturnValue(false),
|
||||
getToolOutputMaskingConfig: vi.fn().mockReturnValue({
|
||||
@@ -2004,7 +2005,8 @@ ${JSON.stringify(
|
||||
});
|
||||
});
|
||||
|
||||
it('should use getSystemInstructionMemory for system instruction', async () => {
|
||||
it('should use getSystemInstructionMemory for system instruction when JIT is enabled', async () => {
|
||||
vi.mocked(mockConfig.isJitContextEnabled).mockReturnValue(true);
|
||||
vi.mocked(mockConfig.getSystemInstructionMemory).mockReturnValue(
|
||||
'Global JIT Memory',
|
||||
);
|
||||
@@ -2020,6 +2022,23 @@ ${JSON.stringify(
|
||||
);
|
||||
});
|
||||
|
||||
it('should use getSystemInstructionMemory for system instruction when JIT is disabled', async () => {
|
||||
vi.mocked(mockConfig.isJitContextEnabled).mockReturnValue(false);
|
||||
vi.mocked(mockConfig.getSystemInstructionMemory).mockReturnValue(
|
||||
'Legacy Memory',
|
||||
);
|
||||
|
||||
const { getCoreSystemPrompt } = await import('./prompts.js');
|
||||
const mockGetCoreSystemPrompt = vi.mocked(getCoreSystemPrompt);
|
||||
|
||||
client.updateSystemInstruction();
|
||||
|
||||
expect(mockGetCoreSystemPrompt).toHaveBeenCalledWith(
|
||||
mockConfig,
|
||||
'Legacy Memory',
|
||||
);
|
||||
});
|
||||
|
||||
it('should update system instruction when MemoryChanged event is emitted', async () => {
|
||||
vi.mocked(mockConfig.getSystemInstructionMemory).mockReturnValue(
|
||||
'Updated Memory',
|
||||
|
||||
@@ -9,13 +9,10 @@ import {
|
||||
createContentGenerator,
|
||||
AuthType,
|
||||
createContentGeneratorConfig,
|
||||
getAuthTypeFromEnv,
|
||||
type ContentGenerator,
|
||||
} from './contentGenerator.js';
|
||||
import { createCodeAssistContentGenerator } from '../code_assist/codeAssist.js';
|
||||
import { GoogleGenAI } from '@google/genai';
|
||||
import { HttpProxyAgent } from 'http-proxy-agent';
|
||||
import { HttpsProxyAgent } from 'https-proxy-agent';
|
||||
import type { Config } from '../config/config.js';
|
||||
import { LoggingContentGenerator } from './loggingContentGenerator.js';
|
||||
import { loadApiKey } from './apiKeyCredentialStorage.js';
|
||||
@@ -38,45 +35,6 @@ const mockConfig = {
|
||||
getClientName: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as Config;
|
||||
|
||||
describe('getAuthTypeFromEnv', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('GEMINI_API_KEY', '');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('should detect LOGIN_WITH_GOOGLE when GOOGLE_GENAI_USE_GCA is true', () => {
|
||||
vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
|
||||
expect(getAuthTypeFromEnv()).toBe(AuthType.LOGIN_WITH_GOOGLE);
|
||||
});
|
||||
|
||||
it('should detect USE_VERTEX_AI when GOOGLE_GENAI_USE_VERTEXAI is true', () => {
|
||||
vi.stubEnv('GOOGLE_GENAI_USE_VERTEXAI', 'true');
|
||||
expect(getAuthTypeFromEnv()).toBe(AuthType.USE_VERTEX_AI);
|
||||
});
|
||||
|
||||
it('should detect GATEWAY when GOOGLE_GEMINI_BASE_URL is present', () => {
|
||||
vi.stubEnv('GOOGLE_GEMINI_BASE_URL', 'https://gateway.example.com');
|
||||
expect(getAuthTypeFromEnv()).toBe(AuthType.GATEWAY);
|
||||
});
|
||||
|
||||
it('should detect USE_GEMINI when GEMINI_API_KEY is present', () => {
|
||||
vi.stubEnv('GEMINI_API_KEY', 'fake-key');
|
||||
expect(getAuthTypeFromEnv()).toBe(AuthType.USE_GEMINI);
|
||||
});
|
||||
|
||||
it('should detect COMPUTE_ADC when CLOUD_SHELL is true', () => {
|
||||
vi.stubEnv('CLOUD_SHELL', 'true');
|
||||
expect(getAuthTypeFromEnv()).toBe(AuthType.COMPUTE_ADC);
|
||||
});
|
||||
|
||||
it('should return undefined when no matching env variables are set', () => {
|
||||
expect(getAuthTypeFromEnv()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createContentGenerator', () => {
|
||||
beforeEach(() => {
|
||||
resetVersionCache();
|
||||
@@ -466,174 +424,6 @@ describe('createContentGenerator', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should inject HttpsProxyAgent into googleAuthOptions when proxy URL uses https://', async () => {
|
||||
const mockConfigWithProxy = {
|
||||
getModel: vi.fn().mockReturnValue('gemini-pro'),
|
||||
getProxy: vi.fn().mockReturnValue('https://proxy.example.com:8080'),
|
||||
getUsageStatisticsEnabled: () => false,
|
||||
getClientName: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as Config;
|
||||
|
||||
const mockGenerator = {
|
||||
models: {},
|
||||
} as unknown as GoogleGenAI;
|
||||
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator);
|
||||
|
||||
await createContentGenerator(
|
||||
{
|
||||
apiKey: 'test-api-key',
|
||||
vertexai: true,
|
||||
authType: AuthType.USE_VERTEX_AI,
|
||||
proxy: 'https://proxy.example.com:8080',
|
||||
},
|
||||
mockConfigWithProxy,
|
||||
);
|
||||
|
||||
expect(GoogleGenAI).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
googleAuthOptions: {
|
||||
clientOptions: {
|
||||
transporterOptions: {
|
||||
agent: expect.any(HttpsProxyAgent),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should still use HttpsProxyAgent for HTTPS destinations even when proxy URL uses http://', async () => {
|
||||
const mockConfigWithProxy = {
|
||||
getModel: vi.fn().mockReturnValue('gemini-pro'),
|
||||
getProxy: vi.fn().mockReturnValue('http://proxy.example.com:8080'),
|
||||
getUsageStatisticsEnabled: () => false,
|
||||
getClientName: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as Config;
|
||||
|
||||
const mockGenerator = {
|
||||
models: {},
|
||||
} as unknown as GoogleGenAI;
|
||||
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator);
|
||||
|
||||
await createContentGenerator(
|
||||
{
|
||||
apiKey: 'test-api-key',
|
||||
vertexai: true,
|
||||
authType: AuthType.USE_VERTEX_AI,
|
||||
proxy: 'http://proxy.example.com:8080',
|
||||
},
|
||||
mockConfigWithProxy,
|
||||
);
|
||||
|
||||
expect(GoogleGenAI).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
googleAuthOptions: {
|
||||
clientOptions: {
|
||||
transporterOptions: {
|
||||
agent: expect.any(HttpsProxyAgent),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should inject HttpProxyAgent when destination baseUrl uses http://', async () => {
|
||||
const mockConfigWithProxy = {
|
||||
getModel: vi.fn().mockReturnValue('gemini-pro'),
|
||||
getProxy: vi.fn().mockReturnValue('http://proxy.example.com:8080'),
|
||||
getUsageStatisticsEnabled: () => false,
|
||||
getClientName: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as Config;
|
||||
|
||||
const mockGenerator = {
|
||||
models: {},
|
||||
} as unknown as GoogleGenAI;
|
||||
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator);
|
||||
|
||||
vi.stubEnv('GOOGLE_VERTEX_BASE_URL', 'http://localhost:9999');
|
||||
|
||||
await createContentGenerator(
|
||||
{
|
||||
apiKey: 'test-api-key',
|
||||
vertexai: true,
|
||||
authType: AuthType.USE_VERTEX_AI,
|
||||
proxy: 'http://proxy.example.com:8080',
|
||||
},
|
||||
mockConfigWithProxy,
|
||||
);
|
||||
|
||||
expect(GoogleGenAI).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
googleAuthOptions: {
|
||||
clientOptions: {
|
||||
transporterOptions: {
|
||||
agent: expect.any(HttpProxyAgent),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should trim whitespace from proxy URL before instantiating agent', async () => {
|
||||
const mockConfigWithProxy = {
|
||||
getModel: vi.fn().mockReturnValue('gemini-pro'),
|
||||
getProxy: vi.fn().mockReturnValue(' https://proxy.example.com:8080 '),
|
||||
getUsageStatisticsEnabled: () => false,
|
||||
getClientName: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as Config;
|
||||
|
||||
const mockGenerator = {
|
||||
models: {},
|
||||
} as unknown as GoogleGenAI;
|
||||
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator);
|
||||
|
||||
await createContentGenerator(
|
||||
{
|
||||
apiKey: 'test-api-key',
|
||||
vertexai: true,
|
||||
authType: AuthType.USE_VERTEX_AI,
|
||||
proxy: ' https://proxy.example.com:8080 ',
|
||||
},
|
||||
mockConfigWithProxy,
|
||||
);
|
||||
|
||||
expect(GoogleGenAI).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
googleAuthOptions: {
|
||||
clientOptions: {
|
||||
transporterOptions: {
|
||||
agent: expect.any(HttpsProxyAgent),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should not include googleAuthOptions when no proxy is configured', async () => {
|
||||
const mockGenerator = {
|
||||
models: {},
|
||||
} as unknown as GoogleGenAI;
|
||||
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator);
|
||||
|
||||
await createContentGenerator(
|
||||
{
|
||||
apiKey: 'test-api-key',
|
||||
vertexai: true,
|
||||
authType: AuthType.USE_VERTEX_AI,
|
||||
},
|
||||
mockConfig,
|
||||
);
|
||||
|
||||
const callArg = vi.mocked(GoogleGenAI).mock.calls[0][0] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(callArg).not.toHaveProperty('googleAuthOptions');
|
||||
});
|
||||
|
||||
it('should pass api key as Authorization Header when GEMINI_API_KEY_AUTH_MECHANISM is set to bearer', async () => {
|
||||
const mockConfig = {
|
||||
getModel: vi.fn().mockReturnValue('gemini-pro'),
|
||||
@@ -1061,40 +851,6 @@ describe('createContentGenerator', () => {
|
||||
),
|
||||
).rejects.toThrow('Invalid custom base URL: not-a-url');
|
||||
});
|
||||
|
||||
it('should set empty x-goog-api-key header for GATEWAY auth when apiKey is empty string', async () => {
|
||||
const mockConfig = {
|
||||
getModel: vi.fn().mockReturnValue('gemini-pro'),
|
||||
getProxy: vi.fn().mockReturnValue(undefined),
|
||||
getUsageStatisticsEnabled: () => false,
|
||||
getClientName: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as Config;
|
||||
|
||||
const mockGenerator = {
|
||||
models: {},
|
||||
} as unknown as GoogleGenAI;
|
||||
vi.mocked(GoogleGenAI).mockImplementation(() => mockGenerator as never);
|
||||
|
||||
await createContentGenerator(
|
||||
{
|
||||
apiKey: '',
|
||||
authType: AuthType.GATEWAY,
|
||||
baseUrl: 'https://gateway.test.local',
|
||||
},
|
||||
mockConfig,
|
||||
);
|
||||
|
||||
expect(GoogleGenAI).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
apiKey: '',
|
||||
httpOptions: expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
'x-goog-api-key': '',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createContentGeneratorConfig', () => {
|
||||
@@ -1199,33 +955,24 @@ describe('createContentGeneratorConfig', () => {
|
||||
expect(config.apiKey).toBeUndefined();
|
||||
expect(config.vertexai).toBeUndefined();
|
||||
});
|
||||
it('should configure for GATEWAY using provided apiKey if available', async () => {
|
||||
const config = await createContentGeneratorConfig(
|
||||
mockConfig,
|
||||
AuthType.GATEWAY,
|
||||
'custom-gateway-key',
|
||||
);
|
||||
expect(config.apiKey).toBe('custom-gateway-key');
|
||||
expect(config.vertexai).toBe(false);
|
||||
});
|
||||
|
||||
it('should configure for GATEWAY using GEMINI_API_KEY from environment if set', async () => {
|
||||
vi.stubEnv('GEMINI_API_KEY', 'env-gateway-key');
|
||||
it('should configure for GATEWAY using dummy placeholder if GEMINI_API_KEY is set', async () => {
|
||||
vi.stubEnv('GEMINI_API_KEY', 'env-gemini-key');
|
||||
const config = await createContentGeneratorConfig(
|
||||
mockConfig,
|
||||
AuthType.GATEWAY,
|
||||
);
|
||||
expect(config.apiKey).toBe('env-gateway-key');
|
||||
expect(config.apiKey).toBe('gateway-placeholder-key');
|
||||
expect(config.vertexai).toBe(false);
|
||||
});
|
||||
|
||||
it('should configure for GATEWAY using empty string if no apiKey is provided', async () => {
|
||||
it('should configure for GATEWAY using dummy placeholder if GEMINI_API_KEY is not set', async () => {
|
||||
vi.stubEnv('GEMINI_API_KEY', '');
|
||||
vi.mocked(loadApiKey).mockResolvedValue(null);
|
||||
const config = await createContentGeneratorConfig(
|
||||
mockConfig,
|
||||
AuthType.GATEWAY,
|
||||
);
|
||||
expect(config.apiKey).toBe('');
|
||||
expect(config.apiKey).toBe('gateway-placeholder-key');
|
||||
expect(config.vertexai).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,8 +13,6 @@ import {
|
||||
type EmbedContentResponse,
|
||||
type EmbedContentParameters,
|
||||
} from '@google/genai';
|
||||
import { HttpProxyAgent } from 'http-proxy-agent';
|
||||
import { HttpsProxyAgent } from 'https-proxy-agent';
|
||||
import * as os from 'node:os';
|
||||
import { createCodeAssistContentGenerator } from '../code_assist/codeAssist.js';
|
||||
import { isCloudShell } from '../ide/detect-ide.js';
|
||||
@@ -82,9 +80,6 @@ export function getAuthTypeFromEnv(): AuthType | undefined {
|
||||
if (process.env['GOOGLE_GENAI_USE_VERTEXAI'] === 'true') {
|
||||
return AuthType.USE_VERTEX_AI;
|
||||
}
|
||||
if (process.env['GOOGLE_GEMINI_BASE_URL']) {
|
||||
return AuthType.GATEWAY;
|
||||
}
|
||||
if (process.env['GEMINI_API_KEY']) {
|
||||
return AuthType.USE_GEMINI;
|
||||
}
|
||||
@@ -183,8 +178,7 @@ export async function createContentGeneratorConfig(
|
||||
}
|
||||
|
||||
if (authType === AuthType.GATEWAY) {
|
||||
contentGeneratorConfig.apiKey =
|
||||
apiKey || process.env['GEMINI_API_KEY'] || '';
|
||||
contentGeneratorConfig.apiKey = apiKey || 'gateway-placeholder-key';
|
||||
contentGeneratorConfig.vertexai = false;
|
||||
|
||||
return contentGeneratorConfig;
|
||||
@@ -319,9 +313,6 @@ export async function createContentGenerator(
|
||||
'x-gemini-api-privileged-user-id': `${installationId}`,
|
||||
};
|
||||
}
|
||||
if (config.authType === AuthType.GATEWAY && config.apiKey === '') {
|
||||
headers['x-goog-api-key'] = '';
|
||||
}
|
||||
let baseUrl = config.baseUrl;
|
||||
if (!baseUrl) {
|
||||
const envBaseUrl =
|
||||
@@ -345,30 +336,11 @@ export async function createContentGenerator(
|
||||
httpOptions.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
const proxyUrl = config.proxy?.trim();
|
||||
const proxyAgent = proxyUrl
|
||||
? baseUrl?.startsWith('http://')
|
||||
? new HttpProxyAgent(proxyUrl)
|
||||
: new HttpsProxyAgent(proxyUrl)
|
||||
: undefined;
|
||||
|
||||
const googleGenAI = new GoogleGenAI({
|
||||
apiKey:
|
||||
config.authType === AuthType.GATEWAY
|
||||
? config.apiKey
|
||||
: config.apiKey === ''
|
||||
? undefined
|
||||
: config.apiKey,
|
||||
apiKey: config.apiKey === '' ? undefined : config.apiKey,
|
||||
vertexai: config.vertexai ?? config.authType === AuthType.USE_VERTEX_AI,
|
||||
httpOptions,
|
||||
...(apiVersionEnv && { apiVersion: apiVersionEnv }),
|
||||
...(proxyAgent && {
|
||||
googleAuthOptions: {
|
||||
clientOptions: {
|
||||
transporterOptions: { agent: proxyAgent },
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
return new LoggingContentGenerator(googleGenAI.models, gcConfig);
|
||||
}
|
||||
|
||||
@@ -79,7 +79,6 @@ describe('Core System Prompt (prompts.ts)', () => {
|
||||
vi.resetAllMocks();
|
||||
// Stub process.platform to 'linux' by default for deterministic snapshots across OSes
|
||||
mockPlatform('linux');
|
||||
vi.spyOn(os, 'homedir').mockReturnValue('/tmp/test-home');
|
||||
|
||||
vi.stubEnv('SANDBOX', undefined);
|
||||
vi.stubEnv('GEMINI_SYSTEM_MD', undefined);
|
||||
@@ -98,9 +97,6 @@ describe('Core System Prompt (prompts.ts)', () => {
|
||||
storage: {
|
||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
||||
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
|
||||
getProjectMemoryDir: vi
|
||||
.fn()
|
||||
.mockReturnValue('/tmp/project-temp/memory'),
|
||||
getProjectTempTrackerDir: vi
|
||||
.fn()
|
||||
.mockReturnValue('/mock/.gemini/tmp/session/tracker'),
|
||||
@@ -108,6 +104,7 @@ describe('Core System Prompt (prompts.ts)', () => {
|
||||
isInteractive: vi.fn().mockReturnValue(true),
|
||||
isInteractiveShellEnabled: vi.fn().mockReturnValue(true),
|
||||
isTopicUpdateNarrationEnabled: vi.fn().mockReturnValue(false),
|
||||
isMemoryV2Enabled: vi.fn().mockReturnValue(false),
|
||||
isAgentsEnabled: vi.fn().mockReturnValue(false),
|
||||
getPreviewFeatures: vi.fn().mockReturnValue(true),
|
||||
getModel: vi.fn().mockReturnValue(DEFAULT_GEMINI_MODEL_AUTO),
|
||||
@@ -457,13 +454,11 @@ describe('Core System Prompt (prompts.ts)', () => {
|
||||
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
||||
storage: {
|
||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
||||
getProjectMemoryDir: vi
|
||||
.fn()
|
||||
.mockReturnValue('/tmp/project-temp/memory'),
|
||||
},
|
||||
isInteractive: vi.fn().mockReturnValue(false),
|
||||
isInteractiveShellEnabled: vi.fn().mockReturnValue(false),
|
||||
isTopicUpdateNarrationEnabled: vi.fn().mockReturnValue(false),
|
||||
isMemoryV2Enabled: vi.fn().mockReturnValue(false),
|
||||
isAgentsEnabled: vi.fn().mockReturnValue(false),
|
||||
getModel: vi.fn().mockReturnValue('auto'),
|
||||
getActiveModel: vi.fn().mockReturnValue(PREVIEW_GEMINI_MODEL),
|
||||
|
||||
@@ -19,7 +19,6 @@ import type {
|
||||
} from '../tools/tools.js';
|
||||
import { getResponseText } from '../utils/partUtils.js';
|
||||
import { reportError } from '../utils/errorReporting.js';
|
||||
import { ragLogger, type RagSnippet } from '../utils/ragLogger.js';
|
||||
import {
|
||||
getErrorMessage,
|
||||
UnauthorizedError,
|
||||
@@ -245,7 +244,6 @@ export class Turn {
|
||||
private pendingCitations = new Set<string>();
|
||||
private cachedResponseText: string | undefined = undefined;
|
||||
finishReason: FinishReason | undefined = undefined;
|
||||
private hasLoggedRagTrace = false;
|
||||
|
||||
constructor(
|
||||
private readonly chat: GeminiChat,
|
||||
@@ -304,39 +302,6 @@ export class Turn {
|
||||
const resp = streamEvent.value;
|
||||
if (!resp) continue; // Skip if there's no response body
|
||||
|
||||
// Log RAG trace if enabled (only once per turn to avoid log bloat on streams)
|
||||
if (
|
||||
!this.hasLoggedRagTrace &&
|
||||
this.chat.context.config.getLogRagSnippets?.()
|
||||
) {
|
||||
let ragStatus: string | undefined;
|
||||
let snippets: RagSnippet[] | undefined;
|
||||
|
||||
if (
|
||||
typeof resp === 'object' &&
|
||||
resp !== null &&
|
||||
'metadata' in resp &&
|
||||
typeof resp.metadata === 'object' &&
|
||||
resp.metadata !== null
|
||||
) {
|
||||
const metadata = resp.metadata as {
|
||||
ragStatus?: string;
|
||||
snippets?: RagSnippet[];
|
||||
};
|
||||
ragStatus = metadata.ragStatus;
|
||||
snippets = metadata.snippets;
|
||||
}
|
||||
|
||||
if (ragStatus || snippets) {
|
||||
ragLogger.log({
|
||||
sessionId: this.chat.context.config.getSessionId(),
|
||||
ragStatus: ragStatus ?? 'UNKNOWN',
|
||||
snippets: snippets ?? [],
|
||||
});
|
||||
this.hasLoggedRagTrace = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.debugResponses.push(resp);
|
||||
|
||||
const traceId = resp.responseId;
|
||||
|
||||
@@ -77,7 +77,6 @@ const createMockConfig = (overrides: Partial<Config> = {}): Config =>
|
||||
getModel: vi.fn(() => MOCK_PRO_MODEL),
|
||||
getUserTier: vi.fn(() => undefined),
|
||||
isInteractive: vi.fn(() => false),
|
||||
getHasAccessToPreviewModel: vi.fn(() => false),
|
||||
...overrides,
|
||||
}) as unknown as Config;
|
||||
|
||||
@@ -235,7 +234,6 @@ describe('handleFallback', () => {
|
||||
vi.mocked(policyConfig.getModel).mockReturnValue(
|
||||
PREVIEW_GEMINI_MODEL_AUTO,
|
||||
);
|
||||
vi.mocked(policyConfig.getHasAccessToPreviewModel).mockReturnValue(true);
|
||||
|
||||
const result = await handleFallback(
|
||||
policyConfig,
|
||||
|
||||
@@ -28,14 +28,13 @@ export async function handleFallback(
|
||||
authType?: string,
|
||||
error?: unknown,
|
||||
): Promise<string | boolean | null> {
|
||||
const failureKind = classifyFailureKind(error);
|
||||
|
||||
const chain = resolvePolicyChain(config);
|
||||
const { failedPolicy, candidates } = buildFallbackPolicyContext(
|
||||
chain,
|
||||
failedModel,
|
||||
);
|
||||
|
||||
const failureKind = classifyFailureKind(error);
|
||||
const availability = config.getModelAvailabilityService();
|
||||
const getAvailabilityContext = () => {
|
||||
if (!failedPolicy) return undefined;
|
||||
|
||||
@@ -4,26 +4,12 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createPolicyEngineConfig } from './config.js';
|
||||
import { PolicyEngine } from './policy-engine.js';
|
||||
import { PolicyDecision, ApprovalMode } from './types.js';
|
||||
import { Storage } from '../config/storage.js';
|
||||
|
||||
describe('PolicyEngine - Core Tools Mapping', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(Storage, 'getUserPoliciesDir').mockReturnValue(
|
||||
'/mock/user/policies',
|
||||
);
|
||||
vi.spyOn(Storage, 'getSystemPoliciesDir').mockReturnValue(
|
||||
'/mock/system/policies',
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should allow tools explicitly listed in settings.tools.core', async () => {
|
||||
const settings = {
|
||||
tools: {
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { PolicyEngine } from './policy-engine.js';
|
||||
import { loadPoliciesFromToml } from './toml-loader.js';
|
||||
import { PolicyDecision, ApprovalMode } from './types.js';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
describe('Memory Manager Policy', () => {
|
||||
let engine: PolicyEngine;
|
||||
|
||||
beforeEach(async () => {
|
||||
const policiesDir = path.join(__dirname, 'policies');
|
||||
const result = await loadPoliciesFromToml([policiesDir], () => 1);
|
||||
engine = new PolicyEngine({
|
||||
rules: result.rules,
|
||||
approvalMode: ApprovalMode.DEFAULT,
|
||||
});
|
||||
});
|
||||
|
||||
it('should allow save_memory to read ~/.gemini/GEMINI.md', async () => {
|
||||
const toolCall = {
|
||||
name: 'read_file',
|
||||
args: { file_path: '~/.gemini/GEMINI.md' },
|
||||
};
|
||||
const result = await engine.check(
|
||||
toolCall,
|
||||
undefined,
|
||||
undefined,
|
||||
'save_memory',
|
||||
);
|
||||
expect(result.decision).toBe(PolicyDecision.ALLOW);
|
||||
});
|
||||
|
||||
it('should allow save_memory to write ~/.gemini/GEMINI.md', async () => {
|
||||
const toolCall = {
|
||||
name: 'write_file',
|
||||
args: { file_path: '~/.gemini/GEMINI.md', content: 'test' },
|
||||
};
|
||||
const result = await engine.check(
|
||||
toolCall,
|
||||
undefined,
|
||||
undefined,
|
||||
'save_memory',
|
||||
);
|
||||
expect(result.decision).toBe(PolicyDecision.ALLOW);
|
||||
});
|
||||
|
||||
it('should allow save_memory to list ~/.gemini/', async () => {
|
||||
const toolCall = {
|
||||
name: 'list_directory',
|
||||
args: { dir_path: '~/.gemini/' },
|
||||
};
|
||||
const result = await engine.check(
|
||||
toolCall,
|
||||
undefined,
|
||||
undefined,
|
||||
'save_memory',
|
||||
);
|
||||
expect(result.decision).toBe(PolicyDecision.ALLOW);
|
||||
});
|
||||
|
||||
it('should fall through to global allow rule for save_memory reading non-.gemini files', async () => {
|
||||
const toolCall = {
|
||||
name: 'read_file',
|
||||
args: { file_path: '/etc/passwd' },
|
||||
};
|
||||
const result = await engine.check(
|
||||
toolCall,
|
||||
undefined,
|
||||
undefined,
|
||||
'save_memory',
|
||||
);
|
||||
// The memory-manager policy only matches .gemini/ paths.
|
||||
// Other paths fall through to the global read_file allow rule (priority 50).
|
||||
expect(result.decision).toBe(PolicyDecision.ALLOW);
|
||||
});
|
||||
|
||||
it('should not match paths where .gemini is a substring (e.g. not.gemini)', async () => {
|
||||
const toolCall = {
|
||||
name: 'read_file',
|
||||
args: { file_path: '/tmp/not.gemini/evil' },
|
||||
};
|
||||
const result = await engine.check(
|
||||
toolCall,
|
||||
undefined,
|
||||
undefined,
|
||||
'save_memory',
|
||||
);
|
||||
// The tighter argsPattern requires .gemini/ to be preceded by start-of-string
|
||||
// or a path separator, so "not.gemini/" should NOT match the memory-manager rule.
|
||||
// It falls through to the global read_file allow rule instead.
|
||||
expect(result.decision).toBe(PolicyDecision.ALLOW);
|
||||
});
|
||||
|
||||
it('should fall through to global allow rule for other agents accessing ~/.gemini/', async () => {
|
||||
const toolCall = {
|
||||
name: 'read_file',
|
||||
args: { file_path: '~/.gemini/GEMINI.md' },
|
||||
};
|
||||
const result = await engine.check(
|
||||
toolCall,
|
||||
undefined,
|
||||
undefined,
|
||||
'other_agent',
|
||||
);
|
||||
// The memory-manager policy rule (priority 100) only applies to 'save_memory'.
|
||||
// Other agents fall through to the global read_file allow rule (priority 50).
|
||||
expect(result.decision).toBe(PolicyDecision.ALLOW);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
# Policy for Memory Manager Agent
|
||||
# Allows the save_memory agent to manage memories in the ~/.gemini/ folder.
|
||||
|
||||
# Read-only tools: allow access to anything under .gemini/
|
||||
[[rule]]
|
||||
subagent = "save_memory"
|
||||
toolName = ["read_file", "list_directory", "glob", "grep_search"]
|
||||
decision = "allow"
|
||||
priority = 100
|
||||
argsPattern = "(^|.*/)\\.gemini/.*"
|
||||
denyMessage = "Memory Manager is only allowed to access the .gemini folder."
|
||||
|
||||
# Write tools: only allow .md files under .gemini/
|
||||
[[rule]]
|
||||
subagent = "save_memory"
|
||||
toolName = ["write_file", "replace"]
|
||||
decision = "allow"
|
||||
priority = 100
|
||||
argsPattern = "(^|.*/)\\.gemini/.*\\.md\""
|
||||
denyMessage = "Memory Manager is only allowed to write .md files in the .gemini folder."
|
||||
@@ -103,7 +103,7 @@ priority = 50
|
||||
modes = ["plan"]
|
||||
|
||||
[[rule]]
|
||||
toolName = ["ask_user", "web_fetch", "activate_skill"]
|
||||
toolName = ["ask_user", "save_memory", "web_fetch", "activate_skill"]
|
||||
decision = "ask_user"
|
||||
priority = 50
|
||||
modes = ["plan"]
|
||||
|
||||
@@ -44,6 +44,12 @@ type = "in-process"
|
||||
name = "allowed-path"
|
||||
required_context = ["environment"]
|
||||
|
||||
[[rule]]
|
||||
toolName = "save_memory"
|
||||
decision = "ask_user"
|
||||
priority = 10
|
||||
interactive = true
|
||||
|
||||
[[rule]]
|
||||
toolName = "run_shell_command"
|
||||
decision = "ask_user"
|
||||
@@ -90,6 +96,7 @@ interactive = true
|
||||
[[rule]]
|
||||
toolName = [
|
||||
"replace",
|
||||
"save_memory",
|
||||
"run_shell_command",
|
||||
"write_file",
|
||||
"activate_skill",
|
||||
|
||||
@@ -3089,6 +3089,12 @@ describe('PolicyEngine', () => {
|
||||
priority: 70,
|
||||
modes: [ApprovalMode.PLAN],
|
||||
},
|
||||
{
|
||||
toolName: 'save_memory',
|
||||
decision: PolicyDecision.ASK_USER,
|
||||
priority: 70,
|
||||
modes: [ApprovalMode.PLAN],
|
||||
},
|
||||
{
|
||||
toolName: 'exit_plan_mode',
|
||||
decision: PolicyDecision.ASK_USER,
|
||||
@@ -3133,6 +3139,7 @@ describe('PolicyEngine', () => {
|
||||
'web_fetch',
|
||||
'write_todos',
|
||||
'memory',
|
||||
'save_memory',
|
||||
'mcp_mcp-server_read_tool',
|
||||
'mcp_mcp-server_write_tool',
|
||||
]);
|
||||
@@ -3168,6 +3175,7 @@ describe('PolicyEngine', () => {
|
||||
expect(excluded.has('web_fetch')).toBe(false);
|
||||
expect(excluded.has('ask_user')).toBe(false);
|
||||
expect(excluded.has('exit_plan_mode')).toBe(false);
|
||||
expect(excluded.has('save_memory')).toBe(false);
|
||||
// Read-only MCP tool allowed by annotation rule (matched via _serverName)
|
||||
expect(excluded.has('mcp_mcp-server_read_tool')).toBe(false);
|
||||
});
|
||||
|
||||
@@ -66,9 +66,6 @@ describe('PromptProvider', () => {
|
||||
storage: {
|
||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
||||
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
|
||||
getProjectMemoryDir: vi
|
||||
.fn()
|
||||
.mockReturnValue('/tmp/project-temp/memory'),
|
||||
getProjectTempTrackerDir: vi
|
||||
.fn()
|
||||
.mockReturnValue('/tmp/project-temp/tracker'),
|
||||
@@ -76,6 +73,7 @@ describe('PromptProvider', () => {
|
||||
isInteractive: vi.fn().mockReturnValue(true),
|
||||
isInteractiveShellEnabled: vi.fn().mockReturnValue(true),
|
||||
isTopicUpdateNarrationEnabled: vi.fn().mockReturnValue(false),
|
||||
isMemoryV2Enabled: vi.fn().mockReturnValue(false),
|
||||
getSkillManager: vi.fn().mockReturnValue({
|
||||
getSkills: vi.fn().mockReturnValue([]),
|
||||
}),
|
||||
|
||||
@@ -228,10 +228,13 @@ export class PromptProvider {
|
||||
context.config.getEnableShellOutputEfficiency(),
|
||||
interactiveShellEnabled: context.config.isInteractiveShellEnabled(),
|
||||
topicUpdateNarration: isTopicUpdateNarrationEnabled,
|
||||
userProjectMemoryPath: normalizePromptPath(
|
||||
getProjectMemoryIndexFilePath(context.config.storage),
|
||||
),
|
||||
globalMemoryPath: normalizePromptPath(getGlobalMemoryFilePath()),
|
||||
memoryV2Enabled: context.config.isMemoryV2Enabled(),
|
||||
userProjectMemoryPath: context.config.isMemoryV2Enabled()
|
||||
? getProjectMemoryIndexFilePath(context.config.storage)
|
||||
: undefined,
|
||||
globalMemoryPath: context.config.isMemoryV2Enabled()
|
||||
? getGlobalMemoryFilePath()
|
||||
: undefined,
|
||||
}),
|
||||
),
|
||||
sandbox: this.withSection('sandbox', () => ({
|
||||
@@ -335,10 +338,6 @@ export class PromptProvider {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePromptPath(filePath: string): string {
|
||||
return filePath.replaceAll('\\', '/');
|
||||
}
|
||||
|
||||
// --- Internal Context Helpers ---
|
||||
|
||||
function getSandboxMode(): snippets.SandboxMode {
|
||||
|
||||
+23
-4
@@ -7,15 +7,26 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderOperationalGuidelines } from './snippets.js';
|
||||
|
||||
describe('renderOperationalGuidelines - memory', () => {
|
||||
describe('renderOperationalGuidelines - memoryV2Enabled', () => {
|
||||
const baseOptions = {
|
||||
interactive: true,
|
||||
interactiveShellEnabled: false,
|
||||
topicUpdateNarration: false,
|
||||
memoryV2Enabled: false,
|
||||
};
|
||||
|
||||
it('should distinguish shared GEMINI.md instructions from private MEMORY.md', () => {
|
||||
it('should include standard memory tool guidance when memoryV2Enabled is false', () => {
|
||||
const result = renderOperationalGuidelines(baseOptions);
|
||||
expect(result).toContain('save_memory');
|
||||
expect(result).toContain('persist facts across sessions');
|
||||
expect(result).not.toContain('Instruction and Memory Files');
|
||||
});
|
||||
|
||||
it('should distinguish shared GEMINI.md instructions from private MEMORY.md when memoryV2Enabled is true', () => {
|
||||
const result = renderOperationalGuidelines({
|
||||
...baseOptions,
|
||||
memoryV2Enabled: true,
|
||||
});
|
||||
expect(result).toContain('Instruction and Memory Files');
|
||||
expect(result).toContain('GEMINI.md');
|
||||
expect(result).toContain('./GEMINI.md');
|
||||
@@ -47,7 +58,10 @@ describe('renderOperationalGuidelines - memory', () => {
|
||||
});
|
||||
|
||||
it('should NOT include the Private Project Memory bullet when userProjectMemoryPath is undefined', () => {
|
||||
const result = renderOperationalGuidelines(baseOptions);
|
||||
const result = renderOperationalGuidelines({
|
||||
...baseOptions,
|
||||
memoryV2Enabled: true,
|
||||
});
|
||||
expect(result).not.toContain('**Private Project Memory**');
|
||||
});
|
||||
|
||||
@@ -56,6 +70,7 @@ describe('renderOperationalGuidelines - memory', () => {
|
||||
'/Users/test/.gemini/tmp/abc123/memory/MEMORY.md';
|
||||
const result = renderOperationalGuidelines({
|
||||
...baseOptions,
|
||||
memoryV2Enabled: true,
|
||||
userProjectMemoryPath,
|
||||
});
|
||||
expect(result).toContain('**Private Project Memory**');
|
||||
@@ -64,7 +79,10 @@ describe('renderOperationalGuidelines - memory', () => {
|
||||
});
|
||||
|
||||
it('should NOT include the Global Personal Memory bullet or cross-project routing rule when globalMemoryPath is undefined', () => {
|
||||
const result = renderOperationalGuidelines(baseOptions);
|
||||
const result = renderOperationalGuidelines({
|
||||
...baseOptions,
|
||||
memoryV2Enabled: true,
|
||||
});
|
||||
expect(result).not.toContain('**Global Personal Memory**');
|
||||
expect(result).not.toContain('across all my projects');
|
||||
expect(result).not.toContain('cross-project personal preference');
|
||||
@@ -74,6 +92,7 @@ describe('renderOperationalGuidelines - memory', () => {
|
||||
const globalMemoryPath = '/Users/test/.gemini/GEMINI.md';
|
||||
const result = renderOperationalGuidelines({
|
||||
...baseOptions,
|
||||
memoryV2Enabled: true,
|
||||
globalMemoryPath,
|
||||
});
|
||||
expect(result).toContain('**Global Personal Memory**');
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
EXIT_PLAN_MODE_TOOL_NAME,
|
||||
GLOB_TOOL_NAME,
|
||||
GREP_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
READ_FILE_TOOL_NAME,
|
||||
SHELL_PARAM_IS_BACKGROUND,
|
||||
SHELL_TOOL_NAME,
|
||||
@@ -73,6 +74,7 @@ export interface OperationalGuidelinesOptions {
|
||||
enableShellEfficiency: boolean;
|
||||
interactiveShellEnabled: boolean;
|
||||
topicUpdateNarration?: boolean;
|
||||
memoryV2Enabled: boolean;
|
||||
/**
|
||||
* Absolute path to the user's per-project private memory index. See
|
||||
* snippets.ts for full semantics.
|
||||
@@ -702,15 +704,23 @@ function toolUsageInteractive(
|
||||
function toolUsageRememberingFacts(
|
||||
options: OperationalGuidelinesOptions,
|
||||
): string {
|
||||
const userProjectBullet = options.userProjectMemoryPath
|
||||
? `
|
||||
if (options.memoryV2Enabled) {
|
||||
const userProjectBullet = options.userProjectMemoryPath
|
||||
? `
|
||||
- **Private Project Memory** (\`${options.userProjectMemoryPath}\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.`
|
||||
: '';
|
||||
return `
|
||||
: '';
|
||||
return `
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with '${EDIT_TOOL_NAME}' or '${WRITE_FILE_TOOL_NAME}'. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.${userProjectBullet}
|
||||
Whenever the user tells you to "remember" something or states a durable personal workflow for this codebase, save it in the private project memory folder immediately. Put concise index entries in \`MEMORY.md\`; if more detail is useful, create or update a sibling \`*.md\` note in the same folder and keep \`MEMORY.md\` as the pointer. Only update \`GEMINI.md\` files when the memory is a shared project instruction or convention that belongs in the repo. If it could be either tier, ask the user. Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.`;
|
||||
}
|
||||
const base = `
|
||||
- **Remembering Facts:** Use the '${MEMORY_TOOL_NAME}' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases, or a workflow like "always lint after editing"). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information.`;
|
||||
const suffix = options.interactive
|
||||
? ' If unsure whether to save something, you can ask the user, "Should I remember that for you?"'
|
||||
: '';
|
||||
return base + suffix;
|
||||
}
|
||||
|
||||
function gitRepoKeepUserInformed(interactive: boolean): string {
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
TOPIC_PARAM_SUMMARY,
|
||||
GLOB_TOOL_NAME,
|
||||
GREP_TOOL_NAME,
|
||||
MEMORY_TOOL_NAME,
|
||||
READ_FILE_TOOL_NAME,
|
||||
SHELL_TOOL_NAME,
|
||||
WRITE_FILE_TOOL_NAME,
|
||||
@@ -84,16 +85,23 @@ export interface OperationalGuidelinesOptions {
|
||||
interactive: boolean;
|
||||
interactiveShellEnabled: boolean;
|
||||
topicUpdateNarration: boolean;
|
||||
memoryV2Enabled: boolean;
|
||||
/**
|
||||
* Absolute path to the user's per-project private memory index
|
||||
* (e.g. ~/.gemini/tmp/<project-hash>/memory/MEMORY.md).
|
||||
* (e.g. ~/.gemini/tmp/<project-hash>/memory/MEMORY.md). Surfaced to the
|
||||
* model when memoryV2Enabled is true so the prompt-driven memory flow
|
||||
* can route project-specific personal notes there instead of the committed
|
||||
* project GEMINI.md.
|
||||
*/
|
||||
userProjectMemoryPath?: string;
|
||||
/**
|
||||
* Absolute path to the user's global personal memory file
|
||||
* (e.g. ~/.gemini/GEMINI.md). Config.isPathAllowed surgically allowlists
|
||||
* this exact file (only this file, not the rest of `~/.gemini/`) so the
|
||||
* agent can edit it directly.
|
||||
* (e.g. ~/.gemini/GEMINI.md). Surfaced to the model when memoryV2Enabled
|
||||
* is true so the prompt-driven memory flow can route cross-project personal
|
||||
* preferences (preferences that follow the user across all workspaces) there
|
||||
* instead of the project-scoped tiers. Config.isPathAllowed surgically
|
||||
* allowlists this exact file (only this file, not the rest of `~/.gemini/`)
|
||||
* so the agent can edit it directly.
|
||||
*/
|
||||
globalMemoryPath?: string;
|
||||
}
|
||||
@@ -832,19 +840,20 @@ function toolUsageInteractive(
|
||||
function toolUsageRememberingFacts(
|
||||
options: OperationalGuidelinesOptions,
|
||||
): string {
|
||||
const userProjectBullet = options.userProjectMemoryPath
|
||||
? `
|
||||
if (options.memoryV2Enabled) {
|
||||
const userProjectBullet = options.userProjectMemoryPath
|
||||
? `
|
||||
- **Private Project Memory** (\`${options.userProjectMemoryPath}\`): Personal-to-the-user, project-specific notes that must **NOT** be committed to the repo. Keep this file concise: it is the private index for this workspace. Store richer detail in sibling \`*.md\` files in the same folder and use \`MEMORY.md\` to point to them.`
|
||||
: '';
|
||||
const globalMemoryBullet = options.globalMemoryPath
|
||||
? `
|
||||
: '';
|
||||
const globalMemoryBullet = options.globalMemoryPath
|
||||
? `
|
||||
- **Global Personal Memory** (\`${options.globalMemoryPath}\`): Cross-project personal preferences and facts about the user that should follow them into every workspace (e.g. preferred testing framework across all projects, language preferences, coding-style defaults). Loaded automatically in every session. Keep entries concise and durable — never workspace-specific.`
|
||||
: '';
|
||||
const globalRoutingRule = options.globalMemoryPath
|
||||
? `
|
||||
: '';
|
||||
const globalRoutingRule = options.globalMemoryPath
|
||||
? `
|
||||
- When the user states a **cross-project personal preference** that should follow them into every workspace ("I always prefer X", "across all my projects", "my personal coding style is Y", "in general I like Z"), update the global personal memory file. Do **not** also write it into a \`GEMINI.md\` file or the private memory folder.`
|
||||
: '';
|
||||
return `
|
||||
: '';
|
||||
return `
|
||||
- **Instruction and Memory Files:** You persist long-lived project context by editing markdown files directly with ${formatToolName(EDIT_TOOL_NAME)} or ${formatToolName(WRITE_FILE_TOOL_NAME)}. There is no \`save_memory\` tool. The current contents of all loaded \`GEMINI.md\` files and the private project \`MEMORY.md\` index are already in your context — do not re-read them before editing.
|
||||
- **Project Instructions** (\`./GEMINI.md\`): Team-shared architecture, conventions, workflows, and other repo guidance. **Committed to the repo and shared with the team.**
|
||||
- **Subdirectory Instructions** (e.g. \`./src/GEMINI.md\`): Scoped instructions for one part of the project. Reference them from \`./GEMINI.md\` so they remain discoverable.${userProjectBullet}${globalMemoryBullet}
|
||||
@@ -855,6 +864,16 @@ function toolUsageRememberingFacts(
|
||||
**Never duplicate or mirror the same fact across tiers** — each fact lives in exactly one file across all four tiers (project \`GEMINI.md\`, subdirectory \`GEMINI.md\`, private project memory, global personal memory). Do not add cross-references between any of them.
|
||||
**Inside the private memory folder:** \`MEMORY.md\` is the index for its sibling \`*.md\` notes **in that same folder only** — never use it to point at, summarize, or duplicate content from any \`GEMINI.md\` file. For brief facts, write the entry directly into \`MEMORY.md\`. When a note has substantial detail (multiple sections, procedures, or fields), put the detail in a sibling \`*.md\` file in the same folder and add a one-line pointer entry in \`MEMORY.md\`.
|
||||
Never save transient session state, summaries of code changes, bug fixes, or task-specific findings — these files are loaded into every session and must stay lean.`;
|
||||
}
|
||||
const base = `
|
||||
- **Memory Tool:** Use ${formatToolName(MEMORY_TOOL_NAME)} to persist facts across sessions. It supports two scopes via the \`scope\` parameter:
|
||||
- \`"global"\` (default): Cross-project preferences and personal facts loaded in every workspace.
|
||||
- \`"project"\`: Facts specific to the current workspace, private to the user (not committed to the repo). Use this for local dev setup notes, project-specific workflows, or personal reminders about this codebase.
|
||||
Never save transient session state. Do not use memory to store summaries of code changes, bug fixes, or findings discovered during a task.`;
|
||||
const suffix = options.interactive
|
||||
? ' If unsure whether a fact is global or project-specific, ask the user.'
|
||||
: '';
|
||||
return base + suffix;
|
||||
}
|
||||
|
||||
function gitRepoKeepUserInformed(interactive: boolean): string {
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import {
|
||||
isStrictlyApproved,
|
||||
isKnownSafeCommand,
|
||||
isDangerousCommand,
|
||||
} from './commandSafety.js';
|
||||
import * as paths from '../../utils/paths.js';
|
||||
|
||||
vi.mock('../../utils/paths.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../utils/paths.js')>();
|
||||
return {
|
||||
...actual,
|
||||
resolveToRealPath: vi.fn((p: string) => p),
|
||||
isTrustedSystemPath: vi.fn(() => false),
|
||||
};
|
||||
});
|
||||
|
||||
describe('commandSafety', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe('rg specific logic', () => {
|
||||
it('should consider rg safe without unsafe args if path is trusted', () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/usr/bin/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(true);
|
||||
|
||||
// Using isKnownSafeCommand which calls isSafeToCallWithExec under the hood
|
||||
expect(isKnownSafeCommand(['/usr/bin/rg', 'pattern', 'file.txt'])).toBe(
|
||||
true,
|
||||
);
|
||||
expect(paths.resolveToRealPath).toHaveBeenCalledWith('/usr/bin/rg');
|
||||
expect(paths.isTrustedSystemPath).toHaveBeenCalledWith('/usr/bin/rg');
|
||||
});
|
||||
|
||||
it('should not consider bare rg safe (Search Path Interruption prevention)', () => {
|
||||
// Bare 'rg' is not an absolute path, so it fails `isTrustedCommandPath`
|
||||
expect(isKnownSafeCommand(['rg', 'pattern', 'file.txt'])).toBe(false);
|
||||
});
|
||||
|
||||
it('should not consider rg safe with unsafe args even if path is trusted', () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/usr/bin/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(true);
|
||||
|
||||
expect(
|
||||
isKnownSafeCommand(['/usr/bin/rg', '--search-zip', 'pattern']),
|
||||
).toBe(false);
|
||||
expect(isKnownSafeCommand(['/usr/bin/rg', '-z', 'pattern'])).toBe(false);
|
||||
expect(isKnownSafeCommand(['/usr/bin/rg', '--pre=cat', 'pattern'])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should consider rg dangerous with unsafe args', () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/usr/bin/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(true);
|
||||
|
||||
expect(
|
||||
isDangerousCommand(['/usr/bin/rg', '--search-zip', 'pattern']),
|
||||
).toBe(true);
|
||||
expect(isDangerousCommand(['/usr/bin/rg', '--pre=cat', 'pattern'])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('should not consider rg safe if path is untrusted', () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/tmp/malicious/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(false);
|
||||
|
||||
expect(isKnownSafeCommand(['/tmp/malicious/rg', 'pattern'])).toBe(false);
|
||||
expect(paths.resolveToRealPath).toHaveBeenCalledWith('/tmp/malicious/rg');
|
||||
});
|
||||
|
||||
it('should not consider rg safe if path resolution throws', () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockImplementation(() => {
|
||||
throw new Error('Resolution failed');
|
||||
});
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(true);
|
||||
|
||||
expect(isKnownSafeCommand(['/some/path/rg', 'pattern'])).toBe(false);
|
||||
});
|
||||
|
||||
it('should flag untrusted rg as dangerous if it has unsafe args (Paranoid validation)', () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/tmp/malicious/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(false);
|
||||
|
||||
// isDangerousCommand relies on isRipgrepCommand, which strictly identifies intent (name)
|
||||
// and doesn't care about path safety. So even an untrusted rg will be flagged if it has unsafe args.
|
||||
expect(isDangerousCommand(['/tmp/malicious/rg', '--search-zip'])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isStrictlyApproved', () => {
|
||||
it('should approve rg if explicitly in approved tools regardless of path', async () => {
|
||||
// In this case, isStrictlyApproved relies on `tools.includes(command)`
|
||||
expect(
|
||||
await isStrictlyApproved(
|
||||
'/tmp/malicious/rg',
|
||||
['pattern'],
|
||||
['/tmp/malicious/rg'],
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should approve rg if path is trusted', async () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/usr/bin/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(true);
|
||||
|
||||
expect(await isStrictlyApproved('/usr/bin/rg', ['pattern'])).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject rg if path is untrusted and not explicitly approved', async () => {
|
||||
vi.mocked(paths.resolveToRealPath).mockReturnValue('/tmp/malicious/rg');
|
||||
vi.mocked(paths.isTrustedSystemPath).mockReturnValue(false);
|
||||
|
||||
expect(await isStrictlyApproved('/tmp/malicious/rg', ['pattern'])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user