| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "reasonix/internal/capability" |
| 10 | "reasonix/internal/tool" |
| 11 | ) |
| 12 | |
| 13 | type capabilityContextKey struct{} |
| 14 | |
| 15 | type contextualDiscoveryTool struct{ fakeTool } |
| 16 | |
| 17 | func (contextualDiscoveryTool) ProviderVisible(ctx context.Context) bool { |
| 18 | return ctx.Value(capabilityContextKey{}) == true |
| 19 | } |
| 20 | |
| 21 | func (contextualDiscoveryTool) UnavailableReason(context.Context) string { |
| 22 | return "the host has disabled this capability" |
| 23 | } |
| 24 | |
| 25 | func TestCapabilityDiscoveryUsesCurrentExecutionContext(t *testing.T) { |
| 26 | reg := tool.NewRegistry() |
| 27 | target := contextualDiscoveryTool{fakeTool{name: "contextual_reader", readOnly: true}} |
| 28 | reg.Add(target) |
| 29 | reg.SetProviderVisibleTools([]string{"use_capability"}) |
| 30 | cat := capability.BuildCatalog(capability.CatalogOptions{Tools: reg.CapabilityContractEntries()}) |
| 31 | proxy := NewUseCapabilityTool(context.Background(), nil, nil, reg, nil, nil, func() capability.Catalog { return cat }) |
| 32 | before := string(proxy.Schema()) |
| 33 | for _, available := range []bool{false, true, false} { |
| 34 | ctx := context.WithValue(context.Background(), capabilityContextKey{}, available) |
| 35 | for _, action := range []string{"search", "list", "inspect"} { |
| 36 | args, _ := json.Marshal(map[string]any{"action": action, "query": "contextual_reader", "capability_id": "tool:contextual_reader"}) |
| 37 | out, err := proxy.Execute(ctx, args) |
| 38 | if err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | want := `"status": "disabled"` |
| 42 | if available { |
| 43 | want = `"status": "ready"` |
| 44 | } |
| 45 | if !strings.Contains(out, want) || (!available && !strings.Contains(out, "the host has disabled this capability")) { |
| 46 | t.Errorf("%s available=%v: %s", action, available, out) |
| 47 | } |
| 48 | if action == "inspect" && !strings.Contains(out, `"input_schema"`) { |
| 49 | t.Errorf("inspect must disclose the registered tool contract: %s", out) |
| 50 | } |
| 51 | } |
| 52 | outcome, blocked := contextualToolGateOutcome(ctx, target, target.Name()) |
| 53 | if blocked == available || (blocked && !strings.Contains(outcome.output, "the host has disabled this capability")) { |
| 54 | t.Errorf("execution gate disagrees with discovery: %+v, blocked=%v", outcome, blocked) |
| 55 | } |
| 56 | } |
| 57 | if string(proxy.Schema()) != before || cat.Entries[0].Status != capability.StatusReady { |
| 58 | t.Fatal("context checks mutated the stable tool schema or catalog") |
| 59 | } |
| 60 | } |
| 61 |