package thin import ( "bytes" "context" "encoding/json" "errors" "io" "log/slog" "os" "os/exec" "path" "path/filepath" "regexp" "runtime" "slices" "strconv" "strings" "sync" "time" "unicode" "unicode/utf8" "amadan.net/oficina/equipo/internal/runner/checks" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // Read tool bounds: the model gets enough to answer, never a whole repo. const ( maxSearchLines = 60 maxReadLines = 300 maxToolOutput = 16 << 10 indexEvery = time.Hour ) // Index is the runner's context catalog: for every repository the agent // can reach, what it is called and what it is, from a shallow clone of // its default branch. Only names and short summaries leave the runner. type Index struct { Forge Forge Clones *Clones Path string Logger *slog.Logger // Changed is called after a refresh changed the catalog. Changed func() // Refreshed is called after every completed refresh. Refreshed func() // Pace spaces fetches: the hub rate-limits one agent's git requests, // and the production runner shares that agent. Pace time.Duration mu sync.Mutex catalog []wire.RepoInfo settled bool kick chan struct{} } func (x *Index) kicks() chan struct{} { x.mu.Lock() defer x.mu.Unlock() if x.kick == nil { x.kick = make(chan struct{}, 1) } return x.kick } // Kick asks the loop for a delta refresh now: what the agent reaches // changed, so only new repositories are fetched. func (x *Index) Kick() { select { case x.kicks() <- struct{}{}: default: } } // Ready reports whether a refresh completed in this process: before it, // a fresh runner's catalog may be empty or out of date. func (x *Index) Ready() bool { x.mu.Lock() defer x.mu.Unlock() return x.settled } // Catalog is the current catalog, newest refresh. func (x *Index) Catalog() []wire.RepoInfo { x.mu.Lock() defer x.mu.Unlock() if x.catalog == nil && x.Path != "" { raw, err := os.ReadFile(x.Path) if err == nil { _ = json.Unmarshal(raw, &x.catalog) } } return slices.Clone(x.catalog) } // Loop refreshes the catalog now and hourly, and a delta when kicked. func (x *Index) Loop(ctx context.Context) { kick := x.kicks() for { x.Refresh(ctx) full := time.After(indexEvery) wait: for { select { case <-ctx.Done(): return case <-full: break wait case <-kick: x.Delta(ctx) } } } } // Delta drops what the agent no longer reaches and fetches only what is // new, or was empty (its first commit may have arrived), keeping every // other entry as it is. func (x *Index) Delta(ctx context.Context) { repos := x.Forge.Reachable(ctx) if len(repos) > wire.MaxCatalog { repos = repos[:wire.MaxCatalog] } have := map[string]bool{} empty := map[string]wire.RepoInfo{} var out []wire.RepoInfo for _, e := range x.Catalog() { switch { case !slices.Contains(repos, e.Repo): case e.Empty: empty[e.Repo] = e default: out = append(out, e) have[e.Repo] = true } } first := true for _, repo := range repos { if have[repo] { continue } if !first && x.Pace > 0 { select { case <-ctx.Done(): case <-time.After(x.Pace): } } first = false if ctx.Err() != nil { return } e, err := x.entry(ctx, repo) if err != nil { if x.Logger != nil { x.Logger.Warn("index", "repo", repo, "err", sanitize(err)) } if prev, ok := empty[repo]; ok { out = append(out, prev) } continue } out = append(out, e) } slices.SortFunc(out, func(a, b wire.RepoInfo) int { return strings.Compare(a.Repo, b.Repo) }) x.publish(out) } // Refresh fetches each reachable repository's tip and rebuilds its entry. // A repository that cannot be fetched keeps its previous entry. func (x *Index) Refresh(ctx context.Context) { old := map[string]wire.RepoInfo{} for _, e := range x.Catalog() { old[e.Repo] = e } repos := x.Forge.Reachable(ctx) if len(repos) > wire.MaxCatalog { repos = repos[:wire.MaxCatalog] } out := make([]wire.RepoInfo, 0, len(repos)) for i, repo := range repos { if i > 0 && x.Pace > 0 { select { case <-ctx.Done(): case <-time.After(x.Pace): } } if ctx.Err() != nil { return } e, err := x.entry(ctx, repo) if err != nil { if x.Logger != nil { x.Logger.Warn("index", "repo", repo, "err", sanitize(err)) } if prev, ok := old[repo]; ok { out = append(out, prev) } continue } out = append(out, e) } x.publish(out) } // publish installs a new catalog and tells the runner. func (x *Index) publish(out []wire.RepoInfo) { if out == nil { out = []wire.RepoInfo{} } x.mu.Lock() changed := !sameCatalog(x.catalog, out) x.catalog, x.settled = out, true x.mu.Unlock() if x.Path != "" { raw, _ := json.Marshal(out) if os.WriteFile(x.Path+".tmp", raw, 0600) == nil { _ = os.Rename(x.Path+".tmp", x.Path) } } if changed && x.Changed != nil { x.Changed() } if x.Refreshed != nil { x.Refreshed() } } func sameCatalog(a, b []wire.RepoInfo) bool { x, _ := json.Marshal(a) y, _ := json.Marshal(b) return bytes.Equal(x, y) } func (x *Index) entry(ctx context.Context, repo string) (wire.RepoInfo, error) { fctx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() branch, err := x.Clones.DefaultBranch(fctx, repo) if errors.Is(err, ErrEmptyRepo) { // Reachable, nothing pushed yet: listed by name, so the // coordinator can say it is empty rather than out of reach. return wire.RepoInfo{Repo: repo, Names: bounded([]string{path.Base(repo)}, wire.MaxRepoNames), Hints: []string{}, Empty: true}, nil } if err != nil { return wire.RepoInfo{}, err } if err = x.Clones.Shallow(fctx, repo, branch); err != nil { return wire.RepoInfo{}, err } return x.describe(ctx, repo, branch, x.Clones.Path(repo)), nil } // describe reads one clone's default branch: its newest commit, names, // hints, the checks gate and whether this runner can run it. func (x *Index) describe(ctx context.Context, repo, branch, dir string) wire.RepoInfo { e := wire.RepoInfo{Repo: repo, DefaultBranch: branch, Names: []string{}, Hints: []string{}} if out, err := x.git(ctx, dir, "log", "-1", "--format=%ct%x00%H%x00%s", "HEAD"); err == nil { if f := strings.SplitN(strings.TrimSpace(string(out)), "\x00", 3); len(f) == 3 { if sec, err := strconv.ParseInt(f[0], 10, 64); err == nil { e.UpdatedAt = time.Unix(sec, 0).UTC() } if objectName.MatchString(f[1]) { e.HeadSHA = f[1] } e.HeadSubject = clip(strings.ToValidUTF8(f[2], ""), wire.MaxRepoString) } } files, _ := x.git(ctx, dir, "ls-tree", "-r", "--name-only", "HEAD") list := strings.Split(string(files), "\n") read := func(name string) string { if !slices.Contains(list, name) { return "" } out, err := x.git(ctx, dir, "cat-file", "blob", "HEAD:"+name) if err != nil || len(out) > 256<<10 { return "" } return string(out) } readme, agents := read("README.md"), read("AGENTS.md") e.Summary = summary(readme) if e.Summary == "" { e.Summary = summary(agents) } names := []string{path.Base(repo)} names = append(names, headings(readme)...) names = append(names, headings(agents)...) names = append(names, manifestNames(read)...) names = append(names, productNames(readme+"\n"+agents)...) names = append(names, appNames(list)...) e.Names = bounded(names, wire.MaxRepoNames) e.Hints = bounded(hints(list, read), wire.MaxRepoHints) var gateText string e.Gate, gateText = listedGate(list, read) if runtime.GOOS != "darwin" && checks.NeedsMacOS(list, gateText) { e.ChecksReason = "needs_macos" } // Protocol 2: what the instance places checks by. e.NeedsMacOS, e.Simulator = checks.NeedsMacOS(nil, gateText), sharedScheme(list) return e } // listedGate is the checks gate a tree holds, in Amadan's order (as // findGate finds it in a checked-out tree), and the text of its files. func listedGate(list []string, read func(string) string) (name, text string) { var ciD strings.Builder for _, f := range list { if rest, ok := strings.CutPrefix(f, ".amadan/ci.d/"); ok && rest != "" && !strings.Contains(rest, "/") { ciD.WriteString(read(f) + "\n") name = ".amadan/ci.d" } } if name != "" { return name, ciD.String() } if slices.Contains(list, ".amadan/ci") { return ".amadan/ci", read(".amadan/ci") } for _, f := range []string{"GNUmakefile", "makefile", "Makefile"} { if s := read(f); s != "" && makeCI.MatchString(s) { return "make ci", s } } return "", "" } // sharedScheme reports whether a tree has a shared Xcode scheme: its // checks need the iOS simulator. func sharedScheme(list []string) bool { for _, f := range list { if strings.Contains(f, "/xcshareddata/xcschemes/") && strings.HasSuffix(f, ".xcscheme") { return true } } return false } func (x *Index) git(ctx context.Context, dir string, args ...string) ([]byte, error) { return readGit(ctx, x.Clones.Git, dir, args...) } // Read limits for git on a clone: time per command and bytes of output. const ( readTimeout = 20 * time.Second readLimit = 1 << 20 ) // readOnly are the overrides every read runs with. Command-line config // outranks the clone's own config, so nothing in a hostile repository's // config, attributes or hooks can run: no hooks, no fsmonitor, no // textconv or external diff, no attribute files, no network protocol. var readOnly = []string{ "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "diff.external=", "-c", "core.attributesFile=/dev/null", "-c", "protocol.allow=never", "-c", "core.sshCommand=/bin/false", "-c", "core.askPass=/bin/false", "-c", "credential.helper=", "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.untrackedCache=false", "-c", "safe.directory=*", } // readGit runs one read-only plumbing command (grep, cat-file, ls-tree, // rev-parse, log) on a bare clone, with a clean environment, a time limit // and bounded output. func readGit(ctx context.Context, git, dir string, args ...string) ([]byte, error) { ctx, cancel := context.WithTimeout(ctx, readTimeout) defer cancel() cmd := exec.CommandContext(ctx, git, append(append(append([]string{}, readOnly...), "-C", dir), args...)...) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" env["GIT_TERMINAL_PROMPT"] = "0" env["GIT_NO_LAZY_FETCH"] = "1" env["GIT_OPTIONAL_LOCKS"] = "0" env["GIT_CEILING_DIRECTORIES"] = filepath.Dir(dir) env["GIT_DIR"] = dir for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Dir = dir cmd.Stderr = io.Discard out, err := cmd.StdoutPipe() if err != nil { return nil, err } if err = cmd.Start(); err != nil { return nil, err } raw, _ := io.ReadAll(io.LimitReader(out, readLimit+1)) if len(raw) > readLimit { _ = cmd.Process.Kill() _ = cmd.Wait() return nil, errReadPath } return raw, cmd.Wait() } // tip is the commit the read tools look at, resolved once per call so // every read in it sees one fixed tree. func (x *Index) tip(ctx context.Context, dir string) (string, error) { out, err := x.git(ctx, dir, "rev-parse", "--verify", "--end-of-options", "HEAD^{commit}") sha := strings.TrimSpace(string(out)) if err != nil || !objectName.MatchString(sha) { return "", errReadPath } return sha, nil } var objectName = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`) // summary is the first prose paragraph, without markdown decoration. func summary(md string) string { for _, para := range strings.Split(md, "\n\n") { p := strings.TrimSpace(para) if p == "" || strings.HasPrefix(p, "#") || strings.HasPrefix(p, "<") || strings.HasPrefix(p, "```") || strings.HasPrefix(p, "|") { continue } p = mdImage.ReplaceAllString(p, "") p = mdLink.ReplaceAllString(p, "$1") p = strings.Join(strings.Fields(strings.NewReplacer("*", "", "`", "", "_", " ").Replace(p)), " ") if p == "" { continue } return clip(p, wire.MaxRepoString) } return "" } var ( mdImage = regexp.MustCompile(`\[?!\[[^\]]*\]\([^)]*\)(?:\]\([^)]*\))?`) mdLink = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) ) func clip(s string, n int) string { if len(s) <= n { return s } s = s[:n] for !utf8.ValidString(s) { s = s[:len(s)-1] } return s } // heading is a top-level title: section titles are not names. var heading = regexp.MustCompile(`(?m)^#\s+(.+)$`) func headings(md string) []string { var out []string for _, m := range heading.FindAllStringSubmatch(md, 6) { h := strings.TrimSpace(strings.Trim(m[1], "#*` ")) if len(h) > 1 && len(h) < 40 { out = append(out, h) } } return out } var ( jsonName = regexp.MustCompile(`"name"\s*:\s*"([^"]{2,40})"`) tomlName = regexp.MustCompile(`(?m)^name\s*=\s*"([^"]{2,40})"`) goModule = regexp.MustCompile(`(?m)^module\s+(\S+)`) capWord = regexp.MustCompile(`\b[A-Z][a-z]+(?:[A-Z][a-z]+)*\b`) appBundle = regexp.MustCompile(`(?:^|/)([A-Za-z0-9 _-]{2,40})\.(?:xcodeproj|xcworkspace)(?:/|$)`) ) func manifestNames(read func(string) string) []string { var out []string if m := jsonName.FindStringSubmatch(read("package.json")); m != nil { out = append(out, m[1]) } if m := tomlName.FindStringSubmatch(read("Cargo.toml")); m != nil { out = append(out, m[1]) } if m := goModule.FindStringSubmatch(read("go.mod")); m != nil { out = append(out, path.Base(m[1])) } return out } func appNames(files []string) []string { var out []string for _, f := range files { if m := appBundle.FindStringSubmatch(f); m != nil { out = append(out, m[1]) } } return out } // common capitalised words that are not product names. var common = map[string]bool{"The": true, "This": true, "You": true, "Use": true, "Run": true, "See": true, "For": true, "When": true, "If": true, "It": true, "Read": true, "Keep": true, "Never": true, "Do": true, "Each": true, "All": true, "And": true, "Go": true, "Make": true, "Only": true, "Every": true, "With": true, "From": true, "One": true, "No": true, "Not": true, "What": true, "Where": true, "How": true, "Use_": true, "Note": true, "Plan": true, "Task": true, "Write": true, "Test": true, "Tests": true, "Build": true} // productNames are capitalised words used at least twice: app and product // names like Woodstar tend to repeat. func productNames(text string) []string { counts := map[string]int{} var order []string for _, w := range capWord.FindAllString(text, -1) { if common[w] || len(w) < 4 { continue } if counts[w] == 0 { order = append(order, w) } counts[w]++ } var out []string for _, w := range order { if counts[w] >= 2 { out = append(out, w) } } return out } func hints(files []string, read func(string) string) []string { var out []string has := func(name string) bool { return slices.Contains(files, name) } if has("go.mod") { out = append(out, "go") } if has("Package.swift") || slices.ContainsFunc(files, func(f string) bool { return strings.HasSuffix(f, ".swift") }) { out = append(out, "swift") if strings.Contains(strings.Join(files, "\n"), "View.swift") { out = append(out, "swiftui") } } if pkg := read("package.json"); pkg != "" { out = append(out, "javascript") for _, fw := range []string{"react", "vue", "svelte", "next", "vite"} { if strings.Contains(pkg, `"`+fw+`"`) { out = append(out, fw) } } } if has("Cargo.toml") { out = append(out, "rust") } if has("pyproject.toml") || has("requirements.txt") { out = append(out, "python") } if slices.ContainsFunc(files, func(f string) bool { return strings.HasSuffix(f, ".kt") || strings.HasSuffix(f, ".gradle.kts") }) { out = append(out, "android") } return out } func bounded(in []string, n int) []string { out := []string{} for _, s := range in { s = strings.TrimSpace(s) if s == "" || len(s) > 40 || !isPrintableName(s) || slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, s) }) { continue } out = append(out, s) if len(out) == n { break } } return out } // errReadPath refuses paths that leave the tree or name git internals. var errReadPath = errors.New("path refused") func cleanPath(p string) (string, error) { p = strings.TrimPrefix(strings.TrimSpace(p), "/") if p == "" || p == "." { return "", nil } c := path.Clean(p) if c != p || strings.HasPrefix(c, "..") || strings.ContainsAny(c, "\x00\n:") || strings.HasPrefix(c, "-") { return "", errReadPath } return c, nil } // SearchCode is git grep over the default branch tip: fixed string, case // insensitive, bounded. Git reads objects only; no checkout, no hooks. func (x *Index) SearchCode(ctx context.Context, repo, query string) (string, error) { query = strings.TrimSpace(query) if query == "" || len(query) > 200 || strings.ContainsAny(query, "\x00\n") { return "", errReadPath } dir, err := x.ready(ctx, repo) if err != nil { return "", err } sha, err := x.tip(ctx, dir) if err != nil { return "", err } out, err := x.git(ctx, dir, "grep", "--no-textconv", "--no-ext-grep", "-n", "-I", "-i", "-F", "--max-count=5", "-e", query, sha, "--") var exit *exec.ExitError if errors.As(err, &exit) && exit.ExitCode() == 1 { return "No matches.", nil } if err != nil { return "", err } lines := strings.Split(strings.TrimSpace(strings.ReplaceAll(string(out), sha+":", "")), "\n") more := "" if len(lines) > maxSearchLines { more = "\n(" + strconv.Itoa(len(lines)-maxSearchLines) + " more lines; search for something narrower.)" lines = lines[:maxSearchLines] } for i, l := range lines { lines[i] = clip(l, 240) } return clip(strings.Join(lines, "\n"), maxToolOutput) + more, nil } // ReadFile shows a file from the default branch tip with line numbers, // or lists a directory. Bounded to maxReadLines from start. func (x *Index) ReadFile(ctx context.Context, repo, file string, start int) (string, error) { p, err := cleanPath(file) if err != nil { return "", err } dir, err := x.ready(ctx, repo) if err != nil { return "", err } sha, err := x.tip(ctx, dir) if err != nil { return "", err } // The entry's mode says what it is; a symlink is shown as its target // text and never followed, a submodule is not read. object := sha + "^{tree}" if p != "" { entry, err := x.git(ctx, dir, "ls-tree", "--full-tree", sha, "--", p) fields := strings.Fields(string(entry)) if err != nil || len(fields) < 4 { return "No such file.", nil } switch fields[0] { case "040000": case "120000": return "A symbolic link (not followed).", nil case "160000": return "A submodule (not read).", nil } object = fields[2] } kind, err := x.git(ctx, dir, "cat-file", "-t", object) if err != nil { return "No such file.", nil } if strings.TrimSpace(string(kind)) == "tree" { out, err := x.git(ctx, dir, "ls-tree", "--name-only", object) if err != nil { return "", err } return clip(string(out), maxToolOutput), nil } size, err := x.git(ctx, dir, "cat-file", "-s", object) if n, _ := strconv.Atoi(strings.TrimSpace(string(size))); err != nil || n > readLimit { return "The file is too large to read here.", nil } // cat-file blob: raw object bytes, no textconv or filters. out, err := x.git(ctx, dir, "cat-file", "blob", object) if err != nil { return "", err } if bytes.IndexByte(out[:min(len(out), 8000)], 0) >= 0 { return "Binary file.", nil } return numberedLines(out, start), nil } // numberedLines is a read: up to maxReadLines lines from start (1-based), // each numbered and clipped, and how to read on. func numberedLines(out []byte, start int) string { lines := strings.Split(string(out), "\n") start = max(start, 1) if start > len(lines) { return "The file has " + strconv.Itoa(len(lines)) + " lines." } end := min(len(lines), start-1+maxReadLines) var b strings.Builder for i := start - 1; i < end; i++ { b.WriteString(strconv.Itoa(i+1) + "\t" + clip(lines[i], 400) + "\n") } if end < len(lines) { b.WriteString("(" + strconv.Itoa(len(lines)-end) + " more lines; read again with start " + strconv.Itoa(end+1) + ".)\n") } return clip(b.String(), maxToolOutput) } // ready makes sure the index has a clone of repo to read. An empty // repository has nothing to read (ErrEmptyRepo). func (x *Index) ready(ctx context.Context, repo string) (string, error) { catalog := x.Catalog() if slices.ContainsFunc(catalog, func(e wire.RepoInfo) bool { return e.Repo == repo && e.Empty }) { return "", ErrEmptyRepo } dir := x.Clones.Path(repo) if _, err := os.Stat(dir); err == nil { return dir, nil } for _, e := range catalog { if e.Repo == repo { return dir, x.Clones.Shallow(ctx, repo, e.DefaultBranch) } } return "", errReadPath } // isPrintableName keeps only names a person would type. func isPrintableName(s string) bool { for _, r := range s { if !unicode.IsPrint(r) { return false } } return true }