@tanagram/cli 0.1.26 → 0.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,7 @@ import (
10
10
  )
11
11
 
12
12
  // CheckChangesWithLLM checks code changes against ALL policies using LLM
13
- func CheckChangesWithLLM(ctx context.Context, changes []git.ChangedLine, policies []parser.Policy) []Violation {
13
+ func CheckChangesWithLLM(ctx context.Context, changes []git.ChangedLine, policies []parser.Policy, apiKey string) []Violation {
14
14
  if len(policies) == 0 {
15
15
  return []Violation{}
16
16
  }
@@ -23,7 +23,7 @@ func CheckChangesWithLLM(ctx context.Context, changes []git.ChangedLine, policie
23
23
 
24
24
  var allViolations []Violation
25
25
  for file, fileChanges := range changesByFile {
26
- violations := checkFileWithLLM(ctx, file, fileChanges, policies, policyMap)
26
+ violations := checkFileWithLLM(ctx, file, fileChanges, policies, policyMap, apiKey)
27
27
  allViolations = append(allViolations, violations...)
28
28
  }
29
29
 
@@ -49,12 +49,12 @@ func groupChangesByFile(changes []git.ChangedLine) map[string][]git.ChangedLine
49
49
  }
50
50
 
51
51
  // checkFileWithLLM checks a single file's changes using the LLM
52
- func checkFileWithLLM(ctx context.Context, file string, changes []git.ChangedLine, policies []parser.Policy, policyMap map[string]parser.Policy) []Violation {
52
+ func checkFileWithLLM(ctx context.Context, file string, changes []git.ChangedLine, policies []parser.Policy, policyMap map[string]parser.Policy, apiKey string) []Violation {
53
53
  // Format changes for LLM
54
54
  codeChanges := formatChangesForLLM(changes)
55
55
 
56
56
  // Call LLM to check violations
57
- checks, err := CheckViolations(ctx, file, codeChanges, policies)
57
+ checks, err := CheckViolations(ctx, file, codeChanges, policies, apiKey)
58
58
  if err != nil {
59
59
  // Log error but don't fail the whole check
60
60
  fmt.Printf("Warning: LLM check failed for %s: %v\n", file, err)
@@ -26,14 +26,14 @@ type CheckResult struct {
26
26
  }
27
27
 
28
28
  // CheckChanges checks all changed lines against policies using LLM-based detection
29
- func CheckChanges(ctx context.Context, changes []git.ChangedLine, policies []parser.Policy) *CheckResult {
29
+ func CheckChanges(ctx context.Context, changes []git.ChangedLine, policies []parser.Policy, apiKey string) *CheckResult {
30
30
  result := &CheckResult{
31
31
  Violations: []Violation{},
32
32
  TotalChecked: len(changes),
33
33
  }
34
34
 
35
35
  // Use LLM-based checking for all policies
36
- llmViolations := CheckChangesWithLLM(ctx, changes, policies)
36
+ llmViolations := CheckChangesWithLLM(ctx, changes, policies, apiKey)
37
37
  result.Violations = append(result.Violations, llmViolations...)
38
38
 
39
39
  return result
@@ -24,12 +24,12 @@ type ViolationCheckResponse struct {
24
24
 
25
25
  // CheckViolations uses LLM to check if code changes violate any policies
26
26
  // Returns a list of violation checks with policy names and reasons
27
- func CheckViolations(ctx context.Context, file string, codeChanges string, policies []parser.Policy) ([]ViolationCheck, error) {
27
+ func CheckViolations(ctx context.Context, file string, codeChanges string, policies []parser.Policy, apiKey string) ([]ViolationCheck, error) {
28
28
  if len(policies) == 0 {
29
29
  return []ViolationCheck{}, nil
30
30
  }
31
31
 
32
- client, err := llm.NewClient()
32
+ client, err := llm.NewClient(apiKey)
33
33
  if err != nil {
34
34
  return nil, err
35
35
  }
package/commands/run.go CHANGED
@@ -9,6 +9,7 @@ import (
9
9
  "time"
10
10
 
11
11
  "github.com/tanagram/cli/checker"
12
+ "github.com/tanagram/cli/config"
12
13
  "github.com/tanagram/cli/extractor"
13
14
  "github.com/tanagram/cli/git"
14
15
  "github.com/tanagram/cli/metrics"
@@ -71,6 +72,12 @@ func Run() error {
71
72
 
72
73
  // Auto-sync only the files that changed
73
74
  if len(filesToSync) > 0 {
75
+ // Get API key once upfront before parallel processing
76
+ apiKey, err := config.GetAPIKey()
77
+ if err != nil {
78
+ return fmt.Errorf("failed to get API key: %w", err)
79
+ }
80
+
74
81
  fmt.Printf("\nSyncing policies with LLM (processing %d changed file(s) in parallel)...\n", len(filesToSync))
75
82
 
76
83
  syncStart := time.Now()
@@ -117,7 +124,7 @@ func Run() error {
117
124
  go func(file string) {
118
125
  defer wg.Done()
119
126
  relPath, _ := filepath.Rel(gitRoot, file)
120
- policies, err := extractor.ExtractPoliciesFromFile(ctx, file)
127
+ policies, err := extractor.ExtractPoliciesFromFile(ctx, file, apiKey)
121
128
  results <- syncResult{file, relPath, policies, err}
122
129
  }(file)
123
130
  }
@@ -204,10 +211,16 @@ func Run() error {
204
211
 
205
212
  fmt.Printf("Scanning %d changed lines...\n\n", len(diffResult.Changes))
206
213
 
214
+ // Get API key once upfront before checking
215
+ apiKey, err := config.GetAPIKey()
216
+ if err != nil {
217
+ return fmt.Errorf("failed to get API key: %w", err)
218
+ }
219
+
207
220
  // Check changes against policies (both regex and LLM-based)
208
221
  ctx := context.Background()
209
222
  checkStart := time.Now()
210
- result := checker.CheckChanges(ctx, diffResult.Changes, policies)
223
+ result := checker.CheckChanges(ctx, diffResult.Changes, policies, apiKey)
211
224
  checkDuration := time.Since(checkStart)
212
225
 
213
226
  // Track policy check results (similar to policy.execute.result in github-app)
package/commands/sync.go CHANGED
@@ -8,6 +8,7 @@ import (
8
8
  "sync"
9
9
  "time"
10
10
 
11
+ "github.com/tanagram/cli/config"
11
12
  "github.com/tanagram/cli/extractor"
12
13
  "github.com/tanagram/cli/parser"
13
14
  "github.com/tanagram/cli/storage"
@@ -15,6 +16,12 @@ import (
15
16
 
16
17
  // Sync manually syncs all instruction files to the cache
17
18
  func Sync() error {
19
+ // Get API key first before doing any work
20
+ apiKey, err := getAPIKey()
21
+ if err != nil {
22
+ return err
23
+ }
24
+
18
25
  // Find git root
19
26
  gitRoot, err := storage.FindGitRoot()
20
27
  if err != nil {
@@ -103,7 +110,7 @@ func Sync() error {
103
110
  go func(file string) {
104
111
  defer wg.Done()
105
112
  relPath, _ := filepath.Rel(gitRoot, file)
106
- policies, err := extractor.ExtractPoliciesFromFile(ctx, file)
113
+ policies, err := extractor.ExtractPoliciesFromFile(ctx, file, apiKey)
107
114
  results <- syncResult{file, relPath, policies, err}
108
115
  }(file)
109
116
  }
@@ -223,3 +230,12 @@ func FindInstructionFiles(gitRoot string) ([]string, error) {
223
230
 
224
231
  return files, nil
225
232
  }
233
+
234
+ // getAPIKey retrieves the API key once upfront before parallel processing
235
+ func getAPIKey() (string, error) {
236
+ apiKey, err := config.GetAPIKey()
237
+ if err != nil {
238
+ return "", fmt.Errorf("failed to get API key: %w", err)
239
+ }
240
+ return apiKey, nil
241
+ }
@@ -0,0 +1,155 @@
1
+ package config
2
+
3
+ import (
4
+ "bufio"
5
+ "context"
6
+ "encoding/json"
7
+ "fmt"
8
+ "os"
9
+ "path/filepath"
10
+ "strings"
11
+
12
+ "github.com/anthropics/anthropic-sdk-go"
13
+ "github.com/anthropics/anthropic-sdk-go/option"
14
+ )
15
+
16
+ const (
17
+ configDir = ".tanagram"
18
+ configFile = "config.json"
19
+ )
20
+
21
+ // Config represents the application configuration
22
+ type Config struct {
23
+ AnthropicAPIKey string `json:"anthropic_api_key"`
24
+ }
25
+
26
+ // GetConfigPath returns the full path to the config file
27
+ func GetConfigPath() (string, error) {
28
+ home, err := os.UserHomeDir()
29
+ if err != nil {
30
+ return "", fmt.Errorf("failed to get user home directory: %w", err)
31
+ }
32
+ return filepath.Join(home, configDir, configFile), nil
33
+ }
34
+
35
+ // Load reads the config from disk
36
+ func Load() (*Config, error) {
37
+ configPath, err := GetConfigPath()
38
+ if err != nil {
39
+ return nil, err
40
+ }
41
+
42
+ // If config doesn't exist, return empty config
43
+ if _, err := os.Stat(configPath); os.IsNotExist(err) {
44
+ return &Config{}, nil
45
+ }
46
+
47
+ data, err := os.ReadFile(configPath)
48
+ if err != nil {
49
+ return nil, fmt.Errorf("failed to read config file: %w", err)
50
+ }
51
+
52
+ var cfg Config
53
+ if err := json.Unmarshal(data, &cfg); err != nil {
54
+ return nil, fmt.Errorf("failed to parse config file: %w", err)
55
+ }
56
+
57
+ return &cfg, nil
58
+ }
59
+
60
+ // Save writes the config to disk
61
+ func Save(cfg *Config) error {
62
+ configPath, err := GetConfigPath()
63
+ if err != nil {
64
+ return err
65
+ }
66
+
67
+ // Ensure config directory exists
68
+ configDir := filepath.Dir(configPath)
69
+ if err := os.MkdirAll(configDir, 0755); err != nil {
70
+ return fmt.Errorf("failed to create config directory: %w", err)
71
+ }
72
+
73
+ data, err := json.MarshalIndent(cfg, "", " ")
74
+ if err != nil {
75
+ return fmt.Errorf("failed to marshal config: %w", err)
76
+ }
77
+
78
+ if err := os.WriteFile(configPath, data, 0600); err != nil {
79
+ return fmt.Errorf("failed to write config file: %w", err)
80
+ }
81
+
82
+ return nil
83
+ }
84
+
85
+ // GetAPIKey retrieves the Anthropic API key from config
86
+ // If not found, prompts the user and saves it to config
87
+ func GetAPIKey() (string, error) {
88
+ // Check config file
89
+ cfg, err := Load()
90
+ if err != nil {
91
+ return "", fmt.Errorf("failed to load config: %w", err)
92
+ }
93
+
94
+ if cfg.AnthropicAPIKey != "" {
95
+ return cfg.AnthropicAPIKey, nil
96
+ }
97
+
98
+ // Prompt user for API key
99
+ fmt.Println("ANTHROPIC_API_KEY not found.")
100
+ fmt.Print("Please enter your Anthropic API key: ")
101
+
102
+ reader := bufio.NewReader(os.Stdin)
103
+ apiKey, err := reader.ReadString('\n')
104
+ if err != nil {
105
+ return "", fmt.Errorf("failed to read API key: %w", err)
106
+ }
107
+
108
+ apiKey = strings.TrimSpace(apiKey)
109
+ if apiKey == "" {
110
+ return "", fmt.Errorf("API key cannot be empty")
111
+ }
112
+
113
+ // Validate the API key before saving
114
+ fmt.Print("Validating API key... ")
115
+ if err := ValidateAPIKey(apiKey); err != nil {
116
+ fmt.Println("✗")
117
+ return "", fmt.Errorf("invalid API key: %w", err)
118
+ }
119
+ fmt.Println("✓")
120
+
121
+ // Save to config
122
+ cfg.AnthropicAPIKey = apiKey
123
+ if err := Save(cfg); err != nil {
124
+ return "", fmt.Errorf("failed to save config: %w", err)
125
+ }
126
+
127
+ configPath, _ := GetConfigPath()
128
+ fmt.Printf("API key saved to %s\n", configPath)
129
+
130
+ return apiKey, nil
131
+ }
132
+
133
+ // ValidateAPIKey checks if the API key is valid by making a test API call
134
+ func ValidateAPIKey(apiKey string) error {
135
+ client := anthropic.NewClient(option.WithAPIKey(apiKey))
136
+
137
+ ctx := context.Background()
138
+ _, err := client.Messages.New(ctx, anthropic.MessageNewParams{
139
+ MaxTokens: 10,
140
+ Messages: []anthropic.MessageParam{
141
+ anthropic.NewUserMessage(anthropic.NewTextBlock("test")),
142
+ },
143
+ Model: anthropic.ModelClaudeHaiku4_5_20251001,
144
+ })
145
+
146
+ if err != nil {
147
+ // Check if it's an authentication error
148
+ if strings.Contains(err.Error(), "401") || strings.Contains(err.Error(), "authentication_error") {
149
+ return fmt.Errorf("authentication failed - please check your API key")
150
+ }
151
+ return err
152
+ }
153
+
154
+ return nil
155
+ }
@@ -23,8 +23,8 @@ type ExtractorResponse struct {
23
23
  }
24
24
 
25
25
  // ExtractPolicies uses LLM to extract policies from instruction file content
26
- func ExtractPolicies(ctx context.Context, content string) ([]parser.Policy, error) {
27
- client, err := llm.NewClient()
26
+ func ExtractPolicies(ctx context.Context, content string, apiKey string) ([]parser.Policy, error) {
27
+ client, err := llm.NewClient(apiKey)
28
28
  if err != nil {
29
29
  return nil, err
30
30
  }
package/extractor/file.go CHANGED
@@ -11,7 +11,7 @@ import (
11
11
  )
12
12
 
13
13
  // ExtractPoliciesFromFile reads a file and extracts policies using LLM
14
- func ExtractPoliciesFromFile(ctx context.Context, filePath string) ([]parser.Policy, error) {
14
+ func ExtractPoliciesFromFile(ctx context.Context, filePath string, apiKey string) ([]parser.Policy, error) {
15
15
  content, err := os.ReadFile(filePath)
16
16
  if err != nil {
17
17
  return nil, fmt.Errorf("failed to read file: %w", err)
@@ -24,5 +24,5 @@ func ExtractPoliciesFromFile(ctx context.Context, filePath string) ([]parser.Pol
24
24
  contentStr = parser.StripMDCFrontmatter(contentStr)
25
25
  }
26
26
 
27
- return ExtractPolicies(ctx, contentStr)
27
+ return ExtractPolicies(ctx, contentStr, apiKey)
28
28
  }
package/llm/client.go CHANGED
@@ -3,7 +3,7 @@ package llm
3
3
  import (
4
4
  "context"
5
5
  "fmt"
6
- "os"
6
+ "strings"
7
7
 
8
8
  "github.com/anthropics/anthropic-sdk-go"
9
9
  "github.com/anthropics/anthropic-sdk-go/option"
@@ -14,13 +14,8 @@ type Client struct {
14
14
  client *anthropic.Client
15
15
  }
16
16
 
17
- // NewClient creates a new Anthropic API client
18
- func NewClient() (*Client, error) {
19
- apiKey := os.Getenv("ANTHROPIC_API_KEY")
20
- if apiKey == "" {
21
- return nil, fmt.Errorf("ANTHROPIC_API_KEY environment variable not set. Please set it to use LLM-based policy extraction")
22
- }
23
-
17
+ // NewClient creates a new Anthropic API client with the provided API key
18
+ func NewClient(apiKey string) (*Client, error) {
24
19
  client := anthropic.NewClient(
25
20
  option.WithAPIKey(apiKey),
26
21
  )
@@ -40,6 +35,11 @@ func (c *Client) SendMessage(ctx context.Context, prompt string) (string, error)
40
35
  Model: anthropic.ModelClaudeHaiku4_5_20251001,
41
36
  })
42
37
  if err != nil {
38
+ // Check for authentication errors
39
+ errStr := err.Error()
40
+ if strings.Contains(errStr, "401") || strings.Contains(errStr, "authentication_error") {
41
+ return "", fmt.Errorf("authentication failed - your API key is invalid or expired. Please run 'tanagram sync' to update your API key")
42
+ }
43
43
  return "", fmt.Errorf("failed to send message: %w", err)
44
44
  }
45
45
 
package/main.go CHANGED
@@ -96,8 +96,6 @@ COMMANDS:
96
96
  run Check git changes against policies (default)
97
97
  sync Manually sync instruction files to cache
98
98
  list Show all cached policies
99
- welcome Show interactive welcome screen with setup options
100
- puzzle Interactive tangram puzzle editor
101
99
  help Show this help message
102
100
 
103
101
  EXAMPLES:
@@ -105,8 +103,6 @@ EXAMPLES:
105
103
  tanagram run # Same as above
106
104
  tanagram sync # Manually sync policies
107
105
  tanagram list # View all cached policies
108
- tanagram welcome # Show interactive welcome screen
109
- tanagram puzzle # Launch tangram puzzle editor
110
106
 
111
107
  INSTRUCTION FILES:
112
108
  Tanagram looks for instruction files in your git repository:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanagram/cli",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
4
4
  "description": "Tanagram - Catch sloppy code before it ships",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -35,6 +35,7 @@
35
35
  "bin/tanagram.js",
36
36
  "checker/",
37
37
  "commands/",
38
+ "config/",
38
39
  "extractor/",
39
40
  "fixtures/",
40
41
  "git/",