// Package gitea implements capture.IssueTracker against a Gitea instance // over its REST API. It is the new outbound dependency the brain server // gains for the capture capability (#49c/#52): the server otherwise does // brain-local file ops only. // // Owner is hard-coded to the operator and never taken from caller input. // The API token is read once at construction, held in the struct, and // never logged or placed in argv — it travels only in the Authorization // header of outbound requests (AGENTS.md secret-handling). package gitea import ( "bytes" "context" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "strings" "time" "github.com/mathiasbq/hyperguild/ingestion/internal/capture" ) // owner is the fixed repository owner for every ticket operation. It is a // constant, not a parameter, so a caller can never redirect a write to // another owner's repo. const owner = "mathias" // Client is a Gitea REST API IssueTracker. type Client struct { baseURL string token string http *http.Client } // New constructs a Client. It returns nil when either baseURL or token is // empty, so callers can treat missing config as "tracker disabled" with a // single nil check (mirrors embed.New). func New(baseURL, token string) *Client { if baseURL == "" || token == "" { return nil } return &Client{ baseURL: strings.TrimRight(baseURL, "/"), token: token, http: &http.Client{Timeout: 15 * time.Second}, } } // issueResponse is the subset of a Gitea issue/comment payload we read. type issueResponse struct { Number int `json:"number"` HTMLURL string `json:"html_url"` } // CreateIssue opens a new issue under the fixed owner. func (c *Client) CreateIssue(ctx context.Context, repo, title, body string) (capture.IssueRef, error) { var out issueResponse if err := c.do(ctx, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/issues", owner, repo), map[string]any{"title": title, "body": body}, &out); err != nil { return capture.IssueRef{}, err } return capture.IssueRef{Repo: repo, Number: out.Number, URL: out.HTMLURL}, nil } // CommentIssue posts a comment on an existing issue. func (c *Client) CommentIssue(ctx context.Context, repo string, number int, body string) (capture.IssueRef, error) { var out issueResponse if err := c.do(ctx, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments", owner, repo, number), map[string]any{"body": body}, &out); err != nil { return capture.IssueRef{}, err } return capture.IssueRef{Repo: repo, Number: number, URL: out.HTMLURL}, nil } // CloseIssue closes an issue, first posting a closing comment when one is // given (empty comment ⇒ close only). func (c *Client) CloseIssue(ctx context.Context, repo string, number int, comment string) (capture.IssueRef, error) { if strings.TrimSpace(comment) != "" { if _, err := c.CommentIssue(ctx, repo, number, comment); err != nil { return capture.IssueRef{}, err } } var out issueResponse if err := c.do(ctx, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", owner, repo, number), map[string]any{"state": "closed"}, &out); err != nil { return capture.IssueRef{}, err } return capture.IssueRef{Repo: repo, Number: number, URL: out.HTMLURL}, nil } // WriteFile creates or updates a file in repo at path via the Gitea // contents API — the SummaryWriter port (#66). It upserts: a GET resolves // the current blob sha (if any) so an existing file is updated rather than // rejected (the richer-fidelity-supersedes rule for re-captured sessions). // Owner is the fixed const, like every other call. func (c *Client) WriteFile(ctx context.Context, repo, path, content string) error { cpath := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", owner, repo, path) sha, err := c.fileSHA(ctx, cpath) if err != nil { return err } payload := map[string]any{ "message": "capture: " + path, "content": base64.StdEncoding.EncodeToString([]byte(content)), } if sha != "" { payload["sha"] = sha // update in place } status, body, err := c.request(ctx, http.MethodPut, cpath, payload) if err != nil { return err } if status < 200 || status >= 300 { return fmt.Errorf("gitea PUT %s: status %d: %s", cpath, status, strings.TrimSpace(string(body))) } return nil } // fileSHA returns the current blob sha for a contents path, or "" when the // file does not exist (404). Any other non-2xx is an error. func (c *Client) fileSHA(ctx context.Context, cpath string) (string, error) { status, body, err := c.request(ctx, http.MethodGet, cpath, nil) if err != nil { return "", err } if status == http.StatusNotFound { return "", nil } if status < 200 || status >= 300 { return "", fmt.Errorf("gitea GET %s: status %d: %s", cpath, status, strings.TrimSpace(string(body))) } var meta struct { SHA string `json:"sha"` } if err := json.Unmarshal(body, &meta); err != nil { return "", fmt.Errorf("gitea GET %s: decode: %w", cpath, err) } return meta.SHA, nil } // do performs a JSON request against the Gitea API and decodes a 2xx // response into out. Errors carry the status and a truncated body for // diagnosis but never the token. func (c *Client) do(ctx context.Context, method, path string, payload any, out *issueResponse) error { status, body, err := c.request(ctx, method, path, payload) if err != nil { return err } if status < 200 || status >= 300 { return fmt.Errorf("gitea %s %s: status %d: %s", method, path, status, strings.TrimSpace(string(body))) } if out != nil && len(body) > 0 { if err := json.Unmarshal(body, out); err != nil { return fmt.Errorf("gitea %s %s: decode response: %w", method, path, err) } } return nil } // request is the shared HTTP path: marshals an optional JSON payload, // attaches auth (token only ever in the header), and returns the status + // body so callers can branch on status (e.g. 404) without it being an // error. Never logs the token. func (c *Client) request(ctx context.Context, method, path string, payload any) (int, []byte, error) { var reader io.Reader if payload != nil { reqBody, err := json.Marshal(payload) if err != nil { return 0, nil, fmt.Errorf("marshal request: %w", err) } reader = bytes.NewReader(reqBody) } req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader) if err != nil { return 0, nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "token "+c.token) resp, err := c.http.Do(req) if err != nil { return 0, nil, fmt.Errorf("gitea %s %s: %w", method, path, err) } defer func() { _ = resp.Body.Close() }() body, _ := io.ReadAll(io.LimitReader(resp.Body, 8192)) return resp.StatusCode, body, nil }