Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): track popd and credential selectors

Chris1993fe306b6d
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts
index 659f27c465..89ce8f2efa 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-policy.test.ts
@@ -160,7 +160,7 @@ describe('classifyBuiltinToolForAutoReview — Windows 盘符路径边界', () =
describe('classifyBuiltinToolForAutoReview — Bash 只读命令放行', () => {
it('常见只读命令 auto-approve', () => {
- for (const c of ['ls -la', 'cat package.json', 'pwd', 'grep -rn foo src --include="[!.]*.ts"', 'rg TODO', 'wc -l x', 'head -5 f', 'echo hi']) {
+ for (const c of ['ls -la', 'cat package.json', 'pwd', 'grep -rn foo src --include="[b]ook.ts"', 'rg TODO', 'wc -l x', 'head -5 f', 'echo hi']) {
expect(verdict('Bash', { command: c })).toBe('auto-approve');
}
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 7699ff4872..388be4e11a 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -537,6 +537,49 @@ describe('cindy-bridge extension source', () => {
stackOtherOrdinaryLink,
].includes(target)), command).toBe(true);
}
+ for (const command of [
+ `pushd ${nestedDir} && pushd ${stackOtherDir} && popd && cat <${cwdSwitchName}`,
+ `pushd ${nestedDir} && pushd ${stackOtherDir} && builtin popd +0 && cat <${cwdSwitchName}`,
+ `pushd -n ${nestedDir} && popd && cat <${cwdSwitchName}`,
+ ]) {
+ const evidence = context.bashInputReadEvidence?.({ command });
+ expect(evidence, command).toEqual({ targets: [nestedCwdSwitchSecretLink], unresolved: false });
+ expect(context.collectResolvedCredentialPaths?.(evidence?.targets), command)
+ .toEqual([realpathSync(secretPath)]);
+ }
+ for (const command of [
+ `pushd ${nestedDir} && popd && cat <${cwdSwitchName}`,
+ `pushd ${nestedDir} && pushd ${stackOtherDir} && popd && popd && cat <${cwdSwitchName}`,
+ ]) {
+ expect(context.bashInputReadEvidence?.({ command }), command).toEqual({
+ targets: [rootCwdSwitchOrdinaryLink],
+ unresolved: false,
+ });
+ }
+ for (const command of [
+ `pushd ${nestedDir} && pushd ${stackOtherDir} && popd +1 && cat <${cwdSwitchName}`,
+ `pushd ${nestedDir} && pushd ${stackOtherDir} && popd -0 && cat <${cwdSwitchName}`,
+ ]) {
+ expect(context.bashInputReadEvidence?.({ command }), command).toEqual({
+ targets: [stackOtherOrdinaryLink],
+ unresolved: false,
+ });
+ }
+ const sequentialPopdCommand = `pushd ${nestedDir}; pushd ${stackOtherDir}; popd; cat <${cwdSwitchName}`;
+ const sequentialPopdEvidence = context.bashInputReadEvidence?.({ command: sequentialPopdCommand });
+ expect(sequentialPopdEvidence?.unresolved, sequentialPopdCommand).toBe(true);
+ expect(sequentialPopdEvidence?.targets, sequentialPopdCommand)
+ .toContain(nestedCwdSwitchSecretLink);
+ expect(context.collectResolvedCredentialPaths?.(sequentialPopdEvidence?.targets))
+ .toEqual([realpathSync(secretPath)]);
+ expect(context.bashInputReadEvidence?.({
+ command: `popd >/dev/null; cat <ordinary-link.txt`,
+ })).toEqual({ targets: [ordinaryLink], unresolved: true });
+ context.process.env['BASH_FUNC_popd%%'] = '() { builtin cd "$HOME"; }';
+ expect(context.bashInputReadEvidence?.({
+ command: `popd >/dev/null; cat <ordinary-link.txt`,
+ })).toEqual({ targets: [ordinaryLink], unresolved: true });
+ delete context.process.env['BASH_FUNC_popd%%'];
expect(context.bashInputReadEvidence?.({
command: `pushd -n ${nestedDir} >/dev/null && cat <ordinary-link.txt`,
})).toEqual({
@@ -546,7 +589,7 @@ describe('cindy-bridge extension source', () => {
expect(context.bashInputReadEvidence?.({
command: `true && 2>/dev/null builtin pushd ${nestedDir} && cat <${cwdSwitchName}`,
})).toEqual({
- targets: [rootCwdSwitchOrdinaryLink, nestedCwdSwitchSecretLink],
+ targets: [nestedCwdSwitchSecretLink],
unresolved: false,
});
expect(context.bashInputReadEvidence?.({
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index 6087f82a75..e90be67641 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -2131,6 +2131,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
for (const [sessionId, command] of [
['perm-auto-bash-symlink-dotenv-pushd-rotation', 'pushd sub >/dev/null; pushd ../stack-other >/dev/null; pushd +1 >/dev/null; cat<link'],
+ ['perm-auto-bash-symlink-dotenv-popd', 'pushd sub; pushd ../stack-other; popd; cat<link'],
['perm-auto-bash-symlink-dotenv-assignment-cd', 'X=1 cd sub && cat<link'],
['perm-auto-bash-symlink-dotenv-assignment-leading-redirect', 'X=1 2>/dev/null builtin cd sub && cat<link'],
['perm-auto-bash-symlink-dotenv-leading-assignment-wrapper', '2>/dev/null X=1 command -- cd sub && cat<link'],
@@ -2160,6 +2161,27 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
expect(followUp.some((b) => b.includes('User denied this tool call via Cindy.')), command).toBe(true);
}
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('bash', {
+ command: 'pushd sub && popd && cat<link',
+ }),
+ anthropicStreamBody('bash ordinary popd turn finished'),
+ );
+ const ordinaryPopdReqBefore = seenRequests.length;
+ const ordinaryPopdTurn = await runPermissionTurn({
+ sessionId: 'perm-full-access-bash-popd-plain',
+ workingDir,
+ permissionMode: 'bypassPermissions',
+ resolverBehavior: 'allow',
+ });
+ expect(ordinaryPopdTurn.resolverTools).toEqual([]);
+ const ordinaryPopdFollowUp = seenRequests.slice(ordinaryPopdReqBefore)
+ .map((request) => request.body);
+ expect(ordinaryPopdFollowUp.some((body) => body.includes('ordinary-content'))).toBe(true);
+ expect(ordinaryPopdFollowUp.some((body) => body.includes('FAKE_REDIRECT_DOTENV_SECRET')))
+ .toBe(false);
+
scriptedResponses.length = 0;
scriptedResponses.push(
anthropicToolUseBody('bash', { command: 'X=1 2>/dev/null builtin cd sub && cat<link' }),
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index e23fb4ab6f..2dd1b5316d 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -439,14 +439,18 @@ function bashOperatorAfterRedirections(command: string, start: number): BashPost
return { operator: '', end: cursor, unresolved: false, hadRedirection };
}
-function bashInheritedDirectoryChangeIsUncertain(target: string): boolean {
+function bashInheritedDirectoryChangeIsUncertain(
+ command: 'cd' | 'pushd' | 'popd',
+ target: string,
+): boolean {
if (path.sep !== '/') return false;
// Non-interactive Bash startup files and exported builtin overrides can change
// directory semantics before this command runs; their contents are not static evidence.
const bashEnv = process.env.BASH_ENV;
if (typeof bashEnv === 'string' && bashEnv.trim().length > 0) return true;
- if (Object.keys(process.env).some((name) => /^BASH_FUNC_(?:cd|pushd)%%$/.test(name))) return true;
+ if (Object.keys(process.env).some((name) => /^BASH_FUNC_(?:cd|pushd|popd)%%$/.test(name))) return true;
+ if (command === 'popd') return false;
const bashOptions = (process.env.BASHOPTS ?? '').split(':');
if (bashOptions.includes('cdable_vars') && /^[A-Za-z_][A-Za-z0-9_]*$/.test(target)) return true;
@@ -464,7 +468,7 @@ type BashLeadingRedirection = { end: number; unresolved: boolean };
type BashAssignmentPrefix = { end: number; name: string; unresolved: boolean };
type BashDirectoryChangeHead = {
cursor: number;
- command: 'cd' | 'pushd' | null;
+ command: 'cd' | 'pushd' | 'popd' | null;
hadRedirection: boolean;
unresolved: boolean;
};
@@ -565,7 +569,7 @@ function bashUnresolvedHeadHasDirectoryChange(codeMask: string, start: number):
if (/[;&|\n]/.test(char)) break;
visible += char;
}
- return /^\s*(?:[A-Za-z_][A-Za-z0-9_]*(?:\+)?=\S*\s+)*(?:(?:command|builtin)\s+)*(?:cd|pushd)(?:\s|$)/
+ return /^\s*(?:[A-Za-z_][A-Za-z0-9_]*(?:\+)?=\S*\s+)*(?:(?:command|builtin)\s+)*(?:cd|pushd|popd)(?:\s|$)/
.test(visible);
}
@@ -618,7 +622,7 @@ function bashDirectoryChangeHead(
: null;
}
- if ((word.target !== 'cd' && word.target !== 'pushd') || word.unresolved) {
+ if ((word.target !== 'cd' && word.target !== 'pushd' && word.target !== 'popd') || word.unresolved) {
if (unresolved && bashUnresolvedHeadHasDirectoryChange(codeMask, cursor)) {
return { cursor, command: null, hadRedirection, unresolved: true };
}
@@ -627,8 +631,30 @@ function bashDirectoryChangeHead(
return { cursor: word.end, command: word.target, hadRedirection, unresolved };
}
+type BashDirectoryState = { stack: string[] };
+const BASH_DIRECTORY_STATE_LIMIT = 128;
+const BASH_DIRECTORY_STACK_LIMIT = 128;
+
+function bashUniqueDirectoryStates(states: readonly BashDirectoryState[]): BashDirectoryState[] | null {
+ const unique = new Map<string, BashDirectoryState>();
+ for (const state of states) {
+ unique.set(state.stack.join('\u0000'), state);
+ if (unique.size > BASH_DIRECTORY_STATE_LIMIT) return null;
+ }
+ return [...unique.values()];
+}
+
+function bashPopdIndex(operand: string, stackLength: number): number | null {
+ if (!operand) return 0;
+ const match = /^([+-])(\d+)$/.exec(operand);
+ if (!match) return null;
+ const offset = Number(match[2]);
+ if (!Number.isSafeInteger(offset)) return null;
+ return match[1] === '+' ? offset : stackLength - 1 - offset;
+}
+
function bashWorkingDirectoryCandidates(command: string, globBudget: BashGlobBudget): BashPathCandidates {
- let candidates = [process.cwd()];
+ let states: BashDirectoryState[] = [{ stack: [process.cwd()] }];
let unresolved = false;
const codeMask = bashShellCodeMask(command);
const commandStart = /(?:^(?=[^;&|(){}\n])|[;&|(){}\n])\s*(?:(?:if|then|elif|else|while|until|do)\s+)?/g;
@@ -636,15 +662,11 @@ function bashWorkingDirectoryCandidates(command: string, globBudget: BashGlobBud
const matchIndex = match.index ?? 0;
const head = bashDirectoryChangeHead(command, codeMask, matchIndex + match[0].length);
if (!head) continue;
- if (head.unresolved) {
+ if (head.unresolved || !head.command) {
unresolved = true;
continue;
}
let cursor = head.cursor;
- let hadRedirection = head.hadRedirection;
- const precededByConditionalOperator = matchIndex > 0
- && ((codeMask[matchIndex] === '&' && codeMask[matchIndex - 1] === '&')
- || (codeMask[matchIndex] === '|' && codeMask[matchIndex - 1] === '|'));
const changeDepth = bashSubshellDepthAt(codeMask, cursor);
if (!bashSubshellScopeRemainsOpen(codeMask, cursor, changeDepth)) continue;
let parsed = readShellRedirectionTarget(command, bashInlinePaddingEnd(command, cursor));
@@ -654,29 +676,40 @@ function bashWorkingDirectoryCandidates(command: string, globBudget: BashGlobBud
cursor = bashInlinePaddingEnd(command, cursor);
const redirection = bashLeadingRedirectionAt(command, cursor);
if (redirection) {
- hadRedirection = true;
unresolved ||= redirection.unresolved;
cursor = redirection.end;
parsed = readShellRedirectionTarget(command, bashInlinePaddingEnd(command, cursor));
continue;
}
- const knownOption = head.command === 'pushd'
+ const stackOption = head.command === 'pushd' || head.command === 'popd';
+ const knownOption = stackOption
? parsed.target === '-n'
: parsed.target !== '--' && /^-[LPe]+$/.test(parsed.target);
if (parsed.target !== '--' && !knownOption) break;
if (parsed.target === '--') optionsEnded = true;
- if (head.command === 'pushd' && parsed.target === '-n') suppressDirectoryChange = true;
+ if (stackOption && parsed.target === '-n') suppressDirectoryChange = true;
cursor = parsed.end;
parsed = readShellRedirectionTarget(command, bashInlinePaddingEnd(command, cursor));
}
- if (head.command === 'pushd' && !optionsEnded && /^[+-]\d+$/.test(parsed.target)) {
+
+ const pushdRotation = head.command === 'pushd'
+ && !optionsEnded && /^[+-]\d+$/.test(parsed.target);
+ if (pushdRotation) {
+ // Rotation can include an inherited stack that is unavailable to this invocation.
unresolved = true;
continue;
}
- if (!parsed.target || parsed.unresolved || (!optionsEnded && parsed.target.startsWith('-'))) {
+ if (head.command !== 'popd'
+ && (!parsed.target || parsed.unresolved || (!optionsEnded && parsed.target.startsWith('-')))) {
unresolved = true;
continue;
}
+ if (head.command === 'popd' && (parsed.unresolved
+ || (parsed.target && !optionsEnded && !/^[+-]\d+$/.test(parsed.target)))) {
+ unresolved = true;
+ continue;
+ }
+
const operatorEvidence = bashOperatorAfterRedirections(command, parsed.end);
if (operatorEvidence.unresolved) {
unresolved = true;
@@ -684,35 +717,67 @@ function bashWorkingDirectoryCandidates(command: string, globBudget: BashGlobBud
}
const operator = operatorEvidence.operator;
if (!operator || operator === '|' || operator === '&') continue;
- if (suppressDirectoryChange) continue;
- if (bashInheritedDirectoryChangeIsUncertain(parsed.target)) {
+ if (bashInheritedDirectoryChangeIsUncertain(head.command, parsed.target)) {
unresolved = true;
continue;
}
- const changed: string[] = [];
- for (const cwd of candidates) {
- const expanded = bashExpandedPathCandidates(parsed.target, cwd, parsed.mayExpand, globBudget);
- unresolved ||= expanded.unresolved;
- for (const candidate of expanded.paths) {
- try {
- if (statSync(candidate).isDirectory()) changed.push(candidate);
- } catch {
- // A failed cd leaves cwd unchanged for later ;/newline commands.
+ const changed: BashDirectoryState[] = [];
+ let stateChangeUnresolved = false;
+ if (head.command === 'popd') {
+ if (suppressDirectoryChange) {
+ unresolved = true;
+ continue;
+ }
+ for (const state of states) {
+ const index = bashPopdIndex(parsed.target, state.stack.length);
+ if (index === null || index < 0 || index >= state.stack.length
+ || (index === 0 && state.stack.length < 2)) {
+ stateChangeUnresolved = true;
+ continue;
+ }
+ const stack = [...state.stack];
+ stack.splice(index, 1);
+ changed.push({ stack });
+ }
+ } else {
+ for (const state of states) {
+ const cwd = state.stack[0];
+ const expanded = bashExpandedPathCandidates(parsed.target, cwd, parsed.mayExpand, globBudget);
+ unresolved ||= expanded.unresolved;
+ for (const candidate of expanded.paths) {
+ try {
+ if (!statSync(candidate).isDirectory()) continue;
+ if (head.command === 'cd') {
+ changed.push({ stack: [candidate, ...state.stack.slice(1)] });
+ } else if (suppressDirectoryChange) {
+ changed.push({ stack: [cwd, candidate, ...state.stack.slice(1)] });
+ } else if (state.stack.length < BASH_DIRECTORY_STACK_LIMIT) {
+ changed.push({ stack: [candidate, ...state.stack] });
+ } else {
+ stateChangeUnresolved = true;
+ }
+ } catch {
+ // A failed cd/pushd leaves cwd and the directory stack unchanged.
+ }
}
}
}
+ unresolved ||= stateChangeUnresolved;
+
const branchMayHaveBeenSkipped = /\b(?:elif|else|fi|done|esac)\b/.test(
codeMask.slice(operatorEvidence.end),
);
- if (operator === '||' || branchMayHaveBeenSkipped || precededByConditionalOperator
- || ((hadRedirection || operatorEvidence.hadRedirection) && (operator === ';' || operator === '\n'))) {
- candidates = [...new Set([...candidates, ...changed])];
- } else if (changed.length > 0) {
- candidates = [...new Set(changed)];
+ const retainsPriorState = operator === '||' || operator === ';' || operator === '\n'
+ || branchMayHaveBeenSkipped;
+ const nextStates = retainsPriorState ? [...states, ...changed] : changed;
+ if (nextStates.length > 0) {
+ const unique = bashUniqueDirectoryStates(nextStates);
+ if (!unique) unresolved = true;
+ else states = unique;
}
}
- return { paths: candidates, unresolved };
+ return { paths: [...new Set(states.map((state) => state.stack[0]))], unresolved };
}
function bashShellCodeMask(command: string): string {
diff --git a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
index 5a18107742..9fa9b5e7ef 100644
--- a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
@@ -465,7 +465,15 @@ describe('对抗语料 — dotenv 凭证路径', () => {
'grep -ef .env',
'sed -nef .env.local',
'rg -g .env KEY .',
+ "rg -g '.n?trc' SECRET .",
+ "rg -g '?.key' SECRET .",
+ "rg -g '.s?h/config' SECRET .",
+ "rg -g '.config/g?-*/**' SECRET .",
"rg --type-add 'dotenv:.env' -tdotenv SECRET .",
+ "rg --type-add 'dotenv:.env' -Tdotenv -tdotenv SECRET .",
+ "rg --type-add 'dotenv:.env' -Tall -tdotenv SECRET .",
+ "rg --type-add 'dotenv:.env' -Tdotenv -tall SECRET .",
+ "rg --type-add 'credential:.n?trc' -tcredential SECRET .",
'rg --type-add=dotenv:.env --type=dotenv SECRET .',
'rg --type-add dotenv:.env -t dotenv SECRET .',
'rg --type-add dotenv:.env -tall SECRET .',
@@ -497,6 +505,8 @@ describe('对抗语料 — dotenv 凭证路径', () => {
'command grep --recursive API_KEY .',
'printf x | grep -r API_KEY .',
"rg --hidden -g '.env*' API_KEY .",
+ "rg --hidden -g '!.env*' API_KEY .",
+ "rg --hidden -g '!**/.env*' API_KEY .",
"rg --hidden -g '!.env*' -g '.env' API_KEY .",
'rg --hidden --no-ignore API_KEY .',
'rg -. --no-ignore API_KEY .',
@@ -742,24 +752,27 @@ describe('对抗语料 — dotenv 凭证路径', () => {
['grep -e.env data.json', 'auto-approve'],
['grep -ef data.json', 'auto-approve'],
['grep -ef.env data.json', 'auto-approve'],
- ["rg -g '[!.]*.ts' KEY .", 'auto-approve'],
+ ["rg -g '[b]ook.ts' KEY .", 'auto-approve'],
['rg --type-add safe:ordinary.txt -tsafe KEY .', 'auto-approve'],
['rg --type-add dotenv:.env -Tdotenv SECRET .', 'auto-approve'],
+ ['rg --type-add dotenv:.env -tdotenv -Tdotenv SECRET .', 'auto-approve'],
+ ['rg --type-add dotenv:.env -tall -Tdotenv SECRET .', 'auto-approve'],
+ ['rg --type-add dotenv:.env -tdotenv -Tall SECRET .', 'auto-approve'],
['rg --type-add dotenv:.env SECRET .', 'auto-approve'],
['rg --type-add dotenv:.env --type-clear dotenv --type-add dotenv:ordinary.txt -tdotenv KEY .', 'auto-approve'],
- ["grep -r --include='[!.]*.json' KEY .", 'auto-approve'],
- ["rg --hidden -g '[!.]*.ts' KEY .", 'auto-approve'],
+ ["grep -r --include='[b]ook.json' KEY .", 'auto-approve'],
+ ["rg --hidden -g '[b]ook.ts' KEY .", 'auto-approve'],
['rg --no-ignore KEY .', 'auto-approve'],
['rg -u KEY .', 'auto-approve'],
['rg --hidden --no-hidden KEY .', 'auto-approve'],
['rg -. --no-hidden --no-ignore KEY .', 'auto-approve'],
- ["rg -. -g '[!.]*.ts' KEY .", 'auto-approve'],
+ ["rg -. -g '[b]ook.ts' KEY .", 'auto-approve'],
['rg -e-. data.txt', 'auto-approve'],
['rg -uu --no-hidden KEY .', 'auto-approve'],
['rg -e --hidden data.txt', 'auto-approve'],
['rg -- --hidden data.txt', 'auto-approve'],
- ["grep -r --include='[!.]*.ts' KEY .", 'auto-approve'],
- ["grep -r --include='config.env*' KEY .", 'auto-approve'],
+ ["grep -r --include='[b]ook.ts' KEY .", 'auto-approve'],
+ ["grep -r --include='config.env.txt' KEY .", 'auto-approve'],
['grep -e -r data.txt', 'auto-approve'],
['grep -e-r data.txt', 'auto-approve'],
['grep --regexp=-r data.txt', 'auto-approve'],
@@ -772,7 +785,7 @@ describe('对抗语料 — dotenv 凭证路径', () => {
["grep -r --include='foo{.env,.ts}' KEY .", 'prompt'],
['env -- grep KEY data.txt', 'auto-approve'],
['env -- grep -e -r data.txt', 'auto-approve'],
- ["rg --hidden -g '!.env*' KEY .", 'auto-approve'],
+ ["rg -g '!.env*' KEY ordinary.txt", 'auto-approve'],
['git diff --stat', 'auto-approve'],
['git diff --name-only', 'auto-approve'],
['git diff --stat -- .', 'auto-approve'],
diff --git a/packages/maker-core/src/agents/shared/auto-review.corpus.test.ts b/packages/maker-core/src/agents/shared/auto-review.corpus.test.ts
index c6a530d81a..60243b429e 100644
--- a/packages/maker-core/src/agents/shared/auto-review.corpus.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.corpus.test.ts
@@ -26,8 +26,8 @@ const opts = { cwd: '/repo', platform: 'darwin' as const };
describe('语料回归 — 修复源 1:引号内 | 是数据不是管道', () => {
it('grep/rg 的 alternation pattern → auto-approve(改前被切碎落灰区)', () => {
for (const c of [
- 'grep -Rni "readSystemContacts\\|writeSystemContacts" /repo/apps/desktop/src --include="[!.]*.ts"',
- `grep -RniE "智能通讯录|推广|用法|联系人|contacts" apps packages --exclude-dir=node_modules --include='[!.]*.tsx'`,
+ 'grep -Rni "readSystemContacts\\|writeSystemContacts" /repo/apps/desktop/src --include="[b]ook.ts"',
+ `grep -RniE "智能通讯录|推广|用法|联系人|contacts" apps packages --exclude-dir=node_modules --include='[b]ook.tsx'`,
`rg -n "系统通讯录|智能通讯录|system contacts" . --glob '!node_modules'`,
`rg -n "NODE_OPTIONS|max-old-space-size|typecheck" .github/workflows`,
'grep -n "provider\\|chatId\\|threadId" apps/desktop/src/main/im/shared/router.ts',
@@ -51,7 +51,7 @@ describe('语料回归 — 修复源 2:cd 区内目录 && 只读命令', () => {
'cd /repo && git diff --check',
'cd /repo/packages/maker-core && ls -la src',
'cd /repo/.cindy-worktrees/feature-x && git diff upstream/main...HEAD --stat',
- 'cd /repo && grep -rn "classifyShellCommand" packages --include="[!.]*.ts" | head -20',
+ 'cd /repo && grep -rn "classifyShellCommand" packages --include="[b]ook.ts" | head -20',
]) {
expect(classifyShellCommand(c, roots, opts), c).toBe('auto-approve');
}
@@ -300,7 +300,7 @@ describe('review 第三轮 — token/option 解析族', () => {
'git diff --name-only | grep -E "\\.env|\\.pem|credential|secret"', roots, opts,
)).toBe('auto-approve');
expect(classifyShellCommand(
- 'grep -Rni "foo|bar" src --include="[!.]*.ts"', roots, opts,
+ 'grep -Rni "foo|bar" src --include="[b]ook.ts"', roots, opts,
)).toBe('auto-approve');
});
@@ -342,9 +342,9 @@ describe('review 第四轮 — 分类器入口族', () => {
// 命令替换会真的读凭证;变量展开会把令牌摊到命令行 —— 两类都不是纯数据。
expect(classifyShellCommand('grep "$(cat ~/.aws/credentials)" file', roots, opts)).toBe('prompt-each-time');
expect(classifyShellCommand('grep "$GITHUB_TOKEN" file', roots, opts)).toBe('prompt-each-time');
- // 静态模式仍照常剥离,两个方向都不回退;递归范围显式限制为非 dotenv 文件。
+ // 静态模式仍照常剥离,两个方向都不回退;递归范围限制为固定的普通文件 selector。
expect(classifyShellCommand(
- 'grep -Rni "foo|bar" src --include="[!.]*.ts"', roots, opts,
+ 'grep -Rni "foo|bar" src --include="[b]ook.ts"', roots, opts,
)).toBe('auto-approve');
expect(classifyShellCommand(
'git diff --name-only | grep -E "\\.env|\\.pem|credential|secret"', roots, opts,
@@ -408,9 +408,9 @@ describe('review 第五轮 — 选项值与动态执行', () => {
]) {
expect(classifyShellCommand(c, roots, opts), c).toBe('prompt-each-time');
}
- // 真正的搜索模式仍照常剥离;递归范围显式限制为非 dotenv 文件。
+ // 真正的搜索模式仍照常剥离;递归范围限制为固定的普通文件 selector。
expect(classifyShellCommand(
- 'grep -Rni "foo|bar" src --include="[!.]*.ts"', roots, opts,
+ 'grep -Rni "foo|bar" src --include="[b]ook.ts"', roots, opts,
)).toBe('auto-approve');
expect(classifyShellCommand(
'git diff --name-only | grep -E "\\.env|\\.pem|credential|secret"', roots, opts,
@@ -825,7 +825,7 @@ describe('语料回归 — 命中率下限(总量护栏)', () => {
'git branch --show-current',
'ls -la',
'cat package.json',
- 'grep -rn "TODO" src --include="[!.]*.ts" | head -20',
+ 'grep -rn "TODO" src --include="[b]ook.ts" | head -20',
'rg -n "foo|bar" src',
'sed -n 1,120p src/index.ts',
'gh pr view 1 --json state',
diff --git a/packages/maker-core/src/agents/shared/auto-review.test.ts b/packages/maker-core/src/agents/shared/auto-review.test.ts
index 5f66c546e7..776e2d6f24 100644
--- a/packages/maker-core/src/agents/shared/auto-review.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.test.ts
@@ -80,7 +80,7 @@ describe('reviewAction — exec 实际 cwd 边界', () => {
describe('classifyShellCommand — 只读放行', () => {
it('常见只读命令 / git 只读 / curl GET', () => {
- for (const c of ['ls -la', 'cat f', 'grep -rn x . --include="[!.]*.ts"', 'rg TODO', 'git status', 'git log', 'curl -sS https://x.com', 'env FOO=1 ls', 'timeout 5 grep x f']) {
+ for (const c of ['ls -la', 'cat f', 'grep -rn x . --include="[b]ook.ts"', 'rg TODO', 'git status', 'git log', 'curl -sS https://x.com', 'env FOO=1 ls', 'timeout 5 grep x f']) {
expect(classifyShellCommand(c, roots)).toBe('auto-approve');
}
});
@@ -1016,7 +1016,7 @@ describe('classifyShellCommand — 第三轮 bot 审查回归护栏', () => {
expect(classifyShellCommand('{c..c}at notes.txt', roots)).toBe('prompt');
// 反例:位置参数里的 brace 只影响文件名 → 不升级;find 占位符 {} 不算展开。
expect(classifyShellCommand('ls dir/{a,b}', roots)).toBe('auto-approve');
- expect(classifyShellCommand('grep -rn foo src/{a,b} --include="[!.]*.ts"', roots)).toBe('auto-approve');
+ expect(classifyShellCommand('grep -rn foo src/{a,b} --include="[b]ook.ts"', roots)).toBe('auto-approve');
expect(classifyShellCommand('find . -maxdepth 0 -print', roots)).toBe('auto-approve'); // {} 占位符另测,这里确认普通 find 放行
});
@@ -4124,7 +4124,7 @@ describe('伪设备白名单:静音重定向不得打断(实机语料探针发
it('日常命令语料整体不被硬拦(尽量不打扰的回归护栏)', () => {
for (const c of [
- 'ls -la', 'git status', 'cat package.json', 'grep -rn TODO src --include="[!.]*.ts"',
+ 'ls -la', 'git status', 'cat package.json', 'grep -rn TODO src --include="[b]ook.ts"',
'pnpm install', 'npx tsc --noEmit', 'rm -rf node_modules', 'rm -rf build',
'git add .', 'git commit -m "fix: x"', 'git push origin feature/x',
'env NODE_ENV=test npx vitest run', 'timeout 60 pnpm test', 'nohup pnpm dev',
diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.ts
index 9e1a914395..e35ac531c6 100644
--- a/packages/maker-core/src/agents/shared/auto-review.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.ts
@@ -40,6 +40,7 @@
import {
isDotenvCredentialPath,
isSensitiveCredentialPath,
+ SENSITIVE_CREDENTIAL_GLOB_PATTERNS,
SENSITIVE_CREDENTIAL_PATH_PATTERNS,
} from './sensitive-credential-paths.js';
import { parseShellInputRedirections } from './shell-input-redirections.js';
@@ -4935,6 +4936,188 @@ function selectorCouldMatchDotenv(value: string): boolean {
);
}
+const CREDENTIAL_SELECTOR_WORD_BOUNDARY = '\u0001';
+const SHELL_CREDENTIAL_SELECTOR_GLOBS = [...new Set(
+ SENSITIVE_CREDENTIAL_GLOB_PATTERNS.flatMap((pattern) => {
+ const variants: string[] = [pattern];
+ const directory = pattern.endsWith('/**') ? pattern.slice(0, -3) : undefined;
+ if (directory) {
+ variants.push(directory, directory + CREDENTIAL_SELECTOR_WORD_BOUNDARY + '**');
+ } else if (pattern !== '**/.env' && pattern !== '**/.env.*' && !pattern.endsWith('*')) {
+ variants.push(pattern + CREDENTIAL_SELECTOR_WORD_BOUNDARY + '**');
+ }
+ return variants.flatMap((variant) =>
+ variant.startsWith('**/') ? [variant, variant.slice(3)] : [variant]);
+ }),
+)];
+
+type ShellSelectorGlobLabel =
+ | { kind: 'literal'; value: string }
+ | { kind: 'class'; values: ReadonlySet<string>; negated: boolean }
+ | { kind: 'non-slash' | 'non-word' | 'any' };
+
+type ShellSelectorGlobToken =
+ | { kind: 'literal'; value: string }
+ | { kind: 'class'; label: ShellSelectorGlobLabel }
+ | { kind: 'one' | 'star' | 'globstar' | 'nonword' };
+
+function shellSelectorClassLabel(value: string): ShellSelectorGlobLabel | null {
+ if (!value || value.includes('[:')) return null;
+ let cursor = 0;
+ const negated = value.startsWith('!') || value.startsWith('^');
+ if (negated) cursor += 1;
+ const values = new Set<string>();
+ while (cursor < value.length) {
+ const start = value.charCodeAt(cursor);
+ if (value[cursor + 1] === '-' && cursor + 2 < value.length) {
+ const end = value.charCodeAt(cursor + 2);
+ if (end < start || end - start > 64) return null;
+ for (let code = start; code <= end; code += 1) {
+ values.add(String.fromCharCode(code).toLowerCase());
+ }
+ cursor += 3;
+ } else {
+ values.add(value[cursor].toLowerCase());
+ cursor += 1;
+ }
+ if (values.size > 128) return null;
+ }
+ return values.size > 0 ? { kind: 'class', values, negated } : null;
+}
+
+const SHELL_SELECTOR_MAX_PATTERN_LENGTH = 4_096;
+
+function shellSelectorGlobTokens(pattern: string): ShellSelectorGlobToken[] | null {
+ if (pattern.length > SHELL_SELECTOR_MAX_PATTERN_LENGTH || /[{}()|+@]/.test(pattern)) return null;
+ const normalized = pattern.replace(/\\/g, '/').toLowerCase();
+ const tokens: ShellSelectorGlobToken[] = [];
+ for (let index = 0; index < normalized.length; index += 1) {
+ const char = normalized[index];
+ if (char === CREDENTIAL_SELECTOR_WORD_BOUNDARY) {
+ tokens.push({ kind: 'nonword' });
+ continue;
+ }
+ if (char === '[') {
+ const end = normalized.indexOf(']', index + 1);
+ if (end < 0) return null;
+ const label = shellSelectorClassLabel(normalized.slice(index + 1, end));
+ if (!label) return null;
+ tokens.push({ kind: 'class', label });
+ index = end;
+ continue;
+ }
+ if (char === ']') return null;
+ if (char === '?') {
+ tokens.push({ kind: 'one' });
+ continue;
+ }
+ if (char === '*') {
+ let end = index + 1;
+ while (normalized[end] === '*') end += 1;
+ tokens.push({ kind: end - index >= 2 ? 'globstar' : 'star' });
+ index = end - 1;
+ continue;
+ }
+ tokens.push({ kind: 'literal', value: char });
+ }
+ return tokens;
+}
+
+function shellSelectorGlobTransition(
+ tokens: readonly ShellSelectorGlobToken[],
+ index: number,
+): { next: number; label: ShellSelectorGlobLabel } | null {
+ const token = tokens[index];
+ if (!token) return null;
+ if (token.kind === 'literal') return { next: index + 1, label: token };
+ if (token.kind === 'class') return { next: index + 1, label: token.label };
+ if (token.kind === 'one') return { next: index + 1, label: { kind: 'non-slash' } };
+ if (token.kind === 'nonword') return { next: index + 1, label: { kind: 'non-word' } };
+ if (token.kind === 'star') return { next: index, label: { kind: 'non-slash' } };
+ return { next: index, label: { kind: 'any' } };
+}
+
+function shellSelectorClassAllows(
+ label: Extract<ShellSelectorGlobLabel, { kind: 'class' }>,
+ value: string,
+): boolean {
+ if (value === '/') return false;
+ return label.negated !== label.values.has(value);
+}
+
+function shellSelectorGlobLabelsOverlap(
+ left: ShellSelectorGlobLabel,
+ right: ShellSelectorGlobLabel,
+): boolean {
+ if (left.kind === 'any' || right.kind === 'any') return true;
+ if (left.kind === 'literal' && right.kind === 'literal') return left.value === right.value;
+ if (left.kind === 'literal') {
+ if (right.kind === 'class') return shellSelectorClassAllows(right, left.value);
+ if (right.kind === 'non-word') return !/[a-z0-9_]/i.test(left.value);
+ return left.value !== '/';
+ }
+ if (right.kind === 'literal') return shellSelectorGlobLabelsOverlap(right, left);
+ if (left.kind === 'class' && right.kind === 'class') {
+ if (!left.negated && !right.negated) {
+ return [...left.values].some((value) => shellSelectorClassAllows(right, value));
+ }
+ if (!left.negated) return [...left.values].some((value) => shellSelectorClassAllows(right, value));
+ if (!right.negated) return [...right.values].some((value) => shellSelectorClassAllows(left, value));
+ return true;
+ }
+ if (left.kind === 'class') {
+ if (left.negated) return true;
+ return [...left.values].some((value) => value !== '/'
+ && (right.kind !== 'non-word' || !/[a-z0-9_]/i.test(value)));
+ }
+ if (right.kind === 'class') return shellSelectorGlobLabelsOverlap(right, left);
+ return true;
+}
+
+function shellSelectorGlobsIntersect(leftPattern: string, rightPattern: string): boolean | null {
+ const left = shellSelectorGlobTokens(leftPattern);
+ const right = shellSelectorGlobTokens(rightPattern);
+ if (!left || !right) return null;
+ const pending: Array<[number, number]> = [[0, 0]];
+ const visited = new Set<string>();
+ while (pending.length > 0) {
+ const [leftIndex, rightIndex] = pending.pop()!;
+ const key = `${leftIndex}:${rightIndex}`;
+ if (visited.has(key)) continue;
+ visited.add(key);
+ if (leftIndex === left.length && rightIndex === right.length) return true;
+
+ const leftToken = left[leftIndex];
+ const rightToken = right[rightIndex];
+ if (leftToken?.kind === 'star' || leftToken?.kind === 'globstar') {
+ pending.push([leftIndex + 1, rightIndex]);
+ }
+ if (rightToken?.kind === 'star' || rightToken?.kind === 'globstar') {
+ pending.push([leftIndex, rightIndex + 1]);
+ }
+
+ const leftTransition = shellSelectorGlobTransition(left, leftIndex);
+ const rightTransition = shellSelectorGlobTransition(right, rightIndex);
+ if (leftTransition && rightTransition
+ && shellSelectorGlobLabelsOverlap(leftTransition.label, rightTransition.label)) {
+ pending.push([leftTransition.next, rightTransition.next]);
+ }
+ }
+ return false;
+}
+
+function selectorCouldMatchCredential(value: string): boolean {
+ if (value.startsWith('!')) return false;
+ return braceExpansionCouldMatch(value, (candidate) =>
+ SHELL_CREDENTIAL_SELECTOR_GLOBS.some((credentialGlob) => {
+ if (!candidate.includes('/') && credentialGlob.endsWith('/**')) return false;
+ const sensitivePattern = candidate.includes('/')
+ ? credentialGlob
+ : credentialGlob.replace(/\\/g, '/').split('/').pop() ?? '';
+ return shellSelectorGlobsIntersect(candidate, sensitivePattern) !== false;
+ }));
+}
+
function shellOperandCouldMatchDotenv(
value: string,
exactMatcher: (candidate: string) => boolean = isDotenvCredentialPath,
@@ -4951,7 +5134,7 @@ function readerOptionValueIsSensitive(
value: string | undefined,
isSensitiveOperand: (value: string) => boolean,
): boolean {
- if (kind === 'selector') return selectorCouldMatchDotenv(value ?? '');
+ if (kind === 'selector') return selectorCouldMatchCredential(value ?? '');
if (!value || (kind !== 'data-file' && kind !== 'aux-file' && kind !== 'aux-file-list')) return false;
const operands = kind === 'aux-file-list' ? value.split(/[:;]/) : [value];
return operands.some((operand) => shellOperandCouldMatchDotenv(operand, isSensitiveOperand));
@@ -5073,7 +5256,7 @@ function grepRecursesIntoPotentialDotenv(bin: string, args: readonly string[]):
}
}
- return recursive && (includes.length === 0 || includes.some(selectorCouldMatchDotenv));
+ return recursive && (includes.length === 0 || includes.some(selectorCouldMatchCredential));
}
type RgTypeDefinition = { globs: string[]; includes: string[] };
@@ -5097,7 +5280,7 @@ function parseRgTypeSpec(value: string): ParsedRgTypeSpec | null {
: null;
}
-function rgCustomTypeCouldMatchDotenv(
+function rgCustomTypeCouldMatchCredential(
name: string,
definitions: ReadonlyMap<string, RgTypeDefinition>,
visiting = new Set<string>(),
@@ -5105,10 +5288,10 @@ function rgCustomTypeCouldMatchDotenv(
if (visiting.has(name)) return true;
const definition = definitions.get(name);
if (!definition) return true;
- if (definition.globs.some(selectorCouldMatchDotenv)) return true;
+ if (definition.globs.some(selectorCouldMatchCredential)) return true;
const nextVisiting = new Set(visiting).add(name);
return definition.includes.some((included) =>
- rgCustomTypeCouldMatchDotenv(included, definitions, nextVisiting));
+ rgCustomTypeCouldMatchCredential(included, definitions, nextVisiting));
}
function rgSearchesPotentialDotenv(args: readonly string[]): boolean {
@@ -5117,19 +5300,23 @@ function rgSearchesPotentialDotenv(args: readonly string[]): boolean {
let typeParsingUnresolved = false;
const globs: string[] = [];
const definitions = new Map<string, RgTypeDefinition>();
- const includedTypes = new Set<string>();
- const excludedTypes = new Set<string>();
+ let allTypesIncluded = false;
+ const typeSelections = new Map<string, boolean>();
const applyTypeOption = (kind: ReaderOptionKind, value: string | undefined): void => {
if (!value) {
typeParsingUnresolved = true;
return;
}
- if (kind === 'type-include') {
- includedTypes.add(value);
- return;
- }
- if (kind === 'type-exclude') {
- excludedTypes.add(value);
+ if (kind === 'type-include' || kind === 'type-exclude') {
+ const included = kind === 'type-include';
+ if (value === 'all') {
+ allTypesIncluded = included;
+ typeSelections.clear();
+ } else if (!/^[\p{L}\p{N}]+$/u.test(value)) {
+ typeParsingUnresolved = true;
+ } else {
+ typeSelections.set(value, included);
+ }
return;
}
if (kind === 'type-clear') {
@@ -5183,18 +5370,15 @@ function rgSearchesPotentialDotenv(args: readonly string[]): boolean {
}
if (typeParsingUnresolved) return true;
- const selectedCustomTypes = includedTypes.has('all')
- ? [...definitions.keys()]
- : [...includedTypes].filter((name) => definitions.has(name));
- if (!excludedTypes.has('all') && selectedCustomTypes.some((name) =>
- !excludedTypes.has(name) && rgCustomTypeCouldMatchDotenv(name, definitions))) return true;
+ const selectedCustomTypes = [...definitions.keys()].filter((name) =>
+ typeSelections.get(name) ?? allTypesIncluded);
+ if (selectedCustomTypes.some((name) =>
+ rgCustomTypeCouldMatchCredential(name, definitions))) return true;
const positive = globs.filter((glob) => !glob.startsWith('!'));
- const positiveCouldMatchDotenv = positive.some(selectorCouldMatchDotenv);
- const excludesDotenv = !positiveCouldMatchDotenv
- && globs.some((glob) => glob === '!.env*' || glob === '!**/.env*');
- const positiveIsSafe = positive.length > 0 && !positiveCouldMatchDotenv;
- return hidden && !excludesDotenv && !positiveIsSafe;
+ const positiveCouldMatchCredential = positive.some(selectorCouldMatchCredential);
+ const positiveIsSafe = positive.length > 0 && !positiveCouldMatchCredential;
+ return hidden && !positiveIsSafe;
}
function gitGrepExpandsSearchScope(args: readonly string[]): boolean {