-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol.go
More file actions
370 lines (345 loc) · 11.4 KB
/
Copy pathcontrol.go
File metadata and controls
370 lines (345 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package app
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"reflect"
"runtime"
"sort"
"strings"
"time"
"github.com/morluto/gitcontribute/internal/cli"
"github.com/morluto/gitcontribute/internal/config"
"github.com/morluto/gitcontribute/internal/github"
clientsetup "github.com/morluto/gitcontribute/internal/setup"
)
const databaseIntegrityTimeout = 2 * time.Second
// Metadata reports deterministic application and local capability metadata.
// It neither opens the corpus nor performs network access.
func (s *Service) Metadata(ctx context.Context) (*cli.MetadataResult, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
cfg, err := s.loadConfig(false)
if err != nil {
return nil, err
}
configPath, err := s.paths.ConfigFile()
if err != nil {
return nil, err
}
schemaVersion := int64(0)
s.mu.Lock()
c := s.corpus
s.mu.Unlock()
if c != nil {
schemaVersion, _ = c.SchemaVersion(ctx)
}
capabilities := []string{
"archive", "clustering", "collections", "contribution-radar", "contribution-readiness", "dossiers", "evidence",
"evidence-freshness", "github-read", "investigations", "local-search", "mcp-stdio",
"thread-investigation-start", "thread-research-brief", "validation", "workspaces",
}
sort.Strings(capabilities)
return &cli.MetadataResult{
Name: "gitcontribute",
Version: s.version,
GoVersion: runtime.Version(),
OS: runtime.GOOS,
Architecture: runtime.GOARCH,
SchemaVersion: schemaVersion,
ConfigPath: configPath,
CorpusPath: cfg.Database,
Capabilities: capabilities,
Features: map[string]bool{
"contribution_radar": true,
"contribution_readiness": true,
"evidence_freshness": true,
"github_mutations": false,
"mcp_stdio": true,
"semantic_search": false,
"thread_investigation": true,
"thread_research": true,
"validation_exec": true,
},
}, nil
}
// Configure validates and atomically saves supported typed settings. Runtime
// environment overrides are deliberately not persisted.
func (s *Service) Configure(ctx context.Context, opts cli.ConfigureOptions) (*cli.ConfigureResult, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
path, err := s.paths.ConfigFile()
if err != nil {
return nil, err
}
cfg, err := s.persistedConfig(path)
if err != nil {
return nil, err
}
before := *cfg
applyConfigureOptions(cfg, opts)
if err := config.Validate(cfg); err != nil {
return nil, fmt.Errorf("validate configuration: %w", err)
}
changed := !reflect.DeepEqual(before, *cfg)
if changed && !opts.DryRun {
s.mu.Lock()
corpusOpen := s.corpus != nil
s.mu.Unlock()
if corpusOpen && before.Database != cfg.Database {
return nil, errors.New("cannot change database path while the corpus is open")
}
if err := config.Save(path, cfg); err != nil {
return nil, err
}
if _, err := s.loadConfig(false); err != nil {
return nil, fmt.Errorf("reload configuration: %w", err)
}
}
return &cli.ConfigureResult{Path: path, DryRun: opts.DryRun, Changed: changed, Config: configResult(cfg)}, nil
}
// ControlStatus returns local corpus counts and freshness without network
// access or implicit hydration.
func (s *Service) ControlStatus(ctx context.Context) (*cli.ControlStatusResult, error) {
c, err := s.openCorpus(ctx)
if err != nil {
return nil, err
}
stats, err := c.ControlStats(ctx, s.now())
if err != nil {
return nil, err
}
version, err := c.SchemaVersion(ctx)
if err != nil {
return nil, err
}
warnings := make([]string, 0, 4)
rateObservations, err := c.LatestRateLimitObservations(ctx, 4)
if err != nil {
return nil, err
}
rateLimits := make([]cli.RateLimitState, len(rateObservations))
for i, observation := range rateObservations {
resource := observation.Resource
if resource == "" {
resource = "unknown"
}
rateLimits[i] = cli.RateLimitState{
Resource: resource, Limit: observation.Limit, Remaining: observation.Remaining,
Used: observation.Used, ResetAt: formatTime(observation.ResetAt),
StatusCode: observation.StatusCode, ObservedAt: formatTime(observation.ObservedAt),
}
if observation.Limit > 0 && observation.Remaining == 0 && observation.ResetAt.After(s.now()) {
warnings = append(warnings, fmt.Sprintf("GitHub %s rate limit resets at %s", resource, formatTime(observation.ResetAt)))
}
}
if stats.Repositories == 0 {
warnings = append(warnings, "corpus has no repositories")
}
if stats.FrontierReady > 0 {
warnings = append(warnings, fmt.Sprintf("%d frontier items are ready", stats.FrontierReady))
}
if stats.ActiveRuns > 0 || stats.ActiveJobs > 0 {
warnings = append(warnings, "background work is active")
}
if !stats.Freshest.IsZero() && s.now().Sub(stats.Freshest) > 7*24*time.Hour {
warnings = append(warnings, "freshest GitHub observation is older than 7 days")
}
return &cli.ControlStatusResult{
Healthy: true,
Corpus: s.databasePath(),
Version: s.version,
SchemaVersion: version,
Counts: cli.ControlCounts{
Repositories: stats.Repositories,
Threads: stats.Threads,
Sources: stats.Sources,
FrontierReady: stats.FrontierReady,
ActiveRuns: stats.ActiveRuns,
ActiveJobs: stats.ActiveJobs,
},
FreshestSource: formatTime(stats.Freshest),
RateLimits: rateLimits,
Warnings: warnings,
}, nil
}
// Doctor performs bounded local diagnostics. It reports authentication source
// availability but never returns credential values or command output.
func (s *Service) Doctor(ctx context.Context) (*cli.DoctorResult, error) {
return s.doctor(ctx)
}
func (s *Service) doctor(ctx context.Context) (*cli.DoctorResult, error) {
checks := make([]cli.DoctorCheck, 0, 10)
add := func(name string, required bool, err error, success string) {
check := cli.DoctorCheck{Name: name, Required: required, Status: "ok", Message: success}
if err != nil {
check.Status = "error"
if !required {
check.Status = "warning"
}
check.Message = redactDiagnostic(err.Error())
}
checks = append(checks, check)
}
_, pathErr := s.paths.ConfigFile()
var cfg *config.Config
if pathErr == nil {
cfg, pathErr = s.loadConfig(false)
}
add("config", true, pathErr, "configuration is readable and valid")
c, dbErr := s.openCorpus(ctx)
add("database", true, dbErr, "corpus is readable")
if dbErr == nil {
current, target, schemaErr := c.SchemaVersions(ctx)
if schemaErr == nil && current != target {
schemaErr = fmt.Errorf("database schema version %d does not match expected version %d", current, target)
}
add("schema", true, schemaErr, fmt.Sprintf("schema is current at version %d", current))
integrityCtx, cancel := context.WithTimeout(ctx, databaseIntegrityTimeout)
integrityErr := c.CheckIntegrity(integrityCtx)
cancel()
add("database_integrity", true, integrityErr, "database quick check passed")
writeErr := c.CheckWriteAccess(ctx)
add("database_write", false, writeErr, "database is ready for writes")
}
gitErr := commandAvailable(ctx, "git", "--version")
add("git", true, gitErr, "Git is available")
var authErr error
authSuccess := "GitHub authentication source is configured; credentials were not read"
if cfg == nil {
authErr = errors.New("authentication source unavailable because configuration is invalid")
} else if cfg.TokenSource.Method == "none" {
authErr = errors.New("no GitHub authentication source configured; public reads remain available")
} else {
authErr = checkAuthSource(ctx, cfg, tokenSource(cfg))
authSuccess = "GitHub authentication source is available"
}
add("github_auth", false, authErr, authSuccess)
add("rg", false, lookPathError("rg"), "ripgrep is available")
if home := s.paths.HomeDir(); home != "" {
for _, client := range clientsetup.Detect(home) {
registered, _, checkErr := clientsetup.CheckRegistration(client, home)
if checkErr == nil && !registered {
checkErr = errors.New("client detected but GitContribute MCP registration is absent")
}
add("mcp_"+string(client), false, checkErr, "GitContribute MCP registration is present")
}
}
healthy := true
for _, check := range checks {
if check.Required && check.Status == "error" {
healthy = false
break
}
}
return &cli.DoctorResult{Healthy: healthy, Checks: checks}, nil
}
func (s *Service) persistedConfig(path string) (*config.Config, error) {
var cfg *config.Config
if _, err := os.Stat(path); err == nil {
loaded, err := config.LoadFile(path)
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
}
cfg = loaded
} else if errors.Is(err, os.ErrNotExist) {
cfg = config.Default()
} else {
return nil, fmt.Errorf("inspect config: %w", err)
}
if err := config.ApplyDefaults(cfg, s.paths); err != nil {
return nil, err
}
if err := config.Validate(cfg); err != nil {
return nil, err
}
return cfg, nil
}
func applyConfigureOptions(cfg *config.Config, opts cli.ConfigureOptions) {
if opts.Database != nil {
cfg.Database = strings.TrimSpace(*opts.Database)
}
if opts.TokenSource != nil {
cfg.TokenSource.Method = strings.ToLower(strings.TrimSpace(*opts.TokenSource))
}
if opts.TokenSourceKey != nil {
cfg.TokenSource.Key = strings.TrimSpace(*opts.TokenSourceKey)
}
if opts.CrawlBudget != nil {
cfg.Crawl.Budget = *opts.CrawlBudget
}
if opts.CrawlConcurrency != nil {
cfg.Crawl.Concurrency = *opts.CrawlConcurrency
}
if opts.CrawlRetryLimit != nil {
cfg.Crawl.RetryLimit = *opts.CrawlRetryLimit
}
if opts.CrawlTimeout != nil {
cfg.Crawl.Timeout = strings.TrimSpace(*opts.CrawlTimeout)
}
if opts.OutputFormat != nil {
cfg.Output.Format = strings.ToLower(strings.TrimSpace(*opts.OutputFormat))
}
if opts.OutputMaxResults != nil {
cfg.Output.MaxResults = *opts.OutputMaxResults
}
}
func configResult(cfg *config.Config) cli.ConfigResult {
return cli.ConfigResult{
Database: cfg.Database,
TokenSource: cfg.TokenSource.Method,
TokenSourceKey: cfg.TokenSource.Key,
CrawlBudget: cfg.Crawl.Budget,
CrawlConcurrency: cfg.Crawl.Concurrency,
CrawlRetryLimit: cfg.Crawl.RetryLimit,
CrawlTimeout: cfg.Crawl.Timeout,
OutputFormat: cfg.Output.Format,
OutputMaxResults: cfg.Output.MaxResults,
}
}
func commandAvailable(ctx context.Context, name string, args ...string) error {
path, err := exec.LookPath(name)
if err != nil {
return fmt.Errorf("%s is not available", name)
}
commandCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
cmd := exec.CommandContext(commandCtx, path, args...)
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s check failed", name)
}
return nil
}
func lookPathError(name string) error {
if _, err := exec.LookPath(name); err != nil {
return fmt.Errorf("%s is not available", name)
}
return nil
}
func checkAuthSource(ctx context.Context, cfg *config.Config, source github.TokenSource) error {
if cfg.TokenSource.Method == "none" {
return errors.New("no GitHub authentication source configured; public reads remain available")
}
if source == nil {
return errors.New("GitHub authentication source is unavailable")
}
checkCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
_, err := source.Token(checkCtx)
return err
}
func redactDiagnostic(message string) string {
upper := strings.ToUpper(message)
for _, marker := range []string{"TOKEN=", "AUTHORIZATION:", "BEARER "} {
if strings.Contains(upper, marker) {
return "diagnostic failed; sensitive credential detail was redacted"
}
}
return message
}