// Package atomize is the app-side client of the Atomization Service (§5.1) // plus the coefficient validation/normalization rules. package atomize import ( "context" "errors" "fmt" "math" "net/http" "time" "bountyboard/internal/extsvc" ) type Attachment struct { Name string `json:"name"` URL string `json:"url"` MimeType string `json:"mimeType"` } type Constraints struct { MinTasks int `json:"minTasks,omitempty"` MaxTasks int `json:"maxTasks,omitempty"` } type AtomizeRequest struct { TaskID string `json:"taskId"` Title string `json:"title"` Description string `json:"description"` AcceptanceCriteria []string `json:"acceptanceCriteria"` Attachments []Attachment `json:"attachments"` Links []string `json:"links"` SubdivisionNote string `json:"subdivisionNote,omitempty"` Constraints *Constraints `json:"constraints,omitempty"` // CustomerID / CustomerName describe the project the ticket belongs to. // The §5.1 service ignores them; the Anypreta backend requires them to // build its mandatory `system` object. CustomerID string `json:"customerId,omitempty"` CustomerName string `json:"customerName,omitempty"` } type ExtendRequest struct { TaskID string `json:"taskId"` Title string `json:"title"` Description string `json:"description"` AcceptanceCriteria []string `json:"acceptanceCriteria"` Attachments []Attachment `json:"attachments"` Links []string `json:"links"` ExtensionNote string `json:"extensionNote"` } type SubTask struct { Title string `json:"title"` Description string `json:"description"` AcceptanceCriteria []string `json:"acceptanceCriteria"` EffortCoefficient float64 `json:"effortCoefficient"` } type AtomizeResponse struct { Tasks []SubTask `json:"tasks"` Model string `json:"model,omitempty"` Notes string `json:"notes,omitempty"` } type ExtendResponse struct { Task SubTask `json:"task"` Model string `json:"model,omitempty"` Notes string `json:"notes,omitempty"` } // ErrBadCoefficients is the 502-class rejection when the service returns // coefficients we are not willing to repair (§5.1). var ErrBadCoefficients = errors.New("atomizer returned invalid effort coefficients") type Client struct { c *extsvc.Client // remote, when set, serves Atomize from the Anypreta Issue Atomizer // instead of the §5.1 service. Extend and Summarize have no counterpart // there and always go to c. See anypreta.go. remote *remote } // New builds the client. baseURL is resolved per call so the admin settings // override applies without restart. func New(baseURL func() string, token string, timeout time.Duration) *Client { return &Client{c: extsvc.NewClient("atomizer", baseURL, token, timeout)} } // UseRemote routes Atomize to the Anypreta Issue Atomizer at baseURL. func (a *Client) UseRemote(baseURL, apiKey string, timeout time.Duration) { a.remote = newRemote(baseURL, apiKey, timeout) } // RemoteEnabled reports whether Subdivide is served by the Anypreta backend. func (a *Client) RemoteEnabled() bool { return a.remote != nil } func (a *Client) BreakerState() string { if a.remote != nil { if s := a.remote.c.BreakerState(); s != "closed" { return s } } return a.c.BreakerState() } // Healthy probes every backend an atomization can touch, so readiness and the // admin service panel go degraded if either half is down. func (a *Client) Healthy(ctx context.Context) error { if err := a.c.Healthy(ctx); err != nil { return err } if a.remote != nil { if err := a.remote.c.Healthy(ctx); err != nil { return fmt.Errorf("anypreta atomizer: %w", err) } } return nil } // Atomize calls POST /v1/atomize and applies the §5.1 contract: coefficients // must sum to 1 ± 0.001; a deviation ≤ 0.05 is defensively renormalized, // anything worse is rejected as a service error. With a remote backend // configured the call is served by the Anypreta API instead, which normalizes // its own feature estimations. func (a *Client) Atomize(ctx context.Context, req AtomizeRequest) (*AtomizeResponse, error) { if a.remote != nil { return a.remote.Atomize(ctx, req) } var resp AtomizeResponse if err := a.c.Call(ctx, http.MethodPost, "/v1/atomize", req, &resp); err != nil { return nil, err } if len(resp.Tasks) == 0 { return nil, fmt.Errorf("%w: empty task list", ErrBadCoefficients) } coeffs := make([]float64, len(resp.Tasks)) for i, t := range resp.Tasks { coeffs[i] = t.EffortCoefficient } normalized, err := NormalizeCoefficients(coeffs) if err != nil { return nil, err } for i := range resp.Tasks { resp.Tasks[i].EffortCoefficient = normalized[i] } return &resp, nil } // Extend calls POST /v1/extend. The sibling coefficient is relative to the // source task and may exceed 1 up to 2.0 (§5.1). func (a *Client) Extend(ctx context.Context, req ExtendRequest) (*ExtendResponse, error) { var resp ExtendResponse if err := a.c.Call(ctx, http.MethodPost, "/v1/extend", req, &resp); err != nil { return nil, err } c := resp.Task.EffortCoefficient if c <= 0 || c > 2.0 || math.IsNaN(c) { return nil, fmt.Errorf("%w: extension coefficient %v outside (0, 2]", ErrBadCoefficients, c) } return &resp, nil } // NormalizeCoefficients enforces the §5.1 sum contract. Each coefficient // must be in (0, 1]; the sum must be 1 ± 0.001 (accepted as-is) or within // ± 0.05 (renormalized proportionally, then rounded to 4 decimals with the // remainder folded into the largest entry so the sum is exactly 1). func NormalizeCoefficients(coeffs []float64) ([]float64, error) { if len(coeffs) == 0 { return nil, fmt.Errorf("%w: empty", ErrBadCoefficients) } sum := 0.0 for _, c := range coeffs { if math.IsNaN(c) || c <= 0 || c > 1 { return nil, fmt.Errorf("%w: coefficient %v outside (0, 1]", ErrBadCoefficients, c) } sum += c } if math.Abs(sum-1) > 0.05 { return nil, fmt.Errorf("%w: sum %.4f deviates more than 0.05 from 1", ErrBadCoefficients, sum) } out := make([]float64, len(coeffs)) largest := 0 total := 0.0 for i, c := range coeffs { out[i] = math.Round(c/sum*10000) / 10000 total += out[i] if out[i] > out[largest] { largest = i } } out[largest] = math.Round((out[largest]+1-total)*10000) / 10000 return out, nil }