Repository navigation
feat(agent-core-v2): add experimental auto review - #4655
Conversation
🦋 Changeset detectedLatest commit: 1189e1d The changes in this PR will be included in the next version bump. This PR includes changesets to release 6 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
@codex review |
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2cdeac76b6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const thinkingEffort = modelAlias === resolved.modelAlias | ||
| ? resolved.thinkingLevel | ||
| : resolveThinkingEffortForModel( | ||
| undefined, | ||
| this.config.get<ThinkingConfig>(THINKING_SECTION), |
There was a problem hiding this comment.
Apply the review model's thinking effort to its request
When [auto_review].model differs from the primary model, this computes the alternate model's compatible thinkingEffort, but protocolRegistry.request still receives params copied from the primary profile. For example, a thinking-enabled primary model with high effort and a non-thinking review model will raise a thinking configuration error, causing every review to fall back to manual approval or be denied in headless mode. Insert the resolved effort into params before constructing the requester rather than using it only for logging.
Useful? React with 👍 / 👎.
| if (message.origin?.kind === 'skill_activation' && message.origin.trigger === 'user-slash') { | ||
| return 'human-instruction'; | ||
| } | ||
| if (message.name === 'Agent' || message.name === 'Task') return 'direct-parent-instruction'; |
There was a problem hiding this comment.
Recognize the actual subagent prompt origin
For an Agent subagent, runAgentTurn.ts stores the delegated prompt as a user-role message with origin: { kind: 'system_trigger', name: 'subagent' } and no message.name, so this condition never classifies the prompt as a direct-parent instruction. The reviewer therefore loses the only authorization for a normal non-forked subagent; explicitly delegated medium-risk actions such as deleting or overwriting a file are treated as ambiguous and denied or sent to approval, and cannot run in headless mode. Match the subagent prompt origin instead of relying on message.name.
Useful? React with 👍 / 👎.
| const authorization = retained.flatMap((message) => { | ||
| if (authorizationChars >= MAX_AUTHORIZATION_TOTAL_CHARS) return []; |
There was a problem hiding this comment.
Preserve the newest authorization under the total cap
When retained human instructions exceed 48,000 characters, this traversal spends the budget on the oldest messages and silently drops every later instruction. If an earlier prompt authorizes deletion but the latest prompt says not to delete a particular target, the reviewer sees only the stale grant and can approve the destructive pending action. Select entries from newest to oldest under the cap, then restore chronological order before sending them.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
| const text = boundedText(part.text, remaining); | ||
| remaining -= text.length; |
There was a problem hiding this comment.
Stop before slicing with a negative character budget
When one text part exceeds the remaining budget, boundedText appends a truncation marker, so the returned string is longer than remaining and this subtraction makes the budget negative. A subsequent text part is then processed with slice(0, negative), which retains nearly the entire part rather than none; a multi-part user prompt can therefore bypass both authorization-size limits and make reviews overflow or time out. Clamp the budget at zero and stop processing text once it is exhausted.
Useful? React with 👍 / 👎.
| decision: { type: 'string', enum: ['allow', 'deny'] }, | ||
| reason: { type: 'string' }, | ||
| }, | ||
| required: ['risk', 'decision'], |
There was a problem hiding this comment.
Make every strict OpenAI schema field required
When [auto_review].model selects an openai or openai_responses provider, its strict structured-output schema is rejected because reason appears in properties but not in required; OpenAI's strict schema subset requires every declared property to be required. The request then fails before inference, so interactive sessions always fall back to approval and headless sessions deny every reviewed tool call. Encode the variants with a supported union or make reason required and nullable, then align DecisionSchema accordingly.
Useful? React with 👍 / 👎.
| const content = boundedContent(message.content, MAX_AUTHORIZATION_ENTRY_CHARS); | ||
| return [{ role, content }]; |
There was a problem hiding this comment.
Exclude prompt-hook output from human authorization
For users with a UserPromptSubmit hook, hook output is appended as tagged text parts to the original user-origin message, but authorizationEntry copies every part and boundedContent discards the tag metadata. The reviewer therefore receives automatic hook output labeled as human-instruction; a hook message that requests a deletion or external write can authorize that medium-risk action without the human ever requesting it. Filter isUserPromptSubmitHookPart content or classify it as a non-authorizing constraint/fact.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
| const agentsMd = this.instructions.agentsMd; | ||
| const cwd = this.workspace.workDir; |
There was a problem hiding this comment.
Include the bound environment in review context
For sessions bound to an SSH, Docker, or command environment, the payload includes only workspace.workDir, so a local workspace and a remote target with the same path produce identical ENVIRONMENT input. The reviewer can consequently classify a Write or Bash call as ordinary project-local work and approve it without knowing that it executes across a trust boundary or on a production target. Include the active environment identity/type in the snapshot and invalidate the decision if that binding changes during review.
AGENTS.md reference: AGENTS.md:L28-L28
Useful? React with 👍 / 👎.
| return { | ||
| kind: 'ask', | ||
| reason: { review_risk: decision.risk }, |
There was a problem hiding this comment.
Show the reviewer rationale in fallback approval
When the reviewer denies an action in an interactive session, the returned ask result carries only review_risk; the model's actionable decision.reason is used only in the later rejection message. AgentToolApprovalService therefore builds a normal approval request from the tool description and arguments without telling the human why the reviewer denied it, even for findings such as credential exposure, while still allowing that human to override the denial. Propagate the rationale into the approval request's displayed action or detail.
Useful? React with 👍 / 👎.
| const modelAlias = overrides.modelAlias ?? resolved.modelAlias; | ||
| const baseParams = turnConfig?.params ?? this.profile.resolveRequestParams(); | ||
| const model = this.modelCatalog.get(resolved.modelAlias); | ||
| const model = this.modelCatalog.get(modelAlias); |
There was a problem hiding this comment.
Attribute override failures to the selected model
When an operation supplies the new modelAlias override and that reviewer request fails, logRequestFailure and trackApiError still resolve the model, provider, protocol, and alias from the primary agent profile rather than from this selected alias. Auto-review failures from a configured provider are therefore recorded against the main model, corrupting provider error rates and making the experiment appear to fail on the wrong backend. Carry the resolved request model into the failure handlers.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 30853cecc2
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (configured !== undefined) return configured; | ||
| const managed = this.models.findByName(AUTO_REVIEW_MODEL_NAME).find((alias) => { | ||
| try { | ||
| return this.models.get(alias).providerName === AUTO_REVIEW_PROVIDER; |
There was a problem hiding this comment.
Match the managed provider's actual ID
When K2.8 is provisioned by the managed login flow, its catalog providerName is managed:kimi-code, so comparing it with kimi-code always rejects the candidate and silently falls back to the main model. This affects users who enable Auto Review without setting [auto_review].model: they do not get the documented managed reviewer, and reviews can fail if their main provider cannot satisfy the strict response schema. Compare against the managed provider ID instead.
Useful? React with 👍 / 👎.
| id: AUTO_REVIEW_FLAG_ID, | ||
| title: 'Auto Review', | ||
| description: 'Review non-read-only tool calls with a separate model in Ask When Needed and Never Ask modes.', | ||
| env: AUTO_REVIEW_FLAG_ENV, |
There was a problem hiding this comment.
Add a changeset for the experimental reviewer
This adds a user-perceivable CLI feature that users can enable with an experimental flag, but the diff contains no .changeset entry, so the next release changelog will omit both the capability and how to enable it. Add an @moonshot-ai/kimi-code changeset that names the Auto Review feature and its enabling flag.
AGENTS.md reference: AGENTS.md:L89-L90
Useful? React with 👍 / 👎.
| const mode = this.modes.mode; | ||
| if (!this.flags.enabled(AUTO_REVIEW_FLAG_ID) || (mode !== 'auto' && mode !== 'yolo')) return undefined; | ||
| if (EXEMPT_TOOLS.has(context.toolCall.name)) return undefined; | ||
| const startedAt = Date.now(); | ||
| const result = await this.reviewService.review(context); |
There was a problem hiding this comment.
Revalidate the permission mode after review
When a review starts in auto mode, the existing static policy has already approved the call, but this snapshots mode before a review that can run for up to 120 seconds. If the user switches to manual while it is pending, an allow response still follows the stale auto path and executes without the approval now required by Always Ask; stale mode similarly maps denials to the wrong hard-deny versus approval behavior. Recheck the mode after the await and invalidate or reevaluate the decision when it changes.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
| return; | ||
| } | ||
| if (review?.kind === 'ask') { | ||
| event.waitUntil(() => this.toolApproval.requestToolApproval(event, review, this.autoReview.name)); |
There was a problem hiding this comment.
Prevent final allow from bypassing review approval
In yolo Plan mode, a Write or Edit targeting the plan file reaches PlanService, which calls event.allow(); BeforeToolExecuteEmitter then returns immediately without processing pending veto factories. Consequently, when Auto Review denies or fails, this fallback approval is skipped—if the permission gate listener ran first—or the review is skipped entirely if the plan listener ran first, and the reviewer-rejected call executes without asking the user. Ensure the plan-file final allow cannot discard the Auto Review decision.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f9c1ea407
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (message.origin?.kind === 'user' || message.origin?.kind === 'plugin_command') { | ||
| return 'human-instruction'; |
There was a problem hiding this comment.
Treat originless legacy user messages as human instructions
When Auto Review is enabled on a resumed legacy session, user messages written before prompt origins were recorded have origin === undefined; replay and undo code explicitly treat these as real user prompts, but this branch assigns them no authorization role. An earlier task instruction authorizing a deletion or overwrite is therefore omitted, causing the reviewer to reject a legitimate follow-up and Never Ask mode to hard-deny it. Treat an originless user-role message as a human-instruction, matching the existing legacy replay semantics.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
| if (review?.kind === 'ask') { | ||
| const staticAsk = evaluation?.result.kind === 'ask' ? evaluation.result : undefined; | ||
| const result = staticAsk ?? review; | ||
| const origin = evaluation?.result.kind === 'ask' ? evaluation.policyName : this.autoReview.name; | ||
| const resolved = await this.toolApproval.requestToolApproval(event, result, origin); |
There was a problem hiding this comment.
Reuse the existing Plan exit approval
In Ask When Needed with an active nonempty plan, a reviewer denial or timeout makes this call open an approval request immediately, while AgentPlanService has independently registered its ExitPlanModeReview as a pending veto factory. After the user approves this fallback, the emitter runs that factory and presents the same plan approval a second time, so one ExitPlanMode call requires two approvals and records approval telemetry twice. Combine the reviewer fallback with the pending Plan review instead of issuing a separate prompt.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
| } | ||
| if (result.kind === 'approve') { | ||
| event.pass(result.executionMetadata); | ||
| const review = await this.autoReview.evaluate(event); |
There was a problem hiding this comment.
Honor approve-for-session for reviewer fallbacks
In Ask When Needed, when the reviewer denies and the user selects Approve for this session, the approval service records context.execution.approvalRule and reports approved_for_session. The next matching call is therefore statically approved by SessionApprovalHistoryPermissionPolicyService, but this unconditional review runs again; because approval results are absent from buildReviewMessages and historical calls are explicitly non-authorizing, the reviewer denies again and presents another prompt. Either carry the session approval into reviewer authorization or prevent reviewer fallback prompts from offering and recording a session-scoped approval.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
commit: |
Keep one static-plus-review decision for both permission entry points, leave turn-context measurement untouched by auto review requests, and require a nullable reason in the strict decision schema.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a38e766068
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (reviewed === undefined) return; | ||
| if (reviewed.result.kind === 'ask') { | ||
| const ask = reviewed.result; | ||
| const resolved = await this.toolApproval.requestToolApproval(event, ask, reviewed.origin); |
There was a problem hiding this comment.
Defer Auto Review approval until Plan guards run
When Auto Review is active in Plan mode and a Write or Edit targets anything other than the current plan file, this awaits the reviewer fallback before the Plan guard can veto. If the user approves a reviewer denial or failure, the approval can even be recorded for the session, although AgentPlanService.guardToolExecution will still reject the write. The previous event.waitUntil deferred approval until after listeners, allowing the Plan veto to skip it; defer this fallback too so users are not prompted to approve an action that cannot run.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
| `PROJECT_INSTRUCTIONS\n${JSON.stringify({ | ||
| role: 'constraint', | ||
| paths: instructionPaths ?? [], | ||
| content: instructions ?? '', |
There was a problem hiding this comment.
Bound project instructions in reviewer requests
When [auto_review].model selects a model whose context limit is below the combined review prompt, this adds the complete AGENTS.md snapshot without a bound. loadAgentsMdForRoots only warns when the total exceeds 32 KiB, so a large instruction set can make each review fail; in auto mode that failure denies every non-exempt tool call. Bound or truncate the instruction content before sending it to the reviewer.
Useful? React with 👍 / 👎.
| } | ||
|
|
||
| async evaluate(context: ResolvedToolExecutionHookContext): Promise<PermissionPolicyResult | undefined> { | ||
| if (!this.enabled || EXEMPT_TOOLS.has(context.toolCall.name)) return undefined; |
There was a problem hiding this comment.
Restrict exemptions to built-in read-only tools
When an integration registers a user tool named Read, the registry allows it to replace the built-in tool, but this name-only exemption skips Auto Review. The user tool dispatches to host-provided execution, and the default policy also approves Read, so its side effects can run without review in auto or yolo mode. Exempt only known built-in read-only registrations or reject reserved-name collisions.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
Keep the default permission gate on main's two-phase flow so a static ask waits for every listener before prompting, and run the reviewer inside the same deferred phase. Move the review/static result mapping into the auto review feature, drop the plan guard special case, mark session approvals explicitly, and replace the implicit temperature/requestKind coupling in the requester with explicit sampling and detached overrides. Reviewer requests now send the selected model's thinking effort.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e2b0abceb5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| {"risk":"low","decision":"allow"} | ||
| {"risk":"medium","decision":"allow"} | ||
| {"risk":"medium","decision":"deny","reason":"..."} | ||
| {"risk":"high","decision":"deny","reason":"..."} |
There was a problem hiding this comment.
Align allow examples with the required response schema
When a configured reviewer backend does not strictly constrain generation from responseFormat, the prompt tells it to return either {"risk":"low","decision":"allow"} or {"risk":"medium","decision":"allow"}, but DecisionSchema requires reason: null and explicitly rejects those exact examples. A reviewer that follows the prompt therefore turns every allow into a failed review, which denies the call in Never Ask mode or unnecessarily prompts in Ask When Needed mode; include "reason":null in both allow examples and clarify that null is required.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74a83a716e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| name: context.toolCall.name, | ||
| description: tool?.description ?? '', | ||
| parameters: tool?.parameters ?? {}, | ||
| arguments: context.args, |
There was a problem hiding this comment.
Bound the pending action payload
When Auto Review is enabled, calls with large arguments—such as Write with a generated file containing hundreds of kilobytes—place the complete context.args into the reviewer prompt without any limit. This can exceed the selected review model's context window, making the review fail and causing Never Ask mode to deny an otherwise valid operation (or Ask When Needed to present an unnecessary fallback approval); truncate or otherwise bound large pending arguments while retaining the security-relevant fields.
Useful? React with 👍 / 👎.
| tools: overrides.tools === undefined ? undefined : [...overrides.tools], | ||
| messages: [...messages], | ||
| responseFormat: overrides.responseFormat, | ||
| detached: overrides.detached === true, |
There was a problem hiding this comment.
Keep detached reviews out of loop request records
For every Auto Review request, detached is honored only by the token-counting and cache-measurement guards; onAttempt still calls recordRequest, which dispatches a durable llm.request with kind: "loop" and may also persist an empty llm.tools_snapshot. Sessions therefore expose internal reviewer calls as ordinary agent-loop requests to wire consumers, and the v2 persistence fold at human/persist/v2/fold.ts:628-630 treats their provider/model as the latest loop model. Skip durable loop recording for detached operations or add an explicit operation kind so these records cannot be mistaken for agent steps.
AGENTS.md reference: AGENTS.md:L122-L124
Useful? React with 👍 / 👎.
Route auto review through a shadow policy evaluation that skips the mode-level approvals, and send review requests through a standalone model requester with retries and credential recovery instead of the agent loop requester.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9aa2be4be
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| name: context.toolCall.name, | ||
| description: tool?.description ?? '', | ||
| parameters: tool?.parameters ?? {}, | ||
| arguments: context.args, |
There was a problem hiding this comment.
Avoid sending secrets to a second reviewer provider
When Auto Review is enabled and a pending call embeds a credential in its arguments—for example, a Bash command or an MCP argument—this serializes the complete secret into the review request. Because the reviewer defaults to managed K2.8 even when the main model uses a different or self-hosted provider, the credential is silently disclosed to an additional provider before the reviewer can classify that disclosure as high risk. Redact secret-bearing values or constrain review to the same provider trust boundary.
Useful? React with 👍 / 👎.
| description: tool?.description ?? '', | ||
| parameters: tool?.parameters ?? {}, |
There was a problem hiding this comment.
Treat tool metadata as untrusted reviewer input
For MCP and user tools, the tool provider controls description and parameters (for example, createMcpTool copies both directly), but these fields are inserted into the reviewer's user message without an untrusted-data label. The system policy only warns about instructions in historical facts and tool output, so malicious metadata such as an instruction to return allow can influence the decision; in Never Ask mode that silently executes the call without human approval. Delimit this metadata as untrusted and explicitly instruct the reviewer never to follow instructions contained in it.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
| projectInstructions.agentsMd, | ||
| projectInstructions.agentsMdPaths, | ||
| cwd, | ||
| this.tools.resolve(context.toolCall.name), |
There was a problem hiding this comment.
Review the tool instance that will execute
When an MCP or plugin hot reload replaces or removes a tool after preflight but before the deferred review starts, this registry lookup returns the new registration (or undefined), while context.execution and context.tool still refer to the original tool that will actually run. The reviewer can therefore judge a different description and schema, potentially allowing the old side-effecting implementation based on a benign replacement or denying a valid call because its metadata disappeared. Pass context.tool to buildReviewMessages so the reviewed metadata belongs to the resolved instance being executed.
Useful? React with 👍 / 👎.
| if (message.role === 'tool') { | ||
| if (message.toolCallId === pendingCallId) return []; | ||
| return [{ | ||
| kind: 'tool-result', | ||
| role: 'fact', | ||
| toolCallId: message.toolCallId, | ||
| isError: message.isError === true, | ||
| }]; |
There was a problem hiding this comment.
Preserve trusted human interaction responses
When the user answers AskUserQuestion or rejects an approval with corrective feedback, that human input is encoded in a tool result, but this projection retains only the call ID and isError flag and authorizationEntry ignores tool messages entirely. The reviewer therefore cannot see a newly selected scope such as “delete generated caches only”; the following action is denied or prompts again in Ask When Needed mode and is hard-denied in Never Ask mode. Preserve responses from trusted interaction surfaces with distinct provenance while continuing to exclude arbitrary tool output.
Useful? React with 👍 / 👎.
…view on non-managed main models
|
@codex review |
# Conflicts: # packages/acp-server/src/approval.ts
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 18fbae2fd6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const latestHistory = this.loop.history(); | ||
| if (latestHistory !== snapshot.history) { | ||
| const drift = detectAuthorizationDrift(snapshot.authorization, this.authorizationOf(latestHistory)); |
There was a problem hiding this comment.
Reject review results after project instructions change
If an AGENTS.md instruction authorizing the pending action is removed while the review model call is running, snapshot.messages still contains the old instructions. This completion path rechecks the working directory and chat history, but not the instructions, so it can still accept an allow based on revoked guidance. The new onDidChange handler only refreshes the cache for later snapshots; compare or invalidate the in-flight snapshot before using its result.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
Add [auto_review].effort so the review effort can differ from the main agent without registering a model variant. It is validated with the same checks as [secondary_model].default_effort, which now share one helper. When the reviewer borrows the [secondary_model] default model, it also borrows that section's default_effort instead of falling back to the model entry's own default.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: db21a7af29
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| role: 'constraint', | ||
| paths: instructionPaths ?? [], | ||
| content: instructions ?? '', | ||
| }), |
There was a problem hiding this comment.
Stop self-authored instructions from approving actions
When Auto Review is enabled in auto or yolo mode, an agent can use the unreviewed Write tool to change a project AGENTS.md and authorize a later workflow. This passes the changed text to the reviewer as a constraint, and the review policy allows project instructions to authorize medium-risk actions, so a later Bash or MCP deployment or publish call can be silently approved based on authorization the agent manufactured. Only treat independently trusted, user-established project instructions as authorization, or track their provenance.
AGENTS.md reference: AGENTS.md:L213-L213
Useful? React with 👍 / 👎.
Fold case-specific sentences into the rules they refine and drop text that repeats another rule or describes inputs the reviewer never sees. Name the history roles once so the rules can refer to the labels that appear in the request data.
Align Auto Review with the Workspace -> Project rename, refresh the KAP contract digest, fix the auto_review doc anchors, and drop an unrelated BROWSER_TOOL_NAME display-kind check.
|
@codex review |
Show the "Reviewing" hint only after a review has run for 3 seconds, so reviews that finish quickly no longer flash it. This applies to the TUI tool card and fullscreen tail, and to the desktop and web tool rows and activity summary. Title the approval prompt after a denial "Auto Review didn't approve" instead of "recommends rejecting": the user still decides whether to approve, and the new wording states the verdict without implying the action was blocked.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 484b868566
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| await reviewService.review(context, askEval.policyName), | ||
| flags.enabled(AUTO_REVIEW_FLAG_ID) ? modes.mode : 'manual', |
There was a problem hiding this comment.
Re-evaluate permission policies after review
When permission rules change while the model review is in flight—for example, another client adds a session-runtime deny or config reload introduces a deny rule—this continuation uses the original evaluation and only refreshes the flag and mode. Since AgentPermissionRulesService.rules reads live state/config, a new deny would apply to a fresh evaluation, but a reviewer allow here still resolves to approve and silently executes the call. Re-run the current policy chain after review and let a new deny or explicit ask take precedence.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
| } catch (error) { | ||
| context.signal.throwIfAborted(); | ||
| outcome = deadline.signal.aborted | ||
| ? { decision: 'failed', reason: deadline.timedOut() ? 'Review timed out.' : 'Review cancelled.' } |
There was a problem hiding this comment.
Emit a terminal review event when cancellation aborts
When the user cancels while Auto Review is running, this rethrow exits review() before AutoReviewCompleted is dispatched. Consumers set their review state on auto_review.started and clear it only on auto_review.decision, so the recorded KAP tool item can retain auto_review: true and event consumers never receive a matching terminal transition. Dispatch the failed/cancelled completion during cleanup before propagating cancellation.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
| ...(bootstrap.args.nonInteractive | ||
| ? [] | ||
| : [this.instantiation.createInstance(DangerousCommandAskPermissionPolicyService)]), | ||
| this.instantiation.createInstance(DangerousCommandAskPermissionPolicyService), |
There was a problem hiding this comment.
Preserve noninteractive behavior when Auto Review is disabled
When an SDK host sets nonInteractive: true, uses Ask When Needed mode, and leaves the experimental flag disabled, unconditionally registering this policy changes dangerous Bash calls from the previous yolo-mode-approve result to ask; AgentToolApprovalService then denies them because no approval surface exists. Thus merely upgrading breaks existing headless SDK workflows even though Auto Review defaults off. Keep the old noninteractive policy set unless review is enabled, while still making the detector available for Auto Review's explicit Always Ask reevaluation.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
- Validate the review model and effort once per execute instead of re-running the configured-model check and the effort check twice. - Require the base ask in resolveAutoReview and inline the reason merge. - Derive the AutoReviewCompleted payload type from its schema. - Drop the empty-inherited shortcut when merging authorization. Tests: - Use a mutating command in the outside-workspace git status test; with the read-only `ls` it no longer reached the workspace check. - Remove table rows and cases that repeat a branch already covered: policy-name variants, duplicate tool and mode rows, shared risk guidance, thinking rules tested in the core thinking suites, read-only shell classification tested by the permission policy suite, and the Bash tool copy of the desktop hint delay test.
…ory filtering Re-review once whenever authorization or the working directory changes during a review, and fail if it changes again. This replaces the unchanged/appended/changed classification: a rewritten authorization or a cwd change now gets one re-review on the latest state instead of failing outright. Omit history calls to every tool the default-tool-approve policy approves, reusing its list instead of a second hand-kept subset. Agent, Skill, ExitPlanMode, AskUserQuestion, goal, and select_tools calls now also drop out of the reviewer history; the policy prompt now says calls that never need approval are omitted.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd09c5157b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| gitStatus?: ReviewGitStatus, | ||
| ): ReturnType<typeof createUserMessage>[] { | ||
| const completedIds = new Set( | ||
| messages.flatMap((message) => (message.role === 'tool' ? [message.toolCallId] : [])), |
There was a problem hiding this comment.
Exclude failed tool calls from review history
Fresh evidence in this commit: the new completedIds set includes every role: 'tool' message without checking isError, so a denied or failed call passes the completion filter and is emitted as an ordinary fact; the reviewer prompt omits tool outputs and describes facts as completed calls. If a failed overwrite is followed by a removal, the reviewer can mistake the failed write for an agent-authored change and allow deleting the original file under the cleanup exception. Require a successful result or include the failure outcome in history.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
| } | ||
|
|
||
| humanAuthorization(): readonly ReviewText[] { | ||
| const own = extractAuthorization(this.loop.history()).filter((entry) => entry.role === 'human-instruction'); |
There was a problem hiding this comment.
Carry compacted boundaries into child reviews
Fresh evidence in this commit: subagent ancestry is persisted from parent.humanAuthorization(), but that method retains only human-instruction entries. When an explicit user prohibition survives compaction only as a compaction_summary (constraint), this filter drops it before a newly created child gets its ancestry snapshot, so that child’s Never Ask review can silently approve a medium-risk action the user explicitly ruled out. Preserve compacted entries as constraints in the child snapshot without treating them as authorization.
AGENTS.md reference: AGENTS.md:L115-L115
Useful? React with 👍 / 👎.
| if (input.expanded === true && members.some((member) => reviewHintAt(member.facts, now))) { | ||
| return undefined; |
There was a problem hiding this comment.
Replay review state when a tool card is registered
Fresh evidence in this commit: the timeline now records pre-card review state, but expanded mode suppresses the timeline tail here, while setToolAutoReviewing only updates a component that already exists and handleToolCall does not replay the state. When auto_review.started arrives during the permission gate before tool.call.started and the review lasts over 3 seconds, the later card has no Reviewing… hint and the expanded transcript hides the progress. Initialize the new card from the timeline or retain the state until registration.
AGENTS.md reference: AGENTS.md:L114-L114
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 63770aa4f5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const keys = Object.keys(status.entries); | ||
| if (keys.length === 0) return { cwd: targetCwd, branch: status.branch, clean: true }; | ||
| const entries = Object.fromEntries( | ||
| keys.slice(0, MAX_GIT_STATUS_ENTRIES).map((key) => [key, status.entries[key]!]), |
There was a problem hiding this comment.
Expose truncated Git status to the reviewer
When a repository has more than 50 dirty paths, this silently drops every later entry while still presenting clean: false and entries as the working-tree status. If an omitted path was originally changed by the agent and then modified by the user, the action history can make a pending rm or git restore look like cleanup of the agent's own edit, so Auto Review may approve discarding the user's change. Include relevant action targets regardless of the cap or mark the status as truncated so the reviewer fails closed.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
# Conflicts: # packages/kap-server/docs/kap.md # packages/kap-server/test/apiSurface.test.ts
💡 Codex ReviewWhen a AGENTS.md reference: AGENTS.md:L211-L213 ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1189e1d1c7
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| deadline, | ||
| messages: snapshot.messages, | ||
| }); | ||
| context.signal.throwIfAborted(); |
There was a problem hiding this comment.
Enforce the review deadline before accepting allow
When the provider completion arrives at or just after the configured deadline but resolves before the timeout callback runs—or when an adapter returns a completed outcome despite the abort—sessionReview.execute() can return allow, and this checks only the parent context.signal, not deadline.signal. The expired result is therefore accepted and can silently execute an action that should have failed closed as a timeout; check the deadline signal before using the outcome.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
Screenshots / Recordings
复核满 3 秒仍未出结果时,全屏折叠视图在尾部显示状态(3 秒内结束的不显示):
复核未通过后的审批弹窗。标题写"未通过"而不是"已拒绝",因为是否批准仍由用户决定:
Requirement or Bug
Ask When Needed(
yolo)和 Never Ask(auto)省掉了人工确认,Bash和 MCP 调用会直接执行。本 PR 加入默认关闭的实验能力 Auto Review:Always Ask 下会问人的Bash/ MCP 调用,先交给一个独立模型判断一次。其他内置工具(Edit、Write等)不参与。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心思路:是否送审,看 Always Ask 会不会问人。权限模式改成
PermissionPolicy.evaluate(context, mode)的入参,同一条策略链换成manual再求值一次,就是 Always Ask 的结果,不用另外维护名单。复核直接在权限门的permitting钩子里进行,主循环请求路径不变。flowchart TD A["Bash / MCP 调用(实验开启)"] --> B{"实际结果是 ask,或按 Always Ask 求值是 ask?"} B -- "否" --> G["沿用原结果"] B -- "是" --> C{"实际求值命中用户显式 ask 规则?"} C -- "是" --> G C -- "否" --> H["LLM 复核"] H -- "allow" --> E["执行"] H -- "deny / 失败" --> J{"复核结束时的模式"} J -- "yolo" --> K["转人工审批,附复核理由"] J -- "auto" --> L["不执行,返回工具错误"]因为判据就是 Always Ask 的结果,显式 deny、只读
Bash、用户allow规则、本会话已批准都不送审。唯一的例外是危险命令:开启实验时危险命令策略排在allow之前,kimi -p下也启用(关闭实验时非交互宿主仍与main一致跳过),所以被allow覆盖的危险命令也会送审。SessionAutoReviewServiceAGENTS.md缓存、独立请求器发请求与重试AutoReviewServiceautoReviewGate.tsregisterReviewer挂到权限门;权限门不依赖features/autoReviewreviewer 的输入包括:cwd、
AGENTS.md、用户指令(每条带replyTo,即它所回复的 Agent 消息末尾 2000 字符,让 reviewer 知道用户说"可以"时确认的是什么)、有副作用或经人工批准的历史调用、待审参数,以及删文件或改 git 状态的Bash才附带的gitStatus。Prompt 规则:low 放行,medium 需要明确授权,high 始终拒绝;replyTo、工具输出和 Agent 声称的同意都不算授权。KAP 没有扩展
tool_call.stage枚举,而是新增可选字段tool_call.auto_review,旧客户端不受影响;复核结论以approval_detail { outcome, risk?, reason }经 WS 和 REST 下发,标题文案由共享的formatApprovalReviewTitle统一生成。关键决策
Bash与mcp__*requester[auto_review].effort,否则取复核模型的默认档/undo不应改变子 Agent 的授权依据阅读指南(
packages/agent-core-v2/src/features/autoReview/):autoReviewGate.ts(何时送审、怎么分流)→reviewService.ts与context.ts(输入组装、快照、漂移)→sessionReviewService.ts(模型、并发、重试)→auto-review-policy.md(prompt)。策略签名改动、字段透传、manifest、文档和测试可略读。复核请求的细节
[auto_review].model>[secondary_model]默认模型 > 主模型;借用[secondary_model]时连同它的default_effort。无效别名或不支持的档位报CONFIG_INVALID。timeout_ms),瞬时错误和非法 JSON 最多尝试 3 次;401、配额耗尽、Retry-After超出剩余截止时间或上下文溢出不重试。溢出时只让本次复核失败,不压缩主 Agent 上下文。Behavior Changes and Affected Users
除第一行外,都只在开启实验后出现(
KIMI_CODE_EXPERIMENTAL_AUTO_REVIEW=1、[experimental] auto_review = true或KIMI_CODE_EXPERIMENTAL_FLAG=1);关闭实验就是所有行的退路。Bash/ MCPkimi -p)下同类调用(含命中的ask规则)allow规则(危险命令除外)allow覆盖的allow放行危险命令的 auto 用户ask规则[auto_review]配置节[auto_review].model/effort/timeout_msReviewing…auto_review.*记录与可回放状态,manifest 只增不改,旧版本跳过未知记录;触发复核的调用policy_name记为auto-review测试:
permissionGate.test.ts与permissionPolicyService.test.ts覆盖送审范围、分流和危险命令;autoReview.test.ts覆盖输入组装、快照、模型解析、重试与漂移;kap-server、klient、node-sdk、TUI、ACP、app-components 覆盖接口与界面。删除了 main 上的 4 个用例:
permissionGate.test.ts中测authorize()的 3 个(该方法没有调用方,已改为registerReviewer,同样情形由同文件fireBeforeExecute的用例覆盖);permissionPolicyService.test.ts的does not load the dangerous command policy for non-interactive hosts(由keeps dangerous command detection for manual re-evaluation on non-interactive hosts覆盖关闭实验跳过、开启实验拦截及手动重评)。验证:基于最新
main(e3b19047a7)在 macOS 上跑通整仓pnpm lint、pnpm run check:duplication、受影响包构建与tsc类型检查,以及受影响测试套件;此前亦在 Linux 上跑过相关测试文件。未验证:Windows;精简 prompt 后 reviewer 的真实决策质量。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.