From 0c69401dd320374d9467ff5701b697dad6f1e94f Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:13:55 +0530 Subject: [PATCH 01/18] fix: release target waiters when the gate is disabled --- intercept/target_request.go | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/intercept/target_request.go b/intercept/target_request.go index 70430b4e2..108d5e365 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -105,6 +105,9 @@ type targetWaiter struct { // ask: when that call leaves, the system settles it, and a rule timeout never // allows it, because a timeout cannot pin. func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, toolName string, input []byte, targets []TargetRequest, ask *Decision) TargetResult { + if scope.Enabled == nil || !scope.Enabled() { + return TargetResult{Code: TargetDenied, Reason: "the target gate was switched off"} + } ref, err := scope.ref() if err != nil { return TargetResult{Code: TargetGateUnavailable, Reason: err.Error()} @@ -173,7 +176,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" @@ -184,6 +187,8 @@ 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: + status, reason = "denied", "the target gate was switched off" case waitGone: return blocked(merged, TargetGateUnavailable, "the approval request no longer exists") default: @@ -199,7 +204,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 @@ -208,11 +213,14 @@ 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": @@ -220,6 +228,10 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too 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.settleMerged(w.id, "denied", reason) + return blocked(w, TargetDenied, reason) case waitGone: return blocked(w, TargetGateUnavailable, "the approval request no longer exists") default: @@ -297,6 +309,7 @@ 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 + waitGateDisabled = "wait_gate_disabled" // the scope's target gate was switched off waitGone = "wait_gone" // the row no longer exists (its conversation was deleted) ) @@ -304,12 +317,15 @@ const ( // (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 From 902dabdf31c299b060123787ad50ae1f4010c592 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:13:58 +0530 Subject: [PATCH 02/18] fix: reject late target approvals after gate disable --- db/target_pins.go | 58 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 11 deletions(-) diff --git a/db/target_pins.go b/db/target_pins.go index 064b9c385..28f61f941 100644 --- a/db/target_pins.go +++ b/db/target_pins.go @@ -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 @@ -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 && !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" @@ -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 { From cf82ab35a0bae540a70f68f061dd59ac3066c4a3 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:14:01 +0530 Subject: [PATCH 03/18] test: release a pending target wait when gate is disabled --- intercept/target_request_test.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/intercept/target_request_test.go b/intercept/target_request_test.go index 81a5172ef..968723ef9 100644 --- a/intercept/target_request_test.go +++ b/intercept/target_request_test.go @@ -69,7 +69,8 @@ func targetTestDB(t *testing.T) *db.DB { // on and the given wait bound. func taskScope(t *testing.T, d *db.DB, ic *Interceptor, wait time.Duration) TargetScope { t.Helper() - task, err := d.CreateTaskWithOptions("target requests", "request, wait, decide", db.TaskCreateOptions{}) + gateOn := true + task, err := d.CreateTaskWithOptions("target requests", "request, wait, decide", db.TaskCreateOptions{TargetGate: &gateOn}) if err != nil { t.Fatal(err) } @@ -116,6 +117,32 @@ func result(t *testing.T, ch <-chan TargetResult) TargetResult { } } +func TestWaiterStopsWhenTargetGateIsSwitchedOff(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + scope := taskScope(t, d, ic, time.Minute) + var enabled atomic.Bool + enabled.Store(true) + scope.Enabled = enabled.Load + + call := request(context.Background(), ic, scope, nil, target("app.example.com", 443, "203.0.113.7")) + id := oneOpenRow(t, d, scope) + eventually(t, "the call to wait on its target request", func() bool { return waiters(ic, id) == 1 }) + + enabled.Store(false) + res := result(t, call) + if res.Code != TargetDenied || res.PendingID != id || !strings.Contains(res.Reason, "target gate was switched off") { + t.Fatalf("call after disabling the gate: %+v, want a target-gate denial", res) + } + row, err := d.GetInterceptPending(id) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" { + t.Fatalf("request after disabling the gate = %+v, %v; want a system denial", row, err) + } + if got := pins(t, d, scope); len(got) != 0 { + t.Fatalf("disabling the gate created a pin: %+v", got) + } +} + func stillWaiting(t *testing.T, ch <-chan TargetResult) { t.Helper() select { From 1c4e2f00614a3388cb5bb163befe4ec15ae2a570 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:14:04 +0530 Subject: [PATCH 04/18] test: prevent target pins from late approvals after disable --- db/target_pins_test.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/db/target_pins_test.go b/db/target_pins_test.go index 9e4fbec60..a0c7bb063 100644 --- a/db/target_pins_test.go +++ b/db/target_pins_test.go @@ -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) @@ -315,6 +320,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) { From 89ed5192337e9a3a4920a5a32feac2b3cc3ba5e7 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:14:30 +0530 Subject: [PATCH 05/18] fix: fail closed when a target waiter sees gate disabled --- intercept/target_request.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/intercept/target_request.go b/intercept/target_request.go index 108d5e365..de50d831f 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -105,13 +105,13 @@ type targetWaiter struct { // ask: when that call leaves, the system settles it, and a rule timeout never // allows it, because a timeout cannot pin. func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, toolName string, input []byte, targets []TargetRequest, ask *Decision) TargetResult { - if scope.Enabled == nil || !scope.Enabled() { - return TargetResult{Code: TargetDenied, Reason: "the target gate was switched off"} - } ref, err := scope.ref() 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 { @@ -188,7 +188,9 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too case waitCancelled: status, reason = "denied", "work cancelled" case waitGateDisabled: - status, reason = "denied", "the target gate was switched off" + reason := "the target gate was switched off" + i.settleMerged(merged.id, "denied", reason) + return blocked(merged, TargetDenied, reason) case waitGone: return blocked(merged, TargetGateUnavailable, "the approval request no longer exists") default: @@ -238,6 +240,9 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too 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 } From d859f544c60dc90362f8c72ca52623e3d3c8caee Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:14:48 +0530 Subject: [PATCH 06/18] refactor: name target-request settlement by its behavior --- intercept/target_request.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/intercept/target_request.go b/intercept/target_request.go index de50d831f..babbcba6c 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -132,7 +132,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") } }() @@ -189,7 +189,7 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too status, reason = "denied", "work cancelled" case waitGateDisabled: reason := "the target gate was switched off" - i.settleMerged(merged.id, "denied", reason) + i.settleTargetRequest(merged.id, "denied", reason) return blocked(merged, TargetDenied, reason) case waitGone: return blocked(merged, TargetGateUnavailable, "the approval request no longer exists") @@ -197,7 +197,7 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too 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) } } @@ -232,7 +232,7 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too return blocked(w, TargetApprovalPending, "work cancelled; the request stays open") case waitGateDisabled: reason := "the target gate was switched off" - i.settleMerged(w.id, "denied", reason) + i.settleTargetRequest(w.id, "denied", reason) return blocked(w, TargetDenied, reason) case waitGone: return blocked(w, TargetGateUnavailable, "the approval request no longer exists") @@ -351,10 +351,10 @@ func (i *Interceptor) awaitTarget(ctx context.Context, id int64, scope TargetSco } } -// 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 From 7f7467a0dbf3784406379ebdfa575233cc160f74 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:14:51 +0530 Subject: [PATCH 07/18] style: align target pin approval block --- db/target_pins.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/db/target_pins.go b/db/target_pins.go index 28f61f941..579b979ef 100644 --- a/db/target_pins.go +++ b/db/target_pins.go @@ -328,11 +328,11 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca 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 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 } From 5e44ba97e1cec1568f34f5917e1871144e66a5e0 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:27:47 +0530 Subject: [PATCH 08/18] style: apply gofmt alignment to wait result constants --- intercept/target_request.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intercept/target_request.go b/intercept/target_request.go index babbcba6c..662245235 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -314,7 +314,7 @@ 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 - waitGateDisabled = "wait_gate_disabled" // the scope's target gate was switched off + waitGateDisabled = "wait_gate_disabled" // the scope's target gate was switched off waitGone = "wait_gone" // the row no longer exists (its conversation was deleted) ) From 7981b75ba4619313f8ba00a230bca3bfad01bf1c Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 08:48:23 +0530 Subject: [PATCH 09/18] style: format target wait result constants with gofmt --- intercept/target_request.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/intercept/target_request.go b/intercept/target_request.go index 662245235..404f62647 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -311,11 +311,11 @@ 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 - waitGateDisabled = "wait_gate_disabled" // the scope's target gate was switched off - 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 From d4fca08b2fd27dcd5a39f2ae4e3d4f86301e9cf8 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:09 +0530 Subject: [PATCH 10/18] fix(intercept): validate target scopes --- intercept/target_request.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/intercept/target_request.go b/intercept/target_request.go index 404f62647..7e48c4249 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -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 } From e8305a3ac35d3dd9a77f7e8cda9870f2eb5d06fa Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:12 +0530 Subject: [PATCH 11/18] test(agent): use opted-in task fixture for target requests --- agent/hooks_reach_test.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/agent/hooks_reach_test.go b/agent/hooks_reach_test.go index 37af6478a..4fbb2aac2 100644 --- a/agent/hooks_reach_test.go +++ b/agent/hooks_reach_test.go @@ -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 @@ -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) From d6a271bcea226b6969201160981b891792753cbf Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:15 +0530 Subject: [PATCH 12/18] test(guard): opt target-gate integration task in --- guard/target_gate_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/guard/target_gate_test.go b/guard/target_gate_test.go index 5752fdf07..93135680d 100644 --- a/guard/target_gate_test.go +++ b/guard/target_gate_test.go @@ -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) } From 64d7517f0345a121f9f90c9abbbfa67870be1c93 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:18 +0530 Subject: [PATCH 13/18] test(db): keep default-off task cases genuinely opted out --- db/target_pins_test.go | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/db/target_pins_test.go b/db/target_pins_test.go index a0c7bb063..0a5cfc719 100644 --- a/db/target_pins_test.go +++ b/db/target_pins_test.go @@ -46,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) @@ -781,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") } @@ -879,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) From c77d06cbd84e5696da75bc9cb87b0835ebdfca16 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:21 +0530 Subject: [PATCH 14/18] test(server): opt task fixtures in for target approvals --- server/target_gate_flag_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/server/target_gate_flag_test.go b/server/target_gate_flag_test.go index 1aca315fb..1ef2d04b0 100644 --- a/server/target_gate_flag_test.go +++ b/server/target_gate_flag_test.go @@ -511,7 +511,8 @@ func TestConversationTargetGateOverHTTP(t *testing.T) { // address; decided_by stays the actor class. func TestInterceptDecideRecordsApproverOverHTTP(t *testing.T) { g := newGateServer(t) - task := g.newTask(t, db.TaskCreateOptions{}) + gateOn := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &gateOn}) scope := taskRef(t, task) pg := g.m.pg decide := func(id int64, decision string) int { @@ -593,7 +594,8 @@ func TestJWTSubject(t *testing.T) { func TestTargetPinRoutes(t *testing.T) { g := newGateServer(t) pg := g.m.pg - task, other := g.newTask(t, db.TaskCreateOptions{}), g.newTask(t, db.TaskCreateOptions{}) + gateOn := true + task, other := g.newTask(t, db.TaskCreateOptions{TargetGate: &gateOn}), g.newTask(t, db.TaskCreateOptions{TargetGate: &gateOn}) conv, err := pg.CreateConversation("auto", "pin routes", nil) if err != nil { t.Fatal(err) @@ -675,7 +677,8 @@ func TestTargetPinRoutes(t *testing.T) { // that took the intent over attaches to the same request. func TestClaimLostEndsGateWait(t *testing.T) { g := newGateServer(t) - task := g.newTask(t, db.TaskCreateOptions{}) + gateOn := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &gateOn}) pg, ic := g.m.pg, g.m.interceptor store := task.Store intent, err := store.AddIntent(map[string]any{"summary": "leased"}, 1, nil, "planner") From ce0ff070023022c1e2580f152f735c19263d87d7 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:24 +0530 Subject: [PATCH 15/18] test(server): opt in empty-pin approval fixture --- server/target_gate_wiring_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/target_gate_wiring_test.go b/server/target_gate_wiring_test.go index 872520ddb..c315221e9 100644 --- a/server/target_gate_wiring_test.go +++ b/server/target_gate_wiring_test.go @@ -210,7 +210,8 @@ func TestTargetGateEndpointsFollowConfig(t *testing.T) { // request stays open and nothing is pinned. func TestInterceptDecideRefusesEmptyPinOverHTTP(t *testing.T) { g := newGateServer(t) - task := g.newTask(t, db.TaskCreateOptions{}) + gateOn := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &gateOn}) scope := taskRef(t, task) id := openTargetRow(t, g.m.pg, scope, "no-address.example.com") code, body := g.do(t, "POST", fmt.Sprintf("/api/intercept/pending/%d/decide", id), `{"decision":"allowed"}`) From 83f82144cb9a054323e9ea8ed74276abfc40aaec Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:26 +0530 Subject: [PATCH 16/18] test(server): use persisted task for batch target approval --- server/intercept_batch_decide_test.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/server/intercept_batch_decide_test.go b/server/intercept_batch_decide_test.go index 632c8618c..d9e0a08e3 100644 --- a/server/intercept_batch_decide_test.go +++ b/server/intercept_batch_decide_test.go @@ -32,9 +32,15 @@ func TestInterceptBatchDecideHTTP(t *testing.T) { t.Fatal(err) } scope := "approval-http-batch-decide" - // A target request needs a numeric task scope; no foreign key ties it to tasks. - targetTask := 900000000 + time.Now().UnixNano()%1000000 + gateOn := true + task, err := d.CreateTaskWithOptions("approval batch", "target approval batch fixture", db.TaskCreateOptions{TargetGate: &gateOn}) + if err != nil { + t.Fatal(err) + } + targetTask := task.ID t.Cleanup(func() { + _ = d.DeleteTask(task.ID) + _, _ = d.Exec(`DELETE FROM target_pins WHERE task_id=$1`, targetTask) _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1 OR task_id=$2`, scope, strconv.FormatInt(targetTask, 10)) }) do := func(method, path, body string) *httptest.ResponseRecorder { From e44d7e57125a24e32e63f08845ab9cdadb8ed796 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:10:45 +0530 Subject: [PATCH 17/18] test(server): remove unused time import --- server/intercept_batch_decide_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/intercept_batch_decide_test.go b/server/intercept_batch_decide_test.go index d9e0a08e3..2c5fc8469 100644 --- a/server/intercept_batch_decide_test.go +++ b/server/intercept_batch_decide_test.go @@ -8,7 +8,6 @@ import ( "strconv" "strings" "testing" - "time" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" From b781554c57ee55adde2b9b2ca0288a643727b208 Mon Sep 17 00:00:00 2001 From: Jwalith Date: Wed, 2 Dec 2026 11:15:15 +0530 Subject: [PATCH 18/18] style(agent): format fixture comment --- agent/hooks_reach_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent/hooks_reach_test.go b/agent/hooks_reach_test.go index 4fbb2aac2..c2dfdf294 100644 --- a/agent/hooks_reach_test.go +++ b/agent/hooks_reach_test.go @@ -90,7 +90,7 @@ func toolCallThenStop(tool, input string) captureUsageProvider { } // 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. +// 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