Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
0c69401
fix: release target waiters when the gate is disabled
jwalith4418-Mj Dec 2, 2026
902dabd
fix: reject late target approvals after gate disable
jwalith4418-Mj Dec 2, 2026
cf82ab3
test: release a pending target wait when gate is disabled
jwalith4418-Mj Dec 2, 2026
1c4e2f0
test: prevent target pins from late approvals after disable
jwalith4418-Mj Dec 2, 2026
89ed519
fix: fail closed when a target waiter sees gate disabled
jwalith4418-Mj Dec 2, 2026
d859f54
refactor: name target-request settlement by its behavior
jwalith4418-Mj Dec 2, 2026
7f7467a
style: align target pin approval block
jwalith4418-Mj Dec 2, 2026
5e44ba9
style: apply gofmt alignment to wait result constants
jwalith4418-Mj Dec 2, 2026
7981b75
style: format target wait result constants with gofmt
jwalith4418-Mj Dec 2, 2026
d4fca08
fix(intercept): validate target scopes
jwalith4418-Mj Dec 2, 2026
e8305a3
test(agent): use opted-in task fixture for target requests
jwalith4418-Mj Dec 2, 2026
d6a271b
test(guard): opt target-gate integration task in
jwalith4418-Mj Dec 2, 2026
64d7517
test(db): keep default-off task cases genuinely opted out
jwalith4418-Mj Dec 2, 2026
c77d06c
test(server): opt task fixtures in for target approvals
jwalith4418-Mj Dec 2, 2026
ce0ff07
test(server): opt in empty-pin approval fixture
jwalith4418-Mj Dec 2, 2026
83f8214
test(server): use persisted task for batch target approval
jwalith4418-Mj Dec 2, 2026
e44d7e5
test(server): remove unused time import
jwalith4418-Mj Dec 2, 2026
b781554
style(agent): format fixture comment
jwalith4418-Mj Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions agent/hooks_reach_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ func toolCallThenStop(tool, input string) captureUsageProvider {
}}
}

// hookReachFixture is one exploration on the test database plus a Bash call whose
// only effect would be to create marker — which the blocking hooks must prevent.
// hookReachFixture is one opted-in task and its exploration on the test database,
// plus a Bash call whose only effect would be to create marker — which the blocking hooks must prevent.
type hookReachFixture struct {
expID int64
taskID string
Expand All @@ -105,12 +105,14 @@ func newHookReachFixture(t *testing.T) hookReachFixture {
t.Helper()
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
expID, err := d.CreateExploration("hook reach probe", "prove tool calls reach the hooks")
gateOn := true
task, err := d.CreateTaskWithOptions("hook reach probe", "prove tool calls reach the hooks", db.TaskCreateOptions{TargetGate: &gateOn})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
f := hookReachFixture{expID: expID, taskID: fmt.Sprint(expID), ts: d.Exploration(expID), workDir: t.TempDir()}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
expID := task.ExplorationID
f := hookReachFixture{expID: expID, taskID: fmt.Sprint(task.ID), ts: d.Exploration(expID), workDir: t.TempDir()}
f.marker = filepath.Join(f.workDir, "tool-ran")
input, _ := json.Marshal(map[string]string{"command": "touch " + f.marker})
f.bash = string(input)
Expand Down
66 changes: 51 additions & 15 deletions db/target_pins.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,32 @@ func (d *DB) ResolveTargetRequest(id int64, allowed bool, approver, remoteAddr s
return nil, false, err
}
defer tx.Rollback()
// Approval and task-gate updates serialize on the task row. Lock it before
// the pending row, matching task deletion's task -> pending lock order.
var initialTaskID sql.NullString
err = tx.QueryRow(`SELECT task_id FROM intercept_pending
WHERE id=$1 AND status='pending' AND target_key IS NOT NULL`, id).Scan(&initialTaskID)
if errors.Is(err, sql.ErrNoRows) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
taskGateEnabled := true // conversation scopes use the turn's captured gate value
if allowed && initialTaskID.Valid {
taskIDValue, parseErr := strconv.ParseInt(initialTaskID.String, 10, 64)
if parseErr != nil {
return nil, false, fmt.Errorf("target request %d: task id %q: %w", id, initialTaskID.String, parseErr)
}
lockErr := tx.QueryRow(`SELECT target_gate FROM tasks
WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, taskIDValue).Scan(&taskGateEnabled)
if errors.Is(lockErr, sql.ErrNoRows) {
taskGateEnabled = false
} else if lockErr != nil {
return nil, false, lockErr
}
}

var taskID sql.NullString
var convID sql.NullInt64
var raw []byte
Expand All @@ -288,24 +314,34 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
}
}
status, action, reason, execution := "denied", "deny", "user rejected the target; nothing was pinned", "not_executed"
decidedBy := "human"
if allowed {
if len(audit.Targets) != 1 {
return nil, false, fmt.Errorf("target request %d records %d targets, want 1", id, len(audit.Targets))
}
scope := TargetScopeRef{ConversationID: convID.Int64}
if taskID.Valid {
if scope.TaskID, err = strconv.ParseInt(taskID.String, 10, 64); err != nil {
return nil, false, fmt.Errorf("target request %d: task id %q: %w", id, taskID.String, err)
if taskID.Valid && !taskGateEnabled {
// A late approval must not recreate an allow after the operator
// switched the task gate off. The task row lock above makes this
// decision atomic with UpdateTask.
reason = "the target gate was switched off before approval; nothing was pinned"
decidedBy = "system"
audit.Targets[0].Outcome = "denied"
} else {
scope := TargetScopeRef{ConversationID: convID.Int64}
if taskID.Valid {
if scope.TaskID, err = strconv.ParseInt(taskID.String, 10, 64); err != nil {
return nil, false, fmt.Errorf("target request %d: task id %q: %w", id, taskID.String, err)
}
}
if pin, err = writeTargetPin(tx, scope, id, &audit.Targets[0], approver, remoteAddr); err != nil {
return nil, false, err
}
status, action, reason = "allowed", "allow", "user approved the target; the displayed addresses were pinned"
// A plain target request is host-level: no single call owns its result.
execution = "unknown"
if audit.MergedAsk && audit.Correlation == "exact" {
execution = "awaiting_result"
}
}
if pin, err = writeTargetPin(tx, scope, id, &audit.Targets[0], approver, remoteAddr); err != nil {
return nil, false, err
}
status, action, reason = "allowed", "allow", "user approved the target; the displayed addresses were pinned"
// A plain target request is host-level: no single call owns its result.
execution = "unknown"
if audit.MergedAsk && audit.Correlation == "exact" {
execution = "awaiting_result"
}
} else if len(audit.Targets) == 1 {
audit.Targets[0].Outcome = "denied"
Expand All @@ -324,8 +360,8 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
if err != nil {
return nil, false, err
}
if _, err := tx.Exec(`UPDATE intercept_pending SET status=$2, decided_at=NOW(), decided_by='human',
audit=COALESCE(audit,'{}'::jsonb) || $3::jsonb WHERE id=$1`, id, status, patch); err != nil {
if _, err := tx.Exec(`UPDATE intercept_pending SET status=$2, decided_at=NOW(), decided_by=$4,
audit=COALESCE(audit,'{}'::jsonb) || $3::jsonb WHERE id=$1`, id, status, patch, decidedBy); err != nil {
return nil, false, err
}
if err := tx.Commit(); err != nil {
Expand Down
60 changes: 57 additions & 3 deletions db/target_pins_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ func openTargetDB(t *testing.T) *DB {
// the end of the test (pins and approval rows outlive a task delete by design).
func targetTask(t *testing.T, d *DB, opts TaskCreateOptions) *Task {
t.Helper()
// A target-pin fixture represents a task that opted in to the target gate.
if opts.TargetGate == nil {
gateOn := true
opts.TargetGate = &gateOn
}
task, err := d.CreateTaskWithOptions("target gate store", "pins and requests", opts)
if err != nil {
t.Fatal(err)
Expand All @@ -41,6 +46,21 @@ func targetTask(t *testing.T, d *DB, opts TaskCreateOptions) *Task {
return task
}

// defaultOffTargetTask creates a task without opting in to the target gate.
func defaultOffTargetTask(t *testing.T, d *DB) *Task {
t.Helper()
task, err := d.CreateTaskWithOptions("target gate default", "gate defaults off", TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = d.DeleteTask(task.ID)
_, _ = d.Exec(`DELETE FROM target_pins WHERE task_id=$1`, task.ID)
_, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, strconv.FormatInt(task.ID, 10))
})
return task
}

func targetConversation(t *testing.T, d *DB) *Conversation {
t.Helper()
c, err := d.CreateConversation("assistant", fmt.Sprintf("target gate %d", time.Now().UnixNano()), nil)
Expand Down Expand Up @@ -315,6 +335,33 @@ FOR EACH ROW EXECUTE FUNCTION test_refuse_target_pin()`); err != nil {
}
}

func TestResolveTargetRequestDoesNotPinAfterTaskGateDisabled(t *testing.T) {
d := openTargetDB(t)
gateOn, gateOff := true, false
task := targetTask(t, d, TaskCreateOptions{TargetGate: &gateOn})
scope := TargetScopeRef{TaskID: task.ID}
id, created := openTargetRequest(t, d, scope, "late-approval.example.com", 443, "203.0.113.77")
if !created {
t.Fatal("target request was not created")
}
if _, err := d.UpdateTask(task.ID, TaskPatch{TargetGate: &gateOff}); err != nil {
t.Fatal(err)
}

pin, ok, err := d.ResolveTargetRequest(id, true, "ARTEX", "198.51.100.9")
if err != nil || !ok || pin != nil {
t.Fatalf("late approval: pin=%+v ok=%v err=%v, want resolved denial without a pin", pin, ok, err)
}
row, err := d.GetInterceptDetail(id)
if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" ||
!strings.Contains(row.Audit.DecisionReason, "target gate was switched off") {
t.Fatalf("late-approval row = %+v, %v; want system denial explaining gate disable", row, err)
}
if pins, err := d.ListTargetPins(scope); err != nil || len(pins) != 0 {
t.Fatalf("late approval pins = %+v, err=%v; want none", pins, err)
}
}

// Approving a request for a pinned key extends the pin: the new version holds
// the old addresses plus the displayed ones. Addresses leave only by revocation.
func TestTargetPinVersioningExtends(t *testing.T) {
Expand Down Expand Up @@ -749,7 +796,7 @@ func TestConversationBatchDeleteRevokesOnlyDeletedIds(t *testing.T) {

func TestTaskTargetGateDefaultsOff(t *testing.T) {
d := openTargetDB(t)
task := targetTask(t, d, TaskCreateOptions{})
task := defaultOffTargetTask(t, d)
if task.TargetGate {
t.Fatal("a task created without the option has the gate on")
}
Expand Down Expand Up @@ -847,8 +894,15 @@ func TestRetestConversationCopiesFlagNotPins(t *testing.T) {
{"gate off", TaskCreateOptions{}, false},
} {
t.Run(tc.name, func(t *testing.T) {
task := targetTask(t, d, tc.opts)
approveTarget(t, d, TargetScopeRef{TaskID: task.ID}, "app.example.com", 443, "203.0.113.7")
var task *Task
if tc.want {
task = targetTask(t, d, tc.opts)
} else {
task = defaultOffTargetTask(t, d)
}
if tc.want {
approveTarget(t, d, TargetScopeRef{TaskID: task.ID}, "app.example.com", 443, "203.0.113.7")
}
fid, err := d.AddFinding(task.ID, 0, "retest-gate", "gated finding", "high", "summary", "evidence", "worker", nil)
if err != nil {
t.Fatal(err)
Expand Down
3 changes: 2 additions & 1 deletion guard/target_gate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,8 @@ func newGateDB(t *testing.T) *gateDB {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
task, err := d.CreateTaskWithOptions("guard target gate", "the gate in the hook", db.TaskCreateOptions{})
gateOn := true
task, err := d.CreateTaskWithOptions("guard target gate", "the gate in the hook", db.TaskCreateOptions{TargetGate: &gateOn})
if err != nil {
t.Fatal(err)
}
Expand Down
62 changes: 47 additions & 15 deletions intercept/target_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,25 @@ type TargetResult struct {
}

func (s TargetScope) ref() (db.TargetScopeRef, error) {
ref := db.TargetScopeRef{ConversationID: s.ConversationID}
ref := db.TargetScopeRef{}
if s.TaskID != "" {
if s.ConversationID != 0 {
return ref, fmt.Errorf("target scope: task and conversation scopes cannot be combined")
}
id, err := strconv.ParseInt(s.TaskID, 10, 64)
if err != nil {
return ref, fmt.Errorf("target scope: task id %q: %w", s.TaskID, err)
}
if id <= 0 {
return ref, fmt.Errorf("target scope: task id must be positive")
}
ref.TaskID = id
return ref, nil
}
if s.ConversationID <= 0 {
return ref, fmt.Errorf("target scope: a positive task id or conversation id is required")
}
ref.ConversationID = s.ConversationID
return ref, nil
}

Expand Down Expand Up @@ -109,6 +120,9 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
if err != nil {
return TargetResult{Code: TargetGateUnavailable, Reason: err.Error()}
}
if scope.Enabled == nil || !scope.Enabled() {
return TargetResult{Code: TargetDenied, Reason: "the target gate was switched off"}
}
// An approval pins the addresses the request displays, so a request without
// any is never opened: approving it would pin nothing.
for _, t := range targets {
Expand All @@ -129,7 +143,7 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
// is a no-op once the row is decided.
defer func() {
if merged != nil {
i.settleMerged(merged.id, "denied", "the call left before a decision")
i.settleTargetRequest(merged.id, "denied", "the call left before a decision")
}
}()

Expand Down Expand Up @@ -173,7 +187,7 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
ruleTimeout = timer.C
}
status, reason := "", ""
switch st := i.awaitTarget(ctx, merged.id, bound.C, ruleTimeout); st {
switch st := i.awaitTarget(ctx, merged.id, scope, bound.C, ruleTimeout); st {
case "allowed":
case waitRuleTimeout:
status, reason = "timeout", "approval timed out"
Expand All @@ -184,13 +198,17 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
status, reason = "timeout", "no approval within the wait bound"
case waitCancelled:
status, reason = "denied", "work cancelled"
case waitGateDisabled:
reason := "the target gate was switched off"
i.settleTargetRequest(merged.id, "denied", reason)
return blocked(merged, TargetDenied, reason)
case waitGone:
return blocked(merged, TargetGateUnavailable, "the approval request no longer exists")
default:
return blocked(merged, TargetDenied, "the request was denied")
}
// A human decision that lands while the call is leaving still counts.
if status != "" && (i.settleMerged(merged.id, status, reason) || !i.targetAllowed(merged.id)) {
if status != "" && (i.settleTargetRequest(merged.id, status, reason) || !i.targetAllowed(merged.id)) {
return blocked(merged, TargetDenied, reason)
}
}
Expand All @@ -199,7 +217,7 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
if w == merged || w.id == 0 {
continue
}
st := i.awaitTarget(ctx, w.id, bound.C, nil)
st := i.awaitTarget(ctx, w.id, scope, bound.C, nil)
if (st == "denied" || st == "timeout") && !w.created && i.wasMerged(w.id) {
// The row this call attached to was bound to another call and closed
// with it. That says nothing about the host: ask once more, with a
Expand All @@ -208,24 +226,34 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
if err != nil {
return blocked(w, TargetGateUnavailable, err.Error())
}
if !scope.Enabled() {
return blocked(w, TargetDenied, "the target gate was switched off")
}
if retry.id == 0 {
continue
}
w = retry
st = i.awaitTarget(ctx, w.id, bound.C, nil)
st = i.awaitTarget(ctx, w.id, scope, bound.C, nil)
}
switch st {
case "allowed":
case waitElapsed:
return blocked(w, TargetApprovalPending, "no approval within the wait bound; the request stays open")
case waitCancelled:
return blocked(w, TargetApprovalPending, "work cancelled; the request stays open")
case waitGateDisabled:
reason := "the target gate was switched off"
i.settleTargetRequest(w.id, "denied", reason)
return blocked(w, TargetDenied, reason)
case waitGone:
return blocked(w, TargetGateUnavailable, "the approval request no longer exists")
default:
return blocked(w, TargetDenied, "the request was denied")
}
}
if scope.Enabled == nil || !scope.Enabled() {
return blocked(waiters[0], TargetDenied, "the target gate was switched off")
}
return res
}

Expand Down Expand Up @@ -294,22 +322,26 @@ func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeR

// Ways a wait ends without a decision on the row.
const (
waitElapsed = "wait_elapsed" // the scope's wait bound
waitRuleTimeout = "wait_rule_timeout" // the timeout of a merged ask
waitCancelled = "wait_cancelled" // the call's context
waitGone = "wait_gone" // the row no longer exists (its conversation was deleted)
waitElapsed = "wait_elapsed" // the scope's wait bound
waitRuleTimeout = "wait_rule_timeout" // the timeout of a merged ask
waitCancelled = "wait_cancelled" // the call's context
waitGateDisabled = "wait_gate_disabled" // the scope's target gate was switched off
waitGone = "wait_gone" // the row no longer exists (its conversation was deleted)
)

// awaitTarget waits for the decision on one request row and returns its status
// (allowed | denied | timeout) or the way the wait ended. It never settles the
// row. The row is re-read before each wait: that covers a decision taken before
// the waiter registered, and one taken on another instance.
func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTimeout <-chan time.Time) string {
func (i *Interceptor) awaitTarget(ctx context.Context, id int64, scope TargetScope, bound, ruleTimeout <-chan time.Time) string {
ch := i.pending.add(id)
defer i.pending.remove(id, ch)
poll := time.NewTicker(targetPollInterval)
defer poll.Stop()
for {
if scope.Enabled == nil || !scope.Enabled() {
return waitGateDisabled
}
row, err := i.db.GetInterceptPending(id)
if err == nil && row == nil {
return waitGone
Expand All @@ -330,10 +362,10 @@ func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTime
}
}

// settleMerged closes a merged row on behalf of its creating call, which is
// leaving, and wakes the calls attached to it. It reports whether the row was
// still open; a merged row closed this way never pins.
func (i *Interceptor) settleMerged(id int64, status, reason string) bool {
// settleTargetRequest closes a pending target request on behalf of a call whose
// wait is ending or whose scope has been disabled. It wakes local waiters and
// never creates a pin.
func (i *Interceptor) settleTargetRequest(id int64, status, reason string) bool {
resolved, err := i.db.ResolveIntercept(id, status, "deny", reason, "system")
if err != nil || !resolved {
return false
Expand Down
Loading
Loading