Add hook auto review

This commit is contained in:
Abhinav Vedmala
2026-05-02 20:02:40 -07:00
parent 10133d9023
commit b2e53180eb
62 changed files with 2121 additions and 51 deletions
@@ -1710,6 +1710,98 @@
],
"type": "object"
},
"HookAutoReviewCompletedNotification": {
"properties": {
"dangerousCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"dangerousHooks": {
"items": {
"$ref": "#/definitions/HookAutoReviewDangerousHook"
},
"type": "array"
},
"failedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"reviewedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"skippedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"trustedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"turnId": {
"type": "string"
}
},
"required": [
"dangerousCount",
"dangerousHooks",
"failedCount",
"reviewedCount",
"skippedCount",
"threadId",
"trustedCount",
"turnId"
],
"type": "object"
},
"HookAutoReviewDangerousHook": {
"properties": {
"key": {
"type": "string"
},
"reason": {
"type": "string"
},
"sourcePath": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"key",
"reason",
"sourcePath"
],
"type": "object"
},
"HookAutoReviewStartedNotification": {
"properties": {
"hookCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"hookCount",
"threadId",
"turnId"
],
"type": "object"
},
"HookCompletedNotification": {
"properties": {
"run": {
@@ -3017,7 +3109,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -4969,6 +5062,46 @@
"title": "Hook/completedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"hook/autoReview/started"
],
"title": "Hook/autoReview/startedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/HookAutoReviewStartedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Hook/autoReview/startedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"hook/autoReview/completed"
],
"title": "Hook/autoReview/completedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/HookAutoReviewCompletedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Hook/autoReview/completedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -4066,6 +4066,46 @@
"title": "Hook/completedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"hook/autoReview/started"
],
"title": "Hook/autoReview/startedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/HookAutoReviewStartedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Hook/autoReview/startedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"hook/autoReview/completed"
],
"title": "Hook/autoReview/completedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/HookAutoReviewCompletedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Hook/autoReview/completedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -9696,6 +9736,102 @@
"title": "GuardianWarningNotification",
"type": "object"
},
"HookAutoReviewCompletedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"dangerousCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"dangerousHooks": {
"items": {
"$ref": "#/definitions/v2/HookAutoReviewDangerousHook"
},
"type": "array"
},
"failedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"reviewedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"skippedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"trustedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"turnId": {
"type": "string"
}
},
"required": [
"dangerousCount",
"dangerousHooks",
"failedCount",
"reviewedCount",
"skippedCount",
"threadId",
"trustedCount",
"turnId"
],
"title": "HookAutoReviewCompletedNotification",
"type": "object"
},
"HookAutoReviewDangerousHook": {
"properties": {
"key": {
"type": "string"
},
"reason": {
"type": "string"
},
"sourcePath": {
"$ref": "#/definitions/v2/AbsolutePathBuf"
}
},
"required": [
"key",
"reason",
"sourcePath"
],
"type": "object"
},
"HookAutoReviewStartedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"hookCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"hookCount",
"threadId",
"turnId"
],
"title": "HookAutoReviewStartedNotification",
"type": "object"
},
"HookCompletedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -9771,6 +9907,18 @@
"currentHash": {
"type": "string"
},
"dangerousHash": {
"type": [
"string",
"null"
]
},
"dangerousReason": {
"type": [
"string",
"null"
]
},
"displayOrder": {
"format": "int64",
"type": "integer"
@@ -9802,6 +9950,12 @@
"null"
]
},
"reviewedBy": {
"type": [
"string",
"null"
]
},
"source": {
"$ref": "#/definitions/v2/HookSource"
},
@@ -9821,6 +9975,12 @@
},
"trustStatus": {
"$ref": "#/definitions/v2/HookTrustStatus"
},
"trustedHash": {
"type": [
"string",
"null"
]
}
},
"required": [
@@ -10029,7 +10189,8 @@
"managed",
"untrusted",
"trusted",
"modified"
"modified",
"dangerous"
],
"type": "string"
},
@@ -15014,7 +15175,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -6305,6 +6305,102 @@
"title": "GuardianWarningNotification",
"type": "object"
},
"HookAutoReviewCompletedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"dangerousCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"dangerousHooks": {
"items": {
"$ref": "#/definitions/HookAutoReviewDangerousHook"
},
"type": "array"
},
"failedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"reviewedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"skippedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"trustedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"turnId": {
"type": "string"
}
},
"required": [
"dangerousCount",
"dangerousHooks",
"failedCount",
"reviewedCount",
"skippedCount",
"threadId",
"trustedCount",
"turnId"
],
"title": "HookAutoReviewCompletedNotification",
"type": "object"
},
"HookAutoReviewDangerousHook": {
"properties": {
"key": {
"type": "string"
},
"reason": {
"type": "string"
},
"sourcePath": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"key",
"reason",
"sourcePath"
],
"type": "object"
},
"HookAutoReviewStartedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"hookCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"hookCount",
"threadId",
"turnId"
],
"title": "HookAutoReviewStartedNotification",
"type": "object"
},
"HookCompletedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -6380,6 +6476,18 @@
"currentHash": {
"type": "string"
},
"dangerousHash": {
"type": [
"string",
"null"
]
},
"dangerousReason": {
"type": [
"string",
"null"
]
},
"displayOrder": {
"format": "int64",
"type": "integer"
@@ -6411,6 +6519,12 @@
"null"
]
},
"reviewedBy": {
"type": [
"string",
"null"
]
},
"source": {
"$ref": "#/definitions/HookSource"
},
@@ -6430,6 +6544,12 @@
},
"trustStatus": {
"$ref": "#/definitions/HookTrustStatus"
},
"trustedHash": {
"type": [
"string",
"null"
]
}
},
"required": [
@@ -6638,7 +6758,8 @@
"managed",
"untrusted",
"trusted",
"modified"
"modified",
"dangerous"
],
"type": "string"
},
@@ -11187,6 +11308,46 @@
"title": "Hook/completedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"hook/autoReview/started"
],
"title": "Hook/autoReview/startedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/HookAutoReviewStartedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Hook/autoReview/startedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"hook/autoReview/completed"
],
"title": "Hook/autoReview/completedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/HookAutoReviewCompletedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Hook/autoReview/completedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -12900,7 +13061,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -0,0 +1,79 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"AbsolutePathBuf": {
"description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.",
"type": "string"
},
"HookAutoReviewDangerousHook": {
"properties": {
"key": {
"type": "string"
},
"reason": {
"type": "string"
},
"sourcePath": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"key",
"reason",
"sourcePath"
],
"type": "object"
}
},
"properties": {
"dangerousCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"dangerousHooks": {
"items": {
"$ref": "#/definitions/HookAutoReviewDangerousHook"
},
"type": "array"
},
"failedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"reviewedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"skippedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"trustedCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"turnId": {
"type": "string"
}
},
"required": [
"dangerousCount",
"dangerousHooks",
"failedCount",
"reviewedCount",
"skippedCount",
"threadId",
"trustedCount",
"turnId"
],
"title": "HookAutoReviewCompletedNotification",
"type": "object"
}
@@ -0,0 +1,23 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"hookCount": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"hookCount",
"threadId",
"turnId"
],
"title": "HookAutoReviewStartedNotification",
"type": "object"
}
@@ -50,6 +50,18 @@
"currentHash": {
"type": "string"
},
"dangerousHash": {
"type": [
"string",
"null"
]
},
"dangerousReason": {
"type": [
"string",
"null"
]
},
"displayOrder": {
"format": "int64",
"type": "integer"
@@ -81,6 +93,12 @@
"null"
]
},
"reviewedBy": {
"type": [
"string",
"null"
]
},
"source": {
"$ref": "#/definitions/HookSource"
},
@@ -100,6 +118,12 @@
},
"trustStatus": {
"$ref": "#/definitions/HookTrustStatus"
},
"trustedHash": {
"type": [
"string",
"null"
]
}
},
"required": [
@@ -137,7 +161,8 @@
"managed",
"untrusted",
"trusted",
"modified"
"modified",
"dangerous"
],
"type": "string"
},
@@ -1450,7 +1450,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -900,7 +900,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -900,7 +900,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -900,7 +900,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -1450,7 +1450,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -900,7 +900,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -1450,7 +1450,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -900,7 +900,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -4,7 +4,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
@@ -900,7 +900,8 @@
"ThreadActiveFlag": {
"enum": [
"waitingOnApproval",
"waitingOnUserInput"
"waitingOnUserInput",
"reviewingHooks"
],
"type": "string"
},
File diff suppressed because one or more lines are too long
@@ -0,0 +1,6 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { HookAutoReviewDangerousHook } from "./HookAutoReviewDangerousHook";
export type HookAutoReviewCompletedNotification = { threadId: string, turnId: string, reviewedCount: number, trustedCount: number, dangerousCount: number, skippedCount: number, failedCount: number, dangerousHooks: Array<HookAutoReviewDangerousHook>, };
@@ -0,0 +1,6 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
export type HookAutoReviewDangerousHook = { key: string, sourcePath: AbsolutePathBuf, reason: string, };
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type HookAutoReviewStartedNotification = { threadId: string, turnId: string, hookCount: number, };
@@ -7,4 +7,4 @@ import type { HookHandlerType } from "./HookHandlerType";
import type { HookSource } from "./HookSource";
import type { HookTrustStatus } from "./HookTrustStatus";
export type HookMetadata = { key: string, eventName: HookEventName, handlerType: HookHandlerType, matcher: string | null, command: string | null, timeoutSec: bigint, statusMessage: string | null, sourcePath: AbsolutePathBuf, source: HookSource, pluginId: string | null, displayOrder: bigint, enabled: boolean, isManaged: boolean, currentHash: string, trustStatus: HookTrustStatus, };
export type HookMetadata = { key: string, eventName: HookEventName, handlerType: HookHandlerType, matcher: string | null, command: string | null, timeoutSec: bigint, statusMessage: string | null, sourcePath: AbsolutePathBuf, source: HookSource, pluginId: string | null, displayOrder: bigint, enabled: boolean, isManaged: boolean, currentHash: string, trustedHash: string | null, reviewedBy: string | null, dangerousHash: string | null, dangerousReason: string | null, trustStatus: HookTrustStatus, };
@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type HookTrustStatus = "managed" | "untrusted" | "trusted" | "modified";
export type HookTrustStatus = "managed" | "untrusted" | "trusted" | "modified" | "dangerous";
@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
export type ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput" | "reviewingHooks";
@@ -153,6 +153,9 @@ export type { GuardianCommandSource } from "./GuardianCommandSource";
export type { GuardianRiskLevel } from "./GuardianRiskLevel";
export type { GuardianUserAuthorization } from "./GuardianUserAuthorization";
export type { GuardianWarningNotification } from "./GuardianWarningNotification";
export type { HookAutoReviewCompletedNotification } from "./HookAutoReviewCompletedNotification";
export type { HookAutoReviewDangerousHook } from "./HookAutoReviewDangerousHook";
export type { HookAutoReviewStartedNotification } from "./HookAutoReviewStartedNotification";
export type { HookCompletedNotification } from "./HookCompletedNotification";
export type { HookErrorInfo } from "./HookErrorInfo";
export type { HookEventName } from "./HookEventName";
@@ -1388,6 +1388,8 @@ server_notification_definitions! {
HookStarted => "hook/started" (v2::HookStartedNotification),
TurnCompleted => "turn/completed" (v2::TurnCompletedNotification),
HookCompleted => "hook/completed" (v2::HookCompletedNotification),
HookAutoReviewStarted => "hook/autoReview/started" (v2::HookAutoReviewStartedNotification),
HookAutoReviewCompleted => "hook/autoReview/completed" (v2::HookAutoReviewCompletedNotification),
TurnDiffUpdated => "turn/diff/updated" (v2::TurnDiffUpdatedNotification),
TurnPlanUpdated => "turn/plan/updated" (v2::TurnPlanUpdatedNotification),
ItemStarted => "item/started" (v2::ItemStartedNotification),
@@ -213,7 +213,10 @@ impl ThreadHistoryBuilder {
EventMsg::ExitedReviewMode(payload) => self.handle_exited_review_mode(payload),
EventMsg::ItemStarted(payload) => self.handle_item_started(payload),
EventMsg::ItemCompleted(payload) => self.handle_item_completed(payload),
EventMsg::HookStarted(_) | EventMsg::HookCompleted(_) => {}
EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::HookAutoReviewStarted(_)
| EventMsg::HookAutoReviewCompleted(_) => {}
EventMsg::Error(payload) => self.handle_error(payload),
EventMsg::TokenCount(_) => {}
EventMsg::ThreadRolledBack(payload) => self.handle_thread_rollback(payload),
@@ -483,7 +483,7 @@ v2_enum_from_core!(
v2_enum_from_core!(
pub enum HookTrustStatus from CoreHookTrustStatus {
Managed, Untrusted, Trusted, Modified
Managed, Untrusted, Trusted, Modified, Dangerous
}
);
@@ -4411,6 +4411,7 @@ pub enum ThreadStatus {
pub enum ThreadActiveFlag {
WaitingOnApproval,
WaitingOnUserInput,
ReviewingHooks,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
@@ -4807,6 +4808,10 @@ pub struct HookMetadata {
pub enabled: bool,
pub is_managed: bool,
pub current_hash: String,
pub trusted_hash: Option<String>,
pub reviewed_by: Option<String>,
pub dangerous_hash: Option<String>,
pub dangerous_reason: Option<String>,
pub trust_status: HookTrustStatus,
}
@@ -6823,6 +6828,38 @@ pub struct HookCompletedNotification {
pub run: HookRunSummary,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookAutoReviewStartedNotification {
pub thread_id: String,
pub turn_id: String,
pub hook_count: u32,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookAutoReviewDangerousHook {
pub key: String,
pub source_path: AbsolutePathBuf,
pub reason: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookAutoReviewCompletedNotification {
pub thread_id: String,
pub turn_id: String,
pub reviewed_count: u32,
pub trusted_count: u32,
pub dangerous_count: u32,
pub skipped_count: u32,
pub failed_count: u32,
pub dangerous_hooks: Vec<HookAutoReviewDangerousHook>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
+3 -1
View File
@@ -363,7 +363,7 @@ When `nextCursor` is `null`, you’ve reached the final page.
`thread/status/changed` is emitted whenever a loaded thread's status changes after it has already been introduced to the client:
- Includes `threadId` and the new `status`.
- Status can be `notLoaded`, `idle`, `systemError`, or `active` (with `activeFlags`; `active` implies running).
- Status can be `notLoaded`, `idle`, `systemError`, or `active` (with `activeFlags`; `active` implies running). Active flags include `waitingOnApproval`, `waitingOnUserInput`, and `reviewingHooks`.
- `thread/start`, `thread/fork`, and detached review threads do not emit a separate initial `thread/status/changed`; their `thread/started` notification already carries the current `thread.status`.
```json
@@ -1129,6 +1129,8 @@ The app-server streams JSON-RPC notifications while a turn is running. Each turn
- `turn/plan/updated` — `{ turnId, explanation?, plan }` whenever the agent shares or changes its plan; each `plan` entry is `{ step, status }` with `status` in `pending`, `inProgress`, or `completed`.
- `model/rerouted` — `{ threadId, turnId, fromModel, toModel, reason }` when the backend reroutes a request to a different model (for example, due to high-risk cyber safety checks).
- `model/verification` — `{ threadId, turnId, verifications }` when the backend flags additional account verification, such as `trustedAccessForCyber`.
- `hook/autoReview/started` — `{ threadId, turnId, hookCount }` when Codex is blocking startup to scan new or modified hooks in auto-review mode.
- `hook/autoReview/completed` — `{ threadId, turnId, reviewedCount, trustedCount, dangerousCount, skippedCount, failedCount, dangerousHooks }` when hook auto-review finishes. `dangerousHooks` entries include `{ key, sourcePath, reason }`.
Today both notifications carry an empty `items` array even when item events were streamed; rely on `item/*` notifications for the canonical item list until this is fixed.
@@ -31,6 +31,9 @@ use codex_app_server_protocol::FileChangeRequestApprovalParams;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
use codex_app_server_protocol::GrantedPermissionProfile as V2GrantedPermissionProfile;
use codex_app_server_protocol::GuardianWarningNotification;
use codex_app_server_protocol::HookAutoReviewCompletedNotification;
use codex_app_server_protocol::HookAutoReviewDangerousHook;
use codex_app_server_protocol::HookAutoReviewStartedNotification;
use codex_app_server_protocol::HookCompletedNotification;
use codex_app_server_protocol::HookStartedNotification;
use codex_app_server_protocol::ItemCompletedNotification;
@@ -1011,6 +1014,45 @@ pub(crate) async fn apply_bespoke_event_handling(
.send_server_notification(ServerNotification::HookCompleted(notification))
.await;
}
EventMsg::HookAutoReviewStarted(event) => {
thread_watch_manager
.note_hook_auto_review_started(&conversation_id.to_string())
.await;
let notification = HookAutoReviewStartedNotification {
thread_id: conversation_id.to_string(),
turn_id: event.turn_id,
hook_count: event.hook_count,
};
outgoing
.send_server_notification(ServerNotification::HookAutoReviewStarted(notification))
.await;
}
EventMsg::HookAutoReviewCompleted(event) => {
thread_watch_manager
.note_hook_auto_review_completed(&conversation_id.to_string())
.await;
let notification = HookAutoReviewCompletedNotification {
thread_id: conversation_id.to_string(),
turn_id: event.turn_id,
reviewed_count: event.reviewed_count,
trusted_count: event.trusted_count,
dangerous_count: event.dangerous_count,
skipped_count: event.skipped_count,
failed_count: event.failed_count,
dangerous_hooks: event
.dangerous_hooks
.into_iter()
.map(|hook| HookAutoReviewDangerousHook {
key: hook.key,
source_path: hook.source_path,
reason: hook.reason,
})
.collect(),
};
outgoing
.send_server_notification(ServerNotification::HookAutoReviewCompleted(notification))
.await;
}
EventMsg::ExitedReviewMode(review_event) => {
let review = match review_event.review_output {
Some(output) => render_review_output_text(&output),
@@ -8852,6 +8852,10 @@ fn hooks_to_info(hooks: &[codex_hooks::HookListEntry]) -> Vec<HookMetadata> {
enabled: hook.enabled,
is_managed: hook.is_managed,
current_hash: hook.current_hash.clone(),
trusted_hash: hook.trusted_hash.clone(),
reviewed_by: hook.reviewed_by.clone(),
dangerous_hash: hook.dangerous_hash.clone(),
dangerous_reason: hook.dangerous_reason.clone(),
trust_status: hook.trust_status.into(),
})
.collect()
+55
View File
@@ -164,6 +164,7 @@ impl ThreadWatchManager {
runtime.running = false;
runtime.pending_permission_requests = 0;
runtime.pending_user_input_requests = 0;
runtime.pending_hook_auto_reviews = 0;
runtime.is_loaded = false;
})
.await;
@@ -174,6 +175,7 @@ impl ThreadWatchManager {
runtime.running = false;
runtime.pending_permission_requests = 0;
runtime.pending_user_input_requests = 0;
runtime.pending_hook_auto_reviews = 0;
runtime.has_system_error = true;
})
.await;
@@ -184,6 +186,22 @@ impl ThreadWatchManager {
runtime.running = false;
runtime.pending_permission_requests = 0;
runtime.pending_user_input_requests = 0;
runtime.pending_hook_auto_reviews = 0;
})
.await;
}
pub(crate) async fn note_hook_auto_review_started(&self, thread_id: &str) {
self.update_runtime_for_thread(thread_id, |runtime| {
runtime.is_loaded = true;
runtime.pending_hook_auto_reviews = runtime.pending_hook_auto_reviews.saturating_add(1);
})
.await;
}
pub(crate) async fn note_hook_auto_review_completed(&self, thread_id: &str) {
self.update_runtime_for_thread(thread_id, |runtime| {
runtime.pending_hook_auto_reviews = runtime.pending_hook_auto_reviews.saturating_sub(1);
})
.await;
}
@@ -423,6 +441,7 @@ struct RuntimeFacts {
running: bool,
pending_permission_requests: u32,
pending_user_input_requests: u32,
pending_hook_auto_reviews: u32,
has_system_error: bool,
}
@@ -438,6 +457,9 @@ fn loaded_thread_status(runtime: &RuntimeFacts) -> ThreadStatus {
if runtime.pending_user_input_requests > 0 {
active_flags.push(ThreadActiveFlag::WaitingOnUserInput);
}
if runtime.pending_hook_auto_reviews > 0 {
active_flags.push(ThreadActiveFlag::ReviewingHooks);
}
if runtime.running || !active_flags.is_empty() {
return ThreadStatus::Active { active_flags };
@@ -496,6 +518,39 @@ mod tests {
);
}
#[tokio::test]
async fn hook_auto_review_sets_active_flag() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
manager
.note_hook_auto_review_started(INTERACTIVE_THREAD_ID)
.await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Active {
active_flags: vec![ThreadActiveFlag::ReviewingHooks],
},
);
manager
.note_hook_auto_review_completed(INTERACTIVE_THREAD_ID)
.await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Idle,
);
}
#[tokio::test]
async fn status_updates_track_single_thread() {
let manager = ThreadWatchManager::new();
@@ -164,6 +164,10 @@ async fn hooks_list_shows_discovered_hook() -> Result<()> {
/*timeout_sec*/ 5,
Some("running listed hook"),
),
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
trust_status: HookTrustStatus::Untrusted,
}],
warnings: Vec::new(),
@@ -242,6 +246,10 @@ async fn hooks_list_shows_discovered_plugin_hook() -> Result<()> {
/*timeout_sec*/ 7,
Some("running plugin hook"),
),
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
trust_status: HookTrustStatus::Untrusted,
}],
warnings: Vec::new(),
@@ -367,6 +375,10 @@ timeout = 5
/*timeout_sec*/ 5,
/*status_message*/ None,
),
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
trust_status: HookTrustStatus::Untrusted,
}],
warnings: Vec::new(),
+6
View File
@@ -27,6 +27,12 @@ pub struct HookStateToml {
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trusted_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reviewed_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dangerous_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dangerous_reason: Option<String>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
+1
View File
@@ -122,6 +122,7 @@ command = "python3 /tmp/pre.py"
super::HookStateToml {
enabled: Some(false),
trusted_hash: Some("sha256:abc123".to_string()),
..Default::default()
},
)]),
}
+9
View File
@@ -994,9 +994,18 @@
},
"HookStateToml": {
"properties": {
"dangerous_hash": {
"type": "string"
},
"dangerous_reason": {
"type": "string"
},
"enabled": {
"type": "boolean"
},
"reviewed_by": {
"type": "string"
},
"trusted_hash": {
"type": "string"
}
+284
View File
@@ -0,0 +1,284 @@
use std::sync::Arc;
use anyhow::Context;
use anyhow::anyhow;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookSource;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde_json::json;
use tokio_util::sync::CancellationToken;
use crate::codex_delegate::run_codex_thread_one_shot;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use super::GUARDIAN_PREFERRED_MODEL;
use super::GUARDIAN_REVIEW_TIMEOUT;
use super::GUARDIAN_REVIEWER_NAME;
use super::review_session::build_guardian_review_session_config;
const HOOK_REVIEWER_NAME: &str = "hook_auto_review";
const HOOK_REVIEW_POLICY: &str = r#"You are the Codex hook auto-reviewer.
Your job is to review a newly discovered or modified user hook before Codex runs
it. Decide whether this exact hook source appears to contain clear malicious or
dangerous behavior.
Mark a hook dangerous only for clear security risk, such as credential theft,
secret exfiltration, remote code execution/persistence, tampering with Codex or
shell startup files, destructive file operations, or attempts to conceal those
actions. Benign automation, formatting, notifications, logging, and local
developer workflow helpers should not be marked dangerous.
Review the hook source file and the configured command. If the command invokes a
script or nearby source file, inspect that file too using read-only tools. Do not
execute the hook command or any referenced script.
Return only JSON that matches the requested schema. Use `dangerous` for clear
malicious or security-vulnerable behavior, `safe` for benign behavior, and
`unsure` when the evidence is insufficient."#;
#[derive(Debug, Clone)]
pub(crate) struct HookSecurityReviewRequest {
pub(crate) key: String,
pub(crate) event_name: HookEventName,
pub(crate) matcher: Option<String>,
pub(crate) command: Option<String>,
pub(crate) timeout_sec: u64,
pub(crate) source_path: AbsolutePathBuf,
pub(crate) source: HookSource,
pub(crate) current_hash: String,
pub(crate) source_excerpt: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HookSecurityVerdict {
Safe,
Dangerous,
Unsure,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HookSecurityReview {
pub(crate) verdict: HookSecurityVerdict,
pub(crate) reason: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
struct HookSecurityReviewResponse {
verdict: HookSecurityReviewResponseVerdict,
reason: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum HookSecurityReviewResponseVerdict {
Safe,
Dangerous,
Unsure,
}
pub(crate) async fn review_hook_for_security(
session: Arc<Session>,
turn: Arc<TurnContext>,
request: HookSecurityReviewRequest,
) -> anyhow::Result<HookSecurityReview> {
let live_network_config = match session.services.network_proxy.as_ref() {
Some(network_proxy) => Some(
network_proxy
.proxy()
.current_cfg()
.await
.context("failed to read live network proxy config for hook review")?,
),
None => None,
};
let available_models = session
.services
.models_manager
.list_models(RefreshStrategy::Offline)
.await;
let preferred_model = available_models
.iter()
.find(|preset| preset.model == GUARDIAN_PREFERRED_MODEL);
let (review_model, review_reasoning_effort) = if let Some(preset) = preferred_model {
let effort = preferred_reasoning_effort(
preset
.supported_reasoning_efforts
.iter()
.any(|effort| effort.effort == codex_protocol::openai_models::ReasoningEffort::Low),
Some(preset.default_reasoning_effort),
);
(GUARDIAN_PREFERRED_MODEL.to_string(), effort)
} else {
let effort = preferred_reasoning_effort(
turn.model_info
.supported_reasoning_levels
.iter()
.any(|preset| preset.effort == codex_protocol::openai_models::ReasoningEffort::Low),
turn.reasoning_effort
.or(turn.model_info.default_reasoning_level),
);
(turn.model_info.slug.clone(), effort)
};
let mut review_config = build_guardian_review_session_config(
turn.config.as_ref(),
live_network_config,
review_model.as_str(),
review_reasoning_effort,
)
.context("failed to build hook review session config")?;
review_config.base_instructions = Some(HOOK_REVIEW_POLICY.to_string());
let cancel_token = CancellationToken::new();
let codex = run_codex_thread_one_shot(
review_config,
Arc::clone(&session.services.auth_manager),
Arc::clone(&session.services.models_manager),
vec![UserInput::Text {
text: hook_review_prompt(&request),
text_elements: Vec::new(),
}],
session,
turn,
cancel_token.clone(),
SubAgentSource::Other(GUARDIAN_REVIEWER_NAME.to_string()),
Some(hook_review_schema()),
Some(InitialHistory::New),
)
.await
.context("failed to start hook review session")?;
let raw_response = match tokio::time::timeout(GUARDIAN_REVIEW_TIMEOUT, async {
await_hook_review_response(codex).await
})
.await
{
Ok(response) => response?,
Err(_) => {
cancel_token.cancel();
return Err(anyhow!("hook review timed out"));
}
};
parse_hook_review_response(&raw_response)
}
fn hook_review_prompt(request: &HookSecurityReviewRequest) -> String {
format!(
r#"Review this Codex hook.
Hook identity:
- key: {key}
- event: {event_name:?}
- matcher: {matcher}
- source: {source:?}
- source_path: {source_path}
- timeout_sec: {timeout_sec}
- current_hash: {current_hash}
Configured command:
```sh
{command}
```
Source file excerpt:
```
{source_excerpt}
```
Inspect referenced source files when needed. Do not execute the hook command.
"#,
key = request.key,
event_name = request.event_name,
matcher = request.matcher.as_deref().unwrap_or("<none>"),
source = request.source,
source_path = request.source_path.display(),
timeout_sec = request.timeout_sec,
current_hash = request.current_hash,
command = request.command.as_deref().unwrap_or("<none>"),
source_excerpt = request.source_excerpt,
)
}
fn hook_review_schema() -> serde_json::Value {
json!({
"type": "object",
"additionalProperties": false,
"required": ["verdict", "reason"],
"properties": {
"verdict": {
"type": "string",
"enum": ["safe", "dangerous", "unsure"]
},
"reason": {
"type": "string"
}
}
})
}
fn preferred_reasoning_effort(
supports_low: bool,
fallback: Option<codex_protocol::openai_models::ReasoningEffort>,
) -> Option<codex_protocol::openai_models::ReasoningEffort> {
if supports_low {
Some(codex_protocol::openai_models::ReasoningEffort::Low)
} else {
fallback
}
}
async fn await_hook_review_response(codex: crate::session::Codex) -> anyhow::Result<String> {
let mut last_error_message: Option<String> = None;
loop {
let event = codex
.next_event()
.await
.map_err(|err| anyhow!("hook review session failed: {err}"))?;
match event.msg {
EventMsg::TurnComplete(turn_complete) => {
if let Some(last_agent_message) = turn_complete.last_agent_message {
return Ok(last_agent_message);
}
if let Some(last_error_message) = last_error_message {
return Err(anyhow!(last_error_message));
}
return Err(anyhow!("hook review completed without a response"));
}
EventMsg::Error(error) => {
last_error_message = Some(error.message);
}
EventMsg::TurnAborted(_) => {
return Err(anyhow!("hook review was aborted"));
}
_ => {}
}
}
}
fn parse_hook_review_response(raw_response: &str) -> anyhow::Result<HookSecurityReview> {
let response: HookSecurityReviewResponse = serde_json::from_str(raw_response)
.with_context(|| format!("failed to parse hook review response: {raw_response}"))?;
let verdict = match response.verdict {
HookSecurityReviewResponseVerdict::Safe => HookSecurityVerdict::Safe,
HookSecurityReviewResponseVerdict::Dangerous => HookSecurityVerdict::Dangerous,
HookSecurityReviewResponseVerdict::Unsure => HookSecurityVerdict::Unsure,
};
Ok(HookSecurityReview {
verdict,
reason: response.reason,
})
}
pub(crate) fn hook_reviewer_name() -> &'static str {
HOOK_REVIEWER_NAME
}
+6
View File
@@ -12,6 +12,7 @@
//! 4. Apply the guardian's explicit allow/deny outcome.
mod approval_request;
mod hook_review;
mod prompt;
mod review;
mod review_session;
@@ -27,6 +28,11 @@ pub(crate) use approval_request::GuardianApprovalRequest;
pub(crate) use approval_request::GuardianMcpAnnotations;
pub(crate) use approval_request::GuardianNetworkAccessTrigger;
pub(crate) use approval_request::guardian_approval_request_to_json;
pub(crate) use hook_review::HookSecurityReview;
pub(crate) use hook_review::HookSecurityReviewRequest;
pub(crate) use hook_review::HookSecurityVerdict;
pub(crate) use hook_review::hook_reviewer_name;
pub(crate) use hook_review::review_hook_for_security;
pub(crate) use review::guardian_rejection_message;
pub(crate) use review::guardian_timeout_message;
pub(crate) use review::is_guardian_reviewer_source;
+276
View File
@@ -0,0 +1,276 @@
use std::sync::Arc;
use anyhow::Context;
use codex_config::CONFIG_TOML_FILE;
use codex_hooks::HookListEntry;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::HookAutoReviewCompletedEvent;
use codex_protocol::protocol::HookAutoReviewDangerousHook;
use codex_protocol::protocol::HookAutoReviewStartedEvent;
use codex_protocol::protocol::HookTrustStatus;
use codex_protocol::protocol::WarningEvent;
use tokio::fs;
use toml_edit::value;
use tracing::warn;
use crate::config::edit::ConfigEdit;
use crate::config::edit::ConfigEditsBuilder;
use crate::guardian;
use crate::guardian::HookSecurityReviewRequest;
use crate::guardian::HookSecurityVerdict;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
const MAX_SOURCE_EXCERPT_CHARS: usize = 32_000;
#[derive(Debug, Default)]
struct HookAutoReviewStats {
reviewed_count: u32,
trusted_count: u32,
dangerous_count: u32,
skipped_count: u32,
failed_count: u32,
dangerous_hooks: Vec<HookAutoReviewDangerousHook>,
}
pub(crate) async fn maybe_run_hook_auto_review(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
) {
if turn_context.config.approvals_reviewer != ApprovalsReviewer::AutoReview {
return;
}
let hooks = sess.hooks();
let candidates = hooks
.hook_entries()
.iter()
.filter(|hook| {
matches!(
hook.trust_status,
HookTrustStatus::Untrusted | HookTrustStatus::Modified
)
})
.cloned()
.collect::<Vec<_>>();
if candidates.is_empty() {
return;
}
sess.send_event(
turn_context,
EventMsg::HookAutoReviewStarted(HookAutoReviewStartedEvent {
turn_id: turn_context.sub_id.clone(),
hook_count: u32_count(candidates.len()),
}),
)
.await;
let mut stats = HookAutoReviewStats::default();
let mut edits = Vec::new();
for hook in candidates {
let review_request = HookSecurityReviewRequest {
key: hook.key.clone(),
event_name: hook.event_name,
matcher: hook.matcher.clone(),
command: hook.command.clone(),
timeout_sec: hook.timeout_sec,
source_path: hook.source_path.clone(),
source: hook.source,
current_hash: hook.current_hash.clone(),
source_excerpt: read_source_excerpt(&hook).await,
};
let review = guardian::review_hook_for_security(
Arc::clone(sess),
Arc::clone(turn_context),
review_request,
)
.await;
let review: guardian::HookSecurityReview = match review {
Ok(review) => review,
Err(err) => {
warn!("hook auto-review failed for {}: {err:#}", hook.key);
stats.failed_count = stats.failed_count.saturating_add(1);
continue;
}
};
stats.reviewed_count = stats.reviewed_count.saturating_add(1);
match review.verdict {
HookSecurityVerdict::Safe => {
stats.trusted_count = stats.trusted_count.saturating_add(1);
edits.extend(trust_hook_edits(&hook));
}
HookSecurityVerdict::Dangerous => {
stats.dangerous_count = stats.dangerous_count.saturating_add(1);
let reason = normalized_reason(review.reason);
edits.extend(dangerous_hook_edits(&hook, &reason));
stats.dangerous_hooks.push(HookAutoReviewDangerousHook {
key: hook.key.clone(),
source_path: hook.source_path.clone(),
reason,
});
}
HookSecurityVerdict::Unsure => {
stats.skipped_count = stats.skipped_count.saturating_add(1);
}
}
}
if !edits.is_empty() {
let apply_result = ConfigEditsBuilder::new(turn_context.config.codex_home.as_path())
.with_profile(turn_context.config.active_profile.as_deref())
.with_edits(edits)
.apply()
.await
.with_context(|| {
format!(
"failed to persist hook auto-review verdicts to {}",
turn_context
.config
.codex_home
.join(CONFIG_TOML_FILE)
.display()
)
});
if let Err(err) = apply_result {
let persisted_count = stats.trusted_count.saturating_add(stats.dangerous_count);
stats.failed_count = stats.failed_count.saturating_add(persisted_count);
stats.trusted_count = 0;
stats.dangerous_count = 0;
stats.dangerous_hooks.clear();
sess.send_event(
turn_context,
EventMsg::Warning(WarningEvent {
message: format!("{err:#}"),
}),
)
.await;
} else {
sess.reload_user_config_layer().await;
}
}
sess.send_event(
turn_context,
EventMsg::HookAutoReviewCompleted(HookAutoReviewCompletedEvent {
turn_id: turn_context.sub_id.clone(),
reviewed_count: stats.reviewed_count,
trusted_count: stats.trusted_count,
dangerous_count: stats.dangerous_count,
skipped_count: stats.skipped_count,
failed_count: stats.failed_count,
dangerous_hooks: stats.dangerous_hooks,
}),
)
.await;
}
async fn read_source_excerpt(hook: &HookListEntry) -> String {
match fs::read_to_string(hook.source_path.as_path()).await {
Ok(contents) => truncate_source_excerpt(&contents),
Err(err) => format!("Unable to read hook source file: {err}"),
}
}
fn truncate_source_excerpt(contents: &str) -> String {
let mut chars = contents.chars();
let excerpt = chars
.by_ref()
.take(MAX_SOURCE_EXCERPT_CHARS)
.collect::<String>();
if chars.next().is_some() {
format!("{excerpt}\n\n[truncated after {MAX_SOURCE_EXCERPT_CHARS} characters]")
} else {
excerpt
}
}
fn trust_hook_edits(hook: &HookListEntry) -> Vec<ConfigEdit> {
vec![
set_hook_state(&hook.key, "trusted_hash", value(hook.current_hash.clone())),
set_hook_state(
&hook.key,
"reviewed_by",
value(guardian::hook_reviewer_name()),
),
clear_hook_state(&hook.key, "dangerous_hash"),
clear_hook_state(&hook.key, "dangerous_reason"),
]
}
fn dangerous_hook_edits(hook: &HookListEntry, reason: &str) -> Vec<ConfigEdit> {
vec![
set_hook_state(&hook.key, "enabled", value(false)),
set_hook_state(
&hook.key,
"dangerous_hash",
value(hook.current_hash.clone()),
),
set_hook_state(&hook.key, "dangerous_reason", value(reason)),
set_hook_state(
&hook.key,
"reviewed_by",
value(guardian::hook_reviewer_name()),
),
clear_hook_state(&hook.key, "trusted_hash"),
]
}
fn set_hook_state(key: &str, field: &str, value: toml_edit::Item) -> ConfigEdit {
ConfigEdit::SetPath {
segments: hook_state_segments(key, field),
value,
}
}
fn clear_hook_state(key: &str, field: &str) -> ConfigEdit {
ConfigEdit::ClearPath {
segments: hook_state_segments(key, field),
}
}
fn hook_state_segments(key: &str, field: &str) -> Vec<String> {
vec![
"hooks".to_string(),
"state".to_string(),
key.to_string(),
field.to_string(),
]
}
fn normalized_reason(reason: String) -> String {
let reason = reason.trim();
if reason.is_empty() {
"Auto-review marked this hook dangerous.".to_string()
} else {
reason.to_string()
}
}
fn u32_count(count: usize) -> u32 {
u32::try_from(count).unwrap_or(u32::MAX)
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn truncate_source_excerpt_marks_long_content() {
let contents = "a".repeat(MAX_SOURCE_EXCERPT_CHARS + 1);
let excerpt = truncate_source_excerpt(&contents);
assert_eq!(
excerpt,
format!(
"{}\n\n[truncated after {MAX_SOURCE_EXCERPT_CHARS} characters]",
"a".repeat(MAX_SOURCE_EXCERPT_CHARS)
)
);
}
}
+5
View File
@@ -104,6 +104,11 @@ pub(crate) async fn run_pending_session_start_hooks(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
) -> bool {
if sess.should_run_hook_auto_review().await {
crate::hook_auto_review::maybe_run_hook_auto_review(sess, turn_context).await;
sess.mark_hook_auto_review_completed().await;
}
let Some(session_start_source) = sess.take_pending_session_start_source().await else {
return false;
};
+1
View File
@@ -39,6 +39,7 @@ mod flags;
mod git_info_tests;
mod goals;
mod guardian;
mod hook_auto_review;
mod hook_runtime;
mod installation_id;
pub(crate) mod landlock;
+10
View File
@@ -3245,6 +3245,16 @@ impl Session {
state.take_pending_session_start_source()
}
pub(crate) async fn should_run_hook_auto_review(&self) -> bool {
let state = self.state.lock().await;
state.has_pending_session_start_source() && !state.hook_auto_review_completed()
}
pub(crate) async fn mark_hook_auto_review_completed(&self) {
let mut state = self.state.lock().await;
state.mark_hook_auto_review_completed();
}
fn show_raw_agent_reasoning(&self) -> bool {
self.services.show_raw_agent_reasoning
}
+254 -16
View File
@@ -96,6 +96,7 @@ use codex_protocol::protocol::CompactedItem;
use codex_protocol::protocol::ConversationAudioParams;
use codex_protocol::protocol::CreditsSnapshot;
use codex_protocol::protocol::GranularApprovalConfig;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::NetworkApprovalProtocol;
@@ -463,25 +464,21 @@ async fn write_project_trust_config(
.await
}
async fn preview_session_start_hooks(
async fn session_start_hook_entries(
config: &crate::config::Config,
) -> std::io::Result<Vec<codex_protocol::protocol::HookRunSummary>> {
) -> std::io::Result<Vec<codex_hooks::HookListEntry>> {
let hooks = Hooks::new(HooksConfig {
feature_enabled: true,
config_layer_stack: Some(config.config_layer_stack.clone()),
..HooksConfig::default()
});
Ok(
hooks.preview_session_start(&codex_hooks::SessionStartRequest {
session_id: ThreadId::new(),
cwd: config.cwd.clone(),
transcript_path: None,
model: "gpt-5.2".to_string(),
permission_mode: "default".to_string(),
source: codex_hooks::SessionStartSource::Startup,
}),
)
Ok(hooks
.hook_entries()
.iter()
.filter(|hook| hook.event_name == HookEventName::SessionStart)
.cloned()
.collect())
}
fn test_tool_runtime(session: Arc<Session>, turn_context: Arc<TurnContext>) -> ToolCallRuntime {
@@ -1232,6 +1229,247 @@ async fn reload_user_config_layer_refreshes_hooks() -> anyhow::Result<()> {
Ok(())
}
#[tokio::test]
async fn hook_auto_review_persists_verdicts_before_session_start_hooks() -> anyhow::Result<()> {
const INITIAL_HOOK_CONFIG: &str = r#"
[hooks]
[[hooks.SessionStart]]
hooks = [
{ type = "command", command = "echo safe startup hook" },
{ type = "command", command = "echo dangerous startup hook" },
]
"#;
let server = start_mock_server().await;
let review_responses = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-safe"),
ev_assistant_message(
"msg-safe",
&serde_json::json!({
"verdict": "safe",
"reason": "benign startup context",
})
.to_string(),
),
ev_completed("resp-safe"),
]),
sse(vec![
ev_response_created("resp-dangerous"),
ev_assistant_message(
"msg-dangerous",
&serde_json::json!({
"verdict": "dangerous",
"reason": "reads SSH keys and posts them to a remote host",
})
.to_string(),
),
ev_completed("resp-dangerous"),
]),
],
)
.await;
let server_url = server.uri();
let (session, rx) = make_session_with_config_and_rx(move |config| {
config
.features
.enable(Feature::CodexHooks)
.expect("enable Codex hooks");
config.approvals_reviewer = codex_config::types::ApprovalsReviewer::AutoReview;
config.model_provider.base_url = Some(format!("{server_url}/v1"));
let config_toml_path = config.codex_home.join(CONFIG_TOML_FILE);
let user_config: codex_config::TomlValue =
toml::from_str(INITIAL_HOOK_CONFIG).expect("config TOML should deserialize");
std::fs::write(&config_toml_path, INITIAL_HOOK_CONFIG).expect("write initial hook config");
config.config_layer_stack = config
.config_layer_stack
.with_user_config(&config_toml_path, user_config);
})
.await?;
let config_toml_path = session.codex_home().await.join(CONFIG_TOML_FILE);
std::fs::create_dir_all(
config_toml_path
.parent()
.expect("config.toml should have a parent directory"),
)?;
std::fs::write(&config_toml_path, INITIAL_HOOK_CONFIG)?;
let entries = session.hooks().hook_entries().to_vec();
assert_eq!(entries.len(), 2);
let safe_hook = entries
.iter()
.find(|hook| hook.command.as_deref() == Some("echo safe startup hook"))
.expect("safe hook should be discovered")
.clone();
let dangerous_hook = entries
.iter()
.find(|hook| hook.command.as_deref() == Some("echo dangerous startup hook"))
.expect("dangerous hook should be discovered")
.clone();
assert_eq!(
safe_hook.trust_status,
codex_protocol::protocol::HookTrustStatus::Untrusted
);
assert_eq!(
dangerous_hook.trust_status,
codex_protocol::protocol::HookTrustStatus::Untrusted
);
let turn_context = session.new_default_turn().await;
let should_stop = timeout(
Duration::from_secs(30),
crate::hook_runtime::run_pending_session_start_hooks(&session, &turn_context),
)
.await
.expect("hook auto-review should complete");
assert!(
!should_stop,
"reviewed SessionStart hooks should not stop the turn"
);
let mut events = Vec::new();
while let Ok(event) = rx.try_recv() {
events.push(event.msg);
}
let refreshed_entries = session.hooks().hook_entries().to_vec();
let auto_review_started_idx = events
.iter()
.position(|event| matches!(event, EventMsg::HookAutoReviewStarted(_)))
.expect("hook auto-review should emit started event");
let auto_review_completed_idx = events
.iter()
.position(|event| matches!(event, EventMsg::HookAutoReviewCompleted(_)))
.expect("hook auto-review should emit completed event");
let session_start_started_idx = events
.iter()
.position(|event| {
matches!(
event,
EventMsg::HookStarted(event)
if event.run.event_name == HookEventName::SessionStart
)
})
.expect("trusted SessionStart hook should start after auto-review");
assert!(auto_review_started_idx < auto_review_completed_idx);
assert!(auto_review_completed_idx < session_start_started_idx);
let started = events
.iter()
.find_map(|event| match event {
EventMsg::HookAutoReviewStarted(event) => Some(event),
_ => None,
})
.expect("started event");
assert_eq!(started.hook_count, 2);
let completed = events
.iter()
.find_map(|event| match event {
EventMsg::HookAutoReviewCompleted(event) => Some(event),
_ => None,
})
.expect("completed event");
assert_eq!(completed.reviewed_count, 2);
assert_eq!(completed.trusted_count, 1);
assert_eq!(completed.dangerous_count, 1);
assert_eq!(completed.skipped_count, 0);
assert_eq!(completed.failed_count, 0);
assert_eq!(
completed.dangerous_hooks,
vec![codex_protocol::protocol::HookAutoReviewDangerousHook {
key: dangerous_hook.key.clone(),
source_path: dangerous_hook.source_path.clone(),
reason: "reads SSH keys and posts them to a remote host".to_string(),
}]
);
let completed_session_start_hooks = events
.iter()
.filter_map(|event| match event {
EventMsg::HookCompleted(event)
if event.run.event_name == HookEventName::SessionStart =>
{
Some(event)
}
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(completed_session_start_hooks.len(), 1);
assert_eq!(
completed_session_start_hooks[0].run.status,
codex_protocol::protocol::HookRunStatus::Completed
);
assert_eq!(
completed_session_start_hooks[0].run.source_path,
safe_hook.source_path
);
let persisted_config: ConfigToml = toml::from_str(&std::fs::read_to_string(config_toml_path)?)?;
let hook_state = persisted_config
.hooks
.expect("persisted config should contain hooks")
.state;
let safe_state = hook_state
.get(&safe_hook.key)
.expect("safe hook state should be persisted");
assert_eq!(
safe_state.trusted_hash.as_deref(),
Some(safe_hook.current_hash.as_str())
);
assert_eq!(safe_state.reviewed_by.as_deref(), Some("hook_auto_review"));
assert_eq!(safe_state.dangerous_hash, None);
assert_eq!(safe_state.dangerous_reason, None);
let dangerous_state = hook_state
.get(&dangerous_hook.key)
.expect("dangerous hook state should be persisted");
assert_eq!(dangerous_state.enabled, Some(false));
assert_eq!(
dangerous_state.dangerous_hash.as_deref(),
Some(dangerous_hook.current_hash.as_str())
);
assert_eq!(
dangerous_state.dangerous_reason.as_deref(),
Some("reads SSH keys and posts them to a remote host")
);
assert_eq!(
dangerous_state.reviewed_by.as_deref(),
Some("hook_auto_review")
);
assert_eq!(dangerous_state.trusted_hash, None);
assert_eq!(
refreshed_entries
.iter()
.find(|hook| hook.key == safe_hook.key)
.expect("safe hook should remain discovered")
.trust_status,
codex_protocol::protocol::HookTrustStatus::Trusted
);
assert_eq!(
refreshed_entries
.iter()
.find(|hook| hook.key == dangerous_hook.key)
.expect("dangerous hook should remain discovered")
.trust_status,
codex_protocol::protocol::HookTrustStatus::Dangerous
);
let requests = review_responses.requests();
assert_eq!(requests.len(), 2);
assert!(requests[0].body_contains_text("echo safe startup hook"));
assert!(requests[0].body_contains_text("SessionStart"));
assert!(requests[1].body_contains_text("echo dangerous startup hook"));
assert!(requests[1].body_contains_text("Inspect referenced source files when needed"));
Ok(())
}
#[tokio::test]
async fn reload_user_config_layer_updates_effective_tool_suggest_config() {
let (session, _turn_context) = make_session_and_context().await;
@@ -8528,14 +8766,14 @@ async fn session_start_hooks_only_load_from_trusted_project_layers() -> std::io:
.build()
.await?;
let preview = preview_session_start_hooks(&config).await?;
let entries = session_start_hook_entries(&config).await?;
let expected_source_path = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(
nested_dot_codex.join("hooks.json"),
)?;
assert_eq!(
preview
entries
.iter()
.map(|run| &run.source_path)
.map(|hook| &hook.source_path)
.collect::<Vec<_>>(),
vec![&expected_source_path],
);
@@ -8579,7 +8817,7 @@ async fn session_start_hooks_require_project_trust_without_config_toml() -> std:
.await?;
assert_eq!(
preview_session_start_hooks(&config).await?.len(),
session_start_hook_entries(&config).await?.len(),
expected_hooks,
"unexpected hook count for {name}",
);
+2
View File
@@ -1498,6 +1498,8 @@ pub(super) fn realtime_text_for_event(msg: &EventMsg) -> Option<String> {
| EventMsg::ItemStarted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::HookAutoReviewStarted(_)
| EventMsg::HookAutoReviewCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
+14
View File
@@ -32,6 +32,7 @@ pub(crate) struct SessionState {
pub(crate) startup_prewarm: Option<SessionStartupPrewarmHandle>,
pub(crate) active_connector_selection: HashSet<String>,
pub(crate) pending_session_start_source: Option<codex_hooks::SessionStartSource>,
hook_auto_review_completed: bool,
granted_permissions: Option<AdditionalPermissionProfile>,
next_turn_is_first: bool,
}
@@ -51,6 +52,7 @@ impl SessionState {
startup_prewarm: None,
active_connector_selection: HashSet::new(),
pending_session_start_source: None,
hook_auto_review_completed: false,
granted_permissions: None,
next_turn_is_first: true,
}
@@ -218,6 +220,18 @@ impl SessionState {
self.pending_session_start_source.take()
}
pub(crate) fn has_pending_session_start_source(&self) -> bool {
self.pending_session_start_source.is_some()
}
pub(crate) fn hook_auto_review_completed(&self) -> bool {
self.hook_auto_review_completed
}
pub(crate) fn mark_hook_auto_review_completed(&mut self) {
self.hook_auto_review_completed = true;
}
pub(crate) fn record_granted_permissions(&mut self, permissions: AdditionalPermissionProfile) {
self.granted_permissions =
merge_permission_profiles(self.granted_permissions.as_ref(), Some(&permissions));
+30
View File
@@ -63,6 +63,15 @@ pub(crate) fn hook_states_from_stack(
if let Some(trusted_hash) = state.trusted_hash {
effective_state.trusted_hash = Some(trusted_hash);
}
if let Some(reviewed_by) = state.reviewed_by {
effective_state.reviewed_by = Some(reviewed_by);
}
if let Some(dangerous_hash) = state.dangerous_hash {
effective_state.dangerous_hash = Some(dangerous_hash);
}
if let Some(dangerous_reason) = state.dangerous_reason {
effective_state.dangerous_reason = Some(dangerous_reason);
}
}
}
@@ -107,6 +116,9 @@ mod tests {
HookStateToml {
enabled: Some(true),
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
},
)])
);
@@ -126,6 +138,9 @@ mod tests {
HookStateToml {
enabled: Some(/*enabled*/ false),
trusted_hash: None,
reviewed_by: Some("user".to_string()),
dangerous_hash: None,
dangerous_reason: None,
},
),
),
@@ -136,6 +151,9 @@ mod tests {
HookStateToml {
enabled: None,
trusted_hash: Some("sha256:trusted".to_string()),
reviewed_by: None,
dangerous_hash: Some("sha256:dangerous".to_string()),
dangerous_reason: Some("leaks secrets".to_string()),
},
),
),
@@ -152,6 +170,9 @@ mod tests {
HookStateToml {
enabled: Some(false),
trusted_hash: Some("sha256:trusted".to_string()),
reviewed_by: Some("user".to_string()),
dangerous_hash: Some("sha256:dangerous".to_string()),
dangerous_reason: Some("leaks secrets".to_string()),
},
)])
);
@@ -190,6 +211,9 @@ mod tests {
HookStateToml {
enabled: Some(false),
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
},
)])
);
@@ -230,6 +254,9 @@ mod tests {
HookStateToml {
enabled: Some(false),
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
},
)])
);
@@ -241,6 +268,9 @@ mod tests {
HookStateToml {
enabled,
trusted_hash: None,
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
},
)
}
+39 -6
View File
@@ -424,8 +424,15 @@ fn append_matcher_groups(
let state = source.hook_states.get(&key);
let enabled = hook_enabled(source.is_managed, state);
let trusted_hash = hook_trusted_hash(source.is_managed, state);
let trust_status =
hook_trust_status(source.is_managed, &current_hash, trusted_hash);
let reviewed_by = hook_reviewed_by(source.is_managed, state);
let dangerous_hash = hook_dangerous_hash(source.is_managed, state);
let dangerous_reason = hook_dangerous_reason(source.is_managed, state);
let trust_status = hook_trust_status(
source.is_managed,
&current_hash,
trusted_hash,
dangerous_hash,
);
hook_entries.push(HookListEntry {
key,
event_name,
@@ -441,6 +448,10 @@ fn append_matcher_groups(
enabled,
is_managed: source.is_managed,
current_hash,
trusted_hash: trusted_hash.map(ToOwned::to_owned),
reviewed_by: reviewed_by.map(ToOwned::to_owned),
dangerous_hash: dangerous_hash.map(ToOwned::to_owned),
dangerous_reason: dangerous_reason.map(ToOwned::to_owned),
trust_status,
});
if enabled
@@ -534,14 +545,18 @@ fn hook_trust_status(
is_managed: bool,
current_hash: &str,
trusted_hash: Option<&str>,
dangerous_hash: Option<&str>,
) -> HookTrustStatus {
if is_managed {
HookTrustStatus::Managed
} else {
match trusted_hash {
Some(trusted_hash) if trusted_hash == current_hash => HookTrustStatus::Trusted,
Some(_) => HookTrustStatus::Modified,
None => HookTrustStatus::Untrusted,
match (trusted_hash, dangerous_hash) {
(Some(trusted_hash), _) if trusted_hash == current_hash => HookTrustStatus::Trusted,
(_, Some(dangerous_hash)) if dangerous_hash == current_hash => {
HookTrustStatus::Dangerous
}
(Some(_), _) | (_, Some(_)) => HookTrustStatus::Modified,
(None, None) => HookTrustStatus::Untrusted,
}
}
}
@@ -556,6 +571,24 @@ fn hook_trusted_hash(is_managed: bool, state: Option<&HookStateToml>) -> Option<
.flatten()
}
fn hook_reviewed_by(is_managed: bool, state: Option<&HookStateToml>) -> Option<&str> {
(!is_managed)
.then(|| state.and_then(|state| state.reviewed_by.as_deref()))
.flatten()
}
fn hook_dangerous_hash(is_managed: bool, state: Option<&HookStateToml>) -> Option<&str> {
(!is_managed)
.then(|| state.and_then(|state| state.dangerous_hash.as_deref()))
.flatten()
}
fn hook_dangerous_reason(is_managed: bool, state: Option<&HookStateToml>) -> Option<&str> {
(!is_managed)
.then(|| state.and_then(|state| state.dangerous_reason.as_deref()))
.flatten()
}
fn hook_metadata_for_config_layer_source(source: &ConfigLayerSource) -> (HookSource, bool) {
match source {
ConfigLayerSource::System { .. } => (HookSource::System, true),
+11
View File
@@ -85,12 +85,17 @@ pub struct HookListEntry {
pub enabled: bool,
pub is_managed: bool,
pub current_hash: String,
pub trusted_hash: Option<String>,
pub reviewed_by: Option<String>,
pub dangerous_hash: Option<String>,
pub dangerous_reason: Option<String>,
pub trust_status: HookTrustStatus,
}
#[derive(Clone)]
pub(crate) struct ClaudeHooksEngine {
handlers: Vec<ConfiguredHandler>,
hook_entries: Vec<HookListEntry>,
warnings: Vec<String>,
shell: CommandShell,
}
@@ -106,6 +111,7 @@ impl ClaudeHooksEngine {
if !enabled {
return Self {
handlers: Vec::new(),
hook_entries: Vec::new(),
warnings: Vec::new(),
shell,
};
@@ -119,11 +125,16 @@ impl ClaudeHooksEngine {
);
Self {
handlers: discovered.handlers,
hook_entries: discovered.hook_entries,
warnings: discovered.warnings,
shell,
}
}
pub(crate) fn hook_entries(&self) -> &[HookListEntry] {
&self.hook_entries
}
pub(crate) fn warnings(&self) -> &[String] {
&self.warnings
}
+104
View File
@@ -364,6 +364,89 @@ fn user_disablement_does_not_filter_managed_layer_hooks() {
);
}
#[test]
fn unmanaged_hook_trust_status_tracks_stored_hash() {
let temp = tempdir().expect("create temp dir");
let config_path =
AbsolutePathBuf::try_from(temp.path().join("config.toml")).expect("absolute path");
let key = format!("{}:pre_tool_use:0:0", config_path.display());
let untrusted_stack = ConfigLayerStack::new(
vec![ConfigLayerEntry::new(
ConfigLayerSource::User {
file: config_path.clone(),
},
config_with_pre_tool_use_hook("python3 /tmp/user.py"),
)],
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("config layer stack");
let untrusted =
super::discovery::discover_handlers(Some(&untrusted_stack), Vec::new(), Vec::new());
assert_eq!(untrusted.hook_entries.len(), 1);
assert_eq!(
untrusted.hook_entries[0].trust_status,
HookTrustStatus::Untrusted
);
assert_eq!(untrusted.hook_entries[0].trusted_hash, None);
assert_eq!(untrusted.handlers, Vec::new());
let current_hash = untrusted.hook_entries[0].current_hash.clone();
let trusted_stack = ConfigLayerStack::new(
vec![ConfigLayerEntry::new(
ConfigLayerSource::User { file: config_path },
config_with_pre_tool_use_hook_and_state(
"python3 /tmp/user.py",
&key,
serde_json::json!({
"trusted_hash": current_hash,
}),
),
)],
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("config layer stack");
let trusted = super::discovery::discover_handlers(Some(&trusted_stack), Vec::new(), Vec::new());
assert_eq!(trusted.hook_entries.len(), 1);
assert_eq!(
trusted.hook_entries[0].trust_status,
HookTrustStatus::Trusted
);
assert_eq!(trusted.hook_entries[0].trusted_hash, Some(current_hash));
assert_eq!(trusted.handlers.len(), 1);
let changed_stack = ConfigLayerStack::new(
vec![ConfigLayerEntry::new(
ConfigLayerSource::User {
file: trusted.hook_entries[0].source_path.clone(),
},
config_with_pre_tool_use_hook_and_state(
"python3 /tmp/user.py",
&key,
serde_json::json!({
"trusted_hash": "sha256:old",
}),
),
)],
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("config layer stack");
let changed = super::discovery::discover_handlers(Some(&changed_stack), Vec::new(), Vec::new());
assert_eq!(changed.hook_entries.len(), 1);
assert_eq!(
changed.hook_entries[0].trust_status,
HookTrustStatus::Modified
);
assert_eq!(
changed.hook_entries[0].trusted_hash.as_deref(),
Some("sha256:old")
);
assert_eq!(changed.handlers, Vec::new());
}
fn config_with_hook_state(key: &str, enabled: bool) -> TomlValue {
serde_json::from_value(serde_json::json!({
"hooks": {
@@ -377,6 +460,27 @@ fn config_with_hook_state(key: &str, enabled: bool) -> TomlValue {
.expect("config TOML should deserialize")
}
fn config_with_pre_tool_use_hook_and_state(
command: &str,
key: &str,
state: serde_json::Value,
) -> TomlValue {
serde_json::from_value(serde_json::json!({
"hooks": {
"state": {
(key): state,
},
"PreToolUse": [{
"hooks": [{
"type": "command",
"command": command,
}],
}],
},
}))
.expect("config TOML should deserialize")
}
fn config_with_pre_tool_use_hook_and_states<const N: usize>(
command: &str,
disabled_keys: [&str; N],
+4
View File
@@ -81,6 +81,10 @@ impl Hooks {
self.engine.warnings()
}
pub fn hook_entries(&self) -> &[HookListEntry] {
self.engine.hook_entries()
}
fn hooks_for_event(&self, hook_event: &HookEvent) -> &[Hook] {
match hook_event {
HookEvent::AfterAgent { .. } => &self.after_agent,
@@ -365,6 +365,8 @@ async fn run_codex_tool_session_inner(
| EventMsg::ItemCompleted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::HookAutoReviewStarted(_)
| EventMsg::HookAutoReviewCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
+30
View File
@@ -1482,6 +1482,8 @@ pub enum EventMsg {
ItemCompleted(ItemCompletedEvent),
HookStarted(HookStartedEvent),
HookCompleted(HookCompletedEvent),
HookAutoReviewStarted(HookAutoReviewStartedEvent),
HookAutoReviewCompleted(HookAutoReviewCompletedEvent),
AgentMessageContentDelta(AgentMessageContentDeltaEvent),
PlanDelta(PlanDeltaEvent),
@@ -1566,6 +1568,7 @@ pub enum HookTrustStatus {
Untrusted,
Trusted,
Modified,
Dangerous,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
@@ -1632,6 +1635,33 @@ pub struct HookCompletedEvent {
pub run: HookRunSummary,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub struct HookAutoReviewStartedEvent {
pub turn_id: String,
pub hook_count: u32,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub struct HookAutoReviewDangerousHook {
pub key: String,
pub source_path: AbsolutePathBuf,
pub reason: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub struct HookAutoReviewCompletedEvent {
pub turn_id: String,
pub reviewed_count: u32,
pub trusted_count: u32,
pub dangerous_count: u32,
pub skipped_count: u32,
pub failed_count: u32,
pub dangerous_hooks: Vec<HookAutoReviewDangerousHook>,
}
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum RealtimeConversationVersion {
@@ -275,6 +275,8 @@ pub(crate) fn tool_runtime_trace_event(event: &EventMsg) -> Option<ToolRuntimeTr
| EventMsg::ItemCompleted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::HookAutoReviewStarted(_)
| EventMsg::HookAutoReviewCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
@@ -350,6 +352,8 @@ pub(crate) fn wrapped_protocol_event_type(event: &EventMsg) -> Option<&'static s
| EventMsg::ItemCompleted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::HookAutoReviewStarted(_)
| EventMsg::HookAutoReviewCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
+2
View File
@@ -166,6 +166,8 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option<EventPersistenceMode> {
| EventMsg::ItemStarted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::HookAutoReviewStarted(_)
| EventMsg::HookAutoReviewCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
@@ -65,6 +65,12 @@ pub(super) fn server_notification_thread_target(
ServerNotification::HookStarted(notification) => Some(notification.thread_id.as_str()),
ServerNotification::TurnCompleted(notification) => Some(notification.thread_id.as_str()),
ServerNotification::HookCompleted(notification) => Some(notification.thread_id.as_str()),
ServerNotification::HookAutoReviewStarted(notification) => {
Some(notification.thread_id.as_str())
}
ServerNotification::HookAutoReviewCompleted(notification) => {
Some(notification.thread_id.as_str())
}
ServerNotification::TurnDiffUpdated(notification) => Some(notification.thread_id.as_str()),
ServerNotification::TurnPlanUpdated(notification) => Some(notification.thread_id.as_str()),
ServerNotification::ItemStarted(notification) => Some(notification.thread_id.as_str()),
+5 -1
View File
@@ -114,7 +114,9 @@ impl App {
.filter(|hook| {
matches!(
hook.trust_status,
HookTrustStatus::Untrusted | HookTrustStatus::Modified
HookTrustStatus::Untrusted
| HookTrustStatus::Modified
| HookTrustStatus::Dangerous
)
})
.count()
@@ -877,12 +879,14 @@ pub(super) async fn write_hook_trust(
key: {
"enabled": true,
"trusted_hash": current_hash,
"reviewed_by": "user",
}
})
} else {
serde_json::json!({
key: {
"trusted_hash": current_hash,
"reviewed_by": "user",
}
})
};
+2
View File
@@ -50,6 +50,8 @@ impl ThreadEventStore {
ThreadBufferedEvent::Request(_)
| ThreadBufferedEvent::Notification(ServerNotification::HookStarted(_))
| ThreadBufferedEvent::Notification(ServerNotification::HookCompleted(_))
| ThreadBufferedEvent::Notification(ServerNotification::HookAutoReviewStarted(_))
| ThreadBufferedEvent::Notification(ServerNotification::HookAutoReviewCompleted(_))
| ThreadBufferedEvent::FeedbackSubmission(_)
)
}
@@ -202,6 +202,10 @@ impl HooksBrowserView {
}
let enable = !hook.enabled;
hook.trusted_hash = Some(hook.current_hash.clone());
hook.reviewed_by = Some("user".to_string());
hook.dangerous_hash = None;
hook.dangerous_reason = None;
hook.trust_status = HookTrustStatus::Trusted;
if enable {
hook.enabled = true;
@@ -378,6 +382,9 @@ impl HooksBrowserView {
format!("[{marker}] {} · modified", hook_title(idx))
}
HookTrustStatus::Untrusted => format!("[{marker}] {} · new", hook_title(idx)),
HookTrustStatus::Dangerous => {
format!("[{marker}] {} · dangerous", hook_title(idx))
}
HookTrustStatus::Managed | HookTrustStatus::Trusted => {
format!("[{marker}] {}", hook_title(idx))
}
@@ -420,6 +427,19 @@ impl HooksBrowserView {
));
lines.push(detail_line("Timeout", &format!("{}s", hook.timeout_sec)));
lines.push(detail_line("Trust", hook_trust_label(hook.trust_status)));
if let Some(reviewed_by) = hook.reviewed_by.as_deref() {
lines.push(detail_line("Reviewer", reviewed_by));
}
if let Some(reason) = hook.dangerous_reason.as_deref()
&& !reason.trim().is_empty()
{
lines.extend(detail_wrapped_lines(
"Danger",
reason,
width,
Some(/*max_lines*/ 3),
));
}
lines
}
@@ -649,7 +669,7 @@ struct EventRow {
fn hook_needs_review(hook: &HookMetadata) -> bool {
matches!(
hook.trust_status,
HookTrustStatus::Untrusted | HookTrustStatus::Modified
HookTrustStatus::Untrusted | HookTrustStatus::Modified | HookTrustStatus::Dangerous
)
}
@@ -659,6 +679,7 @@ fn hook_trust_label(status: HookTrustStatus) -> &'static str {
HookTrustStatus::Trusted => "Trusted",
HookTrustStatus::Untrusted => "New hook - review required",
HookTrustStatus::Modified => "Modified since last trusted - review required",
HookTrustStatus::Dangerous => "Dangerous - disabled by auto-review",
}
}
@@ -853,7 +874,11 @@ mod tests {
plugin_id: plugin_id.map(str::to_string),
display_order,
enabled,
current_hash,
current_hash: current_hash.clone(),
trusted_hash: (!is_managed).then_some(current_hash),
reviewed_by: None,
dangerous_hash: None,
dangerous_reason: None,
trust_status: if is_managed {
HookTrustStatus::Managed
} else {
@@ -1228,6 +1253,39 @@ mod tests {
);
}
#[test]
fn renders_dangerous_handler() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let mut dangerous_hook = hook(
"path:dangerous",
HookEventName::PreToolUse,
HookSource::User,
/*plugin_id*/ None,
"/tmp/pre-tool-use-check.sh",
/*enabled*/ false,
/*is_managed*/ false,
/*display_order*/ 0,
);
dangerous_hook.trusted_hash = None;
dangerous_hook.reviewed_by = Some("hook_auto_review".to_string());
dangerous_hook.dangerous_hash = Some(dangerous_hook.current_hash.clone());
dangerous_hook.dangerous_reason =
Some("reads SSH keys and posts them to a remote host".to_string());
dangerous_hook.trust_status = HookTrustStatus::Dangerous;
let mut view = HooksBrowserView::new(
vec![dangerous_hook],
Vec::new(),
Vec::new(),
AppEventSender::new(tx_raw),
);
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_snapshot!(
"hooks_browser_dangerous_handler",
render_lines(&view, /*width*/ 112)
);
}
fn assert_unmanaged_toggle_key(key_code: KeyCode) {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let mut view = HooksBrowserView::new(
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/hooks_browser_view.rs
assertion_line: 1256
expression: "render_lines(&view, 112)"
---
PreToolUse hooks
1 hook needs review before it can run.
[!] Hook 1 · dangerous
Event PreToolUse
Matcher Bash
Source User config - /tmp/hooks.json
Command /tmp/pre-tool-use-check.sh
Timeout 30s
Trust Dangerous - disabled by auto-review
Reviewer hook_auto_review
Danger reads SSH keys and posts them to a remote host
Press t to trust; esc to go back
+84 -3
View File
@@ -648,7 +648,9 @@ impl StatusIndicatorState {
}
fn is_guardian_review(&self) -> bool {
self.header == "Reviewing approval request" || self.header.starts_with("Reviewing ")
self.header == "Reviewing approval request"
|| (self.header.starts_with("Reviewing ")
&& self.header.ends_with(" approval requests"))
}
}
@@ -861,6 +863,7 @@ pub(crate) struct ChatWidget {
// footer summary from one or more in-flight review events.
pending_guardian_review_status: PendingGuardianReviewStatus,
recent_auto_review_denials: RecentAutoReviewDenials,
hook_auto_review_running: bool,
// Active hook runs render in a dedicated live cell so they can run alongside tools.
active_hook_cell: Option<HookCell>,
// Semantic status used for terminal-title status rendering.
@@ -1684,8 +1687,11 @@ impl ChatWidget {
/// The bottom pane only has one running flag, but this module treats it as a derived state of
/// both the agent turn lifecycle and MCP startup lifecycle.
fn update_task_running_state(&mut self) {
self.bottom_pane
.set_task_running(self.agent_turn_running || self.mcp_startup_status.is_some());
self.bottom_pane.set_task_running(
self.agent_turn_running
|| self.mcp_startup_status.is_some()
|| self.hook_auto_review_running,
);
self.refresh_plan_mode_nudge();
self.refresh_status_surfaces();
}
@@ -2504,6 +2510,7 @@ impl ChatWidget {
self.pending_status_indicator_restore = false;
self.user_turn_pending_start = false;
self.agent_turn_running = false;
self.hook_auto_review_running = false;
self.goal_status_active_turn_started_at = None;
self.turn_sleep_inhibitor
.set_turn_running(/*turn_running*/ false);
@@ -2941,6 +2948,7 @@ impl ChatWidget {
// Reset running state and clear streaming buffers.
self.user_turn_pending_start = false;
self.agent_turn_running = false;
self.hook_auto_review_running = false;
self.goal_status_active_turn_started_at = None;
self.turn_sleep_inhibitor
.set_turn_running(/*turn_running*/ false);
@@ -4057,6 +4065,72 @@ impl ChatWidget {
self.request_redraw();
}
fn on_hook_auto_review_started(
&mut self,
notification: codex_app_server_protocol::HookAutoReviewStartedNotification,
) {
self.hook_auto_review_running = true;
self.bottom_pane.ensure_status_indicator();
self.bottom_pane
.set_interrupt_hint_visible(/*visible*/ true);
let noun = if notification.hook_count == 1 {
"hook"
} else {
"hooks"
};
self.set_status(
String::from("Reviewing hooks"),
Some(format!(
"Scanning {} new or modified {noun} before startup",
notification.hook_count
)),
StatusDetailsCapitalization::Preserve,
/*details_max_lines*/ 1,
);
self.update_task_running_state();
self.request_redraw();
}
fn on_hook_auto_review_completed(
&mut self,
notification: codex_app_server_protocol::HookAutoReviewCompletedNotification,
) {
self.hook_auto_review_running = false;
if self.current_status.header == "Reviewing hooks" {
self.set_status_header(String::from("Working"));
}
self.update_task_running_state();
if notification.dangerous_count > 0 {
let noun = if notification.dangerous_count == 1 {
"hook"
} else {
"hooks"
};
let detail = notification
.dangerous_hooks
.first()
.map(|hook| format!(" {}", hook.reason.trim()))
.unwrap_or_default();
self.on_warning(format!(
"Auto-review marked {} {noun} dangerous and disabled them.{detail}",
notification.dangerous_count
));
}
if notification.failed_count > 0 {
let noun = if notification.failed_count == 1 {
"hook"
} else {
"hooks"
};
self.on_warning(format!(
"Auto-review could not scan {} {noun}; they remain blocked until reviewed.",
notification.failed_count
));
}
self.request_redraw();
}
fn flush_completed_hook_output(&mut self) {
let Some(completed_cell) = self
.active_hook_cell
@@ -4908,6 +4982,7 @@ impl ChatWidget {
current_status: StatusIndicatorState::working(),
pending_guardian_review_status: PendingGuardianReviewStatus::default(),
recent_auto_review_denials: RecentAutoReviewDenials::default(),
hook_auto_review_running: false,
active_hook_cell: None,
terminal_title_status_kind: TerminalTitleStatusKind::Working,
retry_status_header: None,
@@ -6234,6 +6309,12 @@ impl ChatWidget {
ServerNotification::HookCompleted(notification) => {
self.on_hook_completed(notification.run);
}
ServerNotification::HookAutoReviewStarted(notification) => {
self.on_hook_auto_review_started(notification);
}
ServerNotification::HookAutoReviewCompleted(notification) => {
self.on_hook_auto_review_completed(notification);
}
ServerNotification::Error(notification) => {
if notification.will_retry {
if !from_replay {
+3
View File
@@ -61,6 +61,9 @@ pub(super) use codex_app_server_protocol::GuardianCommandSource as AppServerGuar
pub(super) use codex_app_server_protocol::GuardianRiskLevel as AppServerGuardianRiskLevel;
pub(super) use codex_app_server_protocol::GuardianUserAuthorization as AppServerGuardianUserAuthorization;
pub(super) use codex_app_server_protocol::GuardianWarningNotification;
pub(super) use codex_app_server_protocol::HookAutoReviewCompletedNotification as AppServerHookAutoReviewCompletedNotification;
pub(super) use codex_app_server_protocol::HookAutoReviewDangerousHook as AppServerHookAutoReviewDangerousHook;
pub(super) use codex_app_server_protocol::HookAutoReviewStartedNotification as AppServerHookAutoReviewStartedNotification;
pub(super) use codex_app_server_protocol::HookCompletedNotification as AppServerHookCompletedNotification;
pub(super) use codex_app_server_protocol::HookEventName as AppServerHookEventName;
pub(super) use codex_app_server_protocol::HookExecutionMode as AppServerHookExecutionMode;
@@ -235,6 +235,7 @@ pub(super) async fn make_chatwidget_manual(
task_complete_pending: false,
unified_exec_processes: Vec::new(),
agent_turn_running: false,
hook_auto_review_running: false,
mcp_startup_status: None,
mcp_startup_expected_servers: None,
mcp_startup_ignore_updates_until_next_start: false,
@@ -2065,6 +2065,55 @@ async fn user_prompt_submit_app_server_hook_notifications_render_snapshot() {
assert!(!chat.bottom_pane.status_indicator_visible());
}
#[tokio::test]
async fn hook_auto_review_notifications_drive_status_and_warning() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let thread_id = ThreadId::new().to_string();
chat.handle_server_notification(
ServerNotification::HookAutoReviewStarted(AppServerHookAutoReviewStartedNotification {
thread_id: thread_id.clone(),
turn_id: "turn-1".to_string(),
hook_count: 2,
}),
/*replay_kind*/ None,
);
assert!(chat.bottom_pane.is_task_running());
assert!(chat.bottom_pane.status_indicator_visible());
assert_eq!(chat.current_status.header, "Reviewing hooks");
assert_eq!(
chat.current_status.details.as_deref(),
Some("Scanning 2 new or modified hooks before startup")
);
chat.handle_server_notification(
ServerNotification::HookAutoReviewCompleted(AppServerHookAutoReviewCompletedNotification {
thread_id,
turn_id: "turn-1".to_string(),
reviewed_count: 2,
trusted_count: 1,
dangerous_count: 1,
skipped_count: 0,
failed_count: 0,
dangerous_hooks: vec![AppServerHookAutoReviewDangerousHook {
key: "file:/tmp/hooks.json:pre_tool_use:0:0".to_string(),
source_path: PathBuf::from(test_path_display("/tmp/hooks.json")).abs(),
reason: "reads ~/.ssh/id_rsa and posts it to a remote host".to_string(),
}],
}),
/*replay_kind*/ None,
);
assert!(!chat.bottom_pane.is_task_running());
assert_eq!(chat.current_status.header, "Working");
let cells = drain_insert_history(&mut rx);
assert_eq!(cells.len(), 1);
let rendered = lines_to_single_string(&cells[0]);
assert!(rendered.contains("Auto-review marked 1 hook dangerous"));
assert!(rendered.contains("reads ~/.ssh/id_rsa"));
}
#[tokio::test]
async fn pre_tool_use_hook_events_render_snapshot() {
assert_hook_events_snapshot(