diff --git a/README.md b/README.md index 1e5cd54..58f9d31 100644 --- a/README.md +++ b/README.md @@ -56,8 +56,9 @@ Run the server with `go run ./cmd/server --static-dir web/dist`. Configure: - `PLATFORM_API_URL`, `PLATFORM_PROJECT_ID`, and the platform OIDC identity settings. - `TRACKER_DATABASE_URL` (or `DATABASE_URL`) for PostgreSQL. `TRACKER_DEV_SEED=1` enables - development seed data on an empty database: 40 issues, three closed one-week sprints - with 18/21/24-point velocities, an active two-week sprint, and a planned sprint. + development seed data on an empty database: 42 issues, three closed one-week sprints + with 18/21/24-point velocities, an active two-week sprint, a planned sprint, and + four agents with live/stalled runs, review requests, answers and mentions. - `TRACKER_PUBLIC_URL` for the HTTPS browser origin. - `TRACKER_DIRECTORY_URL` and `TRACKER_DIRECTORY_PUBLIC_URL` for optional Directory links. - `TRACKER_STATIC_DIR` or `--static-dir` to override `/srv/tracker`. @@ -90,11 +91,60 @@ The same 401 expires the edge's session cookies for this host real sign-in and receives a newly minted token instead of replaying the refused one. The SSO session and other apps' sessions are not touched. -Scripts and agents use an Access Key instead of a browser session: create a key -in the `tracker` space (`tracker:read`, `tracker:write`), exchange it with -`apth access-keys exchange`, and send the assertion as the bearer. The key acts -as its user with the Viewer role. The rules are in -[`design/API.md`](design/API.md#access-keys-v0111). +Scripts use an Access Key instead of a browser session: create a key in the +`tracker` space (`tracker:read`, `tracker:write`), exchange it with +`apth access-keys exchange`, and send the assertion as the bearer. User-subject +keys act as their user with the Viewer role. External-subject keys act as an +active registered agent whose immutable handle equals the subject. +The rules are in [`design/API.md`](design/API.md#access-keys-v0111). + +### Agent protocol (0.1.13) + +An Admin registers agents through `POST /api/tracker/v1/agents`, with a handle, +display name, description and accountable person owner. Keys are issued and +revoked by the platform, never by Tracker. Disabling an agent rejects all its +keys, cancels its non-terminal runs and withdraws its open requests. Names and +owners may change; handles cannot. Existing issue attribution is not rewritten. + +Agents poll `/inbox` and `/events`. Initialize the event cursor without `after`, +then poll with `after=next`; sequence allocation and the represented write +commit together. Inbox assignments include Backlog and the agent's own live +run, which it should resume. A run has a ten-minute lease; stalled runs cannot +heartbeat or finish. A new start closes the expired run and its requests. + +Completion defaults to `review`: successful finish opens a review to the +delegator (else owner); the person's approval completes the issue and updates +the sprint ledger. Admins may set `agentCompletion: "direct"` on the workspace +to allow agents to set completed statuses themselves. Finishing a run alone +never changes issue status. Agents may edit fields as assignee or reporter; +comments, attachments and questions/approvals can involve any issue. + +`GET /api/tracker/v1/agent-guide` serves the full protocol as Markdown; its route +inventory uses the handler registration table. The public `openapi.json` includes +all agent shapes and routes. Mentions currently resolve registered `@handle` +agents only, not Directory people. Acknowledge answers by request ID and mentions +by comment ID through `/inbox/ack`; retained mentions preserve acknowledgement +when a comment is edited. + +For safe retries, all JSON/non-multipart POST routes accept `Idempotency-Key` +(1–128 characters). Responses, including handler errors, are stored for 24 hours +per actor and key, atomically with successful writes. Replay requires identical +method, URI, content type and body bytes; a different request returns 409. +Authentication failures are not cached. Multipart attachment upload is excluded. +Use a fresh key for each new heartbeat. `PATCH /issues/{id}` accepts +`expectedUpdatedAt` and returns 409 when it no longer matches. + +The real-server `hack/smoke.sh` also runs `hack/agents-smoke.sh` (signed assertion +fixture, isolated Postgres schema, no live services). With a disposable database: + +```sh +DATABASE_URL='postgres://postgres:pg@127.0.0.1:55443/postgres?sslmode=disable' \ + /home/vagrant/.codex/skills/serialize-vm-tests/scripts/serialize-vm-tests -- bash hack/smoke.sh +``` + +The smoke verifies the collaboration loop, gap-free events for every semantic +write, replay/conflicts, mention acknowledgement, disabling and direct completion. +Both smoke scripts remove their schema, temporary files and processes on exit. PostgreSQL integration tests are opt-in: they skip when both `BUILTIN_APPSERVER_TEST_DATABASE_URL` and `BUILDER_CONSOLE_TEST_DATABASE_URL` are unset. @@ -119,14 +169,14 @@ a required BuildKit secret, never through build arguments or committed files. ## Catalog and release -The next app release is **0.1.12**, also recorded in `web/package.json`. +The next app release is **0.1.13**, also recorded in `web/package.json`. `catalog/entry.yaml` carries no committed version: the first tag (`v0.1.0`) created `versions[]` with `ghcr.io/appthrust/tracker@sha256:`, stream `0.1`; later tags append at publication time. Do not add a version with an unbuilt or placeholder image digest. OpenAPI's `info.version` describes the API schema, not the app release. This repository has no hand-maintained changelog. -After the release prerequisites are available, push the SemVer tag `v0.1.12`. +After the release prerequisites are available, push the SemVer tag `v0.1.13`. The tag workflow: 1. Performs one multi-platform build on `ubuntu-24.04` for Linux amd64 and arm64, @@ -146,8 +196,8 @@ The tag workflow: Publication commands used by the workflow: ```sh -bun hack/publish-entry.ts submit --version 0.1.12 --digest sha256: -bun hack/publish-entry.ts await --version 0.1.12 --digest sha256: +bun hack/publish-entry.ts submit --version 0.1.13 --digest sha256: +bun hack/publish-entry.ts await --version 0.1.13 --digest sha256: ``` Writers are serialized by `tracker-catalog-publish`; the workflow is guarded to @@ -168,7 +218,7 @@ After publication, each estate's `AppCatalogSource` syncs the signed catalog. Install Issues from the Project Marketplace (Directory is an automatic dependency). Existing `follow` installations on stream `0.1` roll to the new version; `pinned` installations show `UpdateAvailable` and require an explicit -version update. Confirm the installation is Ready, `/releasez` reports `0.1.12`, +version update. Confirm the installation is Ready, `/releasez` reports `0.1.13`, the Project lists the `tracker` Access Key space as Ready, and an exchanged key reads `/api/tracker/v1/me`. These are release steps, not actions performed by a source-only version bump. diff --git a/cmd/server/internal/api/actors.go b/cmd/server/internal/api/actors.go new file mode 100644 index 0000000..6180303 --- /dev/null +++ b/cmd/server/internal/api/actors.go @@ -0,0 +1,165 @@ +package api + +import ( + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" +) + +type actorProjection struct { + people []*domain.Person + values []struct { + person *domain.Person + value map[string]any + } +} + +func responseActors(body any) actorProjection { + var p actorProjection + person := func(person *domain.Person) { + if person != nil { + p.people = append(p.people, person) + if person.Agent != nil { + p.people = append(p.people, &person.Agent.Owner) + } + } + } + run := func(run *domain.Run) { + if run != nil { + person(&run.Agent) + } + } + request := func(r *domain.Request) { + if r != nil { + person(&r.From) + person(r.To) + if r.Answer != nil { + person(&r.Answer.By) + } + } + } + comment := func(c *domain.Comment) { + if c != nil { + person(&c.Author) + for i := range c.Mentions { + person(&c.Mentions[i]) + } + } + } + issue := func(i *domain.IssueSummary) { + if i != nil { + person(&i.Reporter) + person(i.Assignee) + person(i.Delegator) + run(i.ActiveRun) + } + } + value := func(raw any) { + m, ok := raw.(map[string]any) + if !ok { + return + } + sub, ok := m["sub"].(string) + if !ok { + return + } + name, _ := m["name"].(string) + who := &domain.Person{Sub: sub, Name: name} + person(who) + p.values = append(p.values, struct { + person *domain.Person + value map[string]any + }{who, m}) + } + switch v := body.(type) { + case *meResponse: + person(&v.Person) + case *domain.Agent: + person(&v.Owner) + case items[domain.Agent]: + for i := range v.Items { + person(&v.Items[i].Owner) + } + case *domain.Issue: + issue(&v.IssueSummary) + case *store.Page: + for i := range v.Items { + issue(&v.Items[i]) + } + case *domain.Comment: + comment(v) + case *domain.Attachment: + person(&v.Uploader) + case *domain.Run: + run(v) + case items[domain.Run]: + for i := range v.Items { + run(&v.Items[i]) + } + case *domain.Request: + request(v) + case items[domain.Request]: + for i := range v.Items { + request(&v.Items[i]) + } + case items[domain.InboxItem]: + for i := range v.Items { + item := &v.Items[i] + request(item.Request) + comment(item.Comment) + issue(item.Issue) + } + case *store.EventPage: + for i := range v.Items { + person(&v.Items[i].Actor) + } + case *domain.View: + person(&v.Owner) + case *items[domain.View]: + for i := range v.Items { + person(&v.Items[i].Owner) + } + case *items[domain.TimelineItem]: + for i := range v.Items { + item := &v.Items[i] + comment(item.Comment) + run(item.Run) + request(item.Request) + if item.Activity != nil { + person(&item.Activity.Actor) + if item.Activity.Field == "assignee" || item.Activity.Field == "delegator" { + value(item.Activity.From) + value(item.Activity.To) + } + if item.Activity.Field == "attachment" { + for _, raw := range []any{item.Activity.From, item.Activity.To} { + if attachment, ok := raw.(map[string]any); ok { + value(attachment["uploader"]) + } + } + } + } + } + } + return p +} + +func (p actorProjection) apply() { + for _, ref := range p.values { + who, m := ref.person, ref.value + m["name"], m["kind"] = who.Name, domain.ActorKind(who.Sub) + if who.Agent != nil { + m["agent"] = who.Agent + } + if who.Email != "" { + m["email"] = who.Email + } + if who.AvatarURL != "" { + m["avatarUrl"] = who.AvatarURL + } else { + delete(m, "avatarUrl") + } + if who.ProfileURL != "" { + m["profileUrl"] = who.ProfileURL + } + } +} diff --git a/cmd/server/internal/api/agents.go b/cmd/server/internal/api/agents.go new file mode 100644 index 0000000..558132f --- /dev/null +++ b/cmd/server/internal/api/agents.go @@ -0,0 +1,188 @@ +package api + +import ( + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" + "strconv" +) + +func (a *API) agentList(s *request) (any, int, error) { + includeDisabled := false + if s.r.URL.Query().Has("includeDisabled") { + switch s.r.URL.Query().Get("includeDisabled") { + case "true": + includeDisabled = true + case "false": + default: + return nil, 0, invalid("includeDisabled must be true or false") + } + } + list, err := s.tx.Agents(includeDisabled) + return items[domain.Agent]{Items: list}, 200, err +} + +func (a *API) agentCreate(s *request) (any, int, error) { + if err := admin(s); err != nil { + return nil, 0, err + } + var input store.AgentCreate + if err := decode(s, &input); err != nil { + return nil, 0, err + } + if domain.ActorKind(input.OwnerSub) != "person" { + return nil, 0, invalid("An agent owner must be a person") + } + owner, err := a.assignee(s, &input.OwnerSub) + if err != nil { + return nil, 0, err + } + item, err := s.tx.CreateAgent(input, *owner, s.actor) + return &item, 201, err +} + +func (a *API) inbox(s *request) (any, int, error) { + list, err := s.tx.Inbox(s.actor) + return items[domain.InboxItem]{Items: list}, 200, err +} + +func (a *API) runStart(s *request) (any, int, error) { + var input store.RunStart + if err := decode(s, &input); err != nil { + return nil, 0, err + } + item, err := s.tx.StartRun(s.r.PathValue("id"), input, s.actor) + return &item, 201, err +} + +func (a *API) runList(s *request) (any, int, error) { + list, err := s.tx.Runs(s.r.PathValue("id")) + return items[domain.Run]{Items: list}, 200, err +} + +func (a *API) runHeartbeat(s *request) (any, int, error) { + var input struct { + Note *string `json:"note"` + } + if err := decode(s, &input); err != nil { + return nil, 0, err + } + item, err := s.tx.HeartbeatRun(s.r.PathValue("id"), input.Note, s.actor) + return &item, 200, err +} + +func (a *API) runFinish(s *request) (any, int, error) { + var input struct { + Outcome string `json:"outcome"` + Summary *string `json:"summary"` + Links []domain.RunLink `json:"links"` + } + if err := decode(s, &input); err != nil { + return nil, 0, err + } + if input.Summary == nil { + return nil, 0, invalid("Summary is required") + } + item, err := s.tx.FinishRun(s.r.PathValue("id"), store.RunFinish{Outcome: input.Outcome, Summary: *input.Summary, Links: input.Links}, s.actor) + return &item, 200, err +} + +func (a *API) runCancel(s *request) (any, int, error) { + item, err := s.tx.CancelRun(s.r.PathValue("id"), s.actor) + return &item, 200, err +} + +func (a *API) requestCreate(s *request) (any, int, error) { + var input store.RequestCreate + if err := decode(s, &input, "to", "runId"); err != nil { + return nil, 0, err + } + to, err := a.assignee(s, input.To.Value) + if err != nil { + return nil, 0, err + } + item, err := s.tx.CreateRequest(s.r.PathValue("id"), input, s.actor, to) + return &item, 201, err +} + +func (a *API) requestAnswer(s *request) (any, int, error) { + var input store.RequestAnswer + if err := decode(s, &input, "option"); err != nil { + return nil, 0, err + } + item, err := s.tx.AnswerRequest(s.r.PathValue("id"), input, s.actor) + return &item, 200, err +} + +func (a *API) agentPatch(s *request) (any, int, error) { + if err := admin(s); err != nil { + return nil, 0, err + } + var input store.AgentPatch + if err := decode(s, &input); err != nil { + return nil, 0, err + } + if input.OwnerSub != nil && domain.ActorKind(*input.OwnerSub) != "person" { + return nil, 0, invalid("An agent owner must be a person") + } + owner, err := a.assignee(s, input.OwnerSub) + if err != nil { + return nil, 0, err + } + item, err := s.tx.PatchAgent(s.r.PathValue("id"), input, owner, s.actor) + return &item, 200, err +} + +func (a *API) inboxAck(s *request) (any, int, error) { + var input store.InboxAck + if err := decode(s, &input); err != nil { + return nil, 0, err + } + return nil, 204, s.tx.AckInbox(input, s.actor) +} + +func (a *API) events(s *request) (any, int, error) { + q := s.r.URL.Query() + var after *int64 + limit := 100 + if q.Has("after") { + value, err := strconv.ParseInt(q.Get("after"), 10, 64) + if err != nil || value < 0 { + return nil, 0, invalid("After must be a nonnegative integer") + } + after = &value + } + if q.Has("limit") { + value, err := strconv.Atoi(q.Get("limit")) + if err != nil || value < 1 || value > 500 { + return nil, 0, invalid("Limit must be between 1 and 500") + } + limit = value + } + page, err := s.tx.Events(after, limit) + return &page, 200, err +} + +func (a *API) runGet(s *request) (any, int, error) { + item, err := s.tx.Run(s.r.PathValue("id")) + return &item, 200, err +} + +func (a *API) requestGet(s *request) (any, int, error) { + item, err := s.tx.Request(s.r.PathValue("id")) + return &item, 200, err +} + +func (a *API) requestList(s *request) (any, int, error) { + q := s.r.URL.Query() + to := q.Get("to") + if to == "me" { + to = s.actor.Sub + } + list, err := s.tx.Requests(store.RequestFilter{State: q.Get("state"), To: to, Issue: q.Get("issue")}) + return items[domain.Request]{Items: list}, 200, err +} + +func (a *API) requestWithdraw(s *request) (any, int, error) { + item, err := s.tx.WithdrawRequest(s.r.PathValue("id"), s.actor) + return &item, 200, err +} diff --git a/cmd/server/internal/api/agents_test.go b/cmd/server/internal/api/agents_test.go new file mode 100644 index 0000000..01a9b32 --- /dev/null +++ b/cmd/server/internal/api/agents_test.go @@ -0,0 +1,155 @@ +package api + +import ( + "testing" + "time" + + "github.com/appthrust/appserver-go/accesskey" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" + "github.com/stretchr/testify/require" +) + +func TestExternalKeyPreservesProjectScopeAndViewerBoundary(t *testing.T) { + for _, tc := range []struct { + name, project, subject string + scopes []string + mutation bool + code int + }{ + {"external", "pj", "external:poc-astra", []string{scopeRead}, false, 200}, + {"user", "pj", "user:pat", []string{scopeWrite}, true, 200}, + {"project", "other", "external:poc-astra", []string{scopeRead}, false, 401}, + {"scope", "pj", "external:poc-astra", []string{scopeRead}, true, 403}, + {"component", "pj", "component:web", []string{scopeRead}, false, 403}, + } { + t.Run(tc.name, func(t *testing.T) { + actor, err := keyActor(accesskey.Principal{Project: tc.project, Subject: tc.subject, Scopes: tc.scopes}, "pj", tc.mutation) + if tc.code == 200 { + require.NoError(t, err) + require.Equal(t, "Viewer", actor.Role) + require.True(t, actor.Key) + require.False(t, domain.Can(actor, domain.ManageWorkspace, domain.Target{})) + } else { + require.Error(t, err) + } + }) + } +} + +func TestAgentLeaseWaitingAndDisabledBoundaries(t *testing.T) { + h := newHarness(t) + now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC) + h.database.Now = func() time.Time { return now } + h.database.RunLease = time.Minute + a := call[domain.Agent](h, "admin", "POST", "/agents", store.AgentCreate{Handle: "astra", Name: "Astra", OwnerSub: "owner"}, 201) + sub := "agent:" + a.ID + statuses := call[items[domain.Status]](h, "admin", "GET", "/statuses", nil, 200) + unstarted := "" + for _, status := range statuses.Items { + if status.Category == "unstarted" { + unstarted = status.ID + break + } + } + assigned := call[domain.Issue](h, "admin", "POST", "/issues", map[string]string{"title": "Delegated", "type": "task", "assigneeSub": sub, "statusId": unstarted}, 201) + require.Equal(t, "admin", assigned.Delegator.Sub) + person := domain.Actor{Person: domain.Person{Sub: "admin", Name: "admin"}, Kind: "person", Role: "Admin"} + var run domain.Run + var first, second domain.Request + write := func(fn func(*store.Tx) error) { + require.NoError(t, h.database.InWorkspace(t.Context(), "pj-test", true, fn)) + } + write(func(tx *store.Tx) error { + actor, err := tx.AgentBySubject("astra") + require.NoError(t, err) + run, err = tx.StartRun(assigned.ID, store.RunStart{}, actor) + require.NoError(t, err) + input := store.RequestCreate{Kind: "question", Title: "Decision?", RunID: &run.ID} + first, err = tx.CreateRequest(assigned.ID, input, actor, nil) + require.NoError(t, err) + second, err = tx.CreateRequest(assigned.ID, input, actor, nil) + require.NoError(t, err) + _, err = tx.AnswerRequest(first.ID, store.RequestAnswer{Body: "First"}, person) + require.NoError(t, err) + current, err := tx.Run(run.ID) + require.NoError(t, err) + require.Equal(t, "waiting", current.State, "one open request still holds the run") + _, err = tx.AnswerRequest(second.ID, store.RequestAnswer{Body: "Second"}, person) + require.NoError(t, err) + current, err = tx.Run(run.ID) + require.NoError(t, err) + require.Equal(t, "running", current.State) + first, err = tx.CreateRequest(assigned.ID, input, actor, nil) + require.NoError(t, err) + inbox, err := tx.Inbox(actor) + require.NoError(t, err) + for _, item := range inbox { + require.NotEqual(t, "assignment", item.Kind, "waiting on a live request is not actionable") + } + return nil + }) + now = now.Add(time.Minute) + write(func(tx *store.Tx) error { + current, err := tx.Run(run.ID) + require.NoError(t, err) + require.Equal(t, "waiting", current.State, "lease equality is still live") + return nil + }) + now = now.Add(time.Microsecond) + write(func(tx *store.Tx) error { + actor, err := tx.AgentBySubject("astra") + require.NoError(t, err) + current, err := tx.Run(run.ID) + require.NoError(t, err) + require.Equal(t, "stalled", current.State) + inbox, err := tx.Inbox(actor) + require.NoError(t, err) + assignments := 0 + for _, item := range inbox { + if item.Kind == "assignment" && item.Issue.ID == assigned.ID { + assignments++ + } + } + require.Equal(t, 1, assignments, "an expired run and its pending request must not hide recovery work") + _, err = tx.HeartbeatRun(run.ID, nil, actor) + require.ErrorContains(t, err, "lease has expired") + _, err = tx.FinishRun(run.ID, store.RunFinish{Outcome: "succeeded"}, actor) + require.ErrorContains(t, err, "lease has expired") + next, err := tx.StartRun(assigned.ID, store.RunStart{}, actor) + require.NoError(t, err) + old, err := tx.Run(run.ID) + require.NoError(t, err) + require.Equal(t, "failed", old.State) + require.Equal(t, "lease_expired", *old.Reason) + _, err = tx.CancelRun(next.ID, person) + require.NoError(t, err) + next, err = tx.StartRun(assigned.ID, store.RunStart{}, actor) + require.NoError(t, err) + pending, err := tx.CreateRequest(assigned.ID, store.RequestCreate{Kind: "question", Title: "Before reassignment", RunID: &next.ID}, actor, nil) + require.NoError(t, err) + _, err = tx.PatchIssue(assigned.ID, store.IssuePatch{AssigneeSub: store.Field[string]{Present: true}}, person.Person, nil) + require.NoError(t, err) + canceled, err := tx.Run(next.ID) + require.NoError(t, err) + require.Equal(t, "canceled", canceled.State) + require.Equal(t, "reassigned", *canceled.Reason) + withdrawn, err := tx.Request(pending.ID) + require.NoError(t, err) + require.Equal(t, "withdrawn", withdrawn.State) + return nil + }) + cleared := call[domain.Issue](h, "admin", "PATCH", "/issues/"+assigned.ID, map[string]any{"assigneeSub": nil}, 200) + require.Nil(t, cleared.Delegator) + write(func(tx *store.Tx) error { return tx.Exec(`UPDATE tracker_agent SET disabled=true WHERE id=$1`, a.ID) }) + write(func(tx *store.Tx) error { + _, err := tx.AgentBySubject("astra") + require.ErrorContains(t, err, "active registered agent") + return nil + }) + for _, target := range []string{sub, "agent:unknown"} { + response := call[map[string]any](h, "admin", "PATCH", "/issues/"+assigned.ID, map[string]string{"assigneeSub": target}, 400) + issues := response["issues"].([]any) + require.Equal(t, "assigneeSub", issues[0].(map[string]any)["path"]) + } +} diff --git a/cmd/server/internal/api/api.go b/cmd/server/internal/api/api.go index 1d7edd6..46f9fcb 100644 --- a/cmd/server/internal/api/api.go +++ b/cmd/server/internal/api/api.go @@ -40,49 +40,9 @@ type endpoint func(*request) (any, int, error) func New(database *store.Store, auth *identity.Authenticator, upstream *platformclient.Client, people *directory.Client, workspace string) http.Handler { a := &API{store: database, identity: auth, platform: upstream, directory: people, workspace: workspace, mux: http.NewServeMux()} a.mux.HandleFunc("GET /api/tracker/v1/openapi.json", a.openapi) - a.route("GET /me", false, true, a.me) - a.route("GET /workspace", false, false, a.workspaceGet) - a.route("PATCH /workspace", true, true, a.workspacePatch) - a.route("GET /statuses", false, false, a.statusList) - a.route("POST /statuses", true, true, a.statusCreate) - a.route("PATCH /statuses/{id}", true, true, a.statusPatch) - a.route("DELETE /statuses/{id}", true, true, a.statusDelete) - a.route("PUT /statuses/order", true, true, a.statusOrder) - a.route("GET /labels", false, false, a.labelList) - a.route("POST /labels", true, true, a.labelCreate) - a.route("PATCH /labels/{id}", true, true, a.labelPatch) - a.route("DELETE /labels/{id}", true, true, a.labelDelete) - a.route("GET /projects", false, false, a.projectList) - a.route("POST /projects", true, false, a.projectCreate) - a.route("GET /projects/{id}", false, false, a.projectGet) - a.route("PATCH /projects/{id}", true, true, a.projectPatch) - a.route("DELETE /projects/{id}", true, true, a.projectDelete) - a.route("GET /sprints", false, false, a.sprintList) - a.route("POST /sprints", true, false, a.sprintCreate) - a.route("GET /sprints/{id}", false, false, a.sprintGet) - a.route("PATCH /sprints/{id}", true, false, a.sprintPatch) - a.route("POST /sprints/{id}/start", true, false, a.sprintStart) - a.route("POST /sprints/{id}/close", true, false, a.sprintClose) - a.route("DELETE /sprints/{id}", true, true, a.sprintDelete) - a.route("GET /sprints/{id}/burndown", false, false, a.sprintBurndown) - a.route("GET /velocity", false, false, a.velocity) - a.route("GET /issues", false, false, a.issueList) - a.route("POST /issues", true, false, a.issueCreate) - a.route("GET /issues/{id}", false, false, a.issueGet) - a.route("PATCH /issues/{id}", true, false, a.issuePatch) - a.route("DELETE /issues/{id}", true, true, a.issueDelete) - a.route("GET /issues/{id}/timeline", false, false, a.timeline) - a.route("POST /issues/{id}/comments", true, false, a.commentCreate) - a.route("PATCH /comments/{id}", true, false, a.commentPatch) - a.route("DELETE /comments/{id}", true, true, a.commentDelete) - a.route("POST /issues/{id}/attachments", true, false, a.attachmentCreate) - a.route("GET /attachments/{id}", false, false, a.attachmentGet) - a.route("DELETE /attachments/{id}", true, true, a.attachmentDelete) - a.route("GET /views", false, false, a.viewList) - a.route("POST /views", true, true, a.viewCreate) - a.route("PATCH /views/{id}", true, true, a.viewPatch) - a.route("DELETE /views/{id}", true, true, a.viewDelete) - a.route("GET /people", false, false, a.people) + for _, route := range a.routes() { + a.route(route.pattern, route.mutation, route.roles, route.handler) + } a.mux.HandleFunc("GET /api/tracker/v1/people/{id}/avatar", a.avatar) a.mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { httpx.WriteError(w, httpx.NotFound(), "tracker") }) return a @@ -126,7 +86,7 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { } } else { s.bearer = r.Header.Get("Authorization") - s.actor = domain.Actor{Person: domain.Person{Sub: claims.Principal.Subject, Name: claims.Name, Email: claims.Email}, Role: "Viewer"} + s.actor = domain.Actor{Person: domain.Person{Sub: claims.Principal.Subject, Name: claims.Name, Email: claims.Email}, Role: "Viewer", Kind: "person"} if s.actor.Name == "" { s.actor.Name = s.actor.Sub } @@ -148,11 +108,27 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { writeStoreError(w, err) return } + if key && s.actor.Kind == "agent" { + if err := a.store.Do(ctx, true, func(tx *store.Tx) error { + tx.WorkspaceID = a.workspace + return tx.ObserveAgent(s.actor.Sub) + }); err != nil { + writeStoreError(w, err) + return + } + } var body any var status int err := a.store.InWorkspace(ctx, a.workspace, mutation, func(tx *store.Tx) error { s.tx = tx - if key { + if key && s.actor.Kind == "agent" { + actor, err := tx.AgentBySubject(s.actor.Sub) + if err != nil { + return err + } + actor.Scopes = s.actor.Scopes + s.actor = actor + } else if key { name, err := tx.KnownName(s.actor.Sub) if err != nil { return err @@ -162,7 +138,7 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { } } var err error - body, status, err = fn(s) + body, status, err = a.execute(s, fn) return err }) if err != nil { @@ -177,6 +153,18 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { download.write(w) return } + if text, ok := body.(markdown); ok { + w.Header().Set("Content-Type", "text/markdown; charset=utf-8") + w.WriteHeader(status) + _, _ = io.WriteString(w, string(text)) + return + } + if replay, ok := body.(store.Replay); ok { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(replay.Status) + _, _ = w.Write(replay.Body) + return + } a.enrich(s, body) httpx.WriteJSON(w, status, body) }) diff --git a/cmd/server/internal/api/api_test.go b/cmd/server/internal/api/api_test.go index 59b55c2..92c1d9d 100644 --- a/cmd/server/internal/api/api_test.go +++ b/cmd/server/internal/api/api_test.go @@ -204,6 +204,18 @@ func TestOpenAPIRouteInventory(t *testing.T) { require.Contains(t, document.Paths[path], method, "%s %s", method, path) } } + registered := map[string]bool{"GET /openapi.json": true, "GET /people/{id}/avatar": true} + for _, route := range (&API{}).routes() { + require.NotContains(t, registered, route.pattern, "duplicate route") + registered[route.pattern] = true + method, path, _ := strings.Cut(route.pattern, " ") + require.Contains(t, document.Paths[path], strings.ToLower(method), route.pattern) + } + for path, methods := range document.Paths { + for method := range methods { + require.True(t, registered[strings.ToUpper(method)+" "+path], "unserved OpenAPI route: %s %s", method, path) + } + } require.Contains(t, document.Paths["/people/{id}/avatar"], "get") w := httptest.NewRecorder() Unavailable().ServeHTTP(w, httptest.NewRequest("GET", "/api/tracker/v1/openapi.json", nil)) diff --git a/cmd/server/internal/api/collaboration_test.go b/cmd/server/internal/api/collaboration_test.go new file mode 100644 index 0000000..ade7f1a --- /dev/null +++ b/cmd/server/internal/api/collaboration_test.go @@ -0,0 +1,209 @@ +package api + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/appthrust/appserver-go/accesskey" + "github.com/appthrust/appserver-go/appserver/identity" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" + "github.com/stretchr/testify/require" +) + +func rawCall(t *testing.T, h *harness, bearer, method, path, key string, body []byte, status int) []byte { + t.Helper() + r, err := http.NewRequest(method, h.server.URL+"/api/tracker/v1"+path, bytes.NewReader(body)) + require.NoError(t, err) + r.Header.Set("Authorization", bearer) + r.Header.Set("Content-Type", "application/json") + if key != "" { + r.Header.Set("Idempotency-Key", key) + } + response, err := h.server.Client().Do(r) + require.NoError(t, err) + defer response.Body.Close() + data, err := io.ReadAll(response.Body) + require.NoError(t, err) + require.Equal(t, status, response.StatusCode, string(data)) + return data +} + +func TestPostIdempotencyReplaysStatusBodyAndExpires(t *testing.T) { + h := newHarness(t) + now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC) + h.database.Now = func() time.Time { return now } + bearer := "Bearer " + token("admin") + body := []byte(`{"title":"Exactly once","type":"task"}`) + first := rawCall(t, h, bearer, "POST", "/issues", "create", body, 201) + replayed := rawCall(t, h, bearer, "POST", "/issues", "create", body, 201) + require.Equal(t, first, replayed, "response bytes are replayed, not reconstructed") + var issue domain.Issue + require.NoError(t, json.Unmarshal(first, &issue)) + conflict := rawCall(t, h, bearer, "POST", "/issues", "create", []byte(`{"title":"Different","type":"task"}`), 409) + require.Contains(t, string(conflict), `"error":"conflict"`) + rawCall(t, h, bearer, "POST", "/issues/"+issue.ID+"/comments", "create", body, 409) + page := call[store.EventPage](h, "admin", "GET", "/events?after=0", nil, 200) + require.Len(t, page.Items, 1) + failure := rawCall(t, h, bearer, "POST", "/issues", "invalid", []byte(`{"type":"task"}`), 400) + require.Equal(t, failure, rawCall(t, h, bearer, "POST", "/issues", "invalid", []byte(`{"type":"task"}`), 400)) + rawCall(t, h, bearer, "POST", "/inbox/ack", "ack", []byte(`{}`), 204) + rawCall(t, h, bearer, "POST", "/inbox/ack", "ack", []byte(`{}`), 204) + rawCall(t, h, bearer, "POST", "/issues", strings.Repeat("x", 129), body, 400) + // Different actors do not share idempotency keys. + rawCall(t, h, "Bearer "+token("other"), "POST", "/issues", "create", body, 201) + now = now.Add(24 * time.Hour) + after := rawCall(t, h, bearer, "POST", "/issues", "create", body, 201) + require.NotEqual(t, first, after) + require.NoError(t, h.database.InWorkspace(t.Context(), "pj-test", false, func(tx *store.Tx) error { + var count int + require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT count(*) FROM tracker_idempotency WHERE workspace_id=$1`, "pj-test").Scan(&count)) + require.Equal(t, 1, count, "the next insert deletes expired rows opportunistically") + return nil + })) +} + +func TestExpectedUpdateAndMentionsOnCreateEditAck(t *testing.T) { + h := newHarness(t) + agent := call[domain.Agent](h, "admin", "POST", "/agents", map[string]string{"handle": "astra", "name": "Astra", "ownerSub": "admin"}, 201) + issue := call[domain.Issue](h, "admin", "POST", "/issues", map[string]string{"title": "Versioned", "type": "task"}, 201) + changed := call[domain.Issue](h, "admin", "PATCH", "/issues/"+issue.ID, map[string]any{"title": "Changed", "expectedUpdatedAt": issue.UpdatedAt}, 200) + require.NotEqual(t, issue.UpdatedAt, changed.UpdatedAt) + call[any](h, "admin", "PATCH", "/issues/"+issue.ID, map[string]any{"title": "Stale", "expectedUpdatedAt": issue.UpdatedAt}, 409) + comment := call[domain.Comment](h, "admin", "POST", "/issues/"+issue.ID+"/comments", map[string]string{"body": "@astra @astra and mail@astra.test"}, 201) + require.Len(t, comment.Mentions, 1) + require.Equal(t, agent.ID, comment.Mentions[0].Agent.ID) + require.NoError(t, h.database.InWorkspace(t.Context(), "pj-test", true, func(tx *store.Tx) error { + actor, err := tx.AgentBySubject("astra") + require.NoError(t, err) + inbox, err := tx.Inbox(actor) + require.NoError(t, err) + require.Len(t, inbox, 1) + require.Equal(t, "mention", inbox[0].Kind) + require.NoError(t, tx.AckInbox(store.InboxAck{Mentions: []string{comment.ID}}, domain.Actor{Person: domain.Person{Sub: "other"}})) + inbox, err = tx.Inbox(actor) + require.NoError(t, err) + require.Len(t, inbox, 1) + require.NoError(t, tx.AckInbox(store.InboxAck{Mentions: []string{comment.ID}}, actor)) + _, err = tx.PatchComment(comment.ID, "Still @astra", domain.Actor{Person: domain.Person{Sub: "admin"}}) + require.NoError(t, err) + inbox, err = tx.Inbox(actor) + require.NoError(t, err) + require.Empty(t, inbox, "editing a retained mention preserves acknowledgement") + _, err = tx.PatchComment(comment.ID, "No mention", domain.Actor{Person: domain.Person{Sub: "admin"}}) + require.NoError(t, err) + c, err := tx.Comment(comment.ID) + require.NoError(t, err) + require.Empty(t, c.Mentions) + _, err = tx.PatchComment(comment.ID, "Again @astra", domain.Actor{Person: domain.Person{Sub: "admin"}}) + require.NoError(t, err) + inbox, err = tx.Inbox(actor) + require.NoError(t, err) + require.Len(t, inbox, 1) + return nil + })) +} + +func TestExternalAgentRoutesAndLastSeen(t *testing.T) { + private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + signer := accesskey.NewES256Signer("agent-test", private) + jwks := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(signer.JWKS()) })) + t.Cleanup(jwks.Close) + issuer := accesskey.IssuerURL(jwks.URL) + h := newHarnessTrusting(t, identity.Trust{AccessIssuer: issuer, AccessAudience: "tracker"}) + now := time.Now().UTC().Truncate(time.Microsecond) + h.database.Now = func() time.Time { return now } + assertion := func(scopes ...string) string { + value, err := signer.Sign(accesskey.Claims{Issuer: issuer, Audience: "tracker", Project: "pj-test", KeyName: "ak-agent", Subject: accesskey.Subject{Kind: accesskey.SubjectExternal, ID: "astra"}, Scopes: scopes, JTI: "test", IssuedAt: time.Now(), ExpiresAt: time.Now().Add(time.Minute)}) + require.NoError(t, err) + return "Bearer " + value + } + bearer := assertion(scopeRead, scopeWrite) + rawCall(t, h, bearer, "GET", "/me", "", nil, 403) + agent := call[domain.Agent](h, "admin", "POST", "/agents", map[string]string{"handle": "astra", "name": "Astra", "ownerSub": "admin"}, 201) + for _, input := range []map[string]any{{"handle": "renamed"}, {"keySubject": "old"}, {"name": nil}} { + call[any](h, "admin", "PATCH", "/agents/"+agent.ID, input, 400) + } + me := rawCall(t, h, bearer, "GET", "/me", "", nil, 200) + require.Contains(t, string(me), `"kind":"agent"`) + require.Contains(t, string(me), `"scopes":["tracker:read","tracker:write"]`) + first := call[items[domain.Agent]](h, "admin", "GET", "/agents", nil, 200).Items[0] + require.Equal(t, now, *first.LastSeenAt) + now = now.Add(30 * time.Second) + rawCall(t, h, bearer, "GET", "/me", "", nil, 200) + second := call[items[domain.Agent]](h, "admin", "GET", "/agents", nil, 200).Items[0] + require.Equal(t, first.LastSeenAt, second.LastSeenAt) + now = now.Add(30 * time.Second) + rawCall(t, h, bearer, "GET", "/me", "", nil, 200) + third := call[items[domain.Agent]](h, "admin", "GET", "/agents", nil, 200).Items[0] + require.Equal(t, now, *third.LastSeenAt) + missing := rawCall(t, h, assertion(scopeRead), "POST", "/issues", "", []byte(`{"title":"No scope","type":"task"}`), 403) + require.Contains(t, string(missing), `"error":"insufficient_scope"`) + unrelated := call[domain.Issue](h, "admin", "POST", "/issues", map[string]string{"title": "Unrelated", "type": "task"}, 201) + rawCall(t, h, bearer, "PATCH", "/issues/"+unrelated.ID, "", []byte(`{"title":"Denied"}`), 403) + rawCall(t, h, bearer, "POST", "/issues/"+unrelated.ID+"/comments", "", []byte(`{"body":"Allowed discussion"}`), 201) + for _, to := range []string{``, `,"to":null`} { + data := rawCall(t, h, bearer, "POST", "/issues/"+unrelated.ID+"/requests", "", []byte(`{"kind":"question","title":"Question"`+to+`}`), 201) + var q domain.Request + require.NoError(t, json.Unmarshal(data, &q)) + if to == "" { + require.Equal(t, "admin", q.To.Sub) + } else { + require.Nil(t, q.To) + } + } + for _, route := range []struct{ method, path, body string }{ + {"PATCH", "/workspace", `{"agentCompletion":"direct"}`}, + {"POST", "/agents", `{}`}, {"POST", "/statuses", `{}`}, {"POST", "/labels", `{}`}, + {"DELETE", "/issues/" + unrelated.ID, ``}, + } { + rawCall(t, h, bearer, route.method, route.path, "", []byte(route.body), 403) + } + call[domain.Agent](h, "admin", "PATCH", "/agents/"+agent.ID, map[string]bool{"disabled": true}, 200) + rawCall(t, h, bearer, "GET", "/me", "", nil, 403) +} + +func TestAgentGuideAndOpenAPIShapes(t *testing.T) { + guide, status, err := (&API{}).agentGuide(nil) + require.NoError(t, err) + require.Equal(t, 200, status) + for _, route := range (&API{}).routes() { + if route.guide != "" { + require.Contains(t, string(guide.(markdown)), route.pattern) + } + } + var document struct { + Components struct{ Schemas map[string]map[string]any } + Paths map[string]map[string]map[string]any + } + require.NoError(t, json.Unmarshal(openapiDocument, &document)) + for _, name := range []string{"Actor", "Agent", "Run", "Request", "InboxItem", "Event", "EventPage", "InboxAck", "RunFinish", "RequestCreate"} { + require.Contains(t, document.Components.Schemas, name) + } + for path, methods := range document.Paths { + if operation, ok := methods["post"]; ok && !strings.HasSuffix(path, "/attachments") { + parameters, err := json.Marshal(operation["parameters"]) + require.NoError(t, err) + require.Contains(t, string(parameters), "Idempotency-Key", path) + } + } +} + +func TestFinishRequiresSummaryBeforeStoreAccess(t *testing.T) { + for _, body := range []string{`{"outcome":"succeeded"}`, `{"outcome":"failed","summary":null}`} { + r := httptest.NewRequest("POST", "/runs/example/finish", strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + _, _, err := (&API{}).runFinish(&request{r: r, w: httptest.NewRecorder()}) + require.Error(t, err) + } +} diff --git a/cmd/server/internal/api/idempotency.go b/cmd/server/internal/api/idempotency.go new file mode 100644 index 0000000..62f9e17 --- /dev/null +++ b/cmd/server/internal/api/idempotency.go @@ -0,0 +1,86 @@ +package api + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" +) + +func (a *API) execute(s *request, fn endpoint) (any, int, error) { + invoke := func() (any, int, error) { + body, status, err := fn(s) + if err != nil { + return nil, 0, err + } + projection := responseActors(body) + if err := s.tx.HydrateActors(projection.people); err != nil { + return nil, 0, err + } + projection.apply() + return body, status, nil + } + key := s.r.Header.Get("Idempotency-Key") + if s.r.Method != http.MethodPost || key == "" || strings.HasSuffix(s.r.URL.Path, "/attachments") { + return invoke() + } + if !domain.Text(key, 1, 128) { + return nil, 0, invalid("Idempotency-Key must contain 1 to 128 characters") + } + data, err := io.ReadAll(http.MaxBytesReader(s.w, s.r.Body, 256<<10)) + if err != nil { + return nil, 0, invalid("Request body exceeds the size limit") + } + s.r.Body = io.NopCloser(bytes.NewReader(data)) + hash := sha256.New() + for _, part := range []string{s.r.Method, s.r.URL.RequestURI(), s.r.Header.Get("Content-Type")} { + _, _ = io.WriteString(hash, part) + _, _ = hash.Write([]byte{0}) + } + _, _ = hash.Write(data) + fingerprint := hash.Sum(nil) + replay, err := s.tx.Idempotency(s.actor.Sub, key, fingerprint) + if err != nil { + return nil, 0, err + } + if replay != nil { + return *replay, replay.Status, nil + } + var body any + var status int + err = s.tx.ResponseAttempt(func() error { + var err error + body, status, err = invoke() + return err + }) + response := store.Replay{Status: status, Body: []byte{}} + if err != nil { + capture := &responseCapture{header: http.Header{}} + writeStoreError(capture, err) + response.Status, response.Body = capture.status, capture.Bytes() + } else if status != http.StatusNoContent { + response.Body, err = json.Marshal(body) + if err != nil { + return nil, 0, err + } + response.Body = append(response.Body, '\n') + } + if err := s.tx.SaveIdempotency(s.actor.Sub, key, fingerprint, response); err != nil { + return nil, 0, err + } + return response, response.Status, nil +} + +type responseCapture struct { + bytes.Buffer + header http.Header + status int +} + +func (w *responseCapture) Header() http.Header { return w.header } +func (w *responseCapture) WriteHeader(status int) { w.status = status } diff --git a/cmd/server/internal/api/issues.go b/cmd/server/internal/api/issues.go index 90ae0ef..db399d6 100644 --- a/cmd/server/internal/api/issues.go +++ b/cmd/server/internal/api/issues.go @@ -49,6 +49,9 @@ func (a *API) assignee(s *request, sub *string) (*domain.Person, error) { if !domain.Text(*sub, 1, 4096) { return nil, invalid("Invalid assignee subject") } + if domain.ActorKind(*sub) == "agent" { + return s.tx.AgentAssignee(*sub) + } person := domain.Person{Sub: *sub, Name: *sub} if *sub == s.actor.Sub { person = s.actor.Person diff --git a/cmd/server/internal/api/keys.go b/cmd/server/internal/api/keys.go index 33fed5c..e5fa3a1 100644 --- a/cmd/server/internal/api/keys.go +++ b/cmd/server/internal/api/keys.go @@ -16,19 +16,16 @@ const ( // keyActor maps an Access Key assertion to the actor it may act as. // -// The assertion audience is the same in every Project, so the Project claim is -// the tenant boundary. A key acts as the person it was issued to with the -// Viewer role: it never reaches the Platform role lookup, so Admin-only -// operations stay with signed-in users. Keys without a person behind them -// (component, external, cluster) are refused because every Tracker write -// records a person. +// The Project claim is the tenant boundary. All keys remain Viewers and never +// reach Platform role lookup or Directory. External subjects are resolved to +// active registered agents inside the request transaction. func keyActor(principal accesskey.Principal, project string, mutation bool) (domain.Actor, error) { if principal.Project != project { return domain.Actor{}, httpx.Fail(401, "unauthenticated", "A valid bearer token is required") } subject, err := accesskey.ParseSubject(principal.Subject) - if err != nil || subject.Kind != accesskey.SubjectUser { - return domain.Actor{}, httpx.Fail(403, "key_subject", "Only access keys issued to a user can call this API") + if err != nil || (subject.Kind != accesskey.SubjectUser && subject.Kind != accesskey.SubjectExternal) { + return domain.Actor{}, httpx.Fail(403, "key_subject", "Only user or registered external access keys can call this API") } required := scopeRead if mutation { @@ -37,5 +34,9 @@ func keyActor(principal accesskey.Principal, project string, mutation bool) (dom if !slices.Contains(principal.Scopes, required) { return domain.Actor{}, httpx.Fail(403, "insufficient_scope", "The access key does not permit this operation") } - return domain.Actor{Person: domain.Person{Sub: subject.ID, Name: subject.ID}, Role: "Viewer"}, nil + kind := "person" + if subject.Kind == accesskey.SubjectExternal { + kind = "agent" + } + return domain.Actor{Person: domain.Person{Sub: subject.ID, Name: subject.ID}, Role: "Viewer", Kind: kind, Key: true, Scopes: principal.Scopes}, nil } diff --git a/cmd/server/internal/api/openapi.json b/cmd/server/internal/api/openapi.json index 1d81f28..1161d1c 100644 --- a/cmd/server/internal/api/openapi.json +++ b/cmd/server/internal/api/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "Tracker API", - "version": "0.1.12", - "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID. The bearer is the signed-in user's token or an Access Key assertion (audience tracker; scope tracker:read for GET, tracker:write otherwise)." + "version": "0.1.13", + "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID. The bearer is the signed-in user's token or an Access Key assertion (audience tracker; scope tracker:read for GET, tracker:write otherwise). External-subject assertions resolve by immutable registered agent handle. GET scopes tracker:read; other methods tracker:write; missing scope is 403 insufficient_scope. Every key is refused on Admin routes. See /agent-guide for the collaboration protocol." }, "servers": [ { @@ -277,6 +277,14 @@ "type": "string", "default": "Asia/Tokyo", "description": "IANA timezone name" + }, + "agentCompletion": { + "type": "string", + "enum": [ + "review", + "direct" + ], + "default": "review" } }, "required": [], @@ -480,7 +488,19 @@ } } } - } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] } }, "/statuses/{id}": { @@ -866,7 +886,19 @@ } } } - } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] } }, "/labels/{id}": { @@ -1247,7 +1279,19 @@ } } } - } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] } }, "/projects/{id}": { @@ -1861,7 +1905,19 @@ } } } - } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] } }, "/issues/{id}": { @@ -1956,7 +2012,7 @@ "patch": { "operationId": "patchIssue", "summary": "patchIssue", - "description": "Authorization: any authenticated user. Every changed field emits one Activity. Changing to bug requires a report; changing away clears it. Parent cycles are invalid. Moving into completed/canceled sets completedAt; leaving clears it.", + "description": "Authorization: any authenticated user. Every changed field emits one Activity. Changing to bug requires a report; changing away clears it. Parent cycles are invalid. Moving into completed/canceled sets completedAt; leaving clears it. Agents may edit only as assignee or reporter. expectedUpdatedAt mismatch returns 409 conflict. Under review an agent cannot set a completed status.", "responses": { "200": { "description": "Success", @@ -2321,6 +2377,16 @@ "type": "string" }, "description": "Resource ULID; issue GET also accepts a case-insensitive KEY-number identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." } ], "requestBody": { @@ -2540,7 +2606,7 @@ "post": { "operationId": "createAttachment", "summary": "createAttachment", - "description": "Authorization: any authenticated user. One multipart file, at most 2 MiB and 10 attachments per issue. Allowed: image/png, image/jpeg, image/webp, text/plain, application/json.", + "description": "Authorization: any authenticated user. One multipart file, at most 2 MiB and 10 attachments per issue. Allowed: image/png, image/jpeg, image/webp, text/plain, application/json. Multipart upload is excluded from Idempotency-Key replay.", "responses": { "201": { "description": "Success", @@ -3034,7 +3100,19 @@ } } } - } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] } }, "/views/{id}": { @@ -3234,7 +3312,7 @@ "items": { "type": "array", "items": { - "$ref": "#/components/schemas/Person" + "$ref": "#/components/schemas/Actor" } }, "source": { @@ -3725,7 +3803,19 @@ } } } - } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] } }, "/sprints/{id}": { @@ -3920,7 +4010,7 @@ "delete": { "operationId": "deleteSprint", "summary": "deleteSprint", - "description": "Authorization: Admin. Only planned sprints; otherwise 409. Members return to backlog.", + "description": "Authorization: Admin. Only planned sprints; otherwise 409. Members return to backlog. Agent actors are refused.", "responses": { "204": { "description": "Success" @@ -4004,7 +4094,7 @@ "post": { "operationId": "startSprint", "summary": "startSprint", - "description": "Authorization: any authenticated user. 409 unless planned with no other active sprint. Future startsOn becomes today, keeping length; overlap returns 409.", + "description": "Authorization: any authenticated user. 409 unless planned with no other active sprint. Future startsOn becomes today, keeping length; overlap returns 409. Agent actors are refused.", "responses": { "200": { "description": "Success", @@ -4087,6 +4177,16 @@ "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, "description": "Sprint ULID." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." } ] } @@ -4095,7 +4195,7 @@ "post": { "operationId": "closeSprint", "summary": "closeSprint", - "description": "Authorization: any authenticated user. 409 unless active. Invalid destination returns 400 at moveIncompleteTo. Freeze ledger, then move unfinished scope to planned destination or backlog. Lineage conflicts go to backlog; done members stay.", + "description": "Authorization: any authenticated user. 409 unless active. Invalid destination returns 400 at moveIncompleteTo. Freeze ledger, then move unfinished scope to planned destination or backlog. Lineage conflicts go to backlog; done members stay. Agent actors are refused.", "responses": { "200": { "description": "Success", @@ -4188,6 +4288,16 @@ "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, "description": "Sprint ULID." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." } ] } @@ -4417,98 +4527,2657 @@ } ] } - } - }, - "components": { - "securitySchemes": { - "bearerAuth": { - "type": "http", - "scheme": "bearer", - "bearerFormat": "JWT" - } }, - "schemas": { - "Person": { - "type": "object", - "properties": { - "sub": { - "type": "string" + "/agents": { + "get": { + "operationId": "listAgents", + "summary": "listAgents", + "description": "Any authenticated actor. Ordered by handle; disabled agents excluded by default.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Agent" + } + } + }, + "required": [ + "items" + ], + "additionalProperties": false + } + } + } }, - "name": { - "type": "string" + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "avatarUrl": { - "type": "string", - "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "email": { - "type": "string" + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "profileUrl": { - "type": "string" + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } } }, - "required": [ - "sub", - "name" - ], - "additionalProperties": false + "parameters": [ + { + "name": "includeDisabled", + "in": "query", + "schema": { + "type": "boolean", + "default": false + }, + "description": "" + } + ] }, - "Me": { - "type": "object", - "properties": { - "sub": { - "type": "string" - }, - "name": { - "type": "string" + "post": { + "operationId": "createAgent", + "summary": "createAgent", + "description": "Signed-in Admin only; all keys refused. Duplicate handle returns 409.", + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Agent" + } + } + } }, - "avatarUrl": { - "type": "string", - "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "email": { - "type": "string" + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "profileUrl": { - "type": "string" + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "role": { - "type": "string", - "enum": [ - "Admin", - "Editor", - "Viewer" + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentCreate" + } + } + } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/agents/{id}": { + "patch": { + "operationId": "patchAgent", + "summary": "patchAgent", + "description": "Signed-in Admin only. Handle is immutable. Disabling cancels all non-terminal runs and withdraws open requests raised by the agent.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Agent" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentPatch" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + } + ] + } + }, + "/inbox": { + "get": { + "operationId": "getInbox", + "summary": "getInbox", + "description": "Caller inbox, open requests first. Answers and mentions remain until acknowledged. Agents also receive actionable assignments, including Backlog and their own live runs.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InboxItem" + } + } + }, + "required": [ + "items" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/inbox/ack": { + "post": { + "operationId": "ackInbox", + "summary": "ackInbox", + "description": "Acknowledge only caller-owned answers/mentions; unknown or other actors' IDs have no effect.", + "responses": { + "204": { + "description": "Success" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InboxAck" + } + } + } + }, + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/events": { + "get": { + "operationId": "listEvents", + "summary": "listEvents", + "description": "Ascending, commit-ordered, gap-free workspace cursor. Omit after to start now: no items, next=current sequence.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EventPage" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "after", + "in": "query", + "schema": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "description": "" + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 500, + "default": 100 + }, + "description": "" + } + ] + } + }, + "/issues/{id}/runs": { + "post": { + "operationId": "startRun", + "summary": "startRun", + "description": "Agent assignee only (403 otherwise). Live run returns 409. A stalled run closes failed/lease_expired and its open requests are withdrawn before the fresh start.", + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Run" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunStart" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + }, + "get": { + "operationId": "listRuns", + "summary": "listRuns", + "description": "Any authenticated actor. Newest first.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Run" + } + } + }, + "required": [ + "items" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + } + ] + } + }, + "/runs/{id}": { + "get": { + "operationId": "getRun", + "summary": "getRun", + "description": "Any authenticated actor. Stalled state is derived at microsecond precision.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Run" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + } + ] + } + }, + "/runs/{id}/heartbeat": { + "post": { + "operationId": "heartbeatRun", + "summary": "heartbeatRun", + "description": "The run's agent only. Renews the ten-minute lease. Terminal/stalled returns 409; never revives a lease.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Run" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunHeartbeat" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/runs/{id}/finish": { + "post": { + "operationId": "finishRun", + "summary": "finishRun", + "description": "The run's agent only. Terminal/stalled or success with open approval returns 409. Success under review opens a review to delegator/owner and withdraws open questions. Failed withdraws all open requests. Does not directly change issue status.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Run" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunFinish" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/runs/{id}/cancel": { + "post": { + "operationId": "cancelRun", + "summary": "cancelRun", + "description": "Any person or the run's agent. Accepts stalled; terminal returns 409. Withdraws open requests.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Run" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/issues/{id}/requests": { + "post": { + "operationId": "createRequest", + "summary": "createRequest", + "description": "Any actor on any issue. review is server-generated only. Attaching a run requires that run's agent and same issue (403); terminal/stalled returns 409; sets waiting.", + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Request" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestCreate" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/requests": { + "get": { + "operationId": "listRequests", + "summary": "listRequests", + "description": "Any authenticated actor. Newest first.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Request" + } + } + }, + "required": [ + "items" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "state", + "in": "query", + "schema": { + "$ref": "#/components/schemas/RequestState" + }, + "description": "" + }, + { + "name": "to", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Subject, me, or none (unaddressed)." + }, + { + "name": "issue", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Issue ULID or identifier." + } + ] + } + }, + "/requests/{id}": { + "get": { + "operationId": "getRequest", + "summary": "getRequest", + "description": "Any authenticated actor.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Request" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + } + ] + } + }, + "/requests/{id}/answer": { + "post": { + "operationId": "answerRequest", + "summary": "answerRequest", + "description": "Addressee, any person when unaddressed, or signed-in Admin. Agents answer questions only. Options must match. Review approval completes as the person in the same transaction, updating the sprint ledger; rejection leaves status unchanged. Last answer resumes a waiting run.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Request" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestAnswerInput" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/requests/{id}/withdraw": { + "post": { + "operationId": "withdrawRequest", + "summary": "withdrawRequest", + "description": "Requester only. Non-open returns 409. Last withdrawal resumes a waiting run.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Request" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Resource ULID; issue routes also accept the issue identifier." + }, + { + "name": "Idempotency-Key", + "in": "header", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "First handler response (status/body) is replayed for 24h per actor and key. Retry identical method, URI, content type and body bytes. Different request returns 409." + } + ] + } + }, + "/agent-guide": { + "get": { + "operationId": "getAgentGuide", + "summary": "getAgentGuide", + "description": "Agent protocol generated from the handler route table.", + "responses": { + "200": { + "description": "Success", + "content": { + "text/markdown": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT" + } + }, + "schemas": { + "Person": { + "type": "object", + "properties": { + "sub": { + "type": "string" + }, + "name": { + "type": "string" + }, + "avatarUrl": { + "type": "string", + "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + }, + "email": { + "type": "string" + }, + "profileUrl": { + "type": "string" + }, + "kind": { + "const": "person" + } + }, + "required": [ + "sub", + "name" + ], + "additionalProperties": false + }, + "Me": { + "type": "object", + "properties": { + "sub": { + "type": "string" + }, + "name": { + "type": "string" + }, + "avatarUrl": { + "type": "string", + "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + }, + "email": { + "type": "string" + }, + "profileUrl": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ + "Admin", + "Editor", + "Viewer" + ] + }, + "isAdmin": { + "type": "boolean" + }, + "kind": { + "$ref": "#/components/schemas/ActorKind" + }, + "agent": { + "$ref": "#/components/schemas/AgentIdentity" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "sub", + "name", + "role", + "isAdmin", + "kind" + ], + "additionalProperties": false + }, + "Workspace": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "key": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9]{1,5}$" + }, + "name": { + "type": "string", + "maxLength": 100, + "minLength": 1 + }, + "issueCount": { + "type": "integer" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "sprintLengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 + ], + "default": 1 + }, + "timezone": { + "type": "string", + "default": "Asia/Tokyo", + "description": "IANA timezone name" + }, + "agentCompletion": { + "type": "string", + "enum": [ + "review", + "direct" + ], + "default": "review" + } + }, + "required": [ + "id", + "key", + "name", + "issueCount", + "createdAt", + "updatedAt", + "sprintLengthWeeks", + "timezone", + "agentCompletion" + ], + "additionalProperties": false + }, + "StatusCategory": { + "type": "string", + "enum": [ + "backlog", + "unstarted", + "started", + "completed", + "canceled" + ] + }, + "Color": { + "type": "string", + "enum": [ + "gray", + "red", + "orange", + "yellow", + "green", + "teal", + "blue", + "indigo", + "purple", + "pink" + ] + }, + "Status": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "name": { + "type": "string", + "maxLength": 40, + "minLength": 1 + }, + "category": { + "$ref": "#/components/schemas/StatusCategory" + }, + "position": { + "type": "integer" + }, + "color": { + "$ref": "#/components/schemas/Color" + } + }, + "required": [ + "id", + "name", + "category", + "position", + "color" + ], + "additionalProperties": false + }, + "Label": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "name": { + "type": "string", + "maxLength": 40, + "minLength": 1 + }, + "color": { + "$ref": "#/components/schemas/Color" + } + }, + "required": [ + "id", + "name", + "color" + ], + "additionalProperties": false + }, + "Project": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "description": { + "type": "string", + "description": "At most 4096 bytes of valid UTF-8", + "maxLength": 4096 + }, + "color": { + "$ref": "#/components/schemas/Color" + }, + "archived": { + "type": "boolean" + }, + "issueCount": { + "type": "integer", + "minimum": 0, + "description": "Number of non-deleted issues" + }, + "openIssueCount": { + "type": "integer", + "minimum": 0, + "description": "Non-deleted issues whose status category is not completed or canceled" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "description", + "color", + "archived", + "issueCount", + "openIssueCount", + "createdAt", + "updatedAt" + ], + "additionalProperties": false + }, + "ProjectCreate": { + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "description": { + "type": "string", + "description": "At most 4096 bytes of valid UTF-8", + "maxLength": 4096 + }, + "color": { + "$ref": "#/components/schemas/Color", + "default": "gray" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "ProjectPatch": { + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "description": { + "type": "string", + "description": "At most 4096 bytes of valid UTF-8", + "maxLength": 4096 + }, + "color": { + "$ref": "#/components/schemas/Color" + }, + "archived": { + "type": "boolean", + "description": "Admin only, including unarchiving" + } + }, + "required": [], + "additionalProperties": false + }, + "IssueType": { + "type": "string", + "enum": [ + "epic", + "story", + "bug", + "feature", + "task" + ] + }, + "Priority": { + "type": "string", + "enum": [ + "urgent", + "high", + "medium", + "low", + "none" + ] + }, + "Surface": { + "type": "string", + "enum": [ + "dashboard", + "platform-api", + "apth", + "builder-console", + "console-app", + "cluster", + "other" + ] + }, + "Sort": { + "type": "string", + "enum": [ + "updated", + "created", + "priority", + "number", + "estimate" + ] + }, + "GroupBy": { + "type": "string", + "enum": [ + "none", + "epic", + "story", + "sprint" + ], + "default": "none" + }, + "Progress": { + "type": "object", + "description": "Counts non-deleted descendant work items at any depth; canceled work items are excluded from total.", + "properties": { + "total": { + "type": "integer", + "minimum": 0 + }, + "completed": { + "type": "integer", + "minimum": 0 + }, + "points": { + "type": "object", + "properties": { + "total": { + "type": "integer", + "minimum": 0 + }, + "completed": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "total", + "completed" + ], + "additionalProperties": false + } + }, + "required": [ + "total", + "completed", + "points" + ], + "additionalProperties": false + }, + "Report": { + "type": "object", + "properties": { + "environment": { + "type": "string", + "maxLength": 4096, + "minLength": 1 + }, + "surface": { + "$ref": "#/components/schemas/Surface" + }, + "version": { + "type": "string", + "maxLength": 4096 + }, + "steps": { + "type": "string", + "maxLength": 4096 + }, + "expected": { + "type": "string", + "maxLength": 4096 + }, + "actual": { + "type": "string", + "maxLength": 4096 + } + }, + "required": [ + "environment", + "surface" + ], + "additionalProperties": false + }, + "IssueRef": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "identifier": { + "type": "string" + }, + "title": { + "type": "string" + }, + "statusId": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + } + }, + "required": [ + "id", + "identifier", + "title", + "statusId" + ], + "additionalProperties": false + }, + "IssueSummary": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "identifier": { + "type": "string" + }, + "number": { + "type": "integer", + "minimum": 1 + }, + "title": { + "type": "string", + "maxLength": 200, + "minLength": 1 + }, + "type": { + "$ref": "#/components/schemas/IssueType" + }, + "priority": { + "$ref": "#/components/schemas/Priority" + }, + "statusId": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "assignee": { + "anyOf": [ + { + "$ref": "#/components/schemas/Actor" + }, + { + "type": "null" + } + ] + }, + "reporter": { + "$ref": "#/components/schemas/Actor" + }, + "labelIds": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + } + }, + "projectId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "null" + } + ] + }, + "parent": { + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } + ] + }, + "epic": { + "description": "Nearest strict epic ancestor within 32 parent hops, or null.", + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } + ] + }, + "story": { + "description": "Nearest strict story ancestor within 32 parent hops, or null.", + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } + ] + }, + "progress": { + "description": "Present for epics and stories only; null for work items. Status is never derived.", + "anyOf": [ + { + "$ref": "#/components/schemas/Progress" + }, + { + "type": "null" + } + ] + }, + "dueOn": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ] + }, + "report": { + "anyOf": [ + { + "$ref": "#/components/schemas/Report" + }, + { + "type": "null" + } + ] + }, + "commentCount": { + "type": "integer" + }, + "attachmentCount": { + "type": "integer" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "completedAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ] + }, + "estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/Size" + }, + { + "type": "null" + } + ] + }, + "sprint": { + "anyOf": [ + { + "$ref": "#/components/schemas/SprintRef" + }, + { + "type": "null" + } + ] + }, + "delegator": { + "anyOf": [ + { + "$ref": "#/components/schemas/Person" + }, + { + "type": "null" + } + ] + }, + "activeRun": { + "anyOf": [ + { + "$ref": "#/components/schemas/Run" + }, + { + "type": "null" + } + ] + }, + "openRequestCount": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "id", + "identifier", + "number", + "title", + "type", + "priority", + "statusId", + "assignee", + "reporter", + "labelIds", + "projectId", + "parent", + "epic", + "story", + "progress", + "dueOn", + "report", + "commentCount", + "attachmentCount", + "createdAt", + "updatedAt", + "completedAt", + "estimate", + "sprint", + "delegator", + "activeRun", + "openRequestCount" + ], + "additionalProperties": false + }, + "Issue": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "identifier": { + "type": "string" + }, + "number": { + "type": "integer", + "minimum": 1 + }, + "title": { + "type": "string", + "maxLength": 200, + "minLength": 1 + }, + "type": { + "$ref": "#/components/schemas/IssueType" + }, + "priority": { + "$ref": "#/components/schemas/Priority" + }, + "statusId": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "assignee": { + "anyOf": [ + { + "$ref": "#/components/schemas/Actor" + }, + { + "type": "null" + } + ] + }, + "reporter": { + "$ref": "#/components/schemas/Actor" + }, + "labelIds": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + } + }, + "projectId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "null" + } ] }, - "isAdmin": { - "type": "boolean" - } - }, - "required": [ - "sub", - "name", - "role", - "isAdmin" - ], - "additionalProperties": false - }, - "Workspace": { - "type": "object", - "properties": { - "id": { - "type": "string" + "parent": { + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } + ] }, - "key": { - "type": "string", - "pattern": "^[A-Z][A-Z0-9]{1,5}$" + "epic": { + "description": "Nearest strict epic ancestor within 32 parent hops, or null.", + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } + ] }, - "name": { - "type": "string", - "maxLength": 100, - "minLength": 1 + "story": { + "description": "Nearest strict story ancestor within 32 parent hops, or null.", + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } + ] }, - "issueCount": { + "progress": { + "description": "Present for epics and stories only; null for work items. Status is never derived.", + "anyOf": [ + { + "$ref": "#/components/schemas/Progress" + }, + { + "type": "null" + } + ] + }, + "dueOn": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ] + }, + "report": { + "anyOf": [ + { + "$ref": "#/components/schemas/Report" + }, + { + "type": "null" + } + ] + }, + "commentCount": { + "type": "integer" + }, + "attachmentCount": { "type": "integer" }, "createdAt": { @@ -4519,382 +7188,647 @@ "type": "string", "format": "date-time" }, - "sprintLengthWeeks": { - "type": "integer", - "enum": [ - 1, - 2 - ], - "default": 1 + "completedAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ] }, - "timezone": { + "description": { "type": "string", - "default": "Asia/Tokyo", - "description": "IANA timezone name" + "description": "Markdown, at most 50 KiB UTF-8" + }, + "children": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IssueRef" + } + }, + "blocks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IssueRef" + } + }, + "blockedBy": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IssueRef" + } + }, + "estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/Size" + }, + { + "type": "null" + } + ] + }, + "sprint": { + "anyOf": [ + { + "$ref": "#/components/schemas/SprintRef" + }, + { + "type": "null" + } + ] + }, + "delegator": { + "anyOf": [ + { + "$ref": "#/components/schemas/Person" + }, + { + "type": "null" + } + ] + }, + "activeRun": { + "anyOf": [ + { + "$ref": "#/components/schemas/Run" + }, + { + "type": "null" + } + ] + }, + "openRequestCount": { + "type": "integer", + "minimum": 0 } }, "required": [ "id", - "key", - "name", - "issueCount", + "identifier", + "number", + "title", + "type", + "priority", + "statusId", + "assignee", + "reporter", + "labelIds", + "projectId", + "parent", + "epic", + "story", + "progress", + "dueOn", + "report", + "commentCount", + "attachmentCount", "createdAt", "updatedAt", - "sprintLengthWeeks", - "timezone" + "completedAt", + "description", + "children", + "blocks", + "blockedBy", + "estimate", + "sprint", + "delegator", + "activeRun", + "openRequestCount" ], "additionalProperties": false }, - "StatusCategory": { - "type": "string", - "enum": [ - "backlog", - "unstarted", - "started", - "completed", - "canceled" - ] - }, - "Color": { - "type": "string", - "enum": [ - "gray", - "red", - "orange", - "yellow", - "green", - "teal", - "blue", - "indigo", - "purple", - "pink" - ] + "Comment": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "issueId": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "author": { + "$ref": "#/components/schemas/Actor" + }, + "body": { + "type": "string", + "description": "1 byte to 20 KiB UTF-8 Markdown" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "editedAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ] + }, + "mentions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Actor" + } + } + }, + "required": [ + "id", + "issueId", + "author", + "body", + "createdAt", + "editedAt", + "mentions" + ], + "additionalProperties": false }, - "Status": { + "Attachment": { "type": "object", "properties": { "id": { "type": "string", "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "name": { + "issueId": { "type": "string", - "maxLength": 40, + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "filename": { + "type": "string", + "maxLength": 200, "minLength": 1 }, - "category": { - "$ref": "#/components/schemas/StatusCategory" + "mediaType": { + "type": "string", + "enum": [ + "image/png", + "image/jpeg", + "image/webp", + "text/plain", + "application/json" + ] }, - "position": { - "type": "integer" + "size": { + "type": "integer", + "minimum": 1, + "maximum": 2097152 }, - "color": { - "$ref": "#/components/schemas/Color" + "url": { + "type": "string" + }, + "uploader": { + "$ref": "#/components/schemas/Actor" + }, + "createdAt": { + "type": "string", + "format": "date-time" } }, "required": [ "id", - "name", - "category", - "position", - "color" + "issueId", + "filename", + "mediaType", + "size", + "url", + "uploader", + "createdAt" ], "additionalProperties": false }, - "Label": { + "Activity": { "type": "object", "properties": { "id": { "type": "string", "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "name": { + "issueId": { "type": "string", - "maxLength": 40, - "minLength": 1 + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "color": { - "$ref": "#/components/schemas/Color" + "actor": { + "$ref": "#/components/schemas/Actor" + }, + "field": { + "type": "string", + "enum": [ + "created", + "title", + "description", + "type", + "priority", + "status", + "assignee", + "labels", + "project", + "parent", + "blocks", + "due", + "report", + "attachment", + "deleted", + "estimate", + "sprint", + "delegator" + ] + }, + "from": {}, + "to": {}, + "createdAt": { + "type": "string", + "format": "date-time" } }, "required": [ "id", - "name", - "color" + "issueId", + "actor", + "field", + "from", + "to", + "createdAt" ], "additionalProperties": false }, - "Project": { + "TimelineItem": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "const": "activity" + }, + "activity": { + "$ref": "#/components/schemas/Activity" + } + }, + "required": [ + "kind", + "activity" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "const": "comment" + }, + "comment": { + "$ref": "#/components/schemas/Comment" + } + }, + "required": [ + "kind", + "comment" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "const": "run" + }, + "run": { + "$ref": "#/components/schemas/Run" + } + }, + "required": [ + "kind", + "run" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "const": "request" + }, + "request": { + "$ref": "#/components/schemas/Request" + } + }, + "required": [ + "kind", + "request" + ], + "additionalProperties": false + } + ] + }, + "Filter": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "status": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + } + }, + "category": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StatusCategory" + } + }, + "assignee": { + "type": "array", + "items": { + "type": "string" + } + }, + "reporter": { + "type": "array", + "description": "Match reporter subjects; 'me' resolves to the caller. 'none' is not supported. Invalid values return 400 invalid with path filter.reporter.", + "maxItems": 20, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "not": { + "const": "none" + } + } + }, + "label": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + } + }, + "project": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "const": "none" + } + ] + } + }, + "epic": { + "type": "array", + "description": "Match the derived strict epic ancestor by ID; none matches issues without an epic.", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "none" + } + ] + } + }, + "story": { + "type": "array", + "description": "Match the derived strict story ancestor by ID; none matches issues without a story.", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "none" + } + ] + } + }, + "type": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IssueType" + } }, - "name": { - "type": "string", - "maxLength": 60, - "minLength": 1 + "priority": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Priority" + } }, - "description": { + "q": { "type": "string", - "description": "At most 4096 bytes of valid UTF-8", "maxLength": 4096 }, - "color": { - "$ref": "#/components/schemas/Color" + "createdAfter": { + "type": "string", + "format": "date-time" }, - "archived": { - "type": "boolean" + "environment": { + "type": "array", + "items": { + "type": "string", + "maxLength": 4096, + "minLength": 1 + } }, - "issueCount": { - "type": "integer", - "minimum": 0, - "description": "Number of non-deleted issues" + "surface": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Surface" + } }, - "openIssueCount": { - "type": "integer", - "minimum": 0, - "description": "Non-deleted issues whose status category is not completed or canceled" + "parent": { + "type": "string" }, - "createdAt": { - "type": "string", - "format": "date-time" + "sprint": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "active" + }, + { + "const": "none" + } + ] + } }, - "updatedAt": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "name", - "description", - "color", - "archived", - "issueCount", - "openIssueCount", - "createdAt", - "updatedAt" - ], - "additionalProperties": false - }, - "ProjectCreate": { - "type": "object", - "properties": { - "name": { - "type": "string", - "maxLength": 60, - "minLength": 1 + "assigneeKind": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ActorKind" + } }, - "description": { - "type": "string", - "description": "At most 4096 bytes of valid UTF-8", - "maxLength": 4096 + "agent": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "description": "Assignee agent IDs." }, - "color": { - "$ref": "#/components/schemas/Color", - "default": "gray" + "run": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "active", + "stalled", + "none" + ] + } + }, + "request": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "open", + "mine" + ] + }, + "description": "Open requests; mine means open requests raised by the caller. Values within a filter are ORed." } }, - "required": [ - "name" - ], + "required": [], "additionalProperties": false }, - "ProjectPatch": { + "View": { "type": "object", "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, "name": { "type": "string", "maxLength": 60, "minLength": 1 }, - "description": { - "type": "string", - "description": "At most 4096 bytes of valid UTF-8", - "maxLength": 4096 - }, - "color": { - "$ref": "#/components/schemas/Color" - }, - "archived": { - "type": "boolean", - "description": "Admin only, including unarchiving" - } - }, - "required": [], - "additionalProperties": false - }, - "IssueType": { - "type": "string", - "enum": [ - "epic", - "story", - "bug", - "feature", - "task" - ] - }, - "Priority": { - "type": "string", - "enum": [ - "urgent", - "high", - "medium", - "low", - "none" - ] - }, - "Surface": { - "type": "string", - "enum": [ - "dashboard", - "platform-api", - "apth", - "builder-console", - "console-app", - "cluster", - "other" - ] - }, - "Sort": { - "type": "string", - "enum": [ - "updated", - "created", - "priority", - "number", - "estimate" - ] - }, - "GroupBy": { - "type": "string", - "enum": [ - "none", - "epic", - "story", - "sprint" - ], - "default": "none" - }, - "Progress": { - "type": "object", - "description": "Counts non-deleted descendant work items at any depth; canceled work items are excluded from total.", - "properties": { - "total": { - "type": "integer", - "minimum": 0 + "owner": { + "$ref": "#/components/schemas/Actor" }, - "completed": { - "type": "integer", - "minimum": 0 + "shared": { + "type": "boolean" }, - "points": { - "type": "object", - "properties": { - "total": { - "type": "integer", - "minimum": 0 - }, - "completed": { - "type": "integer", - "minimum": 0 - } - }, - "required": [ - "total", - "completed" - ], - "additionalProperties": false - } - }, - "required": [ - "total", - "completed", - "points" - ], - "additionalProperties": false - }, - "Report": { - "type": "object", - "properties": { - "environment": { + "layout": { "type": "string", - "maxLength": 4096, - "minLength": 1 + "enum": [ + "list", + "board" + ] }, - "surface": { - "$ref": "#/components/schemas/Surface" + "groupBy": { + "$ref": "#/components/schemas/GroupBy" }, - "version": { - "type": "string", - "maxLength": 4096 + "filter": { + "$ref": "#/components/schemas/Filter" + }, + "sort": { + "$ref": "#/components/schemas/Sort" }, - "steps": { - "type": "string", - "maxLength": 4096 + "position": { + "type": "integer" }, - "expected": { + "createdAt": { "type": "string", - "maxLength": 4096 + "format": "date-time" }, - "actual": { + "updatedAt": { "type": "string", - "maxLength": 4096 + "format": "date-time" } }, "required": [ - "environment", - "surface" + "id", + "name", + "owner", + "shared", + "layout", + "groupBy", + "filter", + "sort", + "position", + "createdAt", + "updatedAt" ], "additionalProperties": false }, - "IssueRef": { + "Error": { "type": "object", "properties": { - "id": { + "error": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - "identifier": { - "type": "string" + "enum": [ + "invalid", + "unauthenticated", + "raw_key_not_accepted", + "forbidden", + "insufficient_scope", + "key_subject", + "not_found", + "conflict", + "tracker_store_unavailable", + "identity_unavailable" + ] }, - "title": { + "message": { "type": "string" }, - "statusId": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "path", + "message" + ], + "additionalProperties": false + } } }, "required": [ - "id", - "identifier", - "title", - "statusId" + "error", + "message" ], "additionalProperties": false }, - "IssueSummary": { + "IssueCreate": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - "identifier": { - "type": "string" - }, - "number": { - "type": "integer", - "minimum": 1 - }, "title": { "type": "string", "maxLength": 200, "minLength": 1 }, + "description": { + "type": "string", + "description": "Markdown, at most 50 KiB UTF-8" + }, "type": { "$ref": "#/components/schemas/IssueType" }, @@ -4905,18 +7839,18 @@ "type": "string", "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "assignee": { + "assigneeSub": { "anyOf": [ { - "$ref": "#/components/schemas/Person" + "type": "string", + "maxLength": 4096, + "minLength": 1 }, { "type": "null" } - ] - }, - "reporter": { - "$ref": "#/components/schemas/Person" + ], + "description": "Person subject or agent:; disabled agents return 400 invalid at assigneeSub. Agents may self-assign only issues they reported." }, "labelIds": { "type": "array", @@ -4936,43 +7870,11 @@ } ] }, - "parent": { - "anyOf": [ - { - "$ref": "#/components/schemas/IssueRef" - }, - { - "type": "null" - } - ] - }, - "epic": { - "description": "Nearest strict epic ancestor within 32 parent hops, or null.", - "anyOf": [ - { - "$ref": "#/components/schemas/IssueRef" - }, - { - "type": "null" - } - ] - }, - "story": { - "description": "Nearest strict story ancestor within 32 parent hops, or null.", - "anyOf": [ - { - "$ref": "#/components/schemas/IssueRef" - }, - { - "type": "null" - } - ] - }, - "progress": { - "description": "Present for epics and stories only; null for work items. Status is never derived.", + "parentId": { "anyOf": [ { - "$ref": "#/components/schemas/Progress" + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, { "type": "null" @@ -5000,31 +7902,6 @@ } ] }, - "commentCount": { - "type": "integer" - }, - "attachmentCount": { - "type": "integer" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "updatedAt": { - "type": "string", - "format": "date-time" - }, - "completedAt": { - "anyOf": [ - { - "type": "string", - "format": "date-time" - }, - { - "type": "null" - } - ] - }, "estimate": { "anyOf": [ { @@ -5035,10 +7912,11 @@ } ] }, - "sprint": { + "sprintId": { "anyOf": [ { - "$ref": "#/components/schemas/SprintRef" + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, { "type": "null" @@ -5047,52 +7925,23 @@ } }, "required": [ - "id", - "identifier", - "number", "title", - "type", - "priority", - "statusId", - "assignee", - "reporter", - "labelIds", - "projectId", - "parent", - "epic", - "story", - "progress", - "dueOn", - "report", - "commentCount", - "attachmentCount", - "createdAt", - "updatedAt", - "completedAt", - "estimate", - "sprint" + "type" ], "additionalProperties": false }, - "Issue": { + "IssuePatch": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - "identifier": { - "type": "string" - }, - "number": { - "type": "integer", - "minimum": 1 - }, "title": { "type": "string", "maxLength": 200, "minLength": 1 }, + "description": { + "type": "string", + "description": "Markdown, at most 50 KiB UTF-8" + }, "type": { "$ref": "#/components/schemas/IssueType" }, @@ -5103,18 +7952,18 @@ "type": "string", "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "assignee": { + "assigneeSub": { "anyOf": [ { - "$ref": "#/components/schemas/Person" + "type": "string", + "maxLength": 4096, + "minLength": 1 }, { "type": "null" } - ] - }, - "reporter": { - "$ref": "#/components/schemas/Person" + ], + "description": "Person subject or agent:; disabled agents return 400 invalid at assigneeSub. Agents may self-assign only issues they reported." }, "labelIds": { "type": "array", @@ -5126,51 +7975,19 @@ "projectId": { "anyOf": [ { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } - ] - }, - "parent": { - "anyOf": [ - { - "$ref": "#/components/schemas/IssueRef" - }, - { - "type": "null" - } - ] - }, - "epic": { - "description": "Nearest strict epic ancestor within 32 parent hops, or null.", - "anyOf": [ - { - "$ref": "#/components/schemas/IssueRef" - }, - { - "type": "null" - } - ] - }, - "story": { - "description": "Nearest strict story ancestor within 32 parent hops, or null.", - "anyOf": [ - { - "$ref": "#/components/schemas/IssueRef" + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, { "type": "null" } ] }, - "progress": { - "description": "Present for epics and stories only; null for work items. Status is never derived.", + "parentId": { "anyOf": [ { - "$ref": "#/components/schemas/Progress" + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, { "type": "null" @@ -5198,51 +8015,11 @@ } ] }, - "commentCount": { - "type": "integer" - }, - "attachmentCount": { - "type": "integer" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "updatedAt": { - "type": "string", - "format": "date-time" - }, - "completedAt": { - "anyOf": [ - { - "type": "string", - "format": "date-time" - }, - { - "type": "null" - } - ] - }, - "description": { - "type": "string", - "description": "Markdown, at most 50 KiB UTF-8" - }, - "children": { - "type": "array", - "items": { - "$ref": "#/components/schemas/IssueRef" - } - }, "blocks": { "type": "array", "items": { - "$ref": "#/components/schemas/IssueRef" - } - }, - "blockedBy": { - "type": "array", - "items": { - "$ref": "#/components/schemas/IssueRef" + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" } }, "estimate": { @@ -5255,72 +8032,220 @@ } ] }, - "sprint": { + "sprintId": { "anyOf": [ { - "$ref": "#/components/schemas/SprintRef" + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, { "type": "null" } ] + }, + "expectedUpdatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [], + "additionalProperties": false + }, + "ViewCreate": { + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "layout": { + "type": "string", + "enum": [ + "list", + "board" + ] + }, + "groupBy": { + "$ref": "#/components/schemas/GroupBy" + }, + "filter": { + "$ref": "#/components/schemas/Filter" + }, + "sort": { + "$ref": "#/components/schemas/Sort" + }, + "shared": { + "type": "boolean" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "ViewPatch": { + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "layout": { + "type": "string", + "enum": [ + "list", + "board" + ] + }, + "groupBy": { + "$ref": "#/components/schemas/GroupBy" + }, + "filter": { + "$ref": "#/components/schemas/Filter" + }, + "sort": { + "$ref": "#/components/schemas/Sort" + }, + "shared": { + "type": "boolean" + }, + "position": { + "type": "integer" + } + }, + "required": [], + "additionalProperties": false + }, + "Size": { + "type": "string", + "enum": [ + "XS", + "S", + "M", + "L", + "XL" + ], + "description": "Fixed points: XS=1, S=2, M=3, L=5, XL=8; null counts zero." + }, + "SprintState": { + "type": "string", + "enum": [ + "planned", + "active", + "closed" + ] + }, + "Unit": { + "type": "string", + "enum": [ + "points", + "issues" + ], + "default": "points" + }, + "Tally": { + "type": "object", + "properties": { + "scopePoints": { + "type": "integer", + "minimum": 0 + }, + "scopeIssues": { + "type": "integer", + "minimum": 0 + }, + "donePoints": { + "type": "integer", + "minimum": 0 + }, + "doneIssues": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "scopePoints", + "scopeIssues", + "donePoints", + "doneIssues" + ], + "additionalProperties": false + }, + "SprintRef": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "number": { + "type": "integer", + "minimum": 1 + }, + "name": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/SprintState" } }, "required": [ "id", - "identifier", "number", - "title", - "type", - "priority", - "statusId", - "assignee", - "reporter", - "labelIds", - "projectId", - "parent", - "epic", - "story", - "progress", - "dueOn", - "report", - "commentCount", - "attachmentCount", - "createdAt", - "updatedAt", - "completedAt", - "description", - "children", - "blocks", - "blockedBy", - "estimate", - "sprint" + "name", + "state" ], "additionalProperties": false }, - "Comment": { + "Sprint": { "type": "object", "properties": { "id": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "number": { + "type": "integer", + "minimum": 1 + }, + "name": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/SprintState" + }, + "goal": { + "type": "string" + }, + "lengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 + ] }, - "issueId": { + "startsOn": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - "author": { - "$ref": "#/components/schemas/Person" + "format": "date" }, - "body": { + "endsOn": { "type": "string", - "description": "1 byte to 20 KiB UTF-8 Markdown" + "format": "date" }, - "createdAt": { - "type": "string", - "format": "date-time" + "startedAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ] }, - "editedAt": { + "closedAt": { "anyOf": [ { "type": "string", @@ -5330,342 +8255,359 @@ "type": "null" } ] + }, + "current": { + "$ref": "#/components/schemas/Tally" + }, + "commitment": { + "anyOf": [ + { + "$ref": "#/components/schemas/Tally" + }, + { + "type": "null" + } + ] + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" } }, "required": [ "id", - "issueId", - "author", - "body", + "number", + "name", + "state", + "goal", + "lengthWeeks", + "startsOn", + "endsOn", + "startedAt", + "closedAt", + "current", + "commitment", "createdAt", - "editedAt" + "updatedAt" ], "additionalProperties": false }, - "Attachment": { + "SprintCreate": { "type": "object", "properties": { - "id": { + "name": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "minLength": 1, + "maxLength": 60 }, - "issueId": { + "goal": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "description": "Valid UTF-8, at most 4096 bytes", + "maxLength": 4096 }, - "filename": { + "startsOn": { "type": "string", - "maxLength": 200, - "minLength": 1 + "format": "date" }, - "mediaType": { - "type": "string", + "lengthWeeks": { + "type": "integer", "enum": [ - "image/png", - "image/jpeg", - "image/webp", - "text/plain", - "application/json" + 1, + 2 ] - }, - "size": { - "type": "integer", - "minimum": 1, - "maximum": 2097152 - }, - "url": { - "type": "string" - }, - "uploader": { - "$ref": "#/components/schemas/Person" - }, - "createdAt": { - "type": "string", - "format": "date-time" } }, - "required": [ - "id", - "issueId", - "filename", - "mediaType", - "size", - "url", - "uploader", - "createdAt" - ], + "required": [], "additionalProperties": false }, - "Activity": { + "SprintPatch": { "type": "object", "properties": { - "id": { + "name": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "minLength": 1, + "maxLength": 60 }, - "issueId": { + "goal": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - "actor": { - "$ref": "#/components/schemas/Person" + "description": "Valid UTF-8, at most 4096 bytes", + "maxLength": 4096 }, - "field": { + "startsOn": { "type": "string", + "format": "date" + }, + "lengthWeeks": { + "type": "integer", "enum": [ - "created", - "title", - "description", - "type", - "priority", - "status", - "assignee", - "labels", - "project", - "parent", - "blocks", - "due", - "report", - "attachment", - "deleted", - "estimate", - "sprint" + 1, + 2 ] - }, - "from": {}, - "to": {}, - "createdAt": { - "type": "string", - "format": "date-time" } }, - "required": [ - "id", - "issueId", - "actor", - "field", - "from", - "to", - "createdAt" - ], + "required": [], "additionalProperties": false }, - "TimelineItem": { - "oneOf": [ - { - "type": "object", - "properties": { - "kind": { - "const": "activity" - }, - "activity": { - "$ref": "#/components/schemas/Activity" - } - }, - "required": [ - "kind", - "activity" - ], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "kind": { - "const": "comment" + "SprintClose": { + "type": "object", + "properties": { + "moveIncompleteTo": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, - "comment": { - "$ref": "#/components/schemas/Comment" + { + "type": "null" } - }, - "required": [ - "kind", - "comment" - ], - "additionalProperties": false + ] } - ] + }, + "required": [ + "moveIncompleteTo" + ], + "additionalProperties": false }, - "Filter": { + "BurndownPoint": { "type": "object", "properties": { - "status": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } + "day": { + "type": "string", + "format": "date" }, - "category": { - "type": "array", - "items": { - "$ref": "#/components/schemas/StatusCategory" - } + "scope": { + "type": "integer", + "minimum": 0 + }, + "done": { + "type": "integer", + "minimum": 0 + }, + "remaining": { + "type": "integer", + "minimum": 0 + }, + "ideal": { + "type": "number" + } + }, + "required": [ + "day", + "ideal" + ], + "additionalProperties": false, + "description": "Future days omit scope, done, remaining. Ideal is rounded to two decimals and flat on weekends." + }, + "Burndown": { + "type": "object", + "properties": { + "sprint": { + "$ref": "#/components/schemas/SprintRef" }, - "assignee": { - "type": "array", - "items": { - "type": "string" - } + "unit": { + "$ref": "#/components/schemas/Unit" }, - "reporter": { - "type": "array", - "description": "Match reporter subjects; 'me' resolves to the caller. 'none' is not supported. Invalid values return 400 invalid with path filter.reporter.", - "maxItems": 20, - "items": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "not": { - "const": "none" - } - } + "today": { + "type": "string", + "format": "date" }, - "label": { + "points": { "type": "array", "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "$ref": "#/components/schemas/BurndownPoint" } + } + }, + "required": [ + "sprint", + "unit", + "today", + "points" + ], + "additionalProperties": false + }, + "VelocityEntry": { + "type": "object", + "properties": { + "sprint": { + "$ref": "#/components/schemas/SprintRef" }, - "project": { - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "const": "none" - } - ] - } + "lengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 + ] }, - "epic": { - "type": "array", - "description": "Match the derived strict epic ancestor by ID; none matches issues without an epic.", - "items": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - { - "const": "none" - } - ] - } + "committed": { + "type": "integer", + "minimum": 0 }, - "story": { - "type": "array", - "description": "Match the derived strict story ancestor by ID; none matches issues without a story.", - "items": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - { - "const": "none" - } - ] - } + "completed": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "sprint", + "lengthWeeks", + "committed", + "completed" + ], + "additionalProperties": false + }, + "Velocity": { + "type": "object", + "properties": { + "unit": { + "$ref": "#/components/schemas/Unit" }, - "type": { + "items": { "type": "array", "items": { - "$ref": "#/components/schemas/IssueType" + "$ref": "#/components/schemas/VelocityEntry" } }, - "priority": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Priority" - } + "averagePerWeek": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "unit", + "items", + "averagePerWeek" + ], + "additionalProperties": false, + "description": "Most recent limit closed sprints, oldest first. Average of completed/lengthWeeks over the last three closed sprints, rounded to two decimals, or null." + }, + "ActorKind": { + "type": "string", + "enum": [ + "person", + "agent" + ] + }, + "Actor": { + "type": "object", + "properties": { + "sub": { + "type": "string" }, - "q": { - "type": "string", - "maxLength": 4096 + "name": { + "type": "string" }, - "createdAfter": { + "avatarUrl": { "type": "string", - "format": "date-time" - }, - "environment": { - "type": "array", - "items": { - "type": "string", - "maxLength": 4096, - "minLength": 1 - } + "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." }, - "surface": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Surface" - } + "email": { + "type": "string" }, - "parent": { + "profileUrl": { "type": "string" }, - "sprint": { - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - { - "const": "active" - }, - { - "const": "none" - } - ] - } + "kind": { + "type": "string", + "enum": [ + "person", + "agent" + ] + }, + "agent": { + "$ref": "#/components/schemas/AgentIdentity" } }, - "required": [], + "required": [ + "sub", + "name", + "kind" + ], "additionalProperties": false }, - "View": { + "AgentIdentity": { "type": "object", "properties": { "id": { "type": "string", "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "name": { + "handle": { "type": "string", - "maxLength": 60, - "minLength": 1 + "pattern": "^[a-z][a-z0-9-]{1,30}$" }, "owner": { "$ref": "#/components/schemas/Person" }, - "shared": { + "disabled": { "type": "boolean" + } + }, + "required": [ + "id", + "handle", + "owner", + "disabled" + ], + "additionalProperties": false + }, + "Agent": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "layout": { + "handle": { "type": "string", - "enum": [ - "list", - "board" - ] + "pattern": "^[a-z][a-z0-9-]{1,30}$", + "description": "Immutable; also the external subject of every Access Key for this agent." }, - "groupBy": { - "$ref": "#/components/schemas/GroupBy" + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 }, - "filter": { - "$ref": "#/components/schemas/Filter" + "description": { + "type": "string", + "description": "At most 4096 UTF-8 bytes" }, - "sort": { - "$ref": "#/components/schemas/Sort" + "owner": { + "$ref": "#/components/schemas/Person" }, - "position": { - "type": "integer" + "disabled": { + "type": "boolean" + }, + "activeRuns": { + "type": "integer", + "minimum": 0, + "description": "Live running/waiting runs, excluding stalled leases." + }, + "openRequests": { + "type": "integer", + "minimum": 0, + "description": "Open requests raised by this agent." + }, + "lastSeenAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ] }, "createdAt": { "type": "string", @@ -5678,284 +8620,175 @@ }, "required": [ "id", + "handle", "name", + "description", "owner", - "shared", - "layout", - "groupBy", - "filter", - "sort", - "position", + "disabled", + "activeRuns", + "openRequests", + "lastSeenAt", "createdAt", "updatedAt" ], "additionalProperties": false }, - "Error": { + "AgentCreate": { "type": "object", "properties": { - "error": { + "handle": { "type": "string", - "enum": [ - "invalid", - "unauthenticated", - "raw_key_not_accepted", - "forbidden", - "insufficient_scope", - "key_subject", - "not_found", - "conflict", - "tracker_store_unavailable", - "identity_unavailable" - ] + "pattern": "^[a-z][a-z0-9-]{1,30}$", + "description": "Immutable; also the external subject of every Access Key for this agent." }, - "message": { - "type": "string" + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 }, - "issues": { - "type": "array", - "items": { - "type": "object", - "properties": { - "path": { - "type": "string" - }, - "message": { - "type": "string" - } - }, - "required": [ - "path", - "message" - ], - "additionalProperties": false - } + "description": { + "type": "string", + "description": "At most 4096 UTF-8 bytes" + }, + "ownerSub": { + "type": "string", + "minLength": 1, + "maxLength": 4096 } }, "required": [ - "error", - "message" + "handle", + "name", + "ownerSub" ], "additionalProperties": false }, - "IssueCreate": { + "AgentPatch": { "type": "object", "properties": { - "title": { + "name": { "type": "string", - "maxLength": 200, - "minLength": 1 + "minLength": 1, + "maxLength": 200 }, "description": { "type": "string", - "description": "Markdown, at most 50 KiB UTF-8" - }, - "type": { - "$ref": "#/components/schemas/IssueType" - }, - "priority": { - "$ref": "#/components/schemas/Priority" + "description": "At most 4096 UTF-8 bytes" }, - "statusId": { + "ownerSub": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - "assigneeSub": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096, - "minLength": 1 - }, - { - "type": "null" - } - ] - }, - "labelIds": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } - }, - "projectId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } - ] - }, - "parentId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } - ] - }, - "dueOn": { - "anyOf": [ - { - "type": "string", - "format": "date" - }, - { - "type": "null" - } - ] + "minLength": 1, + "maxLength": 4096 }, - "report": { - "anyOf": [ - { - "$ref": "#/components/schemas/Report" - }, - { - "type": "null" - } + "disabled": { + "type": "boolean" + } + }, + "required": [], + "additionalProperties": false + }, + "RunState": { + "type": "string", + "enum": [ + "running", + "waiting", + "stalled", + "succeeded", + "failed", + "canceled" + ] + }, + "Link": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "pr", + "commit", + "url" ] }, - "estimate": { - "anyOf": [ - { - "$ref": "#/components/schemas/Size" - }, - { - "type": "null" - } - ] + "url": { + "type": "string", + "format": "uri", + "pattern": "^https://" }, - "sprintId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - { - "type": "null" - } - ] + "title": { + "type": "string", + "maxLength": 200 } }, "required": [ - "title", - "type" + "kind", + "url", + "title" ], "additionalProperties": false }, - "IssuePatch": { + "Run": { "type": "object", "properties": { - "title": { - "type": "string", - "maxLength": 200, - "minLength": 1 - }, - "description": { - "type": "string", - "description": "Markdown, at most 50 KiB UTF-8" - }, - "type": { - "$ref": "#/components/schemas/IssueType" - }, - "priority": { - "$ref": "#/components/schemas/Priority" - }, - "statusId": { + "id": { "type": "string", "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "assigneeSub": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096, - "minLength": 1 - }, - { - "type": "null" - } - ] + "issue": { + "$ref": "#/components/schemas/IssueRef" }, - "labelIds": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } + "agent": { + "$ref": "#/components/schemas/Actor" }, - "projectId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } - ] + "state": { + "$ref": "#/components/schemas/RunState" }, - "parentId": { + "reason": { "anyOf": [ { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "description": "lease_expired, reassigned, or canceled_by:" }, { "type": "null" } ] }, - "dueOn": { - "anyOf": [ - { - "type": "string", - "format": "date" - }, - { - "type": "null" - } - ] + "session": { + "type": "string", + "maxLength": 200 }, - "report": { - "anyOf": [ - { - "$ref": "#/components/schemas/Report" - }, - { - "type": "null" - } - ] + "note": { + "type": "string", + "maxLength": 200 }, - "blocks": { + "summary": { + "type": "string", + "description": "Markdown, at most 20 KiB UTF-8" + }, + "links": { "type": "array", "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } + "$ref": "#/components/schemas/Link" + }, + "maxItems": 10 + }, + "startedAt": { + "type": "string", + "format": "date-time" + }, + "heartbeatAt": { + "type": "string", + "format": "date-time" }, - "estimate": { - "anyOf": [ - { - "$ref": "#/components/schemas/Size" - }, - { - "type": "null" - } - ] + "leaseExpiresAt": { + "type": "string", + "format": "date-time" }, - "sprintId": { + "finishedAt": { "anyOf": [ { "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + "format": "date-time" }, { "type": "null" @@ -5963,221 +8796,188 @@ ] } }, - "required": [], + "required": [ + "id", + "issue", + "agent", + "state", + "reason", + "session", + "note", + "summary", + "links", + "startedAt", + "heartbeatAt", + "leaseExpiresAt", + "finishedAt" + ], "additionalProperties": false }, - "ViewCreate": { + "RunStart": { "type": "object", "properties": { - "name": { + "session": { "type": "string", - "maxLength": 60, - "minLength": 1 + "maxLength": 200 }, - "layout": { + "note": { "type": "string", - "enum": [ - "list", - "board" - ] - }, - "groupBy": { - "$ref": "#/components/schemas/GroupBy" - }, - "filter": { - "$ref": "#/components/schemas/Filter" - }, - "sort": { - "$ref": "#/components/schemas/Sort" - }, - "shared": { - "type": "boolean" + "maxLength": 200 } }, - "required": [ - "name" - ], + "required": [], "additionalProperties": false }, - "ViewPatch": { + "RunHeartbeat": { "type": "object", "properties": { - "name": { + "note": { "type": "string", - "maxLength": 60, - "minLength": 1 - }, - "layout": { + "maxLength": 200 + } + }, + "required": [], + "additionalProperties": false + }, + "RunFinish": { + "type": "object", + "properties": { + "outcome": { "type": "string", "enum": [ - "list", - "board" + "succeeded", + "failed" ] }, - "groupBy": { - "$ref": "#/components/schemas/GroupBy" - }, - "filter": { - "$ref": "#/components/schemas/Filter" - }, - "sort": { - "$ref": "#/components/schemas/Sort" - }, - "shared": { - "type": "boolean" + "summary": { + "type": "string", + "description": "Markdown, at most 20 KiB UTF-8" }, - "position": { - "type": "integer" + "links": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Link" + }, + "maxItems": 10 } }, - "required": [], - "additionalProperties": false - }, - "Size": { - "type": "string", - "enum": [ - "XS", - "S", - "M", - "L", - "XL" + "required": [ + "outcome", + "summary" ], - "description": "Fixed points: XS=1, S=2, M=3, L=5, XL=8; null counts zero." + "additionalProperties": false }, - "SprintState": { + "RequestKind": { "type": "string", "enum": [ - "planned", - "active", - "closed" + "question", + "approval", + "review" ] }, - "Unit": { + "RequestState": { "type": "string", "enum": [ - "points", - "issues" - ], - "default": "points" + "open", + "answered", + "withdrawn" + ] }, - "Tally": { + "RequestAnswer": { "type": "object", "properties": { - "scopePoints": { - "type": "integer", - "minimum": 0 - }, - "scopeIssues": { - "type": "integer", - "minimum": 0 - }, - "donePoints": { - "type": "integer", - "minimum": 0 + "option": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] }, - "doneIssues": { - "type": "integer", - "minimum": 0 - } - }, - "required": [ - "scopePoints", - "scopeIssues", - "donePoints", - "doneIssues" - ], - "additionalProperties": false - }, - "SprintRef": { - "type": "object", - "properties": { - "id": { + "body": { "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - "number": { - "type": "integer", - "minimum": 1 + "description": "Markdown, at most 20 KiB UTF-8" }, - "name": { - "type": "string" + "by": { + "$ref": "#/components/schemas/Actor" }, - "state": { - "$ref": "#/components/schemas/SprintState" + "at": { + "type": "string", + "format": "date-time" } }, "required": [ - "id", - "number", - "name", - "state" + "option", + "body", + "by", + "at" ], "additionalProperties": false }, - "Sprint": { + "Request": { "type": "object", "properties": { "id": { "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - "number": { - "type": "integer", - "minimum": 1 - }, - "name": { - "type": "string" - }, - "state": { - "$ref": "#/components/schemas/SprintState" - }, - "goal": { - "type": "string" + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "lengthWeeks": { - "type": "integer", - "enum": [ - 1, - 2 - ] + "issue": { + "$ref": "#/components/schemas/IssueRef" }, - "startsOn": { - "type": "string", - "format": "date" + "kind": { + "$ref": "#/components/schemas/RequestKind" }, - "endsOn": { - "type": "string", - "format": "date" + "from": { + "$ref": "#/components/schemas/Actor" }, - "startedAt": { + "to": { "anyOf": [ { - "type": "string", - "format": "date-time" + "$ref": "#/components/schemas/Actor" }, { "type": "null" } ] }, - "closedAt": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "body": { + "type": "string", + "description": "Markdown, at most 20 KiB UTF-8" + }, + "options": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 6 + }, + "runId": { "anyOf": [ { "type": "string", - "format": "date-time" + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, { "type": "null" } ] }, - "current": { - "$ref": "#/components/schemas/Tally" + "state": { + "$ref": "#/components/schemas/RequestState" }, - "commitment": { + "answer": { "anyOf": [ { - "$ref": "#/components/schemas/Tally" + "$ref": "#/components/schemas/RequestAnswer" }, { "type": "null" @@ -6185,96 +8985,73 @@ ] }, "createdAt": { - "type": "string", - "format": "date-time" - }, - "updatedAt": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "number", - "name", - "state", - "goal", - "lengthWeeks", - "startsOn", - "endsOn", - "startedAt", - "closedAt", - "current", - "commitment", - "createdAt", - "updatedAt" - ], - "additionalProperties": false - }, - "SprintCreate": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 60 - }, - "goal": { - "type": "string", - "description": "Valid UTF-8, at most 4096 bytes", - "maxLength": 4096 - }, - "startsOn": { - "type": "string", - "format": "date" - }, - "lengthWeeks": { - "type": "integer", - "enum": [ - 1, - 2 - ] + "type": "string", + "format": "date-time" } }, - "required": [], + "required": [ + "id", + "issue", + "kind", + "from", + "to", + "title", + "body", + "options", + "runId", + "state", + "answer", + "createdAt" + ], "additionalProperties": false }, - "SprintPatch": { + "RequestCreate": { "type": "object", "properties": { - "name": { + "kind": { "type": "string", - "minLength": 1, - "maxLength": 60 + "enum": [ + "question", + "approval" + ] }, - "goal": { + "title": { "type": "string", - "description": "Valid UTF-8, at most 4096 bytes", - "maxLength": 4096 + "minLength": 1, + "maxLength": 200 }, - "startsOn": { + "body": { "type": "string", - "format": "date" + "description": "Markdown, at most 20 KiB UTF-8" }, - "lengthWeeks": { - "type": "integer", - "enum": [ - 1, - 2 - ] - } - }, - "required": [], - "additionalProperties": false - }, - "SprintClose": { - "type": "object", - "properties": { - "moveIncompleteTo": { + "options": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 6, + "uniqueItems": true + }, + "to": { "anyOf": [ { "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Actor subject. Omitted for agents: delegator, else owner. Explicit null: any person." + }, + "runId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, { "type": "null" @@ -6283,128 +9060,244 @@ } }, "required": [ - "moveIncompleteTo" + "kind", + "title" ], "additionalProperties": false }, - "BurndownPoint": { + "RequestAnswerInput": { "type": "object", "properties": { - "day": { - "type": "string", - "format": "date" - }, - "scope": { - "type": "integer", - "minimum": 0 - }, - "done": { - "type": "integer", - "minimum": 0 - }, - "remaining": { - "type": "integer", - "minimum": 0 + "option": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] }, - "ideal": { - "type": "number" + "body": { + "type": "string", + "description": "Markdown, at most 20 KiB UTF-8" } }, - "required": [ - "day", - "ideal" - ], - "additionalProperties": false, - "description": "Future days omit scope, done, remaining. Ideal is rounded to two decimals and flat on weekends." + "required": [], + "additionalProperties": false }, - "Burndown": { + "InboxAck": { "type": "object", "properties": { - "sprint": { - "$ref": "#/components/schemas/SprintRef" - }, - "unit": { - "$ref": "#/components/schemas/Unit" - }, - "today": { - "type": "string", - "format": "date" + "answers": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "maxItems": 500, + "description": "Answered request IDs belonging to the caller." }, - "points": { + "mentions": { "type": "array", "items": { - "$ref": "#/components/schemas/BurndownPoint" - } + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "maxItems": 500, + "description": "Mentioned comment IDs; a caller has at most one mention per comment." } }, - "required": [ - "sprint", - "unit", - "today", - "points" - ], + "required": [], "additionalProperties": false }, - "VelocityEntry": { + "InboxItem": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "const": "request" + }, + "request": { + "$ref": "#/components/schemas/Request" + } + }, + "required": [ + "kind", + "request" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "const": "answer" + }, + "request": { + "$ref": "#/components/schemas/Request" + } + }, + "required": [ + "kind", + "request" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "const": "mention" + }, + "comment": { + "$ref": "#/components/schemas/Comment" + }, + "issue": { + "$ref": "#/components/schemas/IssueRef" + } + }, + "required": [ + "kind", + "comment", + "issue" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "const": "assignment" + }, + "issue": { + "$ref": "#/components/schemas/IssueSummary" + } + }, + "required": [ + "kind", + "issue" + ], + "additionalProperties": false + } + ] + }, + "Event": { "type": "object", "properties": { - "sprint": { - "$ref": "#/components/schemas/SprintRef" - }, - "lengthWeeks": { + "seq": { "type": "integer", - "enum": [ - 1, - 2 + "format": "int64", + "minimum": 1 + }, + "at": { + "type": "string", + "format": "date-time" + }, + "issue": { + "anyOf": [ + { + "$ref": "#/components/schemas/IssueRef" + }, + { + "type": "null" + } ] }, - "committed": { - "type": "integer", - "minimum": 0 + "actor": { + "$ref": "#/components/schemas/Actor" }, - "completed": { - "type": "integer", - "minimum": 0 + "type": { + "type": "string", + "enum": [ + "issue.created", + "issue.updated", + "issue.deleted", + "comment.created", + "run.started", + "run.finished", + "run.canceled", + "request.opened", + "request.answered", + "request.withdrawn" + ] + }, + "data": { + "description": "issue.updated: {fields: Activity field[]}; other types: entity ID.", + "oneOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "object", + "properties": { + "fields": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "created", + "title", + "description", + "type", + "priority", + "status", + "assignee", + "labels", + "project", + "parent", + "blocks", + "due", + "report", + "attachment", + "deleted", + "estimate", + "sprint", + "delegator" + ] + } + } + }, + "required": [ + "fields" + ], + "additionalProperties": false + } + ] } }, "required": [ - "sprint", - "lengthWeeks", - "committed", - "completed" + "seq", + "at", + "issue", + "actor", + "type", + "data" ], "additionalProperties": false }, - "Velocity": { + "EventPage": { "type": "object", "properties": { - "unit": { - "$ref": "#/components/schemas/Unit" - }, "items": { "type": "array", "items": { - "$ref": "#/components/schemas/VelocityEntry" + "$ref": "#/components/schemas/Event" } }, - "averagePerWeek": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] + "next": { + "type": "integer", + "format": "int64", + "minimum": 0 } }, "required": [ - "unit", "items", - "averagePerWeek" + "next" ], - "additionalProperties": false, - "description": "Most recent limit closed sprints, oldest first. Average of completed/lengthWeeks over the last three closed sprints, rounded to two decimals, or null." + "additionalProperties": false } } } diff --git a/cmd/server/internal/api/people.go b/cmd/server/internal/api/people.go index b4f9539..d0d171d 100644 --- a/cmd/server/internal/api/people.go +++ b/cmd/server/internal/api/people.go @@ -2,7 +2,6 @@ package api import ( "github.com/appthrust/tracker/cmd/server/internal/domain" - "github.com/appthrust/tracker/cmd/server/internal/store" ) type peopleResponse struct { @@ -31,7 +30,7 @@ func (a *API) enrich(s *request, body any) { } resolved := map[string]resolution{} person := func(p *domain.Person) { - if p == nil { + if p == nil || domain.ActorKind(p.Sub) == "agent" { return } if value, ok := resolved[p.Sub]; ok { @@ -44,70 +43,9 @@ func (a *API) enrich(s *request, body any) { *p = a.directory.Enrich(s.r.Context(), s.bearer, snapshot) resolved[p.Sub] = resolution{person: *p, fallback: *p == snapshot} } - issue := func(i *domain.IssueSummary) { person(&i.Reporter); person(i.Assignee) } - valuePerson := func(value any) { - m, ok := value.(map[string]any) - if !ok { - return - } - sub, ok := m["sub"].(string) - if !ok { - return - } - name, _ := m["name"].(string) - p := domain.Person{Sub: sub, Name: name} - person(&p) - m["name"] = p.Name - if p.Email != "" { - m["email"] = p.Email - } - if p.AvatarURL != "" { - m["avatarUrl"] = p.AvatarURL - } else { - delete(m, "avatarUrl") - } - if p.ProfileURL != "" { - m["profileUrl"] = p.ProfileURL - } - } - switch value := body.(type) { - case *meResponse: - person(&value.Person) - case *domain.Issue: - issue(&value.IssueSummary) - case *store.Page: - for i := range value.Items { - issue(&value.Items[i]) - } - case *domain.Comment: - person(&value.Author) - case *domain.Attachment: - person(&value.Uploader) - case *domain.View: - person(&value.Owner) - case *items[domain.View]: - for i := range value.Items { - person(&value.Items[i].Owner) - } - case *items[domain.TimelineItem]: - for _, item := range value.Items { - if item.Comment != nil { - person(&item.Comment.Author) - } - if item.Activity != nil { - person(&item.Activity.Actor) - if item.Activity.Field == "assignee" { - valuePerson(item.Activity.From) - valuePerson(item.Activity.To) - } - if item.Activity.Field == "attachment" { - for _, raw := range []any{item.Activity.From, item.Activity.To} { - if attachment, ok := raw.(map[string]any); ok { - valuePerson(attachment["uploader"]) - } - } - } - } - } + projection := responseActors(body) + for _, p := range projection.people { + person(p) } + projection.apply() } diff --git a/cmd/server/internal/api/routes.go b/cmd/server/internal/api/routes.go new file mode 100644 index 0000000..036de42 --- /dev/null +++ b/cmd/server/internal/api/routes.go @@ -0,0 +1,159 @@ +package api + +import ( + "fmt" + "strings" +) + +type routeDefinition struct { + pattern string + mutation bool + roles bool + handler endpoint + guide string +} + +// This is the registration and agent-guide authority. Special binary/public +// handlers (Directory avatar and OpenAPI) are mounted separately. +func (a *API) routes() []routeDefinition { + return []routeDefinition{ + {"GET /me", false, true, a.me, "Confirm your kind, agent handle, owner and scopes."}, + {"GET /workspace", false, false, a.workspaceGet, "Read the agentCompletion policy."}, + {"PATCH /workspace", true, true, a.workspacePatch, ""}, + {"GET /statuses", false, false, a.statusList, "Read workflow status IDs and categories."}, + {"POST /statuses", true, true, a.statusCreate, ""}, + {"PATCH /statuses/{id}", true, true, a.statusPatch, ""}, + {"DELETE /statuses/{id}", true, true, a.statusDelete, ""}, + {"PUT /statuses/order", true, true, a.statusOrder, ""}, + {"GET /labels", false, false, a.labelList, ""}, + {"POST /labels", true, true, a.labelCreate, ""}, + {"PATCH /labels/{id}", true, true, a.labelPatch, ""}, + {"DELETE /labels/{id}", true, true, a.labelDelete, ""}, + {"GET /projects", false, false, a.projectList, ""}, + {"POST /projects", true, false, a.projectCreate, ""}, + {"GET /projects/{id}", false, false, a.projectGet, ""}, + {"PATCH /projects/{id}", true, true, a.projectPatch, ""}, + {"DELETE /projects/{id}", true, true, a.projectDelete, ""}, + {"GET /sprints", false, false, a.sprintList, ""}, + {"POST /sprints", true, false, a.sprintCreate, ""}, + {"GET /sprints/{id}", false, false, a.sprintGet, ""}, + {"PATCH /sprints/{id}", true, false, a.sprintPatch, ""}, + {"POST /sprints/{id}/start", true, false, a.sprintStart, ""}, + {"POST /sprints/{id}/close", true, false, a.sprintClose, ""}, + {"DELETE /sprints/{id}", true, true, a.sprintDelete, ""}, + {"GET /sprints/{id}/burndown", false, false, a.sprintBurndown, ""}, + {"GET /velocity", false, false, a.velocity, ""}, + {"GET /issues", false, false, a.issueList, "Filter issues; list rows include delegator, activeRun and openRequestCount."}, + {"POST /issues", true, false, a.issueCreate, "Create an issue; you are its reporter. You may assign it to yourself."}, + {"GET /issues/{id}", false, false, a.issueGet, "Read current fields, updatedAt and blocking issues before editing."}, + {"PATCH /issues/{id}", true, false, a.issuePatch, "Edit only if assignee or reporter; send expectedUpdatedAt to avoid overwriting changes."}, + {"DELETE /issues/{id}", true, true, a.issueDelete, ""}, + {"GET /issues/{id}/timeline", false, false, a.timeline, "Read comments, activities, runs and requests."}, + {"POST /issues/{id}/comments", true, false, a.commentCreate, "Discuss any issue; @handle mentions a registered agent."}, + {"PATCH /comments/{id}", true, false, a.commentPatch, "Edit your own comment; mentions are reparsed."}, + {"DELETE /comments/{id}", true, true, a.commentDelete, ""}, + {"POST /issues/{id}/attachments", true, false, a.attachmentCreate, "Attach evidence (multipart; excluded from idempotent replay)."}, + {"GET /attachments/{id}", false, false, a.attachmentGet, ""}, + {"DELETE /attachments/{id}", true, true, a.attachmentDelete, ""}, + {"GET /views", false, false, a.viewList, ""}, + {"POST /views", true, true, a.viewCreate, ""}, + {"PATCH /views/{id}", true, true, a.viewPatch, ""}, + {"DELETE /views/{id}", true, true, a.viewDelete, ""}, + {"GET /people", false, false, a.people, "Keys cannot access Directory; returns an empty unavailable result."}, + {"GET /agents", false, false, a.agentList, "Discover agents; includeDisabled=true also returns retired identities."}, + {"POST /agents", true, true, a.agentCreate, ""}, + {"PATCH /agents/{id}", true, true, a.agentPatch, ""}, + {"GET /inbox", false, false, a.inbox, "Requests first, then answers, mentions and actionable assignments."}, + {"POST /inbox/ack", true, false, a.inboxAck, "Acknowledge {answers:[requestId], mentions:[commentId]} after handling them."}, + {"GET /events", false, false, a.events, "Initialize without after (empty items and current next); poll with after=next and limit 1–500."}, + {"POST /issues/{id}/runs", true, false, a.runStart, "Start only on your assigned issue with {session?,note?}; retain the returned run ID."}, + {"GET /issues/{id}/runs", false, false, a.runList, "Inspect newest runs first, including stalled and terminal history."}, + {"GET /runs/{id}", false, false, a.runGet, "Re-read your lease and state before resuming."}, + {"POST /runs/{id}/heartbeat", true, false, a.runHeartbeat, "Send {note?} well before the 10-minute lease expires, including while waiting."}, + {"POST /runs/{id}/finish", true, false, a.runFinish, "Send {outcome:'succeeded'|'failed',summary,links?}; links are HTTPS pr/commit/url entries."}, + {"POST /runs/{id}/cancel", true, false, a.runCancel, "Cancel your own run; any person may cancel it too. Open requests are withdrawn."}, + {"POST /issues/{id}/requests", true, false, a.requestCreate, "Raise {kind:'question'|'approval',title,body?,options?,to?,runId?}; omitted to defaults to delegator/owner, null means any person."}, + {"GET /requests", false, false, a.requestList, "Filter by state, to (subject, me, or none), and issue (ID or identifier)."}, + {"GET /requests/{id}", false, false, a.requestGet, "Read a handoff and its answer."}, + {"POST /requests/{id}/answer", true, true, a.requestAnswer, "Answer a question addressed to you using {option?,body?}; choose one offered option if present."}, + {"POST /requests/{id}/withdraw", true, false, a.requestWithdraw, "Withdraw your open request when it is no longer needed."}, + {"GET /agent-guide", false, false, a.agentGuide, "Read this protocol."}, + } +} + +type markdown string + +func (a *API) agentGuide(_ *request) (any, int, error) { + var out strings.Builder + out.WriteString(`# Tracker agent protocol + +## Identity + +Ask an Admin to register your immutable handle and mint an external-subject +Access Key with that same handle. No Tracker-issued secret is involved. +Exchange the key for a short-lived assertion, never send the raw key here: + +` + "```sh\napth access-keys create --project --space tracker --external --scope tracker:read --scope tracker:write\nprintf %s \"$KEY\" | apth access-keys exchange --project \n```\n" + ` +Send Authorization: Bearer and Content-Type: application/json. +GET needs tracker:read; other methods need tracker:write; neither implies the +other. Refresh assertions before expiry. Admin operations refuse every key. + +## Inbox and event loop + +Initialize the event cursor first, then read the inbox. Poll the feed using its +next cursor (drain full pages before sleeping); persist the cursor only after +handling every item. Re-read relevant entities: events are notifications, not +commands. The inbox is the recovery authority if your local cursor is lost. +Handle requests first, then answers and mentions; acknowledge an answer by its +request ID and a mention by its comment ID. Assignments are actionable work, +including Backlog. If activeRun is live, resume it instead of starting another. +Do not start work blocked by unfinished dependencies or your open requests. + +## Runs and handoffs + +One non-terminal run may hold an issue. Keep heartbeating even while waiting. +A stalled run cannot be revived: stop the old execution and start a fresh run; +that start closes the expired lease as failed/lease_expired and withdraws its +requests. Reassignment or disabling cancels runs and withdraws open requests. +Only attach a request to your own live run on that same issue. It makes the run +waiting; the last answer or withdrawal returns it to running. Questions may +be addressed to agents. Approval and review are answered only by people. + +Finishing succeeded is refused while an approval of the run is open: resolve +or withdraw it first. Under review, success opens a review to your delegator +(or owner) and withdraws open questions. Do not set a completed status yourself. +Only a person's approval completes the issue; rejection arrives as an answer. +Under direct you may set a completed status yourself; finishing a run alone +never changes issue status. Failed/canceled runs withdraw all open requests. + +## Safe retries and conflicts + +Use a fresh Idempotency-Key (1–128 characters) for every new POST operation; +retry an uncertain response with exactly the same path and body and same key. +The first response is replayed for 24 hours per actor, across all of its keys. +Use a new key for each heartbeat. Multipart attachment uploads are excluded. +For field edits, send expectedUpdatedAt from your latest issue read. + +401: exchange again; raw_key_not_accepted means you sent a raw key. +403 insufficient_scope: ask for the missing scope. 403 key_subject: ask the +Admin whether your handle is registered and active. 403 forbidden: do not +retry as another actor; ask the delegator to perform the prohibited action. +409 conflict: re-read the issue/run/request. Stop after lease expiry or +reassignment; do not overwrite an updated issue. Resolve open approvals before +success. Never reuse an idempotency key for a different operation. + +## Routes + +All routes below are relative to /api/tracker/v1. This inventory is generated +from the same table used to register the handlers. + +| Method and route | Protocol | +| --- | --- | +`) + for _, route := range a.routes() { + if route.guide != "" { + fmt.Fprintf(&out, "| `%s` | %s |\n", route.pattern, strings.ReplaceAll(route.guide, "|", "\\|")) + } + } + return markdown(out.String()), 200, nil +} diff --git a/cmd/server/internal/api/settings.go b/cmd/server/internal/api/settings.go index 160df90..3a95f91 100644 --- a/cmd/server/internal/api/settings.go +++ b/cmd/server/internal/api/settings.go @@ -1,18 +1,32 @@ package api import ( + "encoding/json" "github.com/appthrust/tracker/cmd/server/internal/domain" "github.com/appthrust/tracker/cmd/server/internal/store" ) type meResponse struct { domain.Person - Role string `json:"role"` - IsAdmin bool `json:"isAdmin"` + Role string `json:"role"` + IsAdmin bool `json:"isAdmin"` + Scopes []string `json:"scopes,omitempty"` +} + +// Person marshals its derived kind; explicitly retain Me's additional fields. +func (m meResponse) MarshalJSON() ([]byte, error) { + type person domain.Person + return json.Marshal(struct { + person + Kind string `json:"kind"` + Role string `json:"role"` + IsAdmin bool `json:"isAdmin"` + Scopes []string `json:"scopes,omitempty"` + }{person(m.Person), domain.ActorKind(m.Sub), m.Role, m.IsAdmin, m.Scopes}) } func (a *API) me(s *request) (any, int, error) { - return &meResponse{Person: s.actor.Person, Role: s.actor.Role, IsAdmin: s.actor.Role == "Admin"}, 200, nil + return &meResponse{Person: s.actor.Person, Role: s.actor.Role, IsAdmin: domain.Can(s.actor, domain.ManageWorkspace, domain.Target{}), Scopes: s.actor.Scopes}, 200, nil } func (a *API) workspaceGet(s *request) (any, int, error) { item, err := s.tx.Workspace() @@ -27,11 +41,12 @@ func (a *API) workspacePatch(s *request) (any, int, error) { Name *string `json:"name"` SprintLengthWeeks *int `json:"sprintLengthWeeks"` Timezone *string `json:"timezone"` + AgentCompletion *string `json:"agentCompletion"` } if err := decode(s, &input); err != nil { return nil, 0, err } - item, err := s.tx.PatchWorkspace(input.Key, input.Name, input.SprintLengthWeeks, input.Timezone) + item, err := s.tx.PatchWorkspace(input.Key, input.Name, input.SprintLengthWeeks, input.Timezone, input.AgentCompletion) return item, 200, err } func (a *API) statusList(s *request) (any, int, error) { diff --git a/cmd/server/internal/api/sprints.go b/cmd/server/internal/api/sprints.go index 9ed9ca1..f8edf1e 100644 --- a/cmd/server/internal/api/sprints.go +++ b/cmd/server/internal/api/sprints.go @@ -1,6 +1,7 @@ package api import ( + "github.com/appthrust/appserver-go/appserver/httpx" "strconv" "github.com/appthrust/tracker/cmd/server/internal/domain" @@ -35,10 +36,16 @@ func (a *API) sprintPatch(s *request) (any, int, error) { return item, 200, err } func (a *API) sprintStart(s *request) (any, int, error) { + if !domain.Can(s.actor, domain.ManageSprint, domain.Target{}) { + return nil, 0, httpx.Forbidden() + } item, err := s.tx.StartSprint(s.r.PathValue("id")) return item, 200, err } func (a *API) sprintClose(s *request) (any, int, error) { + if !domain.Can(s.actor, domain.ManageSprint, domain.Target{}) { + return nil, 0, httpx.Forbidden() + } var input struct { MoveIncompleteTo store.Field[string] `json:"moveIncompleteTo"` } diff --git a/cmd/server/internal/api/sprints_test.go b/cmd/server/internal/api/sprints_test.go index 4103f91..e71bba4 100644 --- a/cmd/server/internal/api/sprints_test.go +++ b/cmd/server/internal/api/sprints_test.go @@ -36,7 +36,7 @@ func TestSprintRequestValidationWithoutDatabase(t *testing.T) { r := httptest.NewRequest("POST", "/", strings.NewReader(tc.body)) r.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() - _, _, err := tc.handler(&request{r: r, w: w}) + _, _, err := tc.handler(&request{r: r, w: w, actor: domain.Actor{Person: domain.Person{Sub: "viewer"}, Kind: "person"}}) require.Error(t, err) writeStoreError(w, err) require.Equal(t, 400, w.Code) diff --git a/cmd/server/internal/assertiontestutil/main.go b/cmd/server/internal/assertiontestutil/main.go new file mode 100644 index 0000000..d6e19e6 --- /dev/null +++ b/cmd/server/internal/assertiontestutil/main.go @@ -0,0 +1,77 @@ +// Command assertiontestutil serves disposable signed assertions, JWKS and an +// Admin role fixture for local smoke tests. It is not linked into the server. +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/base64" + "encoding/json" + "flag" + "log" + "net" + "net/http" + "os" + "time" + + "github.com/appthrust/appserver-go/accesskey" +) + +func main() { + output := flag.String("output", "", "private temporary token bundle path") + flag.Parse() + if *output == "" { + log.Fatal("--output is required") + } + private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + log.Fatal(err) + } + signer := accesskey.NewES256Signer("agents-smoke", private) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + log.Fatal(err) + } + origin := "http://" + listener.Addr().String() + issuer := accesskey.IssuerURL(origin) + bundle := map[string]string{"origin": origin, "issuer": issuer} + for _, subject := range []accesskey.Subject{ + {Kind: accesskey.SubjectExternal, ID: "astra"}, + {Kind: accesskey.SubjectExternal, ID: "other"}, + {Kind: accesskey.SubjectUser, ID: "smoke-person"}, + } { + now := time.Now() + token, err := signer.Sign(accesskey.Claims{Issuer: issuer, Audience: "tracker", Project: "pj-agents-smoke", KeyName: "ak-smoke", Subject: subject, Scopes: []string{"tracker:read", "tracker:write"}, JTI: subject.ID, IssuedAt: now, ExpiresAt: now.Add(5 * time.Minute)}) + if err != nil { + log.Fatal(err) + } + bundle[subject.ID] = token + } + claims, err := json.Marshal(map[string]string{"sub": "smoke-person", "name": "Smoke Person", "email": "smoke@example.test"}) + if err != nil { + log.Fatal(err) + } + bundle["person"] = base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) + "." + base64.RawURLEncoding.EncodeToString(claims) + "." + data, err := json.Marshal(bundle) + if err != nil { + log.Fatal(err) + } + if err := os.WriteFile(*output, data, 0600); err != nil { + log.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("GET /access/jwks.json", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(signer.JWKS()) + }) + mux.HandleFunc("GET /api/v1/projects/pj-agents-smoke/access", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer "+bundle["person"] { + http.Error(w, "unauthorized", 401) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"projectId": "pj-agents-smoke", "member": true, "roles": []string{"Admin"}}) + }) + log.Fatal(http.Serve(listener, mux)) +} diff --git a/cmd/server/internal/domain/agents.go b/cmd/server/internal/domain/agents.go new file mode 100644 index 0000000..f18e0da --- /dev/null +++ b/cmd/server/internal/domain/agents.go @@ -0,0 +1,142 @@ +package domain + +import ( + "encoding/json" + "strings" + "time" +) + +// ActorKind derives attribution for existing snapshots without rewriting history. +func ActorKind(sub string) string { + if strings.HasPrefix(sub, "agent:") { + return "agent" + } + return "person" +} + +func (p Person) MarshalJSON() ([]byte, error) { + type person Person + return json.Marshal(struct { + person + Kind string `json:"kind"` + }{person(p), ActorKind(p.Sub)}) +} + +type AgentIdentity struct { + ID string `json:"id"` + Handle string `json:"handle"` + Owner Person `json:"owner"` + Disabled bool `json:"disabled"` +} + +type Agent struct { + ID string `json:"id"` + Handle string `json:"handle"` + Name string `json:"name"` + Description string `json:"description"` + Owner Person `json:"owner"` + Disabled bool `json:"disabled"` + ActiveRuns int `json:"activeRuns"` + OpenRequests int `json:"openRequests"` + LastSeenAt *time.Time `json:"lastSeenAt"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +func (a Agent) Person() Person { + return Person{Sub: "agent:" + a.ID, Name: a.Name, Agent: &AgentIdentity{ID: a.ID, Handle: a.Handle, Owner: a.Owner, Disabled: a.Disabled}} +} + +type RunLink struct { + Kind string `json:"kind"` + URL string `json:"url"` + Title string `json:"title"` +} + +type Run struct { + ID string `json:"id"` + Issue IssueRef `json:"issue"` + Agent Person `json:"agent"` + State string `json:"state"` + Reason *string `json:"reason"` + Session string `json:"session"` + Note string `json:"note"` + Summary string `json:"summary"` + Links []RunLink `json:"links"` + StartedAt time.Time `json:"startedAt"` + HeartbeatAt time.Time `json:"heartbeatAt"` + LeaseExpiresAt time.Time `json:"leaseExpiresAt"` + FinishedAt *time.Time `json:"finishedAt"` +} + +func RunState(state string, leaseExpiresAt, now time.Time) string { + if (state == "running" || state == "waiting") && leaseExpiresAt.Before(now) { + return "stalled" + } + return state +} + +// Expired leases cannot be revived. The next start closes the old run. +func LiveRun(state string) bool { return state == "running" || state == "waiting" } + +type RequestAnswer struct { + Option *string `json:"option"` + Body string `json:"body"` + By Person `json:"by"` + At time.Time `json:"at"` +} + +type Request struct { + ID string `json:"id"` + Issue IssueRef `json:"issue"` + Kind string `json:"kind"` + From Person `json:"from"` + To *Person `json:"to"` + Title string `json:"title"` + Body string `json:"body"` + Options []string `json:"options"` + RunID *string `json:"runId"` + State string `json:"state"` + Answer *RequestAnswer `json:"answer"` + CreatedAt time.Time `json:"createdAt"` +} + +type InboxItem struct { + Kind string `json:"kind"` + Request *Request `json:"request,omitempty"` + Issue *IssueSummary `json:"issue,omitempty"` + Comment *Comment `json:"comment,omitempty"` +} + +func (i InboxItem) MarshalJSON() ([]byte, error) { + type item InboxItem + if i.Kind == "mention" { + return json.Marshal(struct { + Kind string `json:"kind"` + Comment *Comment `json:"comment"` + Issue IssueRef `json:"issue"` + }{i.Kind, i.Comment, IssueRef{ID: i.Issue.ID, Identifier: i.Issue.Identifier, Title: i.Issue.Title, StatusID: i.Issue.StatusID}}) + } + return json.Marshal(item(i)) +} + +type ActionableInput struct { + Deleted bool + Category string + OtherActiveRun bool + OwnOpenRequest bool + UnfinishedBlock bool +} + +func Actionable(in ActionableInput) bool { + return !in.Deleted && (in.Category == "backlog" || in.Category == "unstarted" || in.Category == "started") && !in.OtherActiveRun && !in.OwnOpenRequest && !in.UnfinishedBlock +} + +type Event struct { + Seq int64 `json:"seq"` + At time.Time `json:"at"` + Issue *IssueRef `json:"issue"` + Actor Person `json:"actor"` + Type string `json:"type"` + Data any `json:"data"` +} diff --git a/cmd/server/internal/domain/agents_test.go b/cmd/server/internal/domain/agents_test.go new file mode 100644 index 0000000..aa24de2 --- /dev/null +++ b/cmd/server/internal/domain/agents_test.go @@ -0,0 +1,129 @@ +package domain + +import ( + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestCollaborationAuthorization(t *testing.T) { + person := Actor{Person: Person{Sub: "pat"}, Kind: "person"} + agent := Actor{Person: Person{Sub: "agent:a"}, Kind: "agent", AgentID: "a", Key: true} + admin := person + admin.Role = "Admin" + key := admin + key.Key = true + for _, tc := range []struct { + name string + actor Actor + action Action + target Target + want bool + }{ + {"person completes", person, SetStatus, Target{Category: "completed", AgentCompletion: "review"}, true}, + {"agent cannot complete", agent, SetStatus, Target{Category: "completed", AgentCompletion: "review"}, false}, + {"direct completion", agent, SetStatus, Target{Category: "completed", AgentCompletion: "direct"}, true}, + {"other status", agent, SetStatus, Target{Category: "started", AgentCompletion: "review"}, true}, + {"self assignment own report", agent, AssignAgent, Target{OwnerSub: "agent:a", ReporterSub: "agent:a"}, true}, + {"cannot pull backlog", agent, AssignAgent, Target{OwnerSub: "agent:a", ReporterSub: "pat"}, false}, + {"cannot assign another agent", agent, AssignAgent, Target{OwnerSub: "agent:b", ReporterSub: "agent:a"}, false}, + {"start assigned", agent, StartRun, Target{OwnerSub: "agent:a"}, true}, + {"start unassigned", agent, StartRun, Target{OwnerSub: "agent:b"}, false}, + {"person cannot start", person, StartRun, Target{OwnerSub: "pat"}, false}, + {"heartbeat owner", agent, HeartbeatRun, Target{OwnerSub: "agent:a"}, true}, + {"heartbeat other", agent, HeartbeatRun, Target{OwnerSub: "agent:b"}, false}, + {"finish owner", agent, FinishRun, Target{OwnerSub: "agent:a"}, true}, + {"finish other", agent, FinishRun, Target{OwnerSub: "agent:b"}, false}, + {"person cancel", person, CancelRun, Target{OwnerSub: "agent:a"}, true}, + {"agent cancel own", agent, CancelRun, Target{OwnerSub: "agent:a"}, true}, + {"agent cancel other", agent, CancelRun, Target{OwnerSub: "agent:b"}, false}, + {"agent question", agent, AnswerRequest, Target{OwnerSub: "agent:a", RequestKind: "question"}, true}, + {"agent not any person", agent, AnswerRequest, Target{RequestKind: "question"}, false}, + {"agent never approves", agent, AnswerRequest, Target{OwnerSub: "agent:a", RequestKind: "approval"}, false}, + {"agent never reviews", agent, AnswerRequest, Target{OwnerSub: "agent:a", RequestKind: "review"}, false}, + {"person addressed", person, AnswerRequest, Target{OwnerSub: "pat", RequestKind: "review"}, true}, + {"person not addressed", person, AnswerRequest, Target{OwnerSub: "other", RequestKind: "review"}, false}, + {"any person", person, AnswerRequest, Target{RequestKind: "approval"}, true}, + {"admin override", admin, AnswerRequest, Target{OwnerSub: "other", RequestKind: "review"}, true}, + {"admin management", admin, ManageWorkspace, Target{}, true}, + {"key never admin", key, ManageWorkspace, Target{}, false}, + {"agent never admin", agent, ManageWorkspace, Target{}, false}, + {"agent reads", agent, Read, Target{}, true}, + {"agent creates", agent, Create, Target{}, true}, + {"agent edits assigned", agent, EditIssue, Target{OwnerSub: agent.Sub}, true}, + {"agent edits reported", agent, EditIssue, Target{ReporterSub: agent.Sub}, true}, + {"agent cannot edit unrelated", agent, EditIssue, Target{}, false}, + {"agent withdraws own", agent, WithdrawRequest, Target{OwnerSub: agent.Sub}, true}, + {"agent cannot withdraw other", agent, WithdrawRequest, Target{OwnerSub: person.Sub}, false}, + {"person withdraws own", person, WithdrawRequest, Target{OwnerSub: person.Sub}, true}, + {"admin cannot withdraw other", admin, WithdrawRequest, Target{OwnerSub: agent.Sub}, false}, + {"agent edits own comment", agent, EditComment, Target{OwnerSub: agent.Sub}, true}, + {"agent cannot edit other comment", agent, EditComment, Target{OwnerSub: person.Sub}, false}, + {"agent cannot delete issue", agent, DeleteIssue, Target{OwnerSub: agent.Sub}, false}, + {"agent cannot delete comment", agent, DeleteComment, Target{OwnerSub: agent.Sub}, false}, + {"agent cannot delete attachment", agent, DeleteAttachment, Target{OwnerSub: agent.Sub}, false}, + {"agent cannot delete private view", agent, DeleteView, Target{OwnerSub: agent.Sub}, false}, + {"person deletes private view", person, DeleteView, Target{OwnerSub: person.Sub}, true}, + {"agent private view", agent, CreateView, Target{}, true}, + {"agent no shared view", agent, CreateView, Target{Shared: true}, false}, + {"agent edits private view", agent, ManageView, Target{OwnerSub: agent.Sub}, true}, + {"agent cannot edit shared view", agent, ManageView, Target{OwnerSub: agent.Sub, Shared: true}, false}, + {"agent cannot start close sprint", agent, ManageSprint, Target{}, false}, + {"person starts closes sprint", person, ManageSprint, Target{}, true}, + {"key starts closes sprint", key, ManageSprint, Target{}, true}, + {"agent cannot archive project", agent, ArchiveProject, Target{}, false}, + {"agent cannot delete project", agent, DeleteProject, Target{}, false}, + {"key cannot delete issue", key, DeleteIssue, Target{}, false}, + {"key cannot share view", key, CreateView, Target{Shared: true}, false}, + {"key cannot override review addressee", key, AnswerRequest, Target{OwnerSub: "other", RequestKind: "review"}, false}, + {"person cannot drive run", person, HeartbeatRun, Target{OwnerSub: person.Sub}, false}, + {"person cannot finish run", person, FinishRun, Target{OwnerSub: person.Sub}, false}, + } { + t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.want, Can(tc.actor, tc.action, tc.target)) }) + } +} + +func TestRunLeaseDerivation(t *testing.T) { + now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC) + for _, state := range []string{"running", "waiting", "succeeded", "failed", "canceled"} { + for _, delta := range []time.Duration{-time.Nanosecond, 0, time.Nanosecond} { + want := state + if LiveRun(state) && delta < 0 { + want = "stalled" + } + require.Equal(t, want, RunState(state, now.Add(delta), now)) + } + } + require.False(t, LiveRun("stalled")) +} + +func TestActionable(t *testing.T) { + for _, tc := range []struct { + input ActionableInput + want bool + }{ + {ActionableInput{Category: "unstarted"}, true}, + {ActionableInput{Category: "started"}, true}, + {ActionableInput{Category: "backlog"}, true}, + {ActionableInput{Category: "completed"}, false}, + {ActionableInput{Category: "canceled"}, false}, + {ActionableInput{Category: "started", Deleted: true}, false}, + {ActionableInput{Category: "started", OtherActiveRun: true}, false}, + {ActionableInput{Category: "started", OwnOpenRequest: true}, false}, + {ActionableInput{Category: "started", UnfinishedBlock: true}, false}, + } { + require.Equal(t, tc.want, Actionable(tc.input)) + } +} + +func TestPersonWireKind(t *testing.T) { + for _, sub := range []string{"pat", "agent:a"} { + data, err := json.Marshal(Person{Sub: sub, Name: sub}) + require.NoError(t, err) + var wire map[string]any + require.NoError(t, json.Unmarshal(data, &wire)) + require.Equal(t, ActorKind(sub), wire["kind"]) + } +} diff --git a/cmd/server/internal/domain/mentions.go b/cmd/server/internal/domain/mentions.go new file mode 100644 index 0000000..2a05580 --- /dev/null +++ b/cmd/server/internal/domain/mentions.go @@ -0,0 +1,39 @@ +package domain + +import ( + "regexp" + "unicode" + "unicode/utf8" +) + +var mentionToken = regexp.MustCompile(`@[a-z][a-z0-9-]*`) + +// MentionHandles recognizes standalone, case-sensitive handles, not email +// addresses or prefixes of longer tokens. Repeated mentions have one target. +func MentionHandles(body string) []string { + handles := []string{} + seen := map[string]bool{} + word := func(r rune) bool { + return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_' || r == '-' || r == '@' || r == '.' + } + for _, at := range mentionToken.FindAllStringIndex(body, -1) { + if at[0] > 0 { + r, _ := utf8.DecodeLastRuneInString(body[:at[0]]) + if word(r) { + continue + } + } + if at[1] < len(body) { + r, _ := utf8.DecodeRuneInString(body[at[1]:]) + if unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_' || r == '-' { + continue + } + } + handle := body[at[0]+1 : at[1]] + if len(handle) >= 2 && len(handle) <= 31 && !seen[handle] { + seen[handle] = true + handles = append(handles, handle) + } + } + return handles +} diff --git a/cmd/server/internal/domain/mentions_test.go b/cmd/server/internal/domain/mentions_test.go new file mode 100644 index 0000000..b1cc718 --- /dev/null +++ b/cmd/server/internal/domain/mentions_test.go @@ -0,0 +1,42 @@ +package domain + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMentionHandles(t *testing.T) { + for _, tc := range []struct { + body string + handles []string + }{ + {"No mentions", []string{}}, + {"@astra and @opus-ui, @astra again", []string{"astra", "opus-ui"}}, + {"(@astra) **@claude**", []string{"astra", "claude"}}, + {"name@astra.example @Astra @a @astra_more @@astra", []string{}}, + {"@" + strings.Repeat("a", 31) + " @" + strings.Repeat("b", 32), []string{strings.Repeat("a", 31)}}, + {"@astraさん text@astra @astra.", []string{"astra"}}, + } { + require.Equal(t, tc.handles, MentionHandles(tc.body), tc.body) + } +} + +func TestAgentFilters(t *testing.T) { + for _, tc := range []struct { + filter Filter + valid bool + }{ + {Filter{AssigneeKind: []string{"person", "agent"}}, true}, + {Filter{AssigneeKind: []string{"robot"}}, false}, + {Filter{Agent: []string{"01M74SFSZ657XZ2HNWWA9VND8T"}}, true}, + {Filter{Agent: []string{"astra"}}, false}, + {Filter{Run: []string{"active", "stalled", "none"}}, true}, + {Filter{Run: []string{"running"}}, false}, + {Filter{Request: []string{"open", "mine"}}, true}, + {Filter{Request: []string{"answered"}}, false}, + } { + require.Equal(t, tc.valid, ValidateFilter(tc.filter) == nil, "%+v", tc.filter) + } +} diff --git a/cmd/server/internal/domain/rules.go b/cmd/server/internal/domain/rules.go index a395929..5db3e73 100644 --- a/cmd/server/internal/domain/rules.go +++ b/cmd/server/internal/domain/rules.go @@ -78,29 +78,66 @@ const ( EditProject Action = "edit_project" ArchiveProject Action = "archive_project" DeleteProject Action = "delete_project" + SetStatus Action = "set_status" + AssignAgent Action = "assign_agent" + StartRun Action = "start_run" + HeartbeatRun Action = "heartbeat_run" + FinishRun Action = "finish_run" + CancelRun Action = "cancel_run" + AnswerRequest Action = "answer_request" + ManageSprint Action = "manage_sprint" + WithdrawRequest Action = "withdraw_request" + DeleteView Action = "delete_view" ) type Target struct { - OwnerSub string - Shared bool + OwnerSub string + Shared bool + Category string + AgentCompletion string + ReporterSub string + RequestKind string } func Can(actor Actor, action Action, target Target) bool { if actor.Sub == "" { return false } - admin := actor.Role == "Admin" + agent := actor.Kind == "agent" + admin := actor.Role == "Admin" && !actor.Key && !agent switch action { - case Read, Create, EditIssue, CreateProject, EditProject: + case SetStatus: + return !agent || target.Category != "completed" || target.AgentCompletion == "direct" + case AssignAgent: + return !agent || (target.OwnerSub == actor.Sub && target.ReporterSub == actor.Sub) + case StartRun, HeartbeatRun, FinishRun: + return agent && actor.Sub == target.OwnerSub + case CancelRun: + return !agent || actor.Sub == target.OwnerSub + case AnswerRequest: + // Approval/review may never be answered by an agent. + if agent && target.RequestKind != "question" { + return false + } + return actor.Sub == target.OwnerSub || (!agent && (target.OwnerSub == "" || admin)) + case WithdrawRequest: + return actor.Sub == target.OwnerSub + case EditIssue: + return !agent || actor.Sub == target.OwnerSub || actor.Sub == target.ReporterSub + case ManageSprint: + return !agent + case Read, Create, CreateProject, EditProject: return true case ManageWorkspace, DeleteIssue, ArchiveProject, DeleteProject: return admin case EditComment: return actor.Sub == target.OwnerSub case DeleteComment, DeleteAttachment: - return admin || actor.Sub == target.OwnerSub + return !agent && (admin || actor.Sub == target.OwnerSub) case CreateView: return !target.Shared || admin + case DeleteView: + return !agent && Can(actor, ManageView, target) case ManageView: if target.Shared { return admin @@ -210,6 +247,9 @@ func ValidateFilter(filter Filter) error { values, allowed []string }{ {"category", filter.Category, Categories}, {"type", filter.Type, Types}, {"priority", filter.Priority, Priorities}, {"surface", filter.Surface, Surfaces}, + {"assigneeKind", filter.AssigneeKind, []string{"person", "agent"}}, + {"run", filter.Run, []string{"active", "stalled", "none"}}, + {"request", filter.Request, []string{"open", "mine"}}, } { for _, value := range field.values { if !slices.Contains(field.allowed, value) { @@ -217,7 +257,7 @@ func ValidateFilter(filter Filter) error { } } } - for _, ids := range [][]string{filter.Status, filter.Label} { + for _, ids := range [][]string{filter.Status, filter.Label, filter.Agent} { for _, id := range ids { if !ValidID(id) { return errors.New("Filter contains an invalid resource ID") diff --git a/cmd/server/internal/domain/types.go b/cmd/server/internal/domain/types.go index 2bde4de..b85b4fb 100644 --- a/cmd/server/internal/domain/types.go +++ b/cmd/server/internal/domain/types.go @@ -4,15 +4,20 @@ package domain import "time" type Person struct { - Sub string `json:"sub"` - Name string `json:"name"` - AvatarURL string `json:"avatarUrl,omitempty"` - Email string `json:"email,omitempty"` - ProfileURL string `json:"profileUrl,omitempty"` + Sub string `json:"sub"` + Name string `json:"name"` + AvatarURL string `json:"avatarUrl,omitempty"` + Email string `json:"email,omitempty"` + ProfileURL string `json:"profileUrl,omitempty"` + Agent *AgentIdentity `json:"agent,omitempty"` } type Actor struct { Person - Role string + Role string + Kind string + AgentID string + Key bool + Scopes []string } type Workspace struct { ID string `json:"id"` @@ -21,6 +26,7 @@ type Workspace struct { IssueCount int `json:"issueCount"` SprintLengthWeeks int `json:"sprintLengthWeeks"` Timezone string `json:"timezone"` + AgentCompletion string `json:"agentCompletion"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } @@ -71,30 +77,33 @@ type ProgressPoints struct { Completed int `json:"completed"` } type IssueSummary struct { - ID string `json:"id"` - Identifier string `json:"identifier"` - Number int64 `json:"number"` - Title string `json:"title"` - Type string `json:"type"` - Priority string `json:"priority"` - StatusID string `json:"statusId"` - Assignee *Person `json:"assignee"` - Reporter Person `json:"reporter"` - LabelIDs []string `json:"labelIds"` - ProjectID *string `json:"projectId"` - Estimate *string `json:"estimate"` - Sprint *SprintRef `json:"sprint"` - Parent *IssueRef `json:"parent"` - Epic *IssueRef `json:"epic"` - Story *IssueRef `json:"story"` - Progress *Progress `json:"progress"` - DueOn *string `json:"dueOn"` - Report *Report `json:"report"` - CommentCount int `json:"commentCount"` - AttachmentCount int `json:"attachmentCount"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - CompletedAt *time.Time `json:"completedAt"` + ID string `json:"id"` + Identifier string `json:"identifier"` + Number int64 `json:"number"` + Title string `json:"title"` + Type string `json:"type"` + Priority string `json:"priority"` + StatusID string `json:"statusId"` + Assignee *Person `json:"assignee"` + Reporter Person `json:"reporter"` + Delegator *Person `json:"delegator"` + ActiveRun *Run `json:"activeRun"` + OpenRequestCount int `json:"openRequestCount"` + LabelIDs []string `json:"labelIds"` + ProjectID *string `json:"projectId"` + Estimate *string `json:"estimate"` + Sprint *SprintRef `json:"sprint"` + Parent *IssueRef `json:"parent"` + Epic *IssueRef `json:"epic"` + Story *IssueRef `json:"story"` + Progress *Progress `json:"progress"` + DueOn *string `json:"dueOn"` + Report *Report `json:"report"` + CommentCount int `json:"commentCount"` + AttachmentCount int `json:"attachmentCount"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + CompletedAt *time.Time `json:"completedAt"` } type Issue struct { IssueSummary @@ -108,6 +117,7 @@ type Comment struct { IssueID string `json:"issueId"` Author Person `json:"author"` Body string `json:"body"` + Mentions []Person `json:"mentions"` CreatedAt time.Time `json:"createdAt"` EditedAt *time.Time `json:"editedAt"` } @@ -134,12 +144,18 @@ type TimelineItem struct { Kind string `json:"kind"` Activity *Activity `json:"activity,omitempty"` Comment *Comment `json:"comment,omitempty"` + Run *Run `json:"run,omitempty"` + Request *Request `json:"request,omitempty"` } type Filter struct { Status []string `json:"status,omitempty"` Category []string `json:"category,omitempty"` Assignee []string `json:"assignee,omitempty"` Reporter []string `json:"reporter,omitempty"` + AssigneeKind []string `json:"assigneeKind,omitempty"` + Agent []string `json:"agent,omitempty"` + Run []string `json:"run,omitempty"` + Request []string `json:"request,omitempty"` Label []string `json:"label,omitempty"` Project []string `json:"project,omitempty"` Sprint []string `json:"sprint,omitempty"` diff --git a/cmd/server/internal/store/actors.go b/cmd/server/internal/store/actors.go new file mode 100644 index 0000000..9d0ac4f --- /dev/null +++ b/cmd/server/internal/store/actors.go @@ -0,0 +1,43 @@ +package store + +import ( + "strings" + + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/lib/pq" +) + +// HydrateActors resolves all agent identities in one response in one query. +// Person snapshots are untouched, and no Directory call is made for a key. +func (t *Tx) HydrateActors(people []*domain.Person) error { + byID := map[string][]*domain.Person{} + ids := []string{} + for _, person := range people { + if person == nil || domain.ActorKind(person.Sub) != "agent" { + continue + } + id := strings.TrimPrefix(person.Sub, "agent:") + if _, found := byID[id]; !found { + ids = append(ids, id) + } + byID[id] = append(byID[id], person) + } + if len(ids) == 0 { + return nil + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT id,handle,name,owner_sub,owner_name,disabled FROM tracker_agent WHERE workspace_id=$1 AND id=ANY($2)`, t.WorkspaceID, pq.Array(ids)) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var a domain.Agent + if err := rows.Scan(&a.ID, &a.Handle, &a.Name, &a.Owner.Sub, &a.Owner.Name, &a.Disabled); err != nil { + return err + } + for _, person := range byID[a.ID] { + *person = a.Person() + } + } + return rows.Err() +} diff --git a/cmd/server/internal/store/agents.go b/cmd/server/internal/store/agents.go new file mode 100644 index 0000000..bbded0c --- /dev/null +++ b/cmd/server/internal/store/agents.go @@ -0,0 +1,225 @@ +package store + +import ( + "database/sql" + "errors" + "regexp" + "strings" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" +) + +const agentColumns = `a.id,a.handle,a.name,a.description,a.owner_sub,a.owner_name,a.disabled,a.created_at,a.updated_at, + (SELECT count(*) FROM tracker_run r JOIN tracker_issue i ON i.id=r.issue_id WHERE r.agent_id=a.id AND i.deleted_at IS NULL AND r.state IN ('running','waiting') AND r.lease_expires_at >= $2), + (SELECT count(*) FROM tracker_request q JOIN tracker_issue i ON i.id=q.issue_id WHERE i.workspace_id=a.workspace_id AND i.deleted_at IS NULL AND q.from_sub='agent:'||a.id AND q.state='open'), + a.last_seen_at` + +func scanAgent(row scanner) (domain.Agent, error) { + var a domain.Agent + err := row.Scan(&a.ID, &a.Handle, &a.Name, &a.Description, &a.Owner.Sub, &a.Owner.Name, &a.Disabled, &a.CreatedAt, &a.UpdatedAt, &a.ActiveRuns, &a.OpenRequests, &a.LastSeenAt) + return a, err +} + +func (t *Tx) Agent(id string) (domain.Agent, error) { + return scanAgent(t.SQL.QueryRowContext(t.Context, `SELECT `+agentColumns+` FROM tracker_agent a WHERE a.workspace_id=$1 AND a.id=$3`, t.WorkspaceID, t.now(), id)) +} + +func (t *Tx) AgentBySubject(subject string) (domain.Actor, error) { + a, err := scanAgent(t.SQL.QueryRowContext(t.Context, `SELECT `+agentColumns+` FROM tracker_agent a WHERE a.workspace_id=$1 AND a.handle=$3 AND NOT a.disabled`, t.WorkspaceID, t.now(), subject)) + if errors.Is(err, sql.ErrNoRows) { + return domain.Actor{}, httpx.Fail(403, "key_subject", "The access key subject is not an active registered agent") + } + if err != nil { + return domain.Actor{}, err + } + return domain.Actor{Person: a.Person(), Kind: "agent", AgentID: a.ID, Role: "Viewer", Key: true}, nil +} + +func (t *Tx) Agents(includeDisabled bool) ([]domain.Agent, error) { + list := []domain.Agent{} + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+agentColumns+` FROM tracker_agent a WHERE a.workspace_id=$1 AND ($3 OR NOT a.disabled) ORDER BY a.handle`, t.WorkspaceID, t.now(), includeDisabled) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + a, err := scanAgent(rows) + if err != nil { + return nil, err + } + list = append(list, a) + } + return list, rows.Err() +} + +type AgentCreate struct { + Handle string `json:"handle"` + Name string `json:"name"` + Description string `json:"description"` + OwnerSub string `json:"ownerSub"` +} + +var agentHandle = regexp.MustCompile(`^[a-z][a-z0-9-]{1,30}$`) + +func (t *Tx) CreateAgent(input AgentCreate, owner domain.Person, actor domain.Actor) (domain.Agent, error) { + if !domain.Can(actor, domain.ManageWorkspace, domain.Target{}) { + return domain.Agent{}, httpx.Forbidden() + } + if !agentHandle.MatchString(input.Handle) || !domain.Text(input.Name, 1, 200) || len(input.Description) > 4096 { + return domain.Agent{}, invalid("Invalid agent handle, name or description") + } + if !domain.Text(owner.Sub, 1, 4096) || domain.ActorKind(owner.Sub) != "person" { + return domain.Agent{}, invalid("An agent owner must be a person") + } + id := ulid.Make().String() + if err := t.Exec(`INSERT INTO tracker_agent(id,workspace_id,handle,name,description,owner_sub,owner_name) VALUES($1,$2,$3,$4,$5,$6,$7)`, id, t.WorkspaceID, input.Handle, strings.TrimSpace(input.Name), input.Description, owner.Sub, owner.Name); err != nil { + return domain.Agent{}, err + } + return t.Agent(id) +} + +func (t *Tx) AgentAssignee(sub string) (*domain.Person, error) { + a, err := t.Agent(strings.TrimPrefix(sub, "agent:")) + if errors.Is(err, sql.ErrNoRows) || (err == nil && a.Disabled) { + return nil, &domain.FieldError{Path: "assigneeSub", Message: "Agent must be active and belong to this workspace"} + } + if err != nil { + return nil, err + } + p := a.Person() + return &p, nil +} + +func (t *Tx) issueActor(person domain.Person) (domain.Actor, error) { + actor := domain.Actor{Person: person, Kind: domain.ActorKind(person.Sub)} + if actor.Kind == "agent" { + a, err := t.Agent(strings.TrimPrefix(person.Sub, "agent:")) + if err != nil { + return actor, err + } + if a.Disabled { + return actor, httpx.Forbidden() + } + actor.Person, actor.AgentID = a.Person(), a.ID + } + return actor, nil +} + +func (t *Tx) completionAllowed(person domain.Person, category string) error { + if domain.ActorKind(person.Sub) == "person" { + return nil + } + var policy string + if err := t.SQL.QueryRowContext(t.Context, `SELECT agent_completion FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&policy); err != nil { + return err + } + actor := domain.Actor{Person: person, Kind: domain.ActorKind(person.Sub)} + if !domain.Can(actor, domain.SetStatus, domain.Target{Category: category, AgentCompletion: policy}) { + return httpx.Forbidden() + } + return nil +} + +func (t *Tx) delegation(person domain.Person, assignee *domain.Person, reporter string) (*domain.Person, error) { + if assignee == nil || domain.ActorKind(assignee.Sub) != "agent" { + return nil, nil + } + if _, err := t.AgentAssignee(assignee.Sub); err != nil { + return nil, err + } + actor, err := t.issueActor(person) + if err != nil { + return nil, err + } + if !domain.Can(actor, domain.AssignAgent, domain.Target{OwnerSub: assignee.Sub, ReporterSub: reporter}) { + return nil, httpx.Forbidden() + } + if actor.Kind == "agent" { + return &actor.Agent.Owner, nil + } + return &person, nil +} + +func (t *Tx) saveDelegator(id string, person *domain.Person) error { + var sub, name any + if person != nil { + sub, name = person.Sub, person.Name + } + return t.Exec(`UPDATE tracker_issue SET delegator_sub=$3,delegator_name=$4 WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, id, sub, name) +} + +type AgentPatch struct { + Name *string `json:"name"` + Description *string `json:"description"` + OwnerSub *string `json:"ownerSub"` + Disabled *bool `json:"disabled"` +} + +func (t *Tx) PatchAgent(id string, input AgentPatch, owner *domain.Person, actor domain.Actor) (domain.Agent, error) { + if !domain.Can(actor, domain.ManageWorkspace, domain.Target{}) { + return domain.Agent{}, httpx.Forbidden() + } + a, err := t.Agent(id) + if err != nil { + return a, err + } + if input.Name != nil { + a.Name = strings.TrimSpace(*input.Name) + } + if input.Description != nil { + a.Description = *input.Description + } + if owner != nil { + a.Owner = *owner + } + if input.Disabled != nil { + a.Disabled = *input.Disabled + } + if !domain.Text(a.Name, 1, 200) || len(a.Description) > 4096 || !domain.Text(a.Description, 0, 4096) { + return a, invalid("Invalid agent name or description") + } + if !domain.Text(a.Owner.Sub, 1, 4096) || domain.ActorKind(a.Owner.Sub) != "person" { + return a, invalid("An agent owner must be a person") + } + if err := t.Exec(`UPDATE tracker_agent SET name=$3,description=$4,owner_sub=$5,owner_name=$6,disabled=$7,updated_at=$8 WHERE workspace_id=$1 AND id=$2`, + t.WorkspaceID, id, a.Name, a.Description, a.Owner.Sub, a.Owner.Name, a.Disabled, t.now()); err != nil { + return a, err + } + if a.Disabled { + rows, err := t.SQL.QueryContext(t.Context, `SELECT r.id FROM tracker_run r JOIN tracker_issue i ON i.id=r.issue_id WHERE i.workspace_id=$1 AND r.agent_id=$2 AND r.state IN ('running','waiting') ORDER BY r.id`, t.WorkspaceID, id) + if err != nil { + return a, err + } + ids := []string{} + for rows.Next() { + var runID string + if err := rows.Scan(&runID); err != nil { + rows.Close() + return a, err + } + ids = append(ids, runID) + } + err = rows.Err() + rows.Close() + if err != nil { + return a, err + } + for _, runID := range ids { + if err := t.closeRun(runID, "canceled", "canceled_by:"+actor.Sub, actor.Person); err != nil { + return a, err + } + } + if err := t.withdrawRequests(`q.from_sub=$2`, "agent:"+id, actor.Person); err != nil { + return a, err + } + } + return t.Agent(id) +} + +// ObserveAgent is called after assertion authentication, including GET requests. +// The predicate bounds writes to once per minute across every key for a handle. +func (t *Tx) ObserveAgent(handle string) error { + return t.Exec(`UPDATE tracker_agent SET last_seen_at=$3 WHERE workspace_id=$1 AND handle=$2 AND NOT disabled AND (last_seen_at IS NULL OR last_seen_at <= $3::timestamptz - interval '1 minute')`, t.WorkspaceID, handle, t.now()) +} diff --git a/cmd/server/internal/store/agents_test.go b/cmd/server/internal/store/agents_test.go new file mode 100644 index 0000000..ee7229c --- /dev/null +++ b/cmd/server/internal/store/agents_test.go @@ -0,0 +1,269 @@ +package store + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/appserver-go/appserver/pgstore/testutil" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/stretchr/testify/require" +) + +func collaborationFixture(t *testing.T) (*Store, domain.Actor, domain.Actor, domain.Issue) { + t.Helper() + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "agents")) + person := domain.Actor{Person: domain.Person{Sub: "pat", Name: "Pat"}, Kind: "person", Role: "Admin"} + var agent domain.Actor + var issue domain.Issue + require.NoError(t, db.InWorkspace(t.Context(), "agents", true, func(tx *Tx) error { + a, err := tx.CreateAgent(AgentCreate{Handle: "astra", Name: "Astra", OwnerSub: person.Sub}, person.Person, person) + if err != nil { + return err + } + agent = domain.Actor{Person: a.Person(), Kind: "agent", AgentID: a.ID, Key: true} + issue, err = tx.CreateIssue(IssueCreate{Title: "Assigned backlog", Type: "task"}, person.Person, &agent.Person) + return err + })) + return db, person, agent, issue +} + +func TestConcurrentStartsHaveOneLiveRun(t *testing.T) { + db, _, agent, issue := collaborationFixture(t) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + start := make(chan struct{}) + results := make(chan error, 12) + for range 12 { + go func() { + <-start + results <- db.InWorkspace(ctx, "agents", true, func(tx *Tx) error { _, err := tx.StartRun(issue.ID, RunStart{}, agent); return err }) + }() + } + close(start) + wins := 0 + for range 12 { + err := <-results + if err == nil { + wins++ + continue + } + var response *httpx.Error + require.ErrorAs(t, err, &response) + require.Equal(t, 409, response.Status) + } + require.Equal(t, 1, wins) + require.NoError(t, db.InWorkspace(ctx, "agents", false, func(tx *Tx) error { + runs, err := tx.Runs(issue.ID) + require.NoError(t, err) + require.Len(t, runs, 1) + events, err := tx.Events(new(int64(0)), 500) + require.NoError(t, err) + require.Len(t, events.Items, 2) + require.Equal(t, "run.started", events.Items[1].Type) + return nil + })) +} + +func TestConcurrentEventCursorHasNoGapsOrLateRows(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "events")) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + const writers = 32 + rollback := errors.New("deliberate rollback") + results := make(chan error, writers) + start := make(chan struct{}) + var wg sync.WaitGroup + for i := range writers { + wg.Add(1) + go func() { + defer wg.Done() + <-start + results <- db.InWorkspace(ctx, "events", true, func(tx *Tx) error { + _, err := tx.CreateIssue(IssueCreate{Title: fmt.Sprintf("writer %d", i), Type: "task"}, domain.Person{Sub: "pat", Name: "Pat"}, nil) + if err == nil && i%4 == 0 { + return rollback + } + return err + }) + }() + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + close(start) + cursor := int64(0) + seen := map[string]bool{} + ticker := time.NewTicker(time.Millisecond) + defer ticker.Stop() + for { + err := db.InWorkspace(ctx, "events", false, func(tx *Tx) error { + page, err := tx.Events(&cursor, 3) + if err != nil { + return err + } + for _, event := range page.Items { + require.Equal(t, cursor+1, event.Seq) + require.Equal(t, "issue.created", event.Type) + require.Equal(t, fmt.Sprintf("APT-%d", event.Seq), event.Issue.Identifier, "issue and event allocation follow commit order") + require.False(t, seen[event.Data.(string)]) + seen[event.Data.(string)] = true + cursor = event.Seq + } + require.Equal(t, cursor, page.Next) + return nil + }) + require.NoError(t, err) + if cursor == writers-writers/4 { + break + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-ticker.C: + } + } + <-done + for range writers { + err := <-results + if !errors.Is(err, rollback) { + require.NoError(t, err) + } + } + require.NoError(t, db.InWorkspace(ctx, "events", false, func(tx *Tx) error { + page, err := tx.Events(&cursor, 500) + require.NoError(t, err) + require.Empty(t, page.Items) + now, err := tx.Events(nil, 100) + require.NoError(t, err) + require.Empty(t, now.Items) + require.Equal(t, cursor, now.Next) + return nil + })) +} + +func TestReviewApprovalUpdatesPersonAttributionAndSprintLedger(t *testing.T) { + db, person, agent, issue := collaborationFixture(t) + now := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) + db.Now = func() time.Time { return now } + require.NoError(t, db.InWorkspace(t.Context(), "agents", true, func(tx *Tx) error { + sprint, err := tx.CreateSprint(SprintCreate{StartsOn: new("2026-11-11"), LengthWeeks: new(1)}) + require.NoError(t, err) + _, err = tx.PatchIssue(issue.ID, IssuePatch{Estimate: field("M"), SprintID: field(sprint.ID)}, person.Person, nil) + require.NoError(t, err) + _, err = tx.StartSprint(sprint.ID) + require.NoError(t, err) + run, err := tx.StartRun(issue.ID, RunStart{}, agent) + require.NoError(t, err) + approval, err := tx.CreateRequest(issue.ID, RequestCreate{Kind: "approval", Title: "Proceed?", RunID: &run.ID}, agent, nil) + require.NoError(t, err) + _, err = tx.FinishRun(run.ID, RunFinish{Outcome: "succeeded", Summary: "Ready"}, agent) + require.ErrorContains(t, err, "open approvals") + _, err = tx.WithdrawRequest(approval.ID, agent) + require.NoError(t, err) + question, err := tx.CreateRequest(issue.ID, RequestCreate{Kind: "question", Title: "Obsolete?", RunID: &run.ID}, agent, nil) + require.NoError(t, err) + _, err = tx.FinishRun(run.ID, RunFinish{Outcome: "succeeded", Summary: "Ready"}, agent) + require.NoError(t, err) + q, err := tx.Request(question.ID) + require.NoError(t, err) + require.Equal(t, "withdrawn", q.State) + requests, err := tx.Requests(RequestFilter{State: "open", Issue: issue.ID}) + require.NoError(t, err) + require.Len(t, requests, 1) + review := requests[0] + require.Equal(t, "review", review.Kind) + require.Equal(t, "Ready", review.Body) + before, err := tx.Sprint(sprint.ID) + require.NoError(t, err) + require.Zero(t, before.Current.DonePoints) + _, err = tx.AnswerRequest(review.ID, RequestAnswer{Option: new("approve")}, agent) + require.Error(t, err) + _, err = tx.AnswerRequest(review.ID, RequestAnswer{Option: new("approve")}, person) + require.NoError(t, err) + after, err := tx.Sprint(sprint.ID) + require.NoError(t, err) + require.Equal(t, 3, after.Current.ScopePoints) + require.Equal(t, 3, after.Current.DonePoints) + require.Equal(t, 1, after.Current.DoneIssues) + assertLedgerRecount(t, tx, sprint.ID) + timeline, err := tx.Timeline(issue.ID) + require.NoError(t, err) + statusActors := []string{} + for _, item := range timeline { + if item.Activity != nil && item.Activity.Field == "status" { + statusActors = append(statusActors, item.Activity.Actor.Sub) + } + } + require.Equal(t, []string{person.Sub}, statusActors) + events, err := tx.Events(new(int64(0)), 500) + require.NoError(t, err) + last := events.Items[len(events.Items)-2:] + require.Equal(t, "issue.updated", last[0].Type) + require.Equal(t, person.Sub, last[0].Actor.Sub) + require.Equal(t, "request.answered", last[1].Type) + return nil + })) +} + +func TestAgentFixtureAndReadFilters(t *testing.T) { + db, _ := testutil.Database(t, Open) + now := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) + db.Now = func() time.Time { return now } + require.NoError(t, db.SeedDev(t.Context(), "seed")) + require.NoError(t, db.InWorkspace(t.Context(), "seed", false, func(tx *Tx) error { + agents, err := tx.Agents(true) + require.NoError(t, err) + require.Len(t, agents, 4) + byHandle := map[string]domain.Agent{} + for _, a := range agents { + byHandle[a.Handle] = a + } + require.Equal(t, 1, byHandle["astra"].ActiveRuns) + require.Equal(t, 1, byHandle["astra"].OpenRequests) + require.Equal(t, 1, byHandle["opus-ui"].ActiveRuns) + require.Equal(t, 1, byHandle["opus-ui"].OpenRequests) + require.Equal(t, 0, byHandle["claude"].ActiveRuns) + require.Equal(t, 1, byHandle["claude"].OpenRequests) + require.True(t, byHandle["legacy-bot"].Disabled) + actor, err := tx.AgentBySubject("astra") + require.NoError(t, err) + inbox, err := tx.Inbox(actor) + require.NoError(t, err) + assigned := []int64{} + kinds := map[string]int{} + for _, item := range inbox { + kinds[item.Kind]++ + if item.Kind == "assignment" { + assigned = append(assigned, item.Issue.Number) + } + } + require.ElementsMatch(t, []int64{4, 9, 15, 19, 42}, assigned) + require.Equal(t, 1, kinds["answer"]) + require.Equal(t, 1, kinds["mention"]) + for _, tc := range []struct { + filter domain.Filter + numbers []int64 + }{ + {domain.Filter{Run: []string{"active"}}, []int64{15, 27}}, + {domain.Filter{Run: []string{"stalled"}}, []int64{9}}, + {domain.Filter{Request: []string{"mine"}}, []int64{16}}, + {domain.Filter{Request: []string{"open"}}, []int64{1, 16, 27}}, + {domain.Filter{Agent: []string{actor.AgentID}}, []int64{4, 9, 15, 16, 19, 42}}, + } { + page, err := tx.ListIssues(ListOptions{Filter: tc.filter, Subject: actor.Sub, Sort: domain.SortNumber}) + require.NoError(t, err) + numbers := []int64{} + for _, i := range page.Items { + numbers = append(numbers, i.Number) + } + require.Equal(t, tc.numbers, numbers) + } + return nil + })) +} diff --git a/cmd/server/internal/store/discussion.go b/cmd/server/internal/store/discussion.go index 622498f..4581ceb 100644 --- a/cmd/server/internal/store/discussion.go +++ b/cmd/server/internal/store/discussion.go @@ -24,14 +24,7 @@ func (t *Tx) touchIssue(id string) error { return t.Exec(`UPDATE tracker_issue SET updated_at=now() WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, id) } func (t *Tx) Comment(id string) (domain.Comment, error) { - var c domain.Comment - err := t.SQL.QueryRowContext(t.Context, `SELECT c.id,c.issue_id,c.author_sub,c.author_name,c.body,c.created_at,c.edited_at FROM tracker_comment c JOIN tracker_issue i ON i.id=c.issue_id WHERE i.workspace_id=$1 AND c.id=$2 AND i.deleted_at IS NULL AND c.deleted_at IS NULL`, t.WorkspaceID, id).Scan(&c.ID, &c.IssueID, &c.Author.Sub, &c.Author.Name, &c.Body, &c.CreatedAt, &c.EditedAt) - c.CreatedAt = c.CreatedAt.UTC() - if c.EditedAt != nil { - at := c.EditedAt.UTC() - c.EditedAt = &at - } - return c, err + return scanComment(t.SQL.QueryRowContext(t.Context, `SELECT `+commentJSON+` FROM tracker_comment c JOIN tracker_issue i ON i.id=c.issue_id WHERE i.workspace_id=$1 AND c.id=$2 AND i.deleted_at IS NULL AND c.deleted_at IS NULL`, t.WorkspaceID, id)) } func (t *Tx) CreateComment(issueID, body string, actor domain.Person) (domain.Comment, error) { if err := validComment(body); err != nil { @@ -48,6 +41,12 @@ func (t *Tx) CreateComment(issueID, body string, actor domain.Person) (domain.Co if err := t.touchIssue(issue.ID); err != nil { return domain.Comment{}, err } + if err := t.syncMentions(id, body); err != nil { + return domain.Comment{}, err + } + if err := t.event(issue.ID, actor, "comment.created", id); err != nil { + return domain.Comment{}, err + } return t.Comment(id) } func (t *Tx) PatchComment(id, body string, actor domain.Actor) (domain.Comment, error) { @@ -65,6 +64,9 @@ func (t *Tx) PatchComment(id, body string, actor domain.Actor) (domain.Comment, if err := t.Exec(`UPDATE tracker_comment SET body=$2,edited_at=now() WHERE id=$1`, c.ID, body); err != nil { return c, err } + if err := t.syncMentions(c.ID, body); err != nil { + return c, err + } if err := t.touchIssue(c.IssueID); err != nil { return c, err } @@ -174,30 +176,46 @@ func (t *Tx) Timeline(issueID string) ([]domain.TimelineItem, error) { if err != nil { return nil, err } - rows, err = t.SQL.QueryContext(t.Context, `SELECT id,author_sub,author_name,body,created_at,edited_at FROM tracker_comment WHERE issue_id=$1 AND deleted_at IS NULL ORDER BY created_at,id`, issue.ID) + rows, err = t.SQL.QueryContext(t.Context, `SELECT `+commentJSON+` FROM tracker_comment c WHERE c.issue_id=$1 AND c.deleted_at IS NULL ORDER BY c.created_at,c.id`, issue.ID) if err != nil { return nil, err } defer rows.Close() for rows.Next() { - c := domain.Comment{IssueID: issue.ID} - if err := rows.Scan(&c.ID, &c.Author.Sub, &c.Author.Name, &c.Body, &c.CreatedAt, &c.EditedAt); err != nil { + c, err := scanComment(rows) + if err != nil { return nil, err } - c.CreatedAt = c.CreatedAt.UTC() - if c.EditedAt != nil { - at := c.EditedAt.UTC() - c.EditedAt = &at - } items = append(items, domain.TimelineItem{Kind: "comment", Comment: &c}) } if err := rows.Err(); err != nil { return nil, err } + rows.Close() + runs, err := t.Runs(issue.ID) + if err != nil { + return nil, err + } + for i := range runs { + items = append(items, domain.TimelineItem{Kind: "run", Run: &runs[i]}) + } + requests, err := t.Requests(RequestFilter{Issue: issue.ID}) + if err != nil { + return nil, err + } + for i := range requests { + items = append(items, domain.TimelineItem{Kind: "request", Request: &requests[i]}) + } key := func(item domain.TimelineItem) (time.Time, string) { if item.Activity != nil { return item.Activity.CreatedAt, item.Activity.ID } + if item.Run != nil { + return item.Run.StartedAt, item.Run.ID + } + if item.Request != nil { + return item.Request.CreatedAt, item.Request.ID + } return item.Comment.CreatedAt, item.Comment.ID } slices.SortFunc(items, func(a, b domain.TimelineItem) int { diff --git a/cmd/server/internal/store/events.go b/cmd/server/internal/store/events.go new file mode 100644 index 0000000..a9fbc59 --- /dev/null +++ b/cmd/server/internal/store/events.go @@ -0,0 +1,71 @@ +package store + +import ( + "encoding/json" + + "github.com/appthrust/tracker/cmd/server/internal/domain" +) + +// The workspace row stays locked through commit. Unlike a sequence, this cannot +// publish a higher cursor before a lower event or leave a gap after rollback. +func (t *Tx) event(issueID string, actor domain.Person, kind string, data any) error { + var seq int64 + if err := t.SQL.QueryRowContext(t.Context, `UPDATE tracker_workspace SET event_seq=event_seq+1 WHERE id=$1 RETURNING event_seq`, t.WorkspaceID).Scan(&seq); err != nil { + return err + } + who, err := jsonValue(actor) + if err != nil { + return err + } + payload, err := jsonValue(data) + if err != nil { + return err + } + return t.Exec(`INSERT INTO tracker_event(workspace_id,seq,at,issue,actor,type,data) + VALUES($1,$2,$3,(SELECT jsonb_build_object('id',i.id,'identifier',w.key||'-'||i.number,'title',i.title,'statusId',i.status_id) FROM tracker_issue i JOIN tracker_workspace w ON w.id=i.workspace_id WHERE i.workspace_id=$1 AND i.id=$4),$5,$6,$7)`, t.WorkspaceID, seq, t.now(), issueID, who, kind, payload) +} + +type EventPage struct { + Items []domain.Event `json:"items"` + Next int64 `json:"next"` +} + +func (t *Tx) Events(after *int64, limit int) (EventPage, error) { + page := EventPage{Items: []domain.Event{}} + if limit == 0 { + limit = 100 + } + if limit < 1 || limit > 500 || (after != nil && *after < 0) { + return page, invalid("After must be nonnegative and limit must be between 1 and 500") + } + if after == nil { + err := t.SQL.QueryRowContext(t.Context, `SELECT event_seq FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&page.Next) + return page, err + } + page.Next = *after + rows, err := t.SQL.QueryContext(t.Context, `SELECT seq,at,issue,actor,type,data FROM tracker_event WHERE workspace_id=$1 AND seq>$2 ORDER BY seq LIMIT $3`, t.WorkspaceID, *after, limit) + if err != nil { + return page, err + } + defer rows.Close() + for rows.Next() { + var event domain.Event + var issue, actor, data []byte + if err := rows.Scan(&event.Seq, &event.At, &issue, &actor, &event.Type, &data); err != nil { + return page, err + } + for _, field := range []struct { + data []byte + out any + }{{issue, &event.Issue}, {actor, &event.Actor}, {data, &event.Data}} { + if len(field.data) > 0 { + if err := json.Unmarshal(field.data, field.out); err != nil { + return page, err + } + } + } + page.Items = append(page.Items, event) + page.Next = event.Seq + } + return page, rows.Err() +} diff --git a/cmd/server/internal/store/hierarchy_test.go b/cmd/server/internal/store/hierarchy_test.go index 36abbad..36382aa 100644 --- a/cmd/server/internal/store/hierarchy_test.go +++ b/cmd/server/internal/store/hierarchy_test.go @@ -243,7 +243,7 @@ func TestHierarchySeed(t *testing.T) { require.NoError(t, database.InWorkspace(t.Context(), "seed", false, func(tx *Tx) error { page, err := tx.ListIssues(ListOptions{Sort: domain.SortNumber}) require.NoError(t, err) - require.Len(t, page.Items, 40) + require.Len(t, page.Items, 42) epics, stories := page.Items[30:32], page.Items[32:36] require.Equal(t, "Reliable bug intake", epics[0].Title) require.Equal(t, "Faster triage", epics[1].Title) diff --git a/cmd/server/internal/store/idempotency.go b/cmd/server/internal/store/idempotency.go new file mode 100644 index 0000000..120dfb2 --- /dev/null +++ b/cmd/server/internal/store/idempotency.go @@ -0,0 +1,58 @@ +package store + +import ( + "bytes" + "database/sql" + "errors" + "time" + + "github.com/appthrust/appserver-go/appserver/httpx" +) + +type Replay struct { + Status int + Body []byte +} + +func (t *Tx) Idempotency(actor, key string, hash []byte) (*Replay, error) { + // InWorkspace(write=true) serializes concurrent uses of the same key, and + // the cached response commits atomically with the write it represents. + if err := t.Exec(`DELETE FROM tracker_idempotency WHERE workspace_id=$1 AND expires_at<=$2`, t.WorkspaceID, t.now()); err != nil { + return nil, err + } + var replay Replay + var previous []byte + err := t.SQL.QueryRowContext(t.Context, `SELECT request_hash,status,body FROM tracker_idempotency WHERE workspace_id=$1 AND actor_sub=$2 AND key=$3`, t.WorkspaceID, actor, key).Scan(&previous, &replay.Status, &replay.Body) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + if !bytes.Equal(previous, hash) { + return nil, httpx.Conflict("Idempotency-Key was already used for a different request") + } + return &replay, nil +} + +func (t *Tx) SaveIdempotency(actor, key string, hash []byte, replay Replay) error { + return t.Exec(`INSERT INTO tracker_idempotency(workspace_id,actor_sub,key,request_hash,status,body,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7)`, t.WorkspaceID, actor, key, hash, replay.Status, replay.Body, t.now().Add(24*time.Hour)) +} + +// ResponseAttempt rolls back failed handler writes before caching their response. +// In particular a PostgreSQL constraint error must not poison the transaction. +func (t *Tx) ResponseAttempt(fn func() error) error { + if err := t.Exec(`SAVEPOINT tracker_response`); err != nil { + return err + } + if err := fn(); err != nil { + if rollback := t.Exec(`ROLLBACK TO SAVEPOINT tracker_response`); rollback != nil { + return rollback + } + if release := t.Exec(`RELEASE SAVEPOINT tracker_response`); release != nil { + return release + } + return translate(err) + } + return t.Exec(`RELEASE SAVEPOINT tracker_response`) +} diff --git a/cmd/server/internal/store/issues_read.go b/cmd/server/internal/store/issues_read.go index ae949f5..5dd9467 100644 --- a/cmd/server/internal/store/issues_read.go +++ b/cmd/server/internal/store/issues_read.go @@ -20,7 +20,10 @@ const issueColumns = `i.id,w.key,i.number,i.title,i.type,i.priority,i.status_id, (SELECT count(*) FROM tracker_comment c WHERE c.issue_id=i.id AND c.deleted_at IS NULL), (SELECT count(*) FROM tracker_attachment a WHERE a.issue_id=i.id),i.created_at,i.updated_at,i.completed_at,i.project_id, lineage.epic,lineage.story,rollup.progress,i.estimate, - (SELECT jsonb_build_object('id',sp.id,'number',sp.number,'name',sp.name,'state',CASE WHEN sp.closed_at IS NOT NULL THEN 'closed' WHEN sp.started_at IS NOT NULL THEN 'active' ELSE 'planned' END) FROM tracker_sprint sp WHERE sp.id=i.sprint_id)` + (SELECT jsonb_build_object('id',sp.id,'number',sp.number,'name',sp.name,'state',CASE WHEN sp.closed_at IS NOT NULL THEN 'closed' WHEN sp.started_at IS NOT NULL THEN 'active' ELSE 'planned' END) FROM tracker_sprint sp WHERE sp.id=i.sprint_id), + CASE WHEN i.delegator_sub IS NULL THEN NULL ELSE jsonb_build_object('sub',i.delegator_sub,'name',i.delegator_name) END, + (SELECT ` + runJSON + ` FROM tracker_run r JOIN tracker_agent a ON a.id=r.agent_id WHERE r.issue_id=i.id AND r.state IN ('running','waiting')), + (SELECT count(*) FROM tracker_request q WHERE q.issue_id=i.id AND q.state='open')` const issueFrom = ` FROM tracker_issue i JOIN tracker_workspace w ON w.id=i.workspace_id JOIN tracker_status s ON s.id=i.status_id ` // Lateral recursive queries keep detail and list projections identical without @@ -65,16 +68,16 @@ const estimateSQL = `(CASE i.estimate WHEN 'XL' THEN 0 WHEN 'L' THEN 1 WHEN 'M' type scanner interface{ Scan(...any) error } -func scanIssue(row scanner) (domain.Issue, error) { +func scanIssue(row scanner, now time.Time) (domain.Issue, error) { var item domain.Issue var key string var sub, name, due sql.NullString - var parent, report, epic, story, progress, sprint []byte + var parent, report, epic, story, progress, sprint, delegator, activeRun []byte item.LabelIDs = []string{} item.Children = []domain.IssueRef{} item.Blocks = []domain.IssueRef{} item.BlockedBy = []domain.IssueRef{} - err := row.Scan(&item.ID, &key, &item.Number, &item.Title, &item.Type, &item.Priority, &item.StatusID, &sub, &name, &item.Reporter.Sub, &item.Reporter.Name, pq.Array(&item.LabelIDs), &parent, &due, &report, &item.CommentCount, &item.AttachmentCount, &item.CreatedAt, &item.UpdatedAt, &item.CompletedAt, &item.ProjectID, &epic, &story, &progress, &item.Estimate, &sprint, &item.Description) + err := row.Scan(&item.ID, &key, &item.Number, &item.Title, &item.Type, &item.Priority, &item.StatusID, &sub, &name, &item.Reporter.Sub, &item.Reporter.Name, pq.Array(&item.LabelIDs), &parent, &due, &report, &item.CommentCount, &item.AttachmentCount, &item.CreatedAt, &item.UpdatedAt, &item.CompletedAt, &item.ProjectID, &epic, &story, &progress, &item.Estimate, &sprint, &delegator, &activeRun, &item.OpenRequestCount, &item.Description) if err != nil { return item, err } @@ -88,13 +91,16 @@ func scanIssue(row scanner) (domain.Issue, error) { for _, field := range []struct { data []byte target any - }{{parent, &item.Parent}, {report, &item.Report}, {epic, &item.Epic}, {story, &item.Story}, {progress, &item.Progress}, {sprint, &item.Sprint}} { + }{{parent, &item.Parent}, {report, &item.Report}, {epic, &item.Epic}, {story, &item.Story}, {progress, &item.Progress}, {sprint, &item.Sprint}, {delegator, &item.Delegator}, {activeRun, &item.ActiveRun}} { if len(field.data) > 0 { if err := json.Unmarshal(field.data, field.target); err != nil { return item, err } } } + if item.ActiveRun != nil { + item.ActiveRun.State = domain.RunState(item.ActiveRun.State, item.ActiveRun.LeaseExpiresAt, now) + } item.CreatedAt = item.CreatedAt.UTC() item.UpdatedAt = item.UpdatedAt.UTC() if item.CompletedAt != nil { @@ -121,7 +127,7 @@ func (t *Tx) Issue(id string) (domain.Issue, error) { predicate = "i.number=$2" value = number } - item, err := scanIssue(t.SQL.QueryRowContext(t.Context, `SELECT `+issueColumns+`,i.description`+issueFrom+issueHierarchy+`WHERE i.workspace_id=$1 AND i.deleted_at IS NULL AND `+predicate, t.WorkspaceID, value)) + item, err := scanIssue(t.SQL.QueryRowContext(t.Context, `SELECT `+issueColumns+`,i.description`+issueFrom+issueHierarchy+`WHERE i.workspace_id=$1 AND i.deleted_at IS NULL AND `+predicate, t.WorkspaceID, value), t.now()) if err != nil { return item, err } @@ -213,6 +219,32 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { anyOf("i.priority", f.Priority) anyOf("i.report->>'environment'", f.Environment) anyOf("i.report->>'surface'", f.Surface) + anyOf("CASE WHEN i.assignee_sub LIKE 'agent:%' THEN 'agent' WHEN i.assignee_sub IS NOT NULL THEN 'person' END", f.AssigneeKind) + if len(f.Agent) > 0 { + clauses = append(clauses, "i.assignee_sub IN (SELECT 'agent:'||a.id FROM tracker_agent a WHERE a.workspace_id=i.workspace_id AND a.id=ANY("+bind(pq.Array(f.Agent))+"))") + } + if len(f.Run) > 0 { + now := bind(t.now()) + states := []string{} + for _, state := range f.Run { + switch state { + case "active": + states = append(states, "EXISTS(SELECT 1 FROM tracker_run r WHERE r.issue_id=i.id AND r.state IN ('running','waiting') AND r.lease_expires_at>="+now+")") + case "stalled": + states = append(states, "EXISTS(SELECT 1 FROM tracker_run r WHERE r.issue_id=i.id AND r.state IN ('running','waiting') AND r.lease_expires_at<"+now+")") + case "none": + states = append(states, "NOT EXISTS(SELECT 1 FROM tracker_run r WHERE r.issue_id=i.id AND r.state IN ('running','waiting'))") + } + } + clauses = append(clauses, "("+strings.Join(states, " OR ")+")") + } + if len(f.Request) > 0 { + predicate := "" + if !slices.Contains(f.Request, "open") { + predicate = " AND q.from_sub=" + bind(options.Subject) + } + clauses = append(clauses, "EXISTS(SELECT 1 FROM tracker_request q WHERE q.issue_id=i.id AND q.state='open'"+predicate+")") + } if len(f.Label) > 0 { clauses = append(clauses, "EXISTS(SELECT 1 FROM tracker_issue_label il WHERE il.issue_id=i.id AND il.label_id=ANY("+bind(pq.Array(f.Label))+"))") } @@ -325,8 +357,9 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { return page, err } defer rows.Close() + now := t.now() for rows.Next() { - item, err := scanIssue(rows) + item, err := scanIssue(rows, now) if err != nil { return page, err } @@ -362,3 +395,25 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { } return page, nil } + +// Inbox assignments reuse the list projection in one query, preserving its order. +func (t *Tx) issueSummaries(ids []string) ([]domain.IssueSummary, error) { + list := []domain.IssueSummary{} + if len(ids) == 0 { + return list, nil + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+issueColumns+`,''`+issueFrom+issueHierarchy+` WHERE i.workspace_id=$1 AND i.deleted_at IS NULL AND i.id=ANY($2) ORDER BY array_position($2::text[],i.id)`, t.WorkspaceID, pq.Array(ids)) + if err != nil { + return nil, err + } + defer rows.Close() + now := t.now() + for rows.Next() { + item, err := scanIssue(rows, now) + if err != nil { + return nil, err + } + list = append(list, item.IssueSummary) + } + return list, rows.Err() +} diff --git a/cmd/server/internal/store/issues_write.go b/cmd/server/internal/store/issues_write.go index db43606..5ec181c 100644 --- a/cmd/server/internal/store/issues_write.go +++ b/cmd/server/internal/store/issues_write.go @@ -6,6 +6,7 @@ import ( "reflect" "slices" "strings" + "time" "github.com/appthrust/appserver-go/appserver/httpx" "github.com/appthrust/tracker/cmd/server/internal/domain" @@ -41,20 +42,21 @@ type IssueCreate struct { Report *domain.Report `json:"report"` } type IssuePatch struct { - Title Field[string] `json:"title"` - Description Field[string] `json:"description"` - Type Field[string] `json:"type"` - Priority Field[string] `json:"priority"` - StatusID Field[string] `json:"statusId"` - AssigneeSub Field[string] `json:"assigneeSub"` - LabelIDs Field[[]string] `json:"labelIds"` - ProjectID Field[string] `json:"projectId"` - Estimate Field[string] `json:"estimate"` - SprintID Field[string] `json:"sprintId"` - ParentID Field[string] `json:"parentId"` - Blocks Field[[]string] `json:"blocks"` - DueOn Field[string] `json:"dueOn"` - Report Field[domain.Report] `json:"report"` + ExpectedUpdatedAt *time.Time `json:"expectedUpdatedAt"` + Title Field[string] `json:"title"` + Description Field[string] `json:"description"` + Type Field[string] `json:"type"` + Priority Field[string] `json:"priority"` + StatusID Field[string] `json:"statusId"` + AssigneeSub Field[string] `json:"assigneeSub"` + LabelIDs Field[[]string] `json:"labelIds"` + ProjectID Field[string] `json:"projectId"` + Estimate Field[string] `json:"estimate"` + SprintID Field[string] `json:"sprintId"` + ParentID Field[string] `json:"parentId"` + Blocks Field[[]string] `json:"blocks"` + DueOn Field[string] `json:"dueOn"` + Report Field[domain.Report] `json:"report"` } func jsonValue(value any) (any, error) { @@ -208,6 +210,13 @@ func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domai if err != nil { return item, invalid("Status must belong to this workspace") } + if err := t.completionAllowed(actor, status.Category); err != nil { + return item, err + } + item.Delegator, err = t.delegation(actor, assignee, actor.Sub) + if err != nil { + return item, err + } item.CompletedAt = domain.TransitionCompletedAt(status.Category, t.now()) if input.ParentID != nil { item.Parent, err = t.parent(item.ID, *input.ParentID, item.Type, "parentId") @@ -239,6 +248,9 @@ func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domai if err := t.Exec(`INSERT INTO tracker_issue (id,workspace_id,number,title,description,type,priority,status_id,assignee_sub,assignee_name,reporter_sub,reporter_name,parent_id,due_on,report,completed_at,project_id,estimate,sprint_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, item.ID, t.WorkspaceID, item.Number, item.Title, item.Description, item.Type, item.Priority, item.StatusID, sub, name, actor.Sub, actor.Name, parent, item.DueOn, report, item.CompletedAt, item.ProjectID, item.Estimate, sprintID(item.Sprint)); err != nil { return item, err } + if err := t.saveDelegator(item.ID, item.Delegator); err != nil { + return item, err + } if _, err := t.replaceLabels(item.ID, input.LabelIDs); err != nil { return item, err } @@ -252,6 +264,9 @@ func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domai if err := t.sprintEvents(item.ID, domain.SprintStanding{}, after); err != nil { return item, err } + if err := t.event(item.ID, actor, "issue.created", item.ID); err != nil { + return item, err + } return t.Issue(item.ID) } func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assignee *domain.Person) (domain.Issue, error) { @@ -259,6 +274,16 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign if err != nil { return old, err } + owner := "" + if old.Assignee != nil { + owner = old.Assignee.Sub + } + if !domain.Can(domain.Actor{Person: actor, Kind: domain.ActorKind(actor.Sub)}, domain.EditIssue, domain.Target{OwnerSub: owner, ReporterSub: old.Reporter.Sub}) { + return old, httpx.Forbidden() + } + if input.ExpectedUpdatedAt != nil && !input.ExpectedUpdatedAt.Equal(old.UpdatedAt) { + return old, httpx.Conflict("The issue has changed; read it again before editing") + } item := old for _, field := range []struct { in Field[string] @@ -277,6 +302,10 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign if assignee != nil { item.Assignee = &domain.Person{Sub: assignee.Sub, Name: assignee.Name} } + item.Delegator, err = t.delegation(actor, assignee, item.Reporter.Sub) + if err != nil { + return item, err + } } if input.ProjectID.Present { item.ProjectID = input.ProjectID.Value @@ -343,12 +372,17 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign return item, err } } - if item.StatusID != old.StatusID { + if input.StatusID.Present { after, err := t.Status(item.StatusID) if err != nil { return item, invalid("Status must belong to this workspace") } - item.CompletedAt = domain.TransitionCompletedAt(after.Category, t.now()) + if err := t.completionAllowed(actor, after.Category); err != nil { + return item, err + } + if item.StatusID != old.StatusID { + item.CompletedAt = domain.TransitionCompletedAt(after.Category, t.now()) + } } if input.LabelIDs.Present { if input.LabelIDs.Value == nil { @@ -369,7 +403,7 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign } slices.SortFunc(old.Blocks, func(a, b domain.IssueRef) int { return strings.Compare(a.ID, b.ID) }) } - changed := false + fields := []string{} for _, field := range []struct { name string from, to any @@ -377,15 +411,16 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign {"title", old.Title, item.Title}, {"description", old.Description, item.Description}, {"type", old.Type, item.Type}, {"priority", old.Priority, item.Priority}, {"status", old.StatusID, item.StatusID}, {"assignee", old.Assignee, item.Assignee}, {"labels", old.LabelIDs, item.LabelIDs}, {"parent", old.Parent, item.Parent}, {"blocks", old.Blocks, item.Blocks}, {"due", old.DueOn, item.DueOn}, {"report", old.Report, item.Report}, {"project", old.ProjectID, item.ProjectID}, {"estimate", old.Estimate, item.Estimate}, {"sprint", old.Sprint, item.Sprint}, + {"delegator", old.Delegator, item.Delegator}, } { if !reflect.DeepEqual(field.from, field.to) { - changed = true + fields = append(fields, field.name) if err := t.activity(item.ID, actor, field.name, field.from, field.to); err != nil { return item, err } } } - if !changed { + if len(fields) == 0 { return old, nil } var sub, name, parent any @@ -402,6 +437,16 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign if err := t.Exec(`UPDATE tracker_issue SET title=$3,description=$4,type=$5,priority=$6,status_id=$7,assignee_sub=$8,assignee_name=$9,parent_id=$10,due_on=$11,report=$12,completed_at=$13,project_id=$14,estimate=$15,sprint_id=$16,updated_at=now() WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID, item.Title, item.Description, item.Type, item.Priority, item.StatusID, sub, name, parent, item.DueOn, report, item.CompletedAt, item.ProjectID, item.Estimate, sprintID(item.Sprint)); err != nil { return item, err } + if err := t.saveDelegator(item.ID, item.Delegator); err != nil { + return item, err + } + if input.AssigneeSub.Present && old.Assignee != nil && domain.ActorKind(old.Assignee.Sub) == "agent" && + (item.Assignee == nil || item.Assignee.Sub != old.Assignee.Sub) && + old.ActiveRun != nil && old.ActiveRun.Agent.Sub == old.Assignee.Sub { + if err := t.closeRun(old.ActiveRun.ID, "canceled", "reassigned", actor); err != nil { + return item, err + } + } before, err := t.standing(old) if err != nil { return item, err @@ -413,6 +458,9 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign if err := t.sprintEvents(item.ID, before, after); err != nil { return item, err } + if err := t.event(item.ID, actor, "issue.updated", map[string]any{"fields": fields}); err != nil { + return item, err + } return t.Issue(item.ID) } func (t *Tx) DeleteIssue(id string, actor domain.Actor) error { @@ -423,6 +471,14 @@ func (t *Tx) DeleteIssue(id string, actor domain.Actor) error { if err != nil { return err } + if item.ActiveRun != nil { + if err := t.closeRun(item.ActiveRun.ID, "canceled", "canceled_by:"+actor.Sub, actor.Person); err != nil { + return err + } + } + if err := t.withdrawRequests(`q.issue_id=$2`, item.ID, actor.Person); err != nil { + return err + } if err := t.Exec(`UPDATE tracker_issue SET deleted_at=now(),updated_at=now() WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID); err != nil { return err } @@ -435,5 +491,8 @@ func (t *Tx) DeleteIssue(id string, actor domain.Actor) error { if err := t.sprintEvents(item.ID, before, after); err != nil { return err } - return t.activity(item.ID, actor.Person, "deleted", nil, nil) + if err := t.activity(item.ID, actor.Person, "deleted", nil, nil); err != nil { + return err + } + return t.event(item.ID, actor.Person, "issue.deleted", item.ID) } diff --git a/cmd/server/internal/store/mentions.go b/cmd/server/internal/store/mentions.go new file mode 100644 index 0000000..d9fbc63 --- /dev/null +++ b/cmd/server/internal/store/mentions.go @@ -0,0 +1,76 @@ +package store + +import ( + "encoding/json" + + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/lib/pq" +) + +const commentJSON = `jsonb_build_object('id',c.id,'issueId',c.issue_id,'author',jsonb_build_object('sub',c.author_sub,'name',c.author_name),'body',c.body,'createdAt',c.created_at,'editedAt',c.edited_at, + 'mentions',coalesce((SELECT jsonb_agg(jsonb_build_object('sub',m.target_sub,'name',a.name) ORDER BY a.handle) FROM tracker_mention m JOIN tracker_agent a ON m.target_sub='agent:'||a.id WHERE m.comment_id=c.id),'[]'::jsonb))` + +func scanComment(row scanner) (domain.Comment, error) { + var item domain.Comment + var data []byte + if err := row.Scan(&data); err != nil { + return item, err + } + err := json.Unmarshal(data, &item) + return item, err +} + +func (t *Tx) syncMentions(commentID, body string) error { + handles := domain.MentionHandles(body) + if err := t.Exec(`DELETE FROM tracker_mention m WHERE comment_id=$1 AND NOT EXISTS(SELECT 1 FROM tracker_agent a WHERE a.workspace_id=$2 AND m.target_sub='agent:'||a.id AND a.handle=ANY($3))`, commentID, t.WorkspaceID, pq.Array(handles)); err != nil { + return err + } + return t.Exec(`INSERT INTO tracker_mention(comment_id,target_sub) SELECT $1,'agent:'||a.id FROM tracker_agent a WHERE a.workspace_id=$2 AND a.handle=ANY($3) ON CONFLICT DO NOTHING`, commentID, t.WorkspaceID, pq.Array(handles)) +} + +func (t *Tx) inboxMentions(sub string) ([]domain.InboxItem, error) { + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+commentJSON+`,i.id,w.key||'-'||i.number,i.title,i.status_id FROM tracker_mention m JOIN tracker_comment c ON c.id=m.comment_id JOIN tracker_issue i ON i.id=c.issue_id JOIN tracker_workspace w ON w.id=i.workspace_id WHERE i.workspace_id=$1 AND m.target_sub=$2 AND m.acknowledged_at IS NULL AND c.deleted_at IS NULL AND i.deleted_at IS NULL ORDER BY c.created_at,c.id`, t.WorkspaceID, sub) + if err != nil { + return nil, err + } + defer rows.Close() + items := []domain.InboxItem{} + for rows.Next() { + var data []byte + var comment domain.Comment + var issue domain.IssueSummary + if err := rows.Scan(&data, &issue.ID, &issue.Identifier, &issue.Title, &issue.StatusID); err != nil { + return nil, err + } + if err := json.Unmarshal(data, &comment); err != nil { + return nil, err + } + items = append(items, domain.InboxItem{Kind: "mention", Comment: &comment, Issue: &issue}) + } + return items, rows.Err() +} + +type InboxAck struct { + Answers []string `json:"answers"` + Mentions []string `json:"mentions"` +} + +// Mention IDs are comment IDs; a caller has at most one mention per comment. +// Unknown IDs and other actors' IDs are ignored, making acknowledgement safe +// to retry without leaking another actor's inbox. +func (t *Tx) AckInbox(input InboxAck, actor domain.Actor) error { + for _, ids := range [][]string{input.Answers, input.Mentions} { + if len(ids) > 500 { + return invalid("Acknowledge at most 500 items at a time") + } + for _, id := range ids { + if !domain.ValidID(id) { + return invalid("Acknowledgement IDs must be resource IDs") + } + } + } + if err := t.Exec(`UPDATE tracker_request q SET answer_acknowledged_at=$4 FROM tracker_issue i WHERE q.issue_id=i.id AND i.workspace_id=$1 AND q.from_sub=$2 AND q.id=ANY($3) AND q.state='answered' AND q.answer_acknowledged_at IS NULL`, t.WorkspaceID, actor.Sub, pq.Array(input.Answers), t.now()); err != nil { + return err + } + return t.Exec(`UPDATE tracker_mention m SET acknowledged_at=$4 FROM tracker_comment c JOIN tracker_issue i ON i.id=c.issue_id WHERE m.comment_id=c.id AND i.workspace_id=$1 AND m.target_sub=$2 AND m.comment_id=ANY($3) AND m.acknowledged_at IS NULL`, t.WorkspaceID, actor.Sub, pq.Array(input.Mentions), t.now()) +} diff --git a/cmd/server/internal/store/migrations/013_agents.sql b/cmd/server/internal/store/migrations/013_agents.sql new file mode 100644 index 0000000..76b1b40 --- /dev/null +++ b/cmd/server/internal/store/migrations/013_agents.sql @@ -0,0 +1,89 @@ +-- Actor references preserve existing snapshots; credentials remain with the platform. +CREATE TABLE tracker_agent ( + id text PRIMARY KEY, + workspace_id text NOT NULL REFERENCES tracker_workspace(id) ON DELETE CASCADE, + handle text NOT NULL CHECK (handle ~ '^[a-z][a-z0-9-]{1,30}$'), + name text NOT NULL CHECK (char_length(name) BETWEEN 1 AND 200), + description text NOT NULL DEFAULT '' CHECK (octet_length(description) <= 4096), + owner_sub text NOT NULL CHECK (owner_sub NOT LIKE 'agent:%'), + owner_name text NOT NULL, + disabled boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + last_seen_at timestamptz, + UNIQUE (workspace_id,handle) +); +CREATE TABLE tracker_run ( + id text PRIMARY KEY, + issue_id text NOT NULL REFERENCES tracker_issue(id) ON DELETE CASCADE, + agent_id text NOT NULL REFERENCES tracker_agent(id), + state text NOT NULL CHECK (state IN ('running','waiting','succeeded','failed','canceled')), + reason text, + session text NOT NULL DEFAULT '', + note text NOT NULL DEFAULT '', + summary text NOT NULL DEFAULT '', + links jsonb NOT NULL DEFAULT '[]', + started_at timestamptz NOT NULL, + heartbeat_at timestamptz NOT NULL, + lease_expires_at timestamptz NOT NULL, + finished_at timestamptz +); +CREATE UNIQUE INDEX tracker_run_active ON tracker_run(issue_id) WHERE state IN ('running','waiting'); +CREATE INDEX tracker_run_agent ON tracker_run(agent_id); +CREATE TABLE tracker_request ( + id text PRIMARY KEY, + issue_id text NOT NULL REFERENCES tracker_issue(id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('question','approval','review')), + from_sub text NOT NULL, + from_name text NOT NULL, + to_sub text, + to_name text, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200), + body text NOT NULL DEFAULT '' CHECK (octet_length(body) <= 20480), + options jsonb NOT NULL DEFAULT '[]', + run_id text REFERENCES tracker_run(id), + state text NOT NULL DEFAULT 'open' CHECK (state IN ('open','answered','withdrawn')), + answer_option text, + answer_body text, + answered_by_sub text, + answered_by_name text, + answered_at timestamptz, + answer_acknowledged_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX tracker_request_issue ON tracker_request(issue_id,state); +CREATE INDEX tracker_request_run ON tracker_request(run_id,state); +ALTER TABLE tracker_issue ADD COLUMN delegator_sub text, ADD COLUMN delegator_name text; +ALTER TABLE tracker_workspace ADD COLUMN agent_completion text NOT NULL DEFAULT 'review' CHECK (agent_completion IN ('review','direct')); +ALTER TABLE tracker_workspace ADD COLUMN event_seq bigint NOT NULL DEFAULT 0; + +CREATE TABLE tracker_mention ( + comment_id text NOT NULL REFERENCES tracker_comment(id) ON DELETE CASCADE, + target_sub text NOT NULL, + acknowledged_at timestamptz, + PRIMARY KEY (comment_id,target_sub) +); +CREATE INDEX tracker_mention_inbox ON tracker_mention(target_sub) WHERE acknowledged_at IS NULL; + +CREATE TABLE tracker_event ( + workspace_id text NOT NULL REFERENCES tracker_workspace(id) ON DELETE CASCADE, + seq bigint NOT NULL, + at timestamptz NOT NULL, + issue jsonb, + actor jsonb NOT NULL, + type text NOT NULL CHECK (type IN ('issue.created','issue.updated','issue.deleted','comment.created','run.started','run.finished','run.canceled','request.opened','request.answered','request.withdrawn')), + data jsonb NOT NULL, + PRIMARY KEY (workspace_id,seq) +); + +CREATE TABLE tracker_idempotency ( + workspace_id text NOT NULL REFERENCES tracker_workspace(id) ON DELETE CASCADE, + actor_sub text NOT NULL, + key text NOT NULL CHECK (char_length(key) BETWEEN 1 AND 128), + request_hash bytea NOT NULL, + status integer NOT NULL, + body bytea NOT NULL, + expires_at timestamptz NOT NULL, + PRIMARY KEY (workspace_id,actor_sub,key) +); +CREATE INDEX tracker_idempotency_expiry ON tracker_idempotency(expires_at); diff --git a/cmd/server/internal/store/projects_test.go b/cmd/server/internal/store/projects_test.go index a657689..23d3d0b 100644 --- a/cmd/server/internal/store/projects_test.go +++ b/cmd/server/internal/store/projects_test.go @@ -178,10 +178,14 @@ func TestProjectSeedAssignment(t *testing.T) { } page, err := tx.ListIssues(ListOptions{Sort: domain.SortNumber}) require.NoError(t, err) - require.Len(t, page.Items, 40) + require.Len(t, page.Items, 42) names := []string{"Dashboard", "Platform API", "Builder Console"} for _, issue := range page.Items { n := issue.Number + if n > 40 { + require.Equal(t, byName["Platform API"].ID, *issue.ProjectID) + continue + } if n > 30 || n%3 == 0 { require.Nil(t, issue.ProjectID) } else { @@ -246,7 +250,7 @@ func TestProjectsMigrationFromV010(t *testing.T) { } var versions int require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT count(*) FROM tracker_schema_migrations`).Scan(&versions)) - require.Equal(t, 12, versions) + require.Equal(t, 13, versions) var reporterIndex string require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND indexname='tracker_issue_reporter'`).Scan(&reporterIndex)) require.Contains(t, reporterIndex, "USING btree (workspace_id, reporter_sub) WHERE (deleted_at IS NULL)") diff --git a/cmd/server/internal/store/requests.go b/cmd/server/internal/store/requests.go new file mode 100644 index 0000000..c562916 --- /dev/null +++ b/cmd/server/internal/store/requests.go @@ -0,0 +1,319 @@ +package store + +import ( + "encoding/json" + "slices" + "strings" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" +) + +const requestJSON = `jsonb_build_object('id',q.id,'issue',jsonb_build_object('id',i.id,'identifier',w.key||'-'||i.number,'title',i.title,'statusId',i.status_id), + 'kind',q.kind,'from',jsonb_build_object('sub',q.from_sub,'name',q.from_name), + 'to',CASE WHEN q.to_sub IS NULL THEN NULL ELSE jsonb_build_object('sub',q.to_sub,'name',q.to_name) END, + 'title',q.title,'body',q.body,'options',q.options,'runId',q.run_id,'state',q.state,'createdAt',q.created_at, + 'answer',CASE WHEN q.answered_at IS NULL THEN NULL ELSE jsonb_build_object('option',q.answer_option,'body',q.answer_body,'by',jsonb_build_object('sub',q.answered_by_sub,'name',q.answered_by_name),'at',q.answered_at) END)` +const requestFrom = ` FROM tracker_request q JOIN tracker_issue i ON i.id=q.issue_id JOIN tracker_workspace w ON w.id=i.workspace_id WHERE i.workspace_id=$1 AND i.deleted_at IS NULL ` + +func scanRequest(row scanner) (domain.Request, error) { + var data []byte + var request domain.Request + if err := row.Scan(&data); err != nil { + return request, err + } + err := json.Unmarshal(data, &request) + return request, err +} + +func (t *Tx) Request(id string) (domain.Request, error) { + return scanRequest(t.SQL.QueryRowContext(t.Context, `SELECT `+requestJSON+requestFrom+` AND q.id=$2`, t.WorkspaceID, id)) +} + +type RequestCreate struct { + Kind string `json:"kind"` + Title string `json:"title"` + Body string `json:"body"` + Options []string `json:"options"` + To Field[string] `json:"to"` + RunID *string `json:"runId"` +} + +func (t *Tx) insertRequest(issue domain.Issue, input RequestCreate, from domain.Person, to *domain.Person) (domain.Request, error) { + id := ulid.Make().String() + var sub, name any + if to != nil { + sub, name = to.Sub, to.Name + } + options, err := jsonValue(input.Options) + if err != nil { + return domain.Request{}, err + } + if err := t.Exec(`INSERT INTO tracker_request(id,issue_id,kind,from_sub,from_name,to_sub,to_name,title,body,options,run_id,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, id, issue.ID, input.Kind, from.Sub, from.Name, sub, name, input.Title, input.Body, options, input.RunID, t.now()); err != nil { + return domain.Request{}, err + } + if err := t.event(issue.ID, from, "request.opened", id); err != nil { + return domain.Request{}, err + } + return t.Request(id) +} + +func (t *Tx) CreateRequest(issueID string, input RequestCreate, actor domain.Actor, to *domain.Person) (domain.Request, error) { + issue, err := t.Issue(issueID) + if err != nil { + return domain.Request{}, err + } + if !slices.Contains([]string{"question", "approval"}, input.Kind) || !domain.Text(input.Title, 1, 200) || len(input.Body) > 20<<10 || !domain.Text(input.Body, 0, 20<<10) || len(input.Options) > 6 { + return domain.Request{}, invalid("Invalid request kind, title, body or options") + } + if input.Kind == "approval" { + input.Options = []string{"approve", "reject"} + } + if input.Options == nil { + input.Options = []string{} + } + for i, option := range input.Options { + if !domain.Text(option, 1, 200) || slices.Contains(input.Options[:i], option) { + return domain.Request{}, invalid("Options must be distinct nonempty strings of at most 200 characters") + } + } + if !input.To.Present && actor.Kind == "agent" { + to = issue.Delegator + if to == nil { + to = &actor.Agent.Owner + } + } + if input.RunID != nil { + run, err := t.ownedRun(*input.RunID, actor, domain.HeartbeatRun) + if err != nil { + return domain.Request{}, err + } + if run.Issue.ID != issue.ID { + return domain.Request{}, httpx.Forbidden() + } + if err := t.Exec(`UPDATE tracker_run SET state='waiting' WHERE id=$1`, run.ID); err != nil { + return domain.Request{}, err + } + } + return t.insertRequest(issue, input, actor.Person, to) +} + +type RequestAnswer struct { + Option *string `json:"option"` + Body string `json:"body"` +} + +func (t *Tx) AnswerRequest(id string, input RequestAnswer, actor domain.Actor) (domain.Request, error) { + request, err := t.Request(id) + if err != nil { + return request, err + } + to := "" + if request.To != nil { + to = request.To.Sub + } + if !domain.Can(actor, domain.AnswerRequest, domain.Target{OwnerSub: to, RequestKind: request.Kind}) { + return request, httpx.Forbidden() + } + if request.State != "open" { + return request, httpx.Conflict("The request is not open") + } + if len(input.Body) > 20<<10 || !domain.Text(input.Body, 0, 20<<10) { + return request, invalid("Answer body must be at most 20 KiB") + } + if len(request.Options) > 0 && (input.Option == nil || !slices.Contains(request.Options, *input.Option)) { + return request, invalid("Answer option must be one of the request options") + } + if len(request.Options) == 0 && input.Option != nil { + return request, invalid("This request has no answer options") + } + if request.Kind == "review" && input.Option != nil && *input.Option == "approve" { + statuses, err := t.Statuses() + if err != nil { + return request, err + } + completed := "" + for _, status := range statuses { + if status.Category == "completed" { + completed = status.ID + break + } + } + if completed == "" { + return request, httpx.Conflict("The workspace has no completed status") + } + if _, err := t.PatchIssue(request.Issue.ID, IssuePatch{StatusID: Field[string]{Present: true, Value: &completed}}, actor.Person, nil); err != nil { + return request, err + } + } + if err := t.Exec(`UPDATE tracker_request SET state='answered',answer_option=$2,answer_body=$3,answered_by_sub=$4,answered_by_name=$5,answered_at=$6 WHERE id=$1`, id, input.Option, input.Body, actor.Sub, actor.Name, t.now()); err != nil { + return request, err + } + if request.RunID != nil { + if err := t.Exec(`UPDATE tracker_run SET state='running' WHERE id=$1 AND state='waiting' AND NOT EXISTS(SELECT 1 FROM tracker_request WHERE run_id=$1 AND state='open')`, *request.RunID); err != nil { + return request, err + } + } + if err := t.event(request.Issue.ID, actor.Person, "request.answered", id); err != nil { + return request, err + } + return t.Request(id) +} + +func (t *Tx) Inbox(actor domain.Actor) ([]domain.InboxItem, error) { + list := []domain.InboxItem{} + predicate := ` AND ((q.state='open' AND (q.to_sub=$2 OR (q.to_sub IS NULL AND $3))) OR (q.state='answered' AND q.from_sub=$2 AND q.answer_acknowledged_at IS NULL))` + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+requestJSON+requestFrom+predicate+` ORDER BY CASE WHEN q.state='open' THEN 0 ELSE 1 END,q.created_at,q.id`, t.WorkspaceID, actor.Sub, actor.Kind != "agent") + if err != nil { + return nil, err + } + for rows.Next() { + request, err := scanRequest(rows) + if err != nil { + rows.Close() + return nil, err + } + kind := "request" + if request.State == "answered" { + kind = "answer" + } + list = append(list, domain.InboxItem{Kind: kind, Request: &request}) + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + mentions, err := t.inboxMentions(actor.Sub) + if err != nil { + return nil, err + } + list = append(list, mentions...) + if actor.Kind != "agent" { + return list, err + } + rows, err = t.SQL.QueryContext(t.Context, `SELECT i.id,s.category, + EXISTS(SELECT 1 FROM tracker_run r WHERE r.issue_id=i.id AND r.state IN ('running','waiting') AND r.lease_expires_at >= $4 AND r.agent_id<>$3), + EXISTS(SELECT 1 FROM tracker_request q WHERE q.issue_id=i.id AND q.state='open' AND q.from_sub=$2 + AND NOT EXISTS(SELECT 1 FROM tracker_run expired WHERE expired.id=q.run_id AND expired.state IN ('running','waiting') AND expired.lease_expires_at < $4)), + EXISTS(SELECT 1 FROM tracker_issue_block b JOIN tracker_issue blocker ON blocker.id=b.blocker_id JOIN tracker_status bs ON bs.id=blocker.status_id WHERE b.blocked_id=i.id AND blocker.deleted_at IS NULL AND bs.category NOT IN ('completed','canceled')) + FROM tracker_issue i JOIN tracker_status s ON s.id=i.status_id LEFT JOIN tracker_sprint sp ON sp.id=i.sprint_id + WHERE i.workspace_id=$1 AND i.assignee_sub=$2 AND i.deleted_at IS NULL + ORDER BY `+prioritySQL+`,CASE WHEN sp.started_at IS NOT NULL AND sp.closed_at IS NULL THEN 0 ELSE 1 END,i.number`, t.WorkspaceID, actor.Sub, actor.AgentID, t.now()) + if err != nil { + return nil, err + } + ids := []string{} + for rows.Next() { + var id string + var facts domain.ActionableInput + if err := rows.Scan(&id, &facts.Category, &facts.OtherActiveRun, &facts.OwnOpenRequest, &facts.UnfinishedBlock); err != nil { + rows.Close() + return nil, err + } + if domain.Actionable(facts) { + ids = append(ids, id) + } + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + issues, err := t.issueSummaries(ids) + if err != nil { + return nil, err + } + for i := range issues { + list = append(list, domain.InboxItem{Kind: "assignment", Issue: &issues[i]}) + } + return list, nil +} + +type RequestFilter struct { + State string + To string + Issue string +} + +func (t *Tx) Requests(filter RequestFilter) ([]domain.Request, error) { + if filter.State != "" && !slices.Contains([]string{"open", "answered", "withdrawn"}, filter.State) { + return nil, invalid("State must be open, answered, or withdrawn") + } + if filter.Issue != "" { + issue, err := t.Issue(filter.Issue) + if err != nil { + return nil, err + } + filter.Issue = issue.ID + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+requestJSON+requestFrom+` AND ($2='' OR q.state=$2) AND ($3='' OR q.to_sub=$3 OR ($3='none' AND q.to_sub IS NULL)) AND ($4='' OR q.issue_id=$4) ORDER BY q.created_at DESC,q.id DESC`, t.WorkspaceID, filter.State, filter.To, filter.Issue) + if err != nil { + return nil, err + } + defer rows.Close() + list := []domain.Request{} + for rows.Next() { + item, err := scanRequest(rows) + if err != nil { + return nil, err + } + list = append(list, item) + } + return list, rows.Err() +} + +func (t *Tx) withdrawRequests(predicate, value string, actor domain.Person) error { + rows, err := t.SQL.QueryContext(t.Context, `UPDATE tracker_request q SET state='withdrawn' FROM tracker_issue i WHERE i.id=q.issue_id AND i.workspace_id=$1 AND q.state='open' AND (`+predicate+`) RETURNING q.id,q.issue_id,q.run_id`, t.WorkspaceID, value) + if err != nil { + return err + } + type withdrawn struct { + id, issue string + run *string + } + list := []withdrawn{} + for rows.Next() { + var item withdrawn + if err := rows.Scan(&item.id, &item.issue, &item.run); err != nil { + rows.Close() + return err + } + list = append(list, item) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + slices.SortFunc(list, func(a, b withdrawn) int { return strings.Compare(a.id, b.id) }) + for _, item := range list { + if err := t.event(item.issue, actor, "request.withdrawn", item.id); err != nil { + return err + } + if item.run != nil { + if err := t.Exec(`UPDATE tracker_run SET state='running' WHERE id=$1 AND state='waiting' AND NOT EXISTS(SELECT 1 FROM tracker_request WHERE run_id=$1 AND state='open')`, *item.run); err != nil { + return err + } + } + } + return nil +} + +func (t *Tx) WithdrawRequest(id string, actor domain.Actor) (domain.Request, error) { + item, err := t.Request(id) + if err != nil { + return item, err + } + if !domain.Can(actor, domain.WithdrawRequest, domain.Target{OwnerSub: item.From.Sub}) { + return item, httpx.Forbidden() + } + if item.State != "open" { + return item, httpx.Conflict("The request is not open") + } + if err := t.withdrawRequests(`q.id=$2`, id, actor.Person); err != nil { + return item, err + } + return t.Request(id) +} diff --git a/cmd/server/internal/store/runs.go b/cmd/server/internal/store/runs.go new file mode 100644 index 0000000..bbe55ee --- /dev/null +++ b/cmd/server/internal/store/runs.go @@ -0,0 +1,242 @@ +package store + +import ( + "encoding/json" + "net/url" + "slices" + "time" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" +) + +const runJSON = `jsonb_build_object('id',r.id,'issue',jsonb_build_object('id',i.id,'identifier',w.key||'-'||i.number,'title',i.title,'statusId',i.status_id), + 'agent',jsonb_build_object('sub','agent:'||a.id,'name',a.name,'agent',jsonb_build_object('id',a.id,'handle',a.handle,'owner',jsonb_build_object('sub',a.owner_sub,'name',a.owner_name),'disabled',a.disabled)), + 'state',r.state,'reason',r.reason,'session',r.session,'note',r.note,'summary',r.summary,'links',r.links, + 'startedAt',r.started_at,'heartbeatAt',r.heartbeat_at,'leaseExpiresAt',r.lease_expires_at,'finishedAt',r.finished_at)` +const runFrom = ` FROM tracker_run r JOIN tracker_issue i ON i.id=r.issue_id JOIN tracker_workspace w ON w.id=i.workspace_id JOIN tracker_agent a ON a.id=r.agent_id WHERE i.workspace_id=$1 AND i.deleted_at IS NULL ` + +func scanRun(row scanner, now time.Time) (domain.Run, error) { + var data []byte + var run domain.Run + if err := row.Scan(&data); err != nil { + return run, err + } + if err := json.Unmarshal(data, &run); err != nil { + return run, err + } + run.State = domain.RunState(run.State, run.LeaseExpiresAt, now) + return run, nil +} + +func (t *Tx) Run(id string) (domain.Run, error) { + return scanRun(t.SQL.QueryRowContext(t.Context, `SELECT `+runJSON+runFrom+` AND r.id=$2`, t.WorkspaceID, id), t.now()) +} + +func (t *Tx) Runs(issueID string) ([]domain.Run, error) { + issue, err := t.Issue(issueID) + if err != nil { + return nil, err + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+runJSON+runFrom+` AND i.id=$2 ORDER BY r.started_at DESC,r.id DESC`, t.WorkspaceID, issue.ID) + if err != nil { + return nil, err + } + defer rows.Close() + list := []domain.Run{} + now := t.now() + for rows.Next() { + run, err := scanRun(rows, now) + if err != nil { + return nil, err + } + list = append(list, run) + } + return list, rows.Err() +} + +func (t *Tx) leaseDuration() time.Duration { + if t.runLease > 0 { + return t.runLease + } + return 10 * time.Minute +} + +type RunStart struct { + Session string `json:"session"` + Note string `json:"note"` +} + +func (t *Tx) StartRun(issueID string, input RunStart, actor domain.Actor) (domain.Run, error) { + issue, err := t.Issue(issueID) + if err != nil { + return domain.Run{}, err + } + owner := "" + if issue.Assignee != nil { + owner = issue.Assignee.Sub + } + if !domain.Can(actor, domain.StartRun, domain.Target{OwnerSub: owner}) { + return domain.Run{}, httpx.Forbidden() + } + if !domain.Text(input.Session, 0, 200) || !domain.Text(input.Note, 0, 200) { + return domain.Run{}, invalid("Session and note must be at most 200 characters") + } + if issue.ActiveRun != nil { + if issue.ActiveRun.State != "stalled" { + return domain.Run{}, httpx.Conflict("An active run already holds this issue") + } + if err := t.closeRun(issue.ActiveRun.ID, "failed", "lease_expired", actor.Person); err != nil { + return domain.Run{}, err + } + } + id, now := ulid.Make().String(), t.now() + if err := t.Exec(`INSERT INTO tracker_run(id,issue_id,agent_id,state,session,note,started_at,heartbeat_at,lease_expires_at) VALUES($1,$2,$3,'running',$4,$5,$6,$6,$7)`, id, issue.ID, actor.AgentID, input.Session, input.Note, now, now.Add(t.leaseDuration())); err != nil { + return domain.Run{}, err + } + if err := t.event(issue.ID, actor.Person, "run.started", id); err != nil { + return domain.Run{}, err + } + return t.Run(id) +} + +func (t *Tx) ownedRun(id string, actor domain.Actor, action domain.Action) (domain.Run, error) { + run, err := t.Run(id) + if err != nil { + return run, err + } + if !domain.Can(actor, action, domain.Target{OwnerSub: run.Agent.Sub}) { + return run, httpx.Forbidden() + } + if !domain.LiveRun(run.State) { + return run, httpx.Conflict("The run is terminal or its lease has expired") + } + return run, nil +} + +func (t *Tx) HeartbeatRun(id string, note *string, actor domain.Actor) (domain.Run, error) { + run, err := t.ownedRun(id, actor, domain.HeartbeatRun) + if err != nil { + return run, err + } + if note != nil { + if !domain.Text(*note, 0, 200) { + return run, invalid("Note must be at most 200 characters") + } + run.Note = *note + } + now := t.now() + if err := t.Exec(`UPDATE tracker_run SET note=$2,heartbeat_at=$3,lease_expires_at=$4 WHERE id=$1`, id, run.Note, now, now.Add(t.leaseDuration())); err != nil { + return run, err + } + return t.Run(id) +} + +type RunFinish struct { + Outcome string `json:"outcome"` + Summary string `json:"summary"` + Links []domain.RunLink `json:"links"` +} + +func (t *Tx) FinishRun(id string, input RunFinish, actor domain.Actor) (domain.Run, error) { + run, err := t.ownedRun(id, actor, domain.FinishRun) + if err != nil { + return run, err + } + if !slices.Contains([]string{"succeeded", "failed"}, input.Outcome) || len(input.Summary) > 20<<10 || !domain.Text(input.Summary, 0, 20<<10) || len(input.Links) > 10 { + return run, invalid("Invalid outcome, summary or links") + } + for _, link := range input.Links { + u, err := url.Parse(link.URL) + if err != nil || u.Scheme != "https" || u.Host == "" || !slices.Contains([]string{"pr", "commit", "url"}, link.Kind) || !domain.Text(link.Title, 0, 200) { + return run, invalid("Links require an HTTPS URL, kind and a title of at most 200 characters") + } + } + if input.Outcome == "succeeded" { + var approval bool + if err := t.SQL.QueryRowContext(t.Context, `SELECT EXISTS(SELECT 1 FROM tracker_request WHERE run_id=$1 AND state='open' AND kind='approval')`, id).Scan(&approval); err != nil { + return run, err + } + if approval { + return run, httpx.Conflict("Resolve or withdraw the run's open approvals before finishing") + } + } + if input.Links == nil { + input.Links = []domain.RunLink{} + } + links, err := jsonValue(input.Links) + if err != nil { + return run, err + } + if err := t.Exec(`UPDATE tracker_run SET state=$2,summary=$3,links=$4,finished_at=$5 WHERE id=$1`, id, input.Outcome, input.Summary, links, t.now()); err != nil { + return run, err + } + if err := t.event(run.Issue.ID, actor.Person, "run.finished", id); err != nil { + return run, err + } + if err := t.withdrawRequests(`q.run_id=$2 AND (q.kind='question' OR $2 IN (SELECT id FROM tracker_run WHERE state='failed'))`, id, actor.Person); err != nil { + return run, err + } + var policy string + if err := t.SQL.QueryRowContext(t.Context, `SELECT agent_completion FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&policy); err != nil { + return run, err + } + if input.Outcome == "succeeded" && policy == "review" { + issue, err := t.Issue(run.Issue.ID) + if err != nil { + return run, err + } + to := issue.Delegator + if to == nil { + to = &run.Agent.Agent.Owner + } + if _, err := t.insertRequest(issue, RequestCreate{Kind: "review", Title: "Review: " + truncateTitle(issue.Title, 192), Body: input.Summary, Options: []string{"approve", "reject"}, RunID: &id}, actor.Person, to); err != nil { + return run, err + } + } + return t.Run(id) +} + +func truncateTitle(title string, limit int) string { + count := 0 + for at := range title { + if count == limit { + return title[:at] + } + count++ + } + return title +} + +func (t *Tx) closeRun(id, state, reason string, actor domain.Person) error { + var issueID string + if err := t.SQL.QueryRowContext(t.Context, `UPDATE tracker_run r SET state=$2,reason=$3,finished_at=$4 FROM tracker_issue i WHERE r.id=$1 AND i.id=r.issue_id AND i.workspace_id=$5 RETURNING r.issue_id`, id, state, reason, t.now(), t.WorkspaceID).Scan(&issueID); err != nil { + return err + } + kind := "run.canceled" + if state == "failed" { + kind = "run.finished" + } + if err := t.event(issueID, actor, kind, id); err != nil { + return err + } + return t.withdrawRequests(`q.run_id=$2`, id, actor) +} + +func (t *Tx) CancelRun(id string, actor domain.Actor) (domain.Run, error) { + run, err := t.Run(id) + if err != nil { + return run, err + } + if !domain.Can(actor, domain.CancelRun, domain.Target{OwnerSub: run.Agent.Sub}) { + return run, httpx.Forbidden() + } + if !domain.LiveRun(run.State) && run.State != "stalled" { + return run, httpx.Conflict("The run is terminal") + } + if err := t.closeRun(id, "canceled", "canceled_by:"+actor.Sub, actor.Person); err != nil { + return run, err + } + return t.Run(id) +} diff --git a/cmd/server/internal/store/seed.go b/cmd/server/internal/store/seed.go index 6122ef5..c864ac0 100644 --- a/cmd/server/internal/store/seed.go +++ b/cmd/server/internal/store/seed.go @@ -96,7 +96,10 @@ func (s *Store) SeedDev(ctx context.Context, workspace string) error { return err } } - return tx.seedSprints(admin.Person, statuses) + if err := tx.seedSprints(admin.Person, statuses); err != nil { + return err + } + return tx.seedAgents(people, statuses, projects[1].ID) }) } diff --git a/cmd/server/internal/store/seed_agents.go b/cmd/server/internal/store/seed_agents.go new file mode 100644 index 0000000..847cea8 --- /dev/null +++ b/cmd/server/internal/store/seed_agents.go @@ -0,0 +1,205 @@ +package store + +import ( + "fmt" + "time" + + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" +) + +// seedAgents mirrors the Agents fixture shared with the SPA mock. Existing +// issue numbers are never moved; the two agent reports are appended as 41/42. +func (t *Tx) seedAgents(people []domain.Person, statuses []domain.Status, projectID string) error { + now, previousClock := t.now(), t.clock + defer func() { t.clock = previousClock }() + at := func(delta time.Duration) time.Time { return now.Add(delta) } + setClock := func(instant time.Time) { t.clock = func() time.Time { return instant } } + admin := domain.Actor{Person: people[0], Role: "Admin", Kind: "person"} + agents := map[string]domain.Agent{} + for _, f := range []struct { + handle, name, description string + owner int + disabled bool + created, updated, seen time.Duration + }{ + {"astra", "Astra", "Backend implementer. Go handlers, store queries, migrations and their tests. Delegate issues with a clear acceptance check.", 1, false, -14 * 24 * time.Hour, -14 * 24 * time.Hour, -2 * time.Minute}, + {"opus-ui", "Opus UI", "UI implementer. React screens, copy and accessibility in the SPA. Delegate issues that include the expected screen or a screenshot.", 0, false, -7 * 24 * time.Hour, -7 * 24 * time.Hour, -time.Minute}, + {"claude", "Claude", "Planner and triage. Reads new reports, finds duplicates, proposes priority and sprint. Does not change code.", 2, false, -14 * 24 * time.Hour, -14 * 24 * time.Hour, -2 * time.Hour}, + {"legacy-bot", "Legacy bot", "Old nightly triage script. Replaced by claude.", 0, true, -60 * 24 * time.Hour, -30 * 24 * time.Hour, -32 * 24 * time.Hour}, + } { + a, err := t.CreateAgent(AgentCreate{Handle: f.handle, Name: f.name, Description: f.description, OwnerSub: people[f.owner].Sub}, people[f.owner], admin) + if err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_agent SET disabled=$2,created_at=$3,updated_at=$4,last_seen_at=$5 WHERE id=$1`, a.ID, f.disabled, at(f.created), at(f.updated), at(f.seen)); err != nil { + return err + } + agents[f.handle] = a + } + for _, f := range []struct { + number int + handle string + delegator int + offset time.Duration + }{ + {15, "astra", 0, -40 * time.Minute}, {27, "opus-ui", 0, -45 * time.Minute}, {9, "astra", 1, -4 * time.Hour}, + {16, "astra", 0, -3 * time.Hour}, {4, "astra", 1, -27 * time.Hour}, {21, "claude", 0, -4 * time.Hour}, + {13, "opus-ui", 0, -24 * time.Hour}, {26, "opus-ui", 2, -24 * time.Hour}, {19, "astra", 1, -48 * time.Hour}, + } { + setClock(at(f.offset)) + person := agents[f.handle].Person() + issue, err := t.PatchIssue(fmt.Sprintf("APT-%d", f.number), IssuePatch{AssigneeSub: Field[string]{Present: true, Value: &person.Sub}}, people[f.delegator], &person) + if err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_issue SET updated_at=$2 WHERE id=$1`, issue.ID, at(f.offset)); err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_activity SET created_at=$2 WHERE issue_id=$1 AND field IN ('assignee','delegator')`, issue.ID, at(f.offset)); err != nil { + return err + } + } + for _, f := range []struct { + handle string + offset time.Duration + input IssueCreate + self bool + }{ + {"claude", -5 * time.Hour, IssueCreate{Title: "Three reports describe the same stale status", Type: "task", Priority: "high", StatusID: statuses[0].ID, ProjectID: &projectID, Description: "APT-4, APT-22 and APT-28 all show a status that lags behind the real one by one refresh. Proposal: keep APT-4 and close the other two as duplicates."}, false}, + {"astra", -3 * time.Hour, IssueCreate{Title: "Flaky test: lease renewal in store/runs_test", Type: "bug", Priority: "medium", StatusID: statuses[1].ID, ProjectID: &projectID, Description: "TestHeartbeatRenewsLease fails about 1 in 30 runs on CI.", Report: &domain.Report{Environment: "local", Surface: "platform-api", Version: "0.1.13", Steps: "go test -count=30 ./cmd/server/internal/store -run TestHeartbeatRenewsLease", Expected: "All runs pass.", Actual: "One run fails with lease_expired."}}, true}, + } { + setClock(at(f.offset)) + person := agents[f.handle].Person() + var assignee *domain.Person + if f.self { + assignee = &person + } + issue, err := t.CreateIssue(f.input, person, assignee) + if err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_issue SET created_at=$2,updated_at=$2 WHERE id=$1`, issue.ID, at(f.offset)); err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_activity SET created_at=$2 WHERE issue_id=$1`, issue.ID, at(f.offset)); err != nil { + return err + } + } + issues := map[int]domain.Issue{} + for _, n := range []int{1, 4, 9, 15, 16, 21, 22, 27, 41} { + i, err := t.Issue(fmt.Sprintf("APT-%d", n)) + if err != nil { + return err + } + issues[n] = i + } + summary16 := "The CLI refreshed its login only after a request failed with 401, so the first command after one hour always failed.\n\n- Refresh the token when less than 5 minutes of its lifetime remain.\n- Retry once on 401 after a refresh.\n- Added `TestLoginRefreshBeforeExpiry`." + summary4 := "Status reads now bypass the list cache after a status change. Added a regression test for the list endpoint." + runs := map[int]string{} + for _, f := range []struct { + number int + handle, state, session, note, summary string + start, heartbeat time.Duration + links []domain.RunLink + }{ + {15, "astra", "running", "astra · lane-2", "running go test ./cmd/server/... after removing 14 unused fixtures", "", -35 * time.Minute, -2 * time.Minute, nil}, + {27, "opus-ui", "waiting", "opus-ui · a11y pass", "waiting for a decision on the close-button label", "", -40 * time.Minute, -time.Minute, nil}, + {9, "astra", "running", "astra · lane-1", "comparing the Gateway page with the current kubeconfig flow", "", -3 * time.Hour, -52 * time.Minute, nil}, + {16, "astra", "succeeded", "astra · lane-2", "opening the pull request", summary16, -2 * time.Hour, -25 * time.Minute, []domain.RunLink{{Kind: "pr", URL: "https://github.com/appthrust/tracker/pull/142", Title: "Refresh the CLI login before the token expires"}}}, + {4, "astra", "succeeded", "astra · lane-1", "opening the pull request", summary4, -26 * time.Hour, -24 * time.Hour, []domain.RunLink{{Kind: "pr", URL: "https://github.com/appthrust/tracker/pull/138", Title: "Invalidate the status cache on change"}}}, + } { + id := ulid.Make().String() + runs[f.number] = id + var finished any + if f.state == "succeeded" { + finished = at(f.heartbeat) + } + if f.links == nil { + f.links = []domain.RunLink{} + } + links, err := jsonValue(f.links) + if err != nil { + return err + } + if err := t.Exec(`INSERT INTO tracker_run(id,issue_id,agent_id,state,session,note,summary,links,started_at,heartbeat_at,lease_expires_at,finished_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, id, issues[f.number].ID, agents[f.handle].ID, f.state, f.session, f.note, f.summary, links, at(f.start), at(f.heartbeat), at(f.heartbeat+10*time.Minute), finished); err != nil { + return err + } + setClock(at(f.start)) + if err := t.event(issues[f.number].ID, agents[f.handle].Person(), "run.started", id); err != nil { + return err + } + if finished != nil { + setClock(at(f.heartbeat)) + if err := t.event(issues[f.number].ID, agents[f.handle].Person(), "run.finished", id); err != nil { + return err + } + } + } + astra, opus, claude := agents["astra"].Person(), agents["opus-ui"].Person(), agents["claude"].Person() + approve := []string{"approve", "reject"} + for _, f := range []struct { + number int + kind, title, body string + from domain.Person + to *domain.Person + run bool + options []string + created time.Duration + answer *domain.RequestAnswer + ack bool + }{ + {27, "question", "Which label should the panel's close button use?", `The panel's close button has no visible text. "Close" matches the rest of the app; "Dismiss" is what the screen reader announces today.`, opus, &people[0], true, []string{"Close", "Dismiss", `Keep both: visible "Close", spoken "Dismiss"`}, -8 * time.Minute, nil, false}, + {15, "question", "Delete the fixtures under testdata/legacy too?", "", astra, &people[0], true, []string{"Yes, delete them", "No, keep them"}, -28 * time.Minute, &domain.RequestAnswer{Option: new("Yes, delete them"), Body: "They are unused since 0.1.7.", By: people[0], At: at(-20 * time.Minute)}, true}, + {16, "review", "Review: CLI login expires too early", summary16, astra, &people[0], true, approve, -25 * time.Minute, nil, false}, + {4, "review", "Review: Platform API returns stale status", summary4, astra, &people[1], true, approve, -24 * time.Hour, &domain.RequestAnswer{Option: new("reject"), Body: "Still stale right after a status change: the 304 path keeps the old ETag. Please add a test for it.", By: people[1], At: at(-20 * time.Hour)}, false}, + {1, "approval", "Add APT-1 to the current sprint?", "Two people lost their filters on appthrust.dev this week. It is urgent but sits in the backlog without a sprint.", claude, nil, false, approve, -90 * time.Minute, nil, false}, + {21, "question", "Which open bugs look like duplicates of APT-22?", "", people[0], &claude, false, []string{}, -3 * time.Hour, &domain.RequestAnswer{Body: "APT-4 and APT-28 describe the same stale-cache symptom; I filed APT-41 to merge them.", By: claude, At: at(-2 * time.Hour)}, false}, + } { + setClock(at(f.created)) + input := RequestCreate{Kind: f.kind, Title: f.title, Body: f.body, Options: f.options} + if f.run { + input.RunID = new(runs[f.number]) + } + request, err := t.insertRequest(issues[f.number], input, f.from, f.to) + if err != nil { + return err + } + if f.answer != nil { + answer := f.answer + var ack any + if f.ack { + ack = answer.At + } + if err := t.Exec(`UPDATE tracker_request SET state='answered',answer_option=$2,answer_body=$3,answered_by_sub=$4,answered_by_name=$5,answered_at=$6,answer_acknowledged_at=$7 WHERE id=$1`, request.ID, answer.Option, answer.Body, answer.By.Sub, answer.By.Name, answer.At, ack); err != nil { + return err + } + setClock(answer.At) + if err := t.event(request.Issue.ID, answer.By, "request.answered", request.ID); err != nil { + return err + } + } + } + for _, f := range []struct { + number int + author domain.Person + offset time.Duration + body string + }{ + {22, people[1], -time.Hour, "@astra could you check whether the cursor encoding changed with APT-15? The skipped rows start after page 2."}, + {41, claude, -5 * time.Hour, "Filed from triage. Evidence: the three reports name the same endpoint and the same one-refresh lag."}, + } { + setClock(at(f.offset)) + c, err := t.CreateComment(issues[f.number].ID, f.body, f.author) + if err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_comment SET created_at=$2 WHERE id=$1`, c.ID, at(f.offset)); err != nil { + return err + } + if err := t.Exec(`UPDATE tracker_issue SET updated_at=$2 WHERE id=$1`, c.IssueID, at(f.offset)); err != nil { + return err + } + } + return nil +} diff --git a/cmd/server/internal/store/sprints.go b/cmd/server/internal/store/sprints.go index e2426aa..50fa160 100644 --- a/cmd/server/internal/store/sprints.go +++ b/cmd/server/internal/store/sprints.go @@ -382,5 +382,8 @@ func (t *Tx) moveSprintMember(item domain.Issue, next *domain.SprintRef, actor d if err := t.sprintEvents(item.ID, before, after); err != nil { return err } - return t.activity(item.ID, actor, "sprint", old, next) + if err := t.activity(item.ID, actor, "sprint", old, next); err != nil { + return err + } + return t.event(item.ID, actor, "issue.updated", map[string]any{"fields": []string{"sprint"}}) } diff --git a/cmd/server/internal/store/sprints_test.go b/cmd/server/internal/store/sprints_test.go index 99527ea..57350dc 100644 --- a/cmd/server/internal/store/sprints_test.go +++ b/cmd/server/internal/store/sprints_test.go @@ -251,7 +251,7 @@ func TestSprintDatesDefaultsAndIsolation(t *testing.T) { var id string require.NoError(t, db.InWorkspace(t.Context(), "dates", true, func(tx *Tx) error { weeks := 2 - _, err := tx.PatchWorkspace(nil, nil, &weeks, nil) + _, err := tx.PatchWorkspace(nil, nil, &weeks, nil, nil) require.NoError(t, err) a, err := tx.CreateSprint(SprintCreate{}) require.NoError(t, err) @@ -404,7 +404,7 @@ func TestSprintSeedFixture(t *testing.T) { require.NoError(t, db.InWorkspace(t.Context(), "seed", false, func(tx *Tx) error { workspace, err := tx.Workspace() require.NoError(t, err) - require.Equal(t, 40, workspace.IssueCount) + require.Equal(t, 42, workspace.IssueCount) sprints, err := tx.Sprints("") require.NoError(t, err) require.Len(t, sprints, 5) @@ -543,7 +543,7 @@ func TestSprintStartOverlapAndDST(t *testing.T) { db.Now = func() time.Time { return now } require.NoError(t, db.InWorkspace(t.Context(), "dst", true, func(tx *Tx) error { timezone := "America/New_York" - _, err := tx.PatchWorkspace(nil, nil, nil, &timezone) + _, err := tx.PatchWorkspace(nil, nil, nil, &timezone, nil) require.NoError(t, err) a, err := tx.CreateSprint(sprintInput("2026-10-31", 1)) require.NoError(t, err) diff --git a/cmd/server/internal/store/store.go b/cmd/server/internal/store/store.go index 703a664..289d202 100644 --- a/cmd/server/internal/store/store.go +++ b/cmd/server/internal/store/store.go @@ -18,12 +18,14 @@ var migrations embed.FS type Store struct { *pgstore.Store // Now may be injected before serving requests for deterministic sprint clocks. - Now func() time.Time + Now func() time.Time + RunLease time.Duration } type Tx struct { *pgstore.Tx WorkspaceID string clock func() time.Time + runLease time.Duration } func Open(ctx context.Context, dsn string) (*Store, error) { @@ -35,7 +37,7 @@ func Open(ctx context.Context, dsn string) (*Store, error) { } func (s *Store) Do(ctx context.Context, write bool, fn func(*Tx) error) error { - return translate(s.Store.Do(ctx, write, func(tx *pgstore.Tx) error { return fn(&Tx{Tx: tx, clock: s.Now}) })) + return translate(s.Store.Do(ctx, write, func(tx *pgstore.Tx) error { return fn(&Tx{Tx: tx, clock: s.Now, runLease: s.RunLease}) })) } func (s *Store) InWorkspace(ctx context.Context, workspace string, write bool, fn func(*Tx) error) error { @@ -50,11 +52,13 @@ func (s *Store) InWorkspace(ctx context.Context, workspace string, write bool, f }) } +// PostgreSQL timestamps have microsecond precision. Use the same clock +// resolution for SQL predicates and Go-derived lease states. func (t *Tx) now() time.Time { if t.clock != nil { - return t.clock().UTC() + return t.clock().UTC().Truncate(time.Microsecond) } - return time.Now().UTC() + return time.Now().UTC().Truncate(time.Microsecond) } func invalid(message string) error { return httpx.Fail(400, "invalid", message) } diff --git a/cmd/server/internal/store/store_test.go b/cmd/server/internal/store/store_test.go index 5f4f320..b876108 100644 --- a/cmd/server/internal/store/store_test.go +++ b/cmd/server/internal/store/store_test.go @@ -35,7 +35,7 @@ func TestSeedPagingAndFilters(t *testing.T) { require.NoError(t, database.InWorkspace(t.Context(), "pj-test", true, func(tx *Tx) error { w, err := tx.Workspace() require.NoError(t, err) - require.Equal(t, 40, w.IssueCount) + require.Equal(t, 42, w.IssueCount) statuses, err := tx.Statuses() require.NoError(t, err) require.Len(t, statuses, 6) @@ -63,7 +63,7 @@ func TestSeedPagingAndFilters(t *testing.T) { } cursor = *page.NextCursor } - require.Len(t, seen, 40) + require.Len(t, seen, 42) } for _, filter := range []domain.Filter{{Type: []string{"bug"}}, {Assignee: []string{"me"}}, {Category: []string{"started"}}, {Q: "Dashboard"}, {Environment: []string{"local"}}, {Surface: []string{"apth"}}, {Label: []string{labels[0].ID}}, {Status: []string{statuses[0].ID}}, {Priority: []string{"urgent"}}, {CreatedAfter: "2025-01-01T00:00:00Z"}, {Parent: "none"}} { page, err := tx.ListIssues(ListOptions{Filter: filter, Subject: "dev-alex"}) @@ -132,7 +132,7 @@ func TestMutationsAndIsolation(t *testing.T) { require.Error(t, tx.DeleteStatus(statuses[1].ID)) require.Error(t, tx.DeleteStatus(statuses[5].ID)) key := "NEW" - _, err = tx.PatchWorkspace(&key, nil, nil, nil) + _, err = tx.PatchWorkspace(&key, nil, nil, nil, nil) require.NoError(t, err) item, err = tx.Issue("new-1") require.NoError(t, err) diff --git a/cmd/server/internal/store/views.go b/cmd/server/internal/store/views.go index 99f8861..d76434f 100644 --- a/cmd/server/internal/store/views.go +++ b/cmd/server/internal/store/views.go @@ -119,7 +119,7 @@ func (t *Tx) PatchView(id string, input ViewPatch, actor domain.Actor) (domain.V item.Sort = *input.Sort } if input.Shared != nil { - if *input.Shared && actor.Role != "Admin" { + if !domain.Can(actor, domain.CreateView, domain.Target{Shared: *input.Shared}) { return item, httpx.Forbidden() } item.Shared = *input.Shared @@ -150,7 +150,7 @@ func (t *Tx) DeleteView(id string, actor domain.Actor) error { if err != nil { return err } - if !domain.Can(actor, domain.ManageView, domain.Target{OwnerSub: item.Owner.Sub, Shared: item.Shared}) { + if !domain.Can(actor, domain.DeleteView, domain.Target{OwnerSub: item.Owner.Sub, Shared: item.Shared}) { return httpx.Forbidden() } return t.Exec(`DELETE FROM tracker_view WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID) diff --git a/cmd/server/internal/store/workspace.go b/cmd/server/internal/store/workspace.go index 61c31fb..d99cdf0 100644 --- a/cmd/server/internal/store/workspace.go +++ b/cmd/server/internal/store/workspace.go @@ -41,10 +41,10 @@ func (t *Tx) EnsureWorkspace() error { } func (t *Tx) Workspace() (domain.Workspace, error) { var w domain.Workspace - err := t.SQL.QueryRowContext(t.Context, `SELECT id,key,name,(SELECT count(*) FROM tracker_issue WHERE workspace_id=$1 AND deleted_at IS NULL),created_at,updated_at,sprint_length_weeks,timezone FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&w.ID, &w.Key, &w.Name, &w.IssueCount, &w.CreatedAt, &w.UpdatedAt, &w.SprintLengthWeeks, &w.Timezone) + err := t.SQL.QueryRowContext(t.Context, `SELECT id,key,name,(SELECT count(*) FROM tracker_issue WHERE workspace_id=$1 AND deleted_at IS NULL),created_at,updated_at,sprint_length_weeks,timezone,agent_completion FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&w.ID, &w.Key, &w.Name, &w.IssueCount, &w.CreatedAt, &w.UpdatedAt, &w.SprintLengthWeeks, &w.Timezone, &w.AgentCompletion) return w, err } -func (t *Tx) PatchWorkspace(key, name *string, lengthWeeks *int, timezone *string) (domain.Workspace, error) { +func (t *Tx) PatchWorkspace(key, name *string, lengthWeeks *int, timezone, agentCompletion *string) (domain.Workspace, error) { w, err := t.Workspace() if err != nil { return w, err @@ -61,6 +61,12 @@ func (t *Tx) PatchWorkspace(key, name *string, lengthWeeks *int, timezone *strin if timezone != nil { w.Timezone = *timezone } + if agentCompletion != nil { + w.AgentCompletion = *agentCompletion + } + if w.AgentCompletion != "review" && w.AgentCompletion != "direct" { + return w, &domain.FieldError{Path: "agentCompletion", Message: "Agent completion must be review or direct"} + } if w.SprintLengthWeeks != 1 && w.SprintLengthWeeks != 2 { return w, &domain.FieldError{Path: "sprintLengthWeeks", Message: "Sprint length must be 1 or 2 weeks"} } @@ -70,7 +76,7 @@ func (t *Tx) PatchWorkspace(key, name *string, lengthWeeks *int, timezone *strin if !domain.ValidKey(w.Key) || !domain.Text(w.Name, 1, 100) { return w, invalid("Workspace requires a key of 2 to 6 uppercase letters/digits and a name of 1 to 100 characters") } - err = t.Exec(`UPDATE tracker_workspace SET key=$2,name=$3,sprint_length_weeks=$4,timezone=$5,updated_at=now() WHERE id=$1`, t.WorkspaceID, w.Key, w.Name, w.SprintLengthWeeks, w.Timezone) + err = t.Exec(`UPDATE tracker_workspace SET key=$2,name=$3,sprint_length_weeks=$4,timezone=$5,agent_completion=$6,updated_at=now() WHERE id=$1`, t.WorkspaceID, w.Key, w.Name, w.SprintLengthWeeks, w.Timezone, w.AgentCompletion) if err != nil { return w, err } diff --git a/cmd/server/tracker.go b/cmd/server/tracker.go index 209acd1..e5d5c6e 100644 --- a/cmd/server/tracker.go +++ b/cmd/server/tracker.go @@ -28,6 +28,13 @@ func trackerHandler(upstreamURL, projectID string) (*pending.Handler, func(), er if err != nil { return nil, nil, err } + runLease := 10 * time.Minute + if raw := os.Getenv("TRACKER_RUN_LEASE"); raw != "" { + runLease, err = time.ParseDuration(raw) + if err != nil || runLease <= 0 { + return nil, nil, errors.New("TRACKER_RUN_LEASE must be a positive duration") + } + } publicURL := os.Getenv("TRACKER_PUBLIC_URL") if publicURL != "" { origin, err := parseOrigin(publicURL) @@ -68,6 +75,7 @@ func trackerHandler(upstreamURL, projectID string) (*pending.Handler, func(), er return nil, err } } + database.RunLease = runLease tracker.Swap(api.New(database, auth, platform, directory.New(links, directoryPublicURL), projectID)) return database, nil }) diff --git a/design/API.md b/design/API.md index 5f095fe..896635e 100644 --- a/design/API.md +++ b/design/API.md @@ -471,3 +471,180 @@ the Directory name. Each mutation request made with a key writes one `tracker access key mutation:` log line (method, path, key name, subject, edge `X-Request-Id`) before authorization. The timeline does not distinguish key writes from the user's own. + +## Agents: people and AI agents on the same board + +An Access Key whose subject is `external` is a registered agent, not a person. +Agents are assignable actors; a run is a lease that shows an agent is working; +a request is a directed, stateful handoff; under the `review` policy only a +person's approval completes an agent's work. User keys ("Access Keys +(v0.1.11)") are unchanged. + +An **Actor** is a person or an agent. Everything a person can be on an issue +(assignee, reporter, comment author, activity actor) an agent can be too. + +| Entity | Owner (sole writer) | Lifecycle | Invariants | +| --- | --- | --- | --- | +| **Agent** | Admin | `active ⇄ disabled`; never deleted (history refers to it) | has an immutable `id` and an immutable, unique `handle` (see "Identifiers"); `name` and `description` are editable; exactly one `owner` Person, who is accountable for what it does; an Assertion whose `external` subject equals no active agent's handle is refused (403 `key_subject`). | +| **Delegation** (fields on Issue) | whoever assigns | set when the assignee becomes an agent, cleared when it becomes a person or nobody | `delegator` is a Person: the person who assigned, or the agent's owner when an agent assigned (itself or another agent). The delegator is who the agent answers to on this issue. | +| **Run** | the agent that started it; a person may cancel | `running ⇄ waiting → succeeded \| failed \| canceled` | only the issue's assignee starts a run; at most one non-terminal run per issue; holds a lease (`leaseExpiresAt`, 10 minutes, renewed by heartbeat, compared at microsecond precision); a run whose lease has passed is `stalled` (derived at read time). A stalled run blocks nothing and is never revived: heartbeat and finish are refused, and the next start on the issue closes it as `failed/lease_expired`. Changing the assignee away from the agent cancels its non-terminal run (`reassigned`) in the same transaction. Whatever ends a run without success (cancel, reassignment, expiry closure) withdraws its open requests. | +| **Request** | requester creates and withdraws; addressee answers | `open → answered \| withdrawn` | `kind ∈ {question, approval, review}`; directed from one actor to one actor, or to "any person"; `approval` and `review` are answered only by people; a `review` exists only as the result of a finished run; only a run's own agent attaches a request to that run, and the run must belong to the same issue (otherwise anyone could force a run into `waiting`). | +| **Mention** | server, parsed from a comment | created with the comment; acknowledged by its target | `@handle` of an agent; one row per (comment, target). People are not mentionable in this version (Directory has no lookup by typed text). | +| **Event** | server, in the transaction of the write it describes | append-only | `seq` allocated from the workspace row, so order of `seq` is commit order and a reader never misses a row behind its cursor. | +| **Completion policy** (on Workspace) | Admin | setting | `agentCompletion ∈ {review, direct}`, default `review`. | + +### Identifiers + +| Identifier | Example | Mutable | Used for | +| --- | --- | --- | --- | +| `id` (ULID, server-assigned) | `01M74SFSZ657XZ2HNWWA9VND8T` | no | the reference history keeps: assignee, reporter, author and actor columns store `agent:` | +| `handle` (`^[a-z][a-z0-9-]{1,30}$`, unique) | `astra` | no | what people type and read (`@astra`, assignee picker) **and** the `external` subject of the agent's Access Keys: `apth access-keys create --space tracker --external astra` | +| `name` | `Astra` | yes | display | + +There is no separate key subject: one name per agent for the Admin to manage. +Keys come and go (expiry, revocation, several at once); every key minted with +the handle as its `external` subject is the same agent. The price is that a +handle cannot be renamed; the display name can. A session or lane has no +identifier of its own: it is the free-text `session` of a Run. + +### Authorization + +`domain.Actor` gains `Kind`. `Can` stays pure and gains these rows: + +| Action | Person | Agent (scope) | +| --- | --- | --- | +| Read issues, timeline, sprints, feed | any | `tracker:read` | +| Create issues, comment, attach, raise `question`/`approval` Requests, answer a `question` addressed to it — on any issue | any | `tracker:write` | +| Edit an issue's fields (`PATCH /issues/{id}`) | any | `tracker:write`, and only as the issue's assignee or reporter | +| Start and drive a run | n/a | `tracker:write`, assignee only | +| Set a `completed` status | any | only when `agentCompletion = direct` | +| Answer `approval` / `review` | addressee, or any person when unaddressed; Admin | never | +| Cancel a run | any | its own | +| Assign to an agent | any | itself, on issues it reported | +| Delete, settings, statuses, labels, shared views, sprint start/close/delete, manage agents | as today | never | +| `GET /people` (Directory) | any | empty, `source: unavailable` (Directory accepts only user bearers) | + + +Authentication: every route accepts the edge user bearer or an Access Key +Assertion (audience `tracker`). A key without the needed scope → 403 +`insufficient_scope` (as for user keys); a refusal by the authorization table +→ 403 `forbidden`. + +```ts +type ActorKind = 'person' | 'agent' +type Actor = Person & { kind: ActorKind; agent?: { id: string; handle: string; owner: Person; disabled: boolean } } +// For agents: sub = 'agent:', name = agent name. Every place that returned Person returns Actor. + +type Agent = { id: string; handle: string /* immutable; also the external subject of its Access Keys */ + name: string; description: string /* ≤ 4096 bytes: what to delegate to it */ + owner: Person; disabled: boolean + activeRuns: number; openRequests: number; lastSeenAt: string | null; createdAt: string; updatedAt: string } + +type RunState = 'running' | 'waiting' | 'stalled' | 'succeeded' | 'failed' | 'canceled' +type Link = { kind: 'pr' | 'commit' | 'url'; url: string /* https */; title: string /* ≤ 200 */ } +type Run = { id: string; issue: IssueRef; agent: Actor; state: RunState; reason: string | null /* 'lease_expired' | 'reassigned' | 'canceled_by:' */ + session: string /* ≤ 200, free text */; note: string /* ≤ 200, latest heartbeat */ + summary: string /* Markdown ≤ 20 KiB, set on finish */; links: Link[] /* ≤ 10 */ + startedAt: string; heartbeatAt: string; leaseExpiresAt: string; finishedAt: string | null } + +type RequestKind = 'question' | 'approval' | 'review' +type Request = { id: string; issue: IssueRef; kind: RequestKind; from: Actor; to: Actor | null /* null = any person */ + title: string /* 1–200 */; body: string /* Markdown ≤ 20 KiB */; options: string[] /* ≤ 6; approval/review: fixed ['approve','reject'] */ + runId: string | null; state: 'open' | 'answered' | 'withdrawn' + answer: { option: string | null; body: string; by: Actor; at: string } | null; createdAt: string } + +type InboxItem = + | { kind: 'request'; request: Request } // open, addressed to me (or to any person, when I am one) + | { kind: 'answer'; request: Request } // my request was answered; until acknowledged + | { kind: 'mention'; comment: Comment; issue: IssueRef } // until acknowledged + | { kind: 'assignment'; issue: IssueSummary } // agents only: assigned to me and actionable; carries activeRun when I already hold a live run (resume, do not start again) +type Event = { seq: number; at: string; issue: IssueRef | null; actor: Actor + type: 'issue.created' | 'issue.updated' | 'issue.deleted' | 'comment.created' | 'run.started' | 'run.finished' | 'run.canceled' | 'request.opened' | 'request.answered' | 'request.withdrawn' + data: unknown /* issue.updated: { fields: Activity['field'][] }; others: the entity id */ } +``` + +"Actionable" (pure, `domain.Actionable`): not deleted; status category +`backlog`, `unstarted` or `started` (assignment is the delegation, so an +issue assigned while still in Backlog reaches the agent); no live (not +stalled) run of another agent; no open Request raised by me on it, ignoring +requests attached to a stalled run; no `blockedBy` issue outside +`completed`/`canceled`. Ordered by priority, then sprint membership (active +sprint first), then number. + +Changes to existing shapes: + +- `Issue`/`IssueSummary`: `assignee`, `reporter` are `Actor`; gain + `delegator: Person | null`, `activeRun: Run | null`, `openRequestCount: number`. +- `POST`/`PATCH /issues`: `assigneeSub` accepts `agent:`; a disabled agent + → 400 (path `assigneeSub`). `PATCH` accepts `expectedUpdatedAt?`; a mismatch + → 409 `conflict`. An agent setting a `completed` status under `review` → 403. +- All `POST` routes except the multipart attachment upload honour + `Idempotency-Key` (≤ 128 chars): the first handler status and body are kept + 24 h per (actor, key) and replayed for the identical request (method, URI, + content type, body bytes); a different request under the same key → 409. + Authentication failures are not stored. +- `Filter` gains `assigneeKind?: ActorKind[]`, `agent?: string[]` (the + assignee is one of these agent ids), + `run?: ('active' | 'stalled' | 'none')[]`, `request?: ('open' | 'mine')[]` + (`open`: the issue has an open request; `mine`: an open request raised by + the caller). +- `TimelineItem` gains `{ kind: 'run'; run: Run }` and `{ kind: 'request'; request: Request }`. +- `Activity.field` gains `'delegator'`. `Me` gains `kind` and, for agents, `agent` and `scopes`. +- `Workspace` gains `agentCompletion: 'review' | 'direct'`; `PATCH /workspace` accepts it (Admin). +- `Comment` gains `mentions: Actor[]`. + +| Method & path | Body → Response | Authz | +| --- | --- | --- | +| `GET /agents?includeDisabled=` | → `{ items: Agent[] }` | any | +| `POST /agents` | `{ handle, name, description?, ownerSub }` → `Agent` 201; duplicate handle → 409 | Admin | +| `PATCH /agents/{id}` | `{ name?, description?, ownerSub?, disabled? }` → `Agent`; disabling cancels its non-terminal runs | Admin | +| `GET /inbox` | → `{ items: InboxItem[] }` for the caller, requests first | any | +| `POST /inbox/ack` | `{ answers?: string[] /* request ids */; mentions?: string[] /* comment ids */ }` → 204 | any | +| `GET /events?after=&limit=` | → `{ items: Event[]; next: number }`, ascending, limit default 100 max 500; `after` omitted = from now | any | +| `POST /issues/{id}/runs` | `{ session?, note? }` → `Run` 201; caller must be the assignee (403); another live run → 409; a stalled run is first closed `failed/lease_expired` and its open requests withdrawn | agent | +| `GET /issues/{id}/runs` · `GET /runs/{id}` | → `{ items: Run[] }` newest first / `Run` | any | +| `POST /runs/{id}/heartbeat` | `{ note? }` → `Run`; renews the lease; 409 when the run is terminal or stalled (the agent must stop and start a fresh run) | the run's agent | +| `POST /runs/{id}/finish` | `{ outcome: 'succeeded' \| 'failed', summary, links? }` → `Run`; 409 when terminal or stalled; `succeeded` with an open `approval` of this run → 409 (resolve or withdraw it first); `succeeded` under `review` opens a `review` Request to the delegator and withdraws the run's open questions | the run's agent | +| `POST /runs/{id}/cancel` | → `Run`; accepts a stalled run; withdraws the run's open requests | any person; the run's agent | +| `POST /issues/{id}/requests` | `{ kind: 'question' \| 'approval', title, body?, options?, to?: string \| null /* sub */, runId? }` → `Request` 201; for agents `to` omitted = the delegator (else the owner), `to: null` = any person; `runId` only by that run's agent and for a run of this issue (403), and sets the run `waiting` | any | +| `GET /requests?state=&to=&issue=` · `GET /requests/{id}` | | any | +| `POST /requests/{id}/answer` | `{ option?, body? }` → `Request`; `option` must be one of `options` when they exist; approving a `review` moves the issue to the first `completed` status in the same transaction, rejecting leaves it and is an inbox `answer` for the agent; the last open request answered returns the run to `running` | per the authorization table | +| `POST /requests/{id}/withdraw` | → `Request` | requester | +| `GET /agent-guide` | → `text/markdown`: this protocol written for an agent (exchange, inbox loop, run, request, finish), generated from the route table | any | + +Catalog entry: unchanged. Agents use the existing `tracker` space and its +scopes (`tracker:read` for `GET`, `tracker:write` otherwise, as for user keys). + +Storage (migration `013_agents.sql`): `tracker_agent`; `tracker_run` +(partial unique index on `issue_id` where not terminal); `tracker_request`; +`tracker_mention`; `tracker_event (workspace_id, seq)` with +`tracker_workspace.event_seq`; `tracker_idempotency (actor_sub, key)`; +`tracker_issue.delegator_sub/name`; `tracker_workspace.agent_completion`. +Agent actors are stored in the existing `*_sub` columns as `agent:`, so no +existing column changes type. Expired idempotency rows are deleted +opportunistically by the write that inserts a new one. + +### UI + +- **Actor rendering**: an agent shows its own glyph and a tooltip "owned by + " wherever a person badge appears. The assignee picker lists agents + in their own section with the agent's description. +- **Board and list**: a card with a live run shows the agent and its latest + note ("astra · running tests · 3 分前"); `stalled` and "waiting for a person" + are visually distinct. Built-in views "Agents at work" (`run: ['active']`) + and "Waiting for people" (`request: ['open']`). +- **Inbox** (`/inbox`, sidebar count, `G I`): the person's queue. Open + requests first, each answerable in place (option buttons, or text); then + answers and mentions. A `review` shows the run summary and links beside + Approve / Reject. +- **Issue panel**: runs and requests appear in the timeline; an open request + is pinned above the description. "Delegate to agent" is the assign action; + "Cancel run" is on the live run. +- **Agents** (`/settings/agents`, Admin): register (handle, name, owner, + description), disable; shows the exact + `apth access-keys create --space tracker --external ` command and + last seen, active runs, open requests and the median time a request waited + for a person. (Runs by outcome needs a cross-issue run listing and a + Dashboard link needs the Dashboard URL; neither exists, so neither is shown.) +- **Settings**: completion policy. +- Copy in Japanese and English (`web/src/copy/agents.ts`). diff --git a/hack/agents-smoke.py b/hack/agents-smoke.py new file mode 100644 index 0000000..2a53532 --- /dev/null +++ b/hack/agents-smoke.py @@ -0,0 +1,259 @@ +"""Real HTTP assertions for the collaboration protocol; invoked by agents-smoke.sh.""" +import concurrent.futures +import json +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +base = sys.argv[1] +with open(sys.argv[2], encoding="utf-8") as source: + tokens = json.load(source) +cursor = 0 +observed = [] +step = "initialization" + + +def raw(who, method, path, body=None, key=None): + data = None if body is None else json.dumps(body, separators=(",", ":")).encode() + headers = {"Authorization": "Bearer " + tokens[who], "Content-Type": "application/json"} + if key is not None: + headers["Idempotency-Key"] = key + request = urllib.request.Request(base + path, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(request, timeout=10) as response: + return response.status, response.read(), response.headers + except urllib.error.HTTPError as error: + return error.code, error.read(), error.headers + + +def check_events(expected): + """Drain every page after every operation, even reads/refusals; never skip a cursor.""" + global cursor + batch = [] + while True: + code, data, _ = raw("person", "GET", f"/events?after={cursor}&limit=2") + assert code == 200, data + page = json.loads(data) + for event in page["items"]: + assert event["seq"] == cursor + 1, (cursor, event) + assert event["actor"]["kind"] in ["person", "agent"] + assert event["issue"] is not None + if event["type"] == "issue.updated": + assert event["data"]["fields"] and len(event["data"]["fields"]) == len(set(event["data"]["fields"])) + else: + assert isinstance(event["data"], str) and len(event["data"]) == 26 + cursor = event["seq"] + batch.append(event) + assert page["next"] == cursor + if len(page["items"]) < 2: + break + assert [e["type"] for e in batch] == expected, (step, expected, batch) + observed.extend(batch) + return batch + + +def call(who, method, path, body=None, expected=200, events=None, key=None, drain=True): + code, data, _ = raw(who, method, path, body, key) + value = json.loads(data) if data else None + if expected is not None: + assert code == expected, f"{method} {path}: {code} {value}, expected {expected}" + if drain: + types = [] if events is None else events + if events is None and code < 300: + if method == "POST" and path == "/issues": + types = ["issue.created"] + elif method == "PATCH" and re.fullmatch(r"/issues/[^/]+", path): + types = ["issue.updated"] + elif method == "DELETE" and re.fullmatch(r"/issues/[^/]+", path): + types = ["issue.deleted"] + elif method == "POST": + for pattern, kind in [ + (r"/issues/[^/]+/comments", "comment.created"), + (r"/issues/[^/]+/runs", "run.started"), + (r"/issues/[^/]+/requests", "request.opened"), + (r"/requests/[^/]+/answer", "request.answered"), + (r"/requests/[^/]+/withdraw", "request.withdrawn"), + (r"/runs/[^/]+/cancel", "run.canceled"), + (r"/runs/[^/]+/finish", "run.finished"), + ]: + if re.fullmatch(pattern, path): + types = [kind] + emitted = check_events(types) + if len(emitted) == 1 and emitted[0]["type"] != "issue.updated" and isinstance(value, dict) and "id" in value: + assert emitted[0]["data"] == value["id"] + return value if expected is not None else (code, value) + + +def issue(who="person", **fields): + return call(who, "POST", "/issues", {"title": "Delegated smoke work", "type": "task", **fields}, 201) + + +def inbox(who): + return call(who, "GET", "/inbox")["items"] + + +def ok(): + print("ok: " + step, flush=True) + + +try: + step = "unregistered key, immutable handle identity and scope projection" + assert call("astra", "GET", "/me", expected=403)["error"] == "key_subject" + origin = call("person", "GET", "/events") + assert origin == {"items": [], "next": 0} + agents = {} + for handle in ["astra", "other"]: + agents[handle] = call("person", "POST", "/agents", {"handle": handle, "name": handle.title(), "ownerSub": "smoke-person"}, 201) + me = call("astra", "GET", "/me") + sub = "agent:" + agents["astra"]["id"] + other = "agent:" + agents["other"]["id"] + assert me["kind"] == "agent" and me["sub"] == sub and me["name"] == "Astra" + assert me["agent"]["handle"] == "astra" and me["agent"]["owner"]["sub"] == "smoke-person" + assert me["scopes"] == ["tracker:read", "tracker:write"] and not me["isAdmin"] + call("astra", "POST", "/agents", {}, 403) + call("person", "PATCH", "/agents/" + agents["astra"]["id"], {"handle": "renamed"}, 400) + ok() + + step = "idempotent create, reported self-assignment and conditional edits" + payload = {"title": "Exactly once", "type": "task"} + created = call("astra", "POST", "/issues", payload, 201, key="issue-once") + assert created["reporter"]["sub"] == sub + replay = call("astra", "POST", "/issues", payload, 201, events=[], key="issue-once") + assert replay == created + call("astra", "POST", "/issues", {**payload, "title": "Different"}, 409, key="issue-once") + updated = call("astra", "PATCH", "/issues/" + created["id"], {"assigneeSub": sub, "expectedUpdatedAt": created["updatedAt"]}) + assert updated["delegator"]["sub"] == "smoke-person" + call("astra", "PATCH", "/issues/" + created["id"], {"title": "Stale", "expectedUpdatedAt": created["updatedAt"]}, 409) + unrelated = issue(title="Unrelated") + call("astra", "PATCH", "/issues/" + unrelated["id"], {"assigneeSub": sub}, 403) + ok() + + step = "person delegates Backlog; only the assignee starts; one concurrent winner" + statuses = call("person", "GET", "/statuses")["items"] + completed = next(s["id"] for s in statuses if s["category"] == "completed") + assigned = issue(title="Clean up fixtures") + assigned = call("person", "PATCH", "/issues/" + assigned["id"], {"assigneeSub": sub}) + iid = assigned["id"] + assert any(i["kind"] == "assignment" and i["issue"]["id"] == iid for i in inbox("astra")) + call("other", "POST", "/issues/" + iid + "/runs", {}, 403) + run = call("astra", "POST", "/issues/" + iid + "/runs", {"session": "smoke-main"}, 201) + rid = run["id"] + call("astra", "POST", "/issues/" + iid + "/runs", {}, 409) + fresh = issue(assigneeSub=sub) + def start(_): + return call("astra", "POST", "/issues/" + fresh["id"] + "/runs", {}, None, drain=False)[0] + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + assert sorted(pool.map(start, range(2))) == [201, 409] + check_events(["run.started"]) + ok() + + step = "heartbeat, question waiting, person answer, four-kind inbox and mention ack" + heartbeat = call("astra", "POST", "/runs/" + rid + "/heartbeat", {"note": "Investigating with the person"}) + assert heartbeat["state"] == "running" + question = call("astra", "POST", "/issues/" + iid + "/requests", {"kind": "question", "title": "Which approach?", "options": ["small", "large"], "runId": rid}, 201) + assert question["to"]["sub"] == "smoke-person" + assert call("person", "GET", "/runs/" + rid)["state"] == "waiting" + call("person", "POST", "/requests/" + question["id"] + "/answer", {"option": "invalid"}, 400) + call("person", "POST", "/requests/" + question["id"] + "/answer", {"option": "small", "body": "Keep it small"}) + assert call("astra", "GET", "/runs/" + rid)["state"] == "running" + incoming = call("person", "POST", "/issues/" + unrelated["id"] + "/requests", {"kind": "question", "title": "Can you explain the cache?", "to": sub}, 201) + mention = call("person", "POST", "/issues/" + unrelated["id"] + "/comments", {"body": "@astra please check this too. @astra"}, 201) + assert len(mention["mentions"]) == 1 and mention["mentions"][0]["agent"]["id"] == agents["astra"]["id"] + agent_inbox = call("astra", "GET", "/inbox") + assert {i["kind"] for i in agent_inbox["items"]} == {"request", "answer", "mention", "assignment"} + assert agent_inbox["items"][0]["kind"] == "request" + agent_json = next(a for a in call("astra", "GET", "/agents")["items"] if a["handle"] == "astra") + issue_row = next(i for i in call("astra", "GET", "/issues")["items"] if i["id"] == iid) + assert issue_row["activeRun"]["id"] == rid and issue_row["assignee"]["agent"]["handle"] == "astra" + call("astra", "POST", "/inbox/ack", {"answers": [question["id"]], "mentions": [mention["id"]]}, 204) + assert not any(i["kind"] in ["answer", "mention"] for i in inbox("astra")) + call("astra", "POST", "/requests/" + incoming["id"] + "/answer", {"body": "It is a stale cache."}) + ok() + + step = "explicit null targets any person; successful finish requires approvals resolved" + approval = call("astra", "POST", "/issues/" + iid + "/requests", {"kind": "approval", "title": "Proceed?", "to": None, "runId": rid}, 201) + assert approval["to"] is None and approval["options"] == ["approve", "reject"] + call("astra", "POST", "/runs/" + rid + "/finish", {"outcome": "succeeded", "summary": "Ready"}, 409) + call("astra", "POST", "/requests/" + approval["id"] + "/answer", {"option": "approve"}, 403) + call("astra", "POST", "/requests/" + approval["id"] + "/withdraw") + call("astra", "PATCH", "/issues/" + iid, {"statusId": completed}, 403) + obsolete = call("astra", "POST", "/issues/" + iid + "/requests", {"kind": "question", "title": "No longer needed", "runId": rid}, 201) + call("astra", "POST", "/runs/" + rid + "/finish", {"outcome": "succeeded", "summary": "Ready for your review", "links": [{"kind": "pr", "url": "https://example.test/pull/1", "title": "Reviewed change"}]}, events=["run.finished", "request.withdrawn", "request.opened"]) + assert call("astra", "GET", "/requests/" + obsolete["id"])["state"] == "withdrawn" + review = next(i["request"] for i in inbox("person") if i["kind"] == "request" and i["request"]["kind"] == "review") + assert review["title"] == "Review: Clean up fixtures" and review["body"] == "Ready for your review" + call("astra", "POST", "/requests/" + review["id"] + "/answer", {"option": "approve"}, 403) + call("person", "POST", "/requests/" + review["id"] + "/answer", {"option": "approve"}, events=["issue.updated", "request.answered"]) + done = call("person", "GET", "/issues/" + iid) + assert done["statusId"] == completed and done["completedAt"] is not None + timeline = call("person", "GET", "/issues/" + iid + "/timeline")["items"] + assert {i["kind"] for i in timeline} >= {"activity", "run", "request"} + changes = [i["activity"] for i in timeline if i["kind"] == "activity" and i["activity"]["field"] == "status"] + assert changes[-1]["actor"]["sub"] == "smoke-person" + call("astra", "POST", "/runs/" + rid + "/heartbeat", {}, 409) + ok() + + step = "expired lease cannot revive, stale requests do not hide recovery assignment" + expiring = issue(assigneeSub=sub) + expired = call("astra", "POST", "/issues/" + expiring["id"] + "/runs", {}, 201) + pending = call("astra", "POST", "/issues/" + expiring["id"] + "/requests", {"kind": "question", "title": "Waiting before expiry", "runId": expired["id"]}, 201) + deadline = time.monotonic() + 12 + while call("person", "GET", "/runs/" + expired["id"])["state"] != "stalled": + assert time.monotonic() < deadline, "short lease did not expire" + time.sleep(0.1) + for action, body in [("heartbeat", {}), ("finish", {"outcome": "failed", "summary": "Too late"})]: + call("astra", "POST", "/runs/" + expired["id"] + "/" + action, body, 409) + assert any(i["kind"] == "assignment" and i["issue"]["id"] == expiring["id"] for i in inbox("astra")) + replacement = call("astra", "POST", "/issues/" + expiring["id"] + "/runs", {}, 201, events=["run.finished", "request.withdrawn", "run.started"]) + assert call("person", "GET", "/runs/" + expired["id"])["reason"] == "lease_expired" + assert call("person", "GET", "/requests/" + pending["id"])["state"] == "withdrawn" + call("person", "POST", "/runs/" + replacement["id"] + "/cancel") + ok() + + step = "reassignment and disabling atomically cancel runs and withdraw requests" + moving = issue(assigneeSub=other) + original = call("other", "POST", "/issues/" + moving["id"] + "/runs", {}, 201) + pending = call("other", "POST", "/issues/" + moving["id"] + "/requests", {"kind": "question", "title": "Reassign?", "runId": original["id"]}, 201) + call("person", "PATCH", "/issues/" + moving["id"], {"assigneeSub": sub}, events=["run.canceled", "request.withdrawn", "issue.updated"]) + old = call("person", "GET", "/runs/" + original["id"]) + assert old["state"] == "canceled" and old["reason"] == "reassigned" + disabled_issue = issue(assigneeSub=other) + disabled_run = call("other", "POST", "/issues/" + disabled_issue["id"] + "/runs", {}, 201) + call("other", "POST", "/issues/" + disabled_issue["id"] + "/requests", {"kind": "question", "title": "Attached", "runId": disabled_run["id"]}, 201) + standalone = call("other", "POST", "/issues/" + disabled_issue["id"] + "/requests", {"kind": "question", "title": "Standalone"}, 201) + call("person", "PATCH", "/agents/" + agents["other"]["id"], {"disabled": True}, events=["run.canceled", "request.withdrawn", "request.withdrawn"]) + assert call("other", "GET", "/me", expected=403)["error"] == "key_subject" + assert call("person", "GET", "/runs/" + disabled_run["id"])["state"] == "canceled" + assert call("person", "GET", "/requests/" + standalone["id"])["state"] == "withdrawn" + call("person", "PATCH", "/issues/" + disabled_issue["id"], {"assigneeSub": other}, 400) + assert len(call("person", "GET", "/agents")["items"]) == 1 + assert len(call("person", "GET", "/agents?includeDisabled=true")["items"]) == 2 + ok() + + step = "direct policy, unchanged user-key authority, deletion and agent guide" + direct = issue(assigneeSub=sub) + call("person", "PATCH", "/workspace", {"agentCompletion": "direct"}) + call("astra", "PATCH", "/issues/" + direct["id"], {"statusId": completed}) + user = call("smoke-person", "GET", "/me") + assert user["sub"] == "smoke-person" and user["name"] == "Smoke Person" and not user["isAdmin"] + assert issue("smoke-person")["reporter"]["kind"] == "person" + call("smoke-person", "PATCH", "/workspace", {"agentCompletion": "review"}, 403) + call("person", "DELETE", "/issues/" + direct["id"], expected=204) + code, guide, headers = raw("astra", "GET", "/agent-guide") + assert code == 200 and headers["Content-Type"].startswith("text/markdown") + assert b"POST /runs/{id}/heartbeat" in guide and b"Idempotency-Key" in guide + check_events([]) + latest = call("person", "GET", "/events") + assert latest == {"items": [], "next": cursor} + event_page = call("person", "GET", "/events?after=0&limit=5") + assert [e["seq"] for e in observed] == list(range(1, cursor + 1)) + ok() + print(f"ok: {cursor} events delivered exactly once in order without gaps across the entire script", flush=True) + for label, value in [("agent", agent_json), ("issue-list-row", issue_row), ("event-page", event_page), ("agent-inbox", agent_inbox)]: + print("JSON " + label + ": " + json.dumps(value, separators=(",", ":")), flush=True) +except Exception as error: + print("FAIL: " + step + ": " + str(error), file=sys.stderr, flush=True) + raise diff --git a/hack/agents-smoke.sh b/hack/agents-smoke.sh new file mode 100755 index 0000000..82d2595 --- /dev/null +++ b/hack/agents-smoke.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Real-server collaboration contract, with disposable signed assertions and schema. +# Run through serialize-vm-tests; also invoked by hack/smoke.sh. +set -euo pipefail +: "${DATABASE_URL:?Set DATABASE_URL to local disposable Postgres}" +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +work=$(mktemp -d) +schema="tracker_agents_smoke_$(date +%s)_$$" +server_pid="" +fixture_pid="" +cleanup() { + if [[ -n "$server_pid" ]]; then kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; fi + if [[ -n "$fixture_pid" ]]; then kill "$fixture_pid" 2>/dev/null || true; wait "$fixture_pid" 2>/dev/null || true; fi + psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "DROP SCHEMA IF EXISTS $schema CASCADE" >/dev/null + rm -rf -- "$work" +} +trap cleanup EXIT +trap 'if [[ -f "$work/server.log" ]]; then cat "$work/server.log" >&2; fi' ERR +psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "CREATE SCHEMA $schema" >/dev/null +scoped_dsn=$(python3 - "$DATABASE_URL" "$schema" <<'PY' +import sys, urllib.parse +url = urllib.parse.urlsplit(sys.argv[1]) +query = urllib.parse.parse_qs(url.query) +query['search_path'] = [sys.argv[2]] +print(urllib.parse.urlunsplit(url._replace(query=urllib.parse.urlencode(query, doseq=True)))) +PY +) +port=$(python3 - <<'PY' +import socket +with socket.socket() as s: + s.bind(('127.0.0.1', 0)) + print(s.getsockname()[1]) +PY +) +cd "$root" +go build -o "$work/tracker-server" ./cmd/server +go build -o "$work/fixture" ./cmd/server/internal/assertiontestutil +"$work/fixture" --output "$work/tokens.json" >"$work/fixture.log" 2>&1 & +fixture_pid=$! +for ((attempt=0; attempt<50; attempt++)); do + if [[ -s "$work/tokens.json" ]]; then break; fi + if ! kill -0 "$fixture_pid" 2>/dev/null; then cat "$work/fixture.log"; exit 1; fi + sleep 0.1 +done +[[ -s "$work/tokens.json" ]] +origin=$(jq -er .origin "$work/tokens.json") +issuer=$(jq -er .issuer "$work/tokens.json") +PLATFORM_OIDC_ISSUER= PLATFORM_OIDC_ISSUER_CA_PEM= PLATFORM_ACCESS_ISSUER="$issuer" \ + TRACKER_ACCESS_AUDIENCE=tracker PLATFORM_API_URL="$origin" PLATFORM_PROJECT_ID=pj-agents-smoke \ + TRACKER_PUBLIC_URL= TRACKER_DIRECTORY_URL= TRACKER_DIRECTORY_PUBLIC_URL= \ + TRACKER_DATABASE_URL="$scoped_dsn" TRACKER_DEV_SEED=0 TRACKER_RUN_LEASE=5s \ + "$work/tracker-server" --listen "127.0.0.1:$port" --static-dir "$work" >"$work/server.log" 2>&1 & +server_pid=$! +ready=0 +for ((attempt=0; attempt<60; attempt++)); do + if curl -fsS "http://127.0.0.1:$port/readyz" >/dev/null 2>&1; then ready=1; break; fi + if ! kill -0 "$server_pid" 2>/dev/null; then cat "$work/server.log"; exit 1; fi + sleep 0.25 +done +[[ "$ready" == 1 ]] +python3 hack/agents-smoke.py "http://127.0.0.1:$port/api/tracker/v1" "$work/tokens.json" diff --git a/hack/smoke.sh b/hack/smoke.sh index 028182b..ad6762f 100755 --- a/hack/smoke.sh +++ b/hack/smoke.sh @@ -80,12 +80,12 @@ PY ) auth="Authorization: Bearer $token" request() { curl -fsS -H "$auth" -H 'Content-Type: application/json' "$@"; } -request "$base/workspace" | jq -e '.key == "APT" and .issueCount == 40' >/dev/null +request "$base/workspace" | jq -e '.key == "APT" and .issueCount == 42' >/dev/null project=$(request -X POST "$base/projects" --data '{"name":"Smoke project","color":"blue"}') project_id=$(jq -er '.id' <<<"$project") issue=$(request -X POST "$base/issues" --data "{\"title\":\"Smoke bug\",\"type\":\"bug\",\"projectId\":\"$project_id\",\"report\":{\"environment\":\"local\",\"surface\":\"apth\",\"steps\":\"Run smoke\",\"expected\":\"Success\",\"actual\":\"Under investigation\"}}") id=$(jq -er '.id' <<<"$issue") -jq -e '.identifier == "APT-41" and .report.environment == "local" and .reporter.sub == "smoke-reporter"' <<<"$issue" >/dev/null +jq -e '.identifier == "APT-43" and .report.environment == "local" and .reporter.sub == "smoke-reporter"' <<<"$issue" >/dev/null jq -e --arg project "$project_id" '.projectId == $project' <<<"$issue" >/dev/null request --get "$base/issues" --data-urlencode "filter={\"project\":[\"$project_id\"]}" | jq -e --arg id "$id" --arg project "$project_id" '.items | length == 1 and .[0].id == $id and .[0].projectId == $project' >/dev/null request --get "$base/issues" --data-urlencode 'filter={"reporter":["me"]}' | jq -e --arg id "$id" '.items | length == 1 and .[0].id == $id and .[0].reporter.sub == "smoke-reporter"' >/dev/null @@ -134,3 +134,4 @@ request "$base/sprints/$sprint_id/burndown?unit=points" | jq -e '. as $chart | [ request -X POST "$base/sprints/$sprint_id/close" --data '{"moveIncompleteTo":null}' | jq -e '.state == "closed" and .current.donePoints == 3' >/dev/null request "$base/velocity?unit=points&limit=1" | jq -e --arg id "$sprint_id" '.items | length == 1 and .[0].sprint.id == $id and .[0].committed == 8 and .[0].completed == 3' >/dev/null printf 'Tracker smoke passed: project → issue → reporter filter → invalid reporter → epic → story → parent patch → ancestry → progress → referenced delete conflict → comment → attachment → status → timeline → project filter → no project → project delete → sprint → estimates → start → burndown drop → close → velocity\n' +bash "$root/hack/agents-smoke.sh" diff --git a/web/package.json b/web/package.json index e4374c5..d455053 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "@appthrust/tracker", - "version": "0.1.12", + "version": "0.1.13", "private": true, "type": "module", "scripts": { diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts index b254886..340950a 100644 --- a/web/src/api/queries.ts +++ b/web/src/api/queries.ts @@ -2,22 +2,28 @@ // `queryOptions()` / `infiniteQueryOptions()` factory so route loaders // (`ensureQueryData`) and components share one key and fetcher. Freshness: // every query refetches every 15 s while the tab is visible and on window -// focus (no push in v1). Issue edits (status, priority, assignee, labels, +// focus (no push in v1) — the inbox, live runs on cards and the run block +// included. Issue edits (status, priority, assignee, labels, // project, parent, …) are optimistic: lists and the open issue change at once // and roll back on failure. Sprints, burndown and velocity share one key // prefix, refreshed by every issue write (estimates, statuses and membership -// move the ledger). +// move the ledger). Agent work (answers, canceled runs) refreshes issues, +// timelines, the inbox and the agents list together. import { infiniteQueryOptions, QueryClient, queryOptions, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query' import { compactFilter, levelOf } from '../model/issues' import { sprintRef } from '../model/sprints' import { trackerApi, TrackerApiError, + type Actor, + type AnswerInput, + type CreateAgentInput, type CreateIssueInput, type CreateProjectInput, type CreateSprintInput, type CreateViewInput, type Filter, + type InboxAck, type Issue, type IssuePage, type IssueSummary, @@ -25,11 +31,13 @@ import { type LabelColor, type Person, type Project, + type RequestListParams, type Sort, type Sprint, type SprintRef, type StatusCategory, type Unit, + type UpdateAgentInput, type UpdateIssueInput, type UpdateProjectInput, type UpdateSprintInput, @@ -62,6 +70,9 @@ export const TRACKER_KEY = ['tracker'] as const const ISSUES_KEY = [...TRACKER_KEY, 'issues'] as const const ISSUE_KEY = [...TRACKER_KEY, 'issue'] as const const SPRINTS_KEY = [...TRACKER_KEY, 'sprints'] as const +const INBOX_KEY = [...TRACKER_KEY, 'inbox'] as const +const AGENTS_KEY = [...TRACKER_KEY, 'agents'] as const +const REQUESTS_KEY = [...TRACKER_KEY, 'requests'] as const export const meQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'me'], queryFn: () => trackerApi.me(), staleTime: 60_000 }) export const workspaceQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'workspace'], queryFn: () => trackerApi.workspace.get() }) @@ -143,6 +154,14 @@ export const timelineQuery = (issueId: string) => queryOptions({ queryKey: [...T export const peopleQuery = (q: string) => queryOptions({ queryKey: [...TRACKER_KEY, 'people', q.trim()], queryFn: () => trackerApi.people(q.trim() || undefined), staleTime: 60_000, refetchInterval: false }) +/** Every agent, disabled ones included: history keeps showing their names; pickers offer active ones only. */ +export const agentsQuery = queryOptions({ queryKey: [...AGENTS_KEY, 'list'], queryFn: () => trackerApi.agents.list({ includeDisabled: true }) }) +/** The caller's queue (open requests first); the sidebar count reads the same query. */ +export const inboxQuery = queryOptions({ queryKey: INBOX_KEY, queryFn: () => trackerApi.inbox.list() }) +export const requestsQuery = (params: RequestListParams) => queryOptions({ queryKey: [...REQUESTS_KEY, params], queryFn: () => trackerApi.requests.list(params) }) +/** One run (a review shows its summary and links). */ +export const runQuery = (id: string) => queryOptions({ queryKey: [...TRACKER_KEY, 'run', id], queryFn: () => trackerApi.runs.get(id) }) + // --- optimistic issue edits -------------------------------------------------- /** @@ -151,7 +170,7 @@ export const peopleQuery = (q: string) => * derived `epic`/`story` follow at once (the server recomputes them), and * `sprint` the ref of the sprint `sprintId` names. */ -export function applyIssuePatch(issue: T, input: UpdateIssueInput, assignee?: Person | null, parent?: IssueSummary | null, sprint?: SprintRef | null): T { +export function applyIssuePatch(issue: T, input: UpdateIssueInput, assignee?: Actor | null, parent?: IssueSummary | null, sprint?: SprintRef | null, delegator?: Person | null): T { const next: T = { ...issue } if (input.title !== undefined) next.title = input.title if (input.type !== undefined) next.type = input.type @@ -163,7 +182,12 @@ export function applyIssuePatch(issue: T, input: UpdateI if (input.projectId !== undefined) next.projectId = input.projectId if (input.estimate !== undefined) next.estimate = input.estimate if (input.sprintId !== undefined) next.sprint = input.sprintId === null ? null : (sprint ?? issue.sprint) - if (input.assigneeSub !== undefined) next.assignee = input.assigneeSub === null ? null : (assignee ?? issue.assignee) + if (input.assigneeSub !== undefined && input.assigneeSub !== (issue.assignee?.sub ?? null)) { + next.assignee = input.assigneeSub === null ? null : (assignee ?? issue.assignee) + // A new assignee ends the agent's run (the server cancels it as `reassigned`); an agent assignee gets its delegator. + next.activeRun = null + next.delegator = next.assignee?.kind === 'agent' ? (delegator ?? issue.delegator) : null + } if (input.parentId === null) Object.assign(next, { parent: null, epic: null, story: null }) else if (input.parentId !== undefined && parent?.id === input.parentId) { const ref = { id: parent.id, identifier: parent.identifier, title: parent.title, statusId: parent.statusId } @@ -185,18 +209,19 @@ function patchCaches(client: QueryClient, id: string, update: ({ queryKey: ISSUE_KEY }, (data) => (data && data.id === id ? update(data) : data)) } -export type IssueEdit = { id: string; input: UpdateIssueInput; assignee?: Person | null; parent?: IssueSummary | null } +/** `assignee`: the picked actor for display; `delegator`: who the agent will answer to (the signed-in person) when the pick is an agent. */ +export type IssueEdit = { id: string; input: UpdateIssueInput; assignee?: Actor | null; parent?: IssueSummary | null; delegator?: Person | null } export function useUpdateIssue() { const client = useQueryClient() return useMutation({ mutationFn: ({ id, input }: IssueEdit) => trackerApi.issues.update(id, input), - onMutate: async ({ id, input, assignee, parent }) => { + onMutate: async ({ id, input, assignee, parent, delegator }) => { await Promise.all([client.cancelQueries({ queryKey: ISSUES_KEY }), client.cancelQueries({ queryKey: ISSUE_KEY })]) const lists = client.getQueriesData({ queryKey: ISSUES_KEY }) const details = client.getQueriesData({ queryKey: ISSUE_KEY }) const picked = input.sprintId ? client.getQueryData(sprintsQuery.queryKey)?.find((sprint) => sprint.id === input.sprintId) : undefined - patchCaches(client, id, (issue) => applyIssuePatch(issue, input, assignee, parent, picked ? sprintRef(picked) : undefined)) + patchCaches(client, id, (issue) => applyIssuePatch(issue, input, assignee, parent, picked ? sprintRef(picked) : undefined, delegator)) return { lists, details } }, onError: (_error, _edit, snapshot) => { @@ -206,7 +231,7 @@ export function useUpdateIssue() { const { description: _description, children: _children, blocks: _blocks, blockedBy: _blockedBy, ...summary } = issue patchCaches(client, issue.id, (cached) => ('description' in cached ? ({ ...cached, ...issue } as typeof cached) : ({ ...cached, ...summary } as typeof cached))) }, - onSettled: (_issue, _error, { id }) => { + onSettled: (_issue, _error, { id, input }) => { void client.invalidateQueries({ queryKey: ISSUES_KEY }) void client.invalidateQueries({ queryKey: ISSUE_KEY }) void client.invalidateQueries({ queryKey: [...TRACKER_KEY, 'timeline', id] }) @@ -214,6 +239,11 @@ export function useUpdateIssue() { void client.invalidateQueries({ queryKey: projectsQuery.queryKey }) // Estimates, statuses and membership move sprint tallies and charts. void client.invalidateQueries({ queryKey: SPRINTS_KEY }) + // Reassignment cancels runs and withdraws requests; an agent's counts and inboxes move. + if (input.assigneeSub !== undefined) { + void client.invalidateQueries({ queryKey: INBOX_KEY }) + void client.invalidateQueries({ queryKey: AGENTS_KEY }) + } }, }) } @@ -223,7 +253,7 @@ export function useUpdateIssues() { const update = useUpdateIssue() return { ...update, - run: (ids: string[], input: UpdateIssueInput, assignee?: Person | null, parent?: IssueSummary | null) => Promise.allSettled(ids.map((id) => update.mutateAsync({ id, input, assignee, parent }))), + run: (ids: string[], input: UpdateIssueInput, assignee?: Actor | null, parent?: IssueSummary | null, delegator?: Person | null) => Promise.allSettled(ids.map((id) => update.mutateAsync({ id, input, assignee, parent, delegator }))), } } @@ -371,3 +401,65 @@ export function useSprintMutations() { remove: useMutation({ mutationFn: (id: string) => trackerApi.sprints.remove(id), onSuccess }), } } + +// --- agents and their work ------------------------------------------------------- + +/** Answers, withdrawals and canceled runs move issues (status, run, request counts), timelines, the inbox and agents' counts. */ +const invalidateAgentWork = (client: QueryClient) => + Promise.all([ + client.invalidateQueries({ queryKey: ISSUES_KEY }), + client.invalidateQueries({ queryKey: ISSUE_KEY }), + client.invalidateQueries({ queryKey: [...TRACKER_KEY, 'timeline'] }), + client.invalidateQueries({ queryKey: INBOX_KEY }), + client.invalidateQueries({ queryKey: AGENTS_KEY }), + client.invalidateQueries({ queryKey: REQUESTS_KEY }), + client.invalidateQueries({ queryKey: [...TRACKER_KEY, 'run'] }), + client.invalidateQueries({ queryKey: SPRINTS_KEY }), + ]) + +export type AnswerEdit = { id: string; input: AnswerInput; /** One per click: a repeated send replays the first answer. */ idempotencyKey: string } + +export function useAnswerRequest() { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ id, input, idempotencyKey }: AnswerEdit) => trackerApi.requests.answer(id, input, idempotencyKey), + onSettled: () => void invalidateAgentWork(client), + }) +} + +export function useWithdrawRequest() { + const client = useQueryClient() + return useMutation({ mutationFn: (id: string) => trackerApi.requests.withdraw(id), onSettled: () => void invalidateAgentWork(client) }) +} + +export function useCancelRun() { + const client = useQueryClient() + return useMutation({ mutationFn: (id: string) => trackerApi.runs.cancel(id), onSettled: () => void invalidateAgentWork(client) }) +} + +/** Acknowledging drops the items from the inbox at once; a failure brings them back. */ +export function useAckInbox() { + const client = useQueryClient() + return useMutation({ + mutationFn: (input: InboxAck) => trackerApi.inbox.ack(input), + onMutate: async (input) => { + await client.cancelQueries({ queryKey: INBOX_KEY }) + const before = client.getQueryData(inboxQuery.queryKey) + client.setQueryData(inboxQuery.queryKey, (items) => + (items ?? []).filter((item) => !(item.kind === 'answer' && input.answers?.includes(item.request.id)) && !(item.kind === 'mention' && input.mentions?.includes(item.comment.id))) + ) + return { before } + }, + onError: (_error, _input, snapshot) => client.setQueryData(inboxQuery.queryKey, snapshot?.before), + onSettled: () => void client.invalidateQueries({ queryKey: INBOX_KEY }), + }) +} + +export function useAgentMutations() { + const client = useQueryClient() + return { + create: useMutation({ mutationFn: (input: CreateAgentInput) => trackerApi.agents.create(input), onSuccess: () => void client.invalidateQueries({ queryKey: AGENTS_KEY }) }), + // Disabling cancels the agent's runs: every board and inbox moves. + update: useMutation({ mutationFn: ({ id, input }: { id: string; input: UpdateAgentInput }) => trackerApi.agents.update(id, input), onSuccess: () => void invalidateAgentWork(client) }), + } +} diff --git a/web/src/api/tracker.test.ts b/web/src/api/tracker.test.ts index eebd7a8..f3eda8c 100644 --- a/web/src/api/tracker.test.ts +++ b/web/src/api/tracker.test.ts @@ -101,10 +101,15 @@ describe('tracker API client', () => { test('optimistic patch: changed fields only; clearing the assignee or picking one shows at once', async () => { const { api } = mockApi() const issue = await api.issues.get('APT-2') - const person = { sub: 'dev-jordan', name: 'Jordan Lee' } + const person = { sub: 'dev-jordan', name: 'Jordan Lee', kind: 'person' as const } const next = applyIssuePatch(issue, { statusId: 'S', priority: 'low', labelIds: [], assigneeSub: person.sub }, person) expect(next).toMatchObject({ statusId: 'S', priority: 'low', labelIds: [], assignee: person, title: issue.title, description: issue.description }) expect(applyIssuePatch(issue, { assigneeSub: null }).assignee).toBeNull() + // Delegating to an agent shows the delegator at once; any reassignment drops the run the server cancels. + const agent = { sub: 'agent:A1', name: 'Astra', kind: 'agent' as const, agent: { id: 'A1', handle: 'astra', owner: { sub: 'dev-sam', name: 'Sam Rivera' }, disabled: false } } + const delegated = applyIssuePatch(issue, { assigneeSub: agent.sub }, agent, undefined, undefined, { sub: 'dev-alex', name: 'Alex Chen' }) + expect(delegated).toMatchObject({ assignee: agent, delegator: { sub: 'dev-alex' }, activeRun: null }) + expect(applyIssuePatch(delegated, { assigneeSub: 'dev-sam' }, { sub: 'dev-sam', name: 'Sam Rivera', kind: 'person' })).toMatchObject({ delegator: null, activeRun: null }) expect(applyIssuePatch(issue, { projectId: 'P' }).projectId).toBe('P') expect(applyIssuePatch({ ...issue, projectId: 'P' }, { projectId: null }).projectId).toBeNull() expect(applyIssuePatch({ ...issue, projectId: 'P' }, { title: 'x' }).projectId).toBe('P') diff --git a/web/src/api/tracker.ts b/web/src/api/tracker.ts index dc93c21..d45d720 100644 --- a/web/src/api/tracker.ts +++ b/web/src/api/tracker.ts @@ -6,11 +6,109 @@ export type Person = { sub: string; name: string; avatarUrl?: string; email?: string; profileUrl?: string } export type Role = 'Admin' | 'Editor' | 'Viewer' -export type Me = Person & { role: Role; isAdmin: boolean } +/** API.md "Agents": an Actor is a person or a registered agent. For agents `sub` is `agent:` and `name` the agent's display name. */ +export type ActorKind = 'person' | 'agent' +export type AgentInfo = { id: string; handle: string; owner: Person; disabled: boolean } +export type Actor = Person & { kind: ActorKind; agent?: AgentInfo } +/** Agents (an `external` Access Key) also carry `agent` and their key's `scopes`. */ +export type Me = Actor & { role: Role; isAdmin: boolean; scopes?: string[] } + +/** `review`: only a person's approval completes an agent's work; `direct`: an agent may set a completed status itself. */ +export type AgentCompletion = 'review' | 'direct' /** `sprintLengthWeeks` is the default length of a new sprint; `timezone` (IANA) sets the day boundaries of sprint dates and charts. */ -export type Workspace = { id: string; key: string; name: string; issueCount: number; sprintLengthWeeks: SprintLength; timezone: string; createdAt: string; updatedAt: string } -export type UpdateWorkspaceInput = { key?: string; name?: string; sprintLengthWeeks?: SprintLength; timezone?: string } +export type Workspace = { id: string; key: string; name: string; issueCount: number; sprintLengthWeeks: SprintLength; timezone: string; agentCompletion: AgentCompletion; createdAt: string; updatedAt: string } +export type UpdateWorkspaceInput = { key?: string; name?: string; sprintLengthWeeks?: SprintLength; timezone?: string; agentCompletion?: AgentCompletion } + +/** A registered agent. `handle` is immutable and is also the `external` subject of its Access Keys. */ +export type Agent = { + id: string + handle: string + name: string + /** ≤ 4096 bytes: what to delegate to it. */ + description: string + owner: Person + disabled: boolean + /** Live (running or waiting, not stalled) runs. */ + activeRuns: number + /** Open requests the agent raised. */ + openRequests: number + lastSeenAt: string | null + createdAt: string + updatedAt: string +} +export type CreateAgentInput = { handle: string; name: string; description?: string; ownerSub: string } +/** Disabling cancels the agent's non-terminal runs. */ +export type UpdateAgentInput = Partial<{ name: string; description: string; ownerSub: string; disabled: boolean }> + +/** `stalled` is derived at read time: a non-terminal run whose lease has passed. */ +export type RunState = 'running' | 'waiting' | 'stalled' | 'succeeded' | 'failed' | 'canceled' +export type LinkKind = 'pr' | 'commit' | 'url' +export type Link = { kind: LinkKind; url: string; title: string } +export type Run = { + id: string + issue: IssueRef + agent: Actor + state: RunState + /** `lease_expired`, `reassigned` or `canceled_by:`. */ + reason: string | null + /** Free text naming the session or lane, ≤ 200. */ + session: string + /** Latest heartbeat note, ≤ 200. */ + note: string + /** Markdown, set on finish. */ + summary: string + links: Link[] + startedAt: string + heartbeatAt: string + leaseExpiresAt: string + finishedAt: string | null +} +export type RequestKind = 'question' | 'approval' | 'review' +export type RequestState = 'open' | 'answered' | 'withdrawn' +export type RequestAnswer = { option: string | null; body: string; by: Actor; at: string } +/** API.md `Request` (named apart from the Fetch API's `Request`): a directed handoff; `to` null = any person. */ +export type TrackerRequest = { + id: string + issue: IssueRef + kind: RequestKind + from: Actor + to: Actor | null + title: string + /** Markdown. */ + body: string + /** ≤ 6; approval and review: `['approve', 'reject']`. */ + options: string[] + runId: string | null + state: RequestState + answer: RequestAnswer | null + createdAt: string +} +export type CreateRequestInput = { kind: 'question' | 'approval'; title: string; body?: string; options?: string[]; to?: string | null; runId?: string } +export type AnswerInput = { option?: string; body?: string } +export type InboxItem = + | { kind: 'request'; request: TrackerRequest } + | { kind: 'answer'; request: TrackerRequest } + | { kind: 'mention'; comment: Comment; issue: IssueRef } + | { kind: 'assignment'; issue: IssueSummary } +export type InboxAck = { answers?: string[]; mentions?: string[] } +export type EventType = + | 'issue.created' + | 'issue.updated' + | 'issue.deleted' + | 'comment.created' + | 'run.started' + | 'run.finished' + | 'run.canceled' + | 'request.opened' + | 'request.answered' + | 'request.withdrawn' +/** `data`: `{ fields }` for `issue.updated`, else the entity id. */ +export type TrackerEvent = { seq: number; at: string; issue: IssueRef | null; actor: Actor; type: EventType; data: unknown } +export type EventPage = { items: TrackerEvent[]; next: number } +export type StartRunInput = { session?: string; note?: string } +export type FinishRunInput = { outcome: 'succeeded' | 'failed'; summary: string; links?: Link[] } +export type RequestListParams = { state?: RequestState; to?: string; issue?: string } export type StatusCategory = 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled' export type Status = { id: string; name: string; category: StatusCategory; position: number; color: string } @@ -95,8 +193,13 @@ export type Issue = { type: IssueType priority: Priority statusId: string - assignee: Person | null - reporter: Person + assignee: Actor | null + reporter: Actor + /** The person the agent assignee answers to on this issue; null unless the assignee is an agent. */ + delegator: Person | null + /** The non-terminal run (its state may be the derived `stalled`), else null. */ + activeRun: Run | null + openRequestCount: number labelIds: string[] /** The tracker project, or null for "no project". */ projectId: string | null @@ -126,8 +229,9 @@ export type Issue = { } export type IssueSummary = Omit -export type Comment = { id: string; issueId: string; author: Person; body: string; createdAt: string; editedAt: string | null } -export type Attachment = { id: string; issueId: string; filename: string; mediaType: string; size: number; url: string; uploader: Person; createdAt: string } +/** `mentions`: the agents its `@handle`s name (people are not mentionable). */ +export type Comment = { id: string; issueId: string; author: Actor; body: string; createdAt: string; editedAt: string | null; mentions: Actor[] } +export type Attachment = { id: string; issueId: string; filename: string; mediaType: string; size: number; url: string; uploader: Actor; createdAt: string } export type ActivityField = | 'created' | 'title' @@ -146,8 +250,13 @@ export type ActivityField = | 'project' | 'estimate' | 'sprint' -export type Activity = { id: string; issueId: string; actor: Person; field: ActivityField; from: unknown; to: unknown; createdAt: string } -export type TimelineItem = { kind: 'activity'; activity: Activity } | { kind: 'comment'; comment: Comment } + | 'delegator' +export type Activity = { id: string; issueId: string; actor: Actor; field: ActivityField; from: unknown; to: unknown; createdAt: string } +export type TimelineItem = + | { kind: 'activity'; activity: Activity } + | { kind: 'comment'; comment: Comment } + | { kind: 'run'; run: Run } + | { kind: 'request'; request: TrackerRequest } export type Filter = { status?: string[] @@ -173,13 +282,21 @@ export type Filter = { story?: string[] /** Sprint ids, `active` (the active sprint) or `none` (the backlog). */ sprint?: string[] + /** The assignee's kind. */ + assigneeKind?: ActorKind[] + /** Agent ids: the assignee is one of these agents. */ + agent?: string[] + /** `active`: a live run; `stalled`: a run whose lease passed; `none`: no non-terminal run. */ + run?: ('active' | 'stalled' | 'none')[] + /** `open`: the issue has an open request; `mine`: it has an open request the caller raised. */ + request?: ('open' | 'mine')[] } /** updated/created: desc; priority: urgent→none then updated desc; number: asc; estimate: XL→XS, none last, then updated desc. */ export type Sort = 'updated' | 'created' | 'priority' | 'number' | 'estimate' export type ViewLayout = 'list' | 'board' /** Client-side sectioning of a list or board by the issues' derived `epic` or `story`, or by sprint (backlog last). */ export type GroupBy = 'none' | 'epic' | 'story' | 'sprint' -export type View = { id: string; name: string; owner: Person; shared: boolean; layout: ViewLayout; groupBy: GroupBy; filter: Filter; sort: Sort; position: number; createdAt: string; updatedAt: string } +export type View = { id: string; name: string; owner: Actor; shared: boolean; layout: ViewLayout; groupBy: GroupBy; filter: Filter; sort: Sort; position: number; createdAt: string; updatedAt: string } export type IssuePage = { items: IssueSummary[]; nextCursor: string | null } export type PeopleResult = { items: Person[]; source: 'directory' | 'unavailable' } @@ -218,6 +335,8 @@ export type UpdateIssueInput = Partial<{ estimate: Size | null /** null moves the issue to the backlog. */ sprintId: string | null + /** The `updatedAt` the edit was made against; another write in between → 409 `conflict`. */ + expectedUpdatedAt: string }> export type CreateViewInput = { name: string; layout?: ViewLayout; groupBy?: GroupBy; filter?: Filter; sort?: Sort; shared?: boolean } export type UpdateViewInput = Partial @@ -330,6 +449,53 @@ export interface TrackerApi { } velocity(scope: ChartScope & { limit?: number }): Promise people(q?: string): Promise + agents: { + /** Active agents; disabled ones too with `includeDisabled`. */ + list(options?: { includeDisabled?: boolean }): Promise + /** Admin; a duplicate handle → 409. */ + create(input: CreateAgentInput): Promise + /** Admin; disabling cancels the agent's non-terminal runs. */ + update(id: string, input: UpdateAgentInput): Promise + } + inbox: { + /** The caller's queue, open requests first. */ + list(): Promise + /** Acknowledges answers (request ids) and mentions (comment ids). */ + ack(input: InboxAck): Promise + } + /** Ascending from `after` (omitted = from now). */ + events(params?: { after?: number; limit?: number }): Promise + runs: { + /** Newest first. */ + list(issueId: string): Promise + get(id: string): Promise + /** Agents only, as the issue's assignee. */ + start(issueId: string, input?: StartRunInput): Promise + heartbeat(id: string, note?: string): Promise + finish(id: string, input: FinishRunInput): Promise + /** Any person, or the run's own agent; accepts a stalled run. */ + cancel(id: string): Promise + } + requests: { + create(issueId: string, input: CreateRequestInput): Promise + list(params?: RequestListParams): Promise + get(id: string): Promise + /** `idempotencyKey` makes a repeated click replay the first answer. */ + answer(id: string, input: AnswerInput, idempotencyKey?: string): Promise + withdraw(id: string): Promise + } + /** The agent protocol as Markdown. */ + agentGuide(): Promise +} + +/** `?state=&to=&issue=` with only the set parameters. */ +export function requestSearch({ state, to, issue }: RequestListParams = {}): string { + const search = new URLSearchParams() + if (state) search.set('state', state) + if (to) search.set('to', to) + if (issue) search.set('issue', issue) + const text = search.toString() + return text ? `?${text}` : '' } /** `?filter=&sort=&cursor=&limit=` with only the set parameters; an empty filter is omitted. */ @@ -352,11 +518,12 @@ export function chartSearch({ unit, project, limit }: ChartScope & { limit?: num } export function createTrackerApi(fetcher: Fetcher = (input, init) => fetch(input, init), reauth = browserReauth): TrackerApi { - async function send(method: string, path: string, body?: unknown): Promise { + async function send(method: string, path: string, body?: unknown, options: { idempotencyKey?: string; text?: boolean } = {}): Promise { const read = method === 'GET' const multipart = body instanceof FormData - const headers: Record = { Accept: 'application/json' } + const headers: Record = { Accept: options.text ? 'text/markdown' : 'application/json' } if (body !== undefined && !multipart) headers['Content-Type'] = 'application/json' + if (options.idempotencyKey) headers['Idempotency-Key'] = options.idempotencyKey let response: Response try { response = await fetcher(`${BASE}${path}`, { @@ -381,7 +548,7 @@ export function createTrackerApi(fetcher: Fetcher = (input, init) => fetch(input throw new TrackerApiError(response.status, parsed) } if (response.status === 204) return undefined as T - return (await response.json()) as T + return (options.text ? await response.text() : await response.json()) as T } const list = async (path: string) => (await send<{ items: T[] }>('GET', path)).items const id = encodeURIComponent @@ -451,6 +618,38 @@ export function createTrackerApi(fetcher: Fetcher = (input, init) => fetch(input }, velocity: (scope) => send('GET', `/velocity${chartSearch(scope)}`), people: (q) => send('GET', `/people${q ? `?q=${encodeURIComponent(q)}` : ''}`), + agents: { + list: (options) => list(`/agents${options?.includeDisabled ? '?includeDisabled=true' : ''}`), + create: (input) => send('POST', '/agents', input), + update: (agentId, input) => send('PATCH', `/agents/${id(agentId)}`, input), + }, + inbox: { + list: () => list('/inbox'), + ack: (input) => send('POST', '/inbox/ack', input), + }, + events: (params = {}) => { + const search = new URLSearchParams() + if (params.after !== undefined) search.set('after', String(params.after)) + if (params.limit !== undefined) search.set('limit', String(params.limit)) + const text = search.toString() + return send('GET', `/events${text ? `?${text}` : ''}`) + }, + runs: { + list: (issueId) => list(`/issues/${id(issueId)}/runs`), + get: (runId) => send('GET', `/runs/${id(runId)}`), + start: (issueId, input = {}) => send('POST', `/issues/${id(issueId)}/runs`, input), + heartbeat: (runId, note) => send('POST', `/runs/${id(runId)}/heartbeat`, note === undefined ? {} : { note }), + finish: (runId, input) => send('POST', `/runs/${id(runId)}/finish`, input), + cancel: (runId) => send('POST', `/runs/${id(runId)}/cancel`), + }, + requests: { + create: (issueId, input) => send('POST', `/issues/${id(issueId)}/requests`, input), + list: (params) => list(`/requests${requestSearch(params)}`), + get: (requestId) => send('GET', `/requests/${id(requestId)}`), + answer: (requestId, input, idempotencyKey) => send('POST', `/requests/${id(requestId)}/answer`, input, { idempotencyKey }), + withdraw: (requestId) => send('POST', `/requests/${id(requestId)}/withdraw`), + }, + agentGuide: () => send('GET', '/agent-guide', undefined, { text: true }), } } diff --git a/web/src/copy/agents.ts b/web/src/copy/agents.ts new file mode 100644 index 0000000..475955e --- /dev/null +++ b/web/src/copy/agents.ts @@ -0,0 +1,206 @@ +// Agents: actor badges, delegation, work in progress (runs), requests, the +// inbox, the agent filters and built-in views, the agents settings page and +// the completion policy. One Japanese term per concept (glossary in +// .tmp/agents-ui and the release notes): エージェント (agent), 作業 (run; +// 作業中 / 確認待ち / 応答なし), 依頼 (request; 質問 / 承認 / 確認), 承認する / +// 差し戻す (approve / reject), 任せる / 任せた人 (delegate / delegator), +// 責任者 (owner), 受信箱 (inbox), 回答 (answer), 最後の連絡 (heartbeat). +import { defineDashboardMessages } from '@appthrust/platform-dashboard-i18n' + +export const agentMessages = defineDashboardMessages({ + // Actors + 'tracker.agent.badge': { defaultMessage: 'Agent', translations: { ja: 'エージェント' } }, + 'tracker.agent.ownedBy': { defaultMessage: 'Owned by {name}', translations: { ja: '責任者: {name}' } }, + 'tracker.agent.avatarLabel': { defaultMessage: '{name}, an agent owned by {owner}', translations: { ja: '{name}(エージェント・責任者 {owner})' } }, + 'tracker.agent.disabled': { defaultMessage: 'Disabled', translations: { ja: '無効' } }, + 'tracker.agent.handle': { defaultMessage: '@{handle}', translations: { ja: '@{handle}' } }, + 'tracker.agent.people': { defaultMessage: 'People', translations: { ja: '人' } }, + 'tracker.agent.delegate': { defaultMessage: 'Delegate to an agent', translations: { ja: 'エージェントに任せる' } }, + 'tracker.agent.delegatedBy': { defaultMessage: 'Delegated by {name}', translations: { ja: '{name} が任せた' } }, + 'tracker.property.delegator': { defaultMessage: 'Delegated by', translations: { ja: '任せた人' } }, + 'tracker.activity.delegated': { defaultMessage: '{actor} delegated it to {to}', translations: { ja: '{actor} が {to} に任せた' } }, + 'tracker.activity.delegator': { defaultMessage: '{actor} made {to} the delegator', translations: { ja: '{actor} が任せた人を {to} に変更' } }, + 'tracker.activity.delegatorCleared': { defaultMessage: '{actor} cleared the delegator', translations: { ja: '{actor} が任せた人を外した' } }, + + // Work in progress (runs) + 'tracker.run.state.running': { defaultMessage: 'Working', translations: { ja: '作業中' } }, + 'tracker.run.state.waiting': { defaultMessage: 'Waiting for a person', translations: { ja: '確認待ち' } }, + 'tracker.run.state.stalled': { defaultMessage: 'Not responding', translations: { ja: '応答なし' } }, + 'tracker.run.state.succeeded': { defaultMessage: 'Reported done', translations: { ja: '完了を報告' } }, + 'tracker.run.state.failed': { defaultMessage: 'Failed', translations: { ja: '失敗' } }, + 'tracker.run.state.canceled': { defaultMessage: 'Stopped', translations: { ja: '中止' } }, + 'tracker.run.line': { defaultMessage: '{agent}: {state}. {note} Last report {time}.', translations: { ja: '{agent}: {state}。{note} 最後の連絡 {time}。' } }, + 'tracker.run.openRequests': { defaultMessage: '{count} open requests', translations: { ja: '未回答の依頼 {count} 件' } }, + 'tracker.run.title': { defaultMessage: 'Agent at work', translations: { ja: 'エージェントの作業' } }, + 'tracker.run.session': { defaultMessage: 'Session', translations: { ja: 'セッション' } }, + 'tracker.run.note': { defaultMessage: 'Latest report', translations: { ja: '最新の報告' } }, + 'tracker.run.noNote': { defaultMessage: 'No report yet', translations: { ja: 'まだ報告はありません' } }, + 'tracker.run.lastReport': { defaultMessage: 'Last report {time}', translations: { ja: '最後の連絡 {time}' } }, + 'tracker.run.leaseLeft': { defaultMessage: 'Counts as not responding {time} without a new report', translations: { ja: '新しい連絡がなければ {time}に応答なしになります' } }, + 'tracker.run.leaseExpired': { defaultMessage: 'No report since {time}. The agent may have stopped; its next start closes this work.', translations: { ja: '{time}から連絡がありません。エージェントが止まっている可能性があります。次に作業を始めるとこの作業は閉じられます。' } }, + 'tracker.run.started': { defaultMessage: 'Started {time}', translations: { ja: '開始 {time}' } }, + 'tracker.run.cancel': { defaultMessage: 'Stop work', translations: { ja: '作業を止める' } }, + 'tracker.run.cancelTitle': { defaultMessage: "Stop {agent}'s work on {identifier}?", translations: { ja: '{agent} の {identifier} の作業を止めますか?' } }, + 'tracker.run.cancelBody': { + defaultMessage: 'The agent is told to stop, and the open requests of this work are withdrawn. The issue stays assigned to it.', + translations: { ja: 'エージェントに作業の中止を伝え、この作業の未回答の依頼を取り下げます。担当はそのままです。' }, + }, + 'tracker.run.canceled': { defaultMessage: 'Work stopped', translations: { ja: '作業を止めました' } }, + 'tracker.run.summary': { defaultMessage: 'Report', translations: { ja: '報告' } }, + 'tracker.run.links': { defaultMessage: 'Links', translations: { ja: 'リンク' } }, + 'tracker.run.timeline.started': { defaultMessage: '{agent} started work', translations: { ja: '{agent} が作業を開始' } }, + 'tracker.run.timeline.succeeded': { defaultMessage: '{agent} finished and reported', translations: { ja: '{agent} が作業を終えて報告' } }, + 'tracker.run.timeline.failed': { defaultMessage: '{agent} could not finish', translations: { ja: '{agent} の作業は失敗' } }, + 'tracker.run.timeline.canceled': { defaultMessage: "{agent}'s work was stopped", translations: { ja: '{agent} の作業は中止' } }, + 'tracker.run.reason.reassigned': { defaultMessage: 'The issue was reassigned.', translations: { ja: '担当が変わったため。' } }, + 'tracker.run.reason.lease_expired': { defaultMessage: 'It stopped responding.', translations: { ja: '応答がなくなったため。' } }, + 'tracker.run.reason.canceledBy': { defaultMessage: 'Stopped by {name}.', translations: { ja: '{name} が止めました。' } }, + 'tracker.link.pr': { defaultMessage: 'Pull request', translations: { ja: 'プルリクエスト' } }, + 'tracker.link.commit': { defaultMessage: 'Commit', translations: { ja: 'コミット' } }, + 'tracker.link.url': { defaultMessage: 'Link', translations: { ja: 'リンク' } }, + + // Requests + 'tracker.request.kind.question': { defaultMessage: 'Question', translations: { ja: '質問' } }, + 'tracker.request.kind.approval': { defaultMessage: 'Approval', translations: { ja: '承認' } }, + 'tracker.request.kind.review': { defaultMessage: 'Review', translations: { ja: '確認' } }, + 'tracker.request.anyPerson': { defaultMessage: 'anyone', translations: { ja: 'だれでも' } }, + 'tracker.request.fromTo': { defaultMessage: '{from} asks {to}', translations: { ja: '{from} → {to}' } }, + 'tracker.request.you': { defaultMessage: 'you', translations: { ja: 'あなた' } }, + 'tracker.request.approve': { defaultMessage: 'Approve', translations: { ja: '承認する' } }, + 'tracker.request.reject': { defaultMessage: 'Send back', translations: { ja: '差し戻す' } }, + 'tracker.request.option.approve': { defaultMessage: 'Approved', translations: { ja: '承認' } }, + 'tracker.request.option.reject': { defaultMessage: 'Sent back', translations: { ja: '差し戻し' } }, + 'tracker.request.reply': { defaultMessage: 'Answer', translations: { ja: '回答' } }, + 'tracker.request.replyPlaceholder': { defaultMessage: 'Write an answer… (Markdown)', translations: { ja: '回答を書く…(Markdown)' } }, + 'tracker.request.notePlaceholder': { defaultMessage: 'Note for the agent (optional)', translations: { ja: 'エージェントへのメモ(任意)' } }, + 'tracker.request.send': { defaultMessage: 'Send answer', translations: { ja: '回答する' } }, + 'tracker.request.answeredBy': { defaultMessage: '{name} answered {time}', translations: { ja: '{name} が回答 {time}' } }, + 'tracker.request.withdrawn': { defaultMessage: 'Withdrawn', translations: { ja: '取り下げ' } }, + 'tracker.request.open': { defaultMessage: 'Waiting for an answer', translations: { ja: '回答待ち' } }, + 'tracker.request.sent': { defaultMessage: 'Answer sent', translations: { ja: '回答しました' } }, + 'tracker.request.completed': { defaultMessage: '{identifier} is done', translations: { ja: '{identifier} を完了にしました' } }, + 'tracker.request.sentBack': { defaultMessage: '{identifier} was sent back to {agent}', translations: { ja: '{identifier} を {agent} に差し戻しました' } }, + 'tracker.request.failed': { defaultMessage: "Couldn't send the answer", translations: { ja: '回答を送れませんでした' } }, + 'tracker.request.waitingFor': { defaultMessage: 'Waiting for {name}', translations: { ja: '{name} の回答待ち' } }, + 'tracker.request.peopleOnly': { defaultMessage: 'Only a person can answer this.', translations: { ja: 'この依頼に回答できるのは人だけです。' } }, + 'tracker.request.chooseHint': { defaultMessage: 'Press 1–{count} to choose, then Enter to send', translations: { ja: '1〜{count} で選んで Enter で送信' } }, + 'tracker.request.chosen': { defaultMessage: '“{option}” chosen. Press Enter to send.', translations: { ja: '「{option}」を選択中。Enter で送信します。' } }, + 'tracker.request.pinned': { defaultMessage: 'Open requests', translations: { ja: '未回答の依頼' } }, + 'tracker.request.reviewHint': { defaultMessage: 'Approving moves {identifier} to {status}. Sending back keeps it open for {agent}.', translations: { ja: '承認すると {identifier} は {status} になります。差し戻すと {agent} が作業を続けます。' } }, + 'tracker.request.withdraw': { defaultMessage: 'Withdraw', translations: { ja: '取り下げる' } }, + 'tracker.request.timeline': { defaultMessage: '{from} opened a request', translations: { ja: '{from} が依頼' } }, + + // Inbox + 'tracker.nav.inbox': { defaultMessage: 'Inbox', translations: { ja: '受信箱' } }, + 'tracker.inbox.count': { defaultMessage: '{count} waiting for you', translations: { ja: '対応待ち {count} 件' } }, + 'tracker.inbox.requests': { defaultMessage: 'Waiting for your answer', translations: { ja: 'あなたの回答待ち' } }, + 'tracker.inbox.updates': { defaultMessage: 'Updates', translations: { ja: 'お知らせ' } }, + 'tracker.inbox.assignments': { defaultMessage: 'Assigned to you', translations: { ja: 'あなたの担当' } }, + 'tracker.inbox.emptyTitle': { defaultMessage: 'Nothing is waiting for you', translations: { ja: 'いま対応することはありません' } }, + 'tracker.inbox.emptyBody': { + defaultMessage: "Agents' questions, approvals and reviews of finished work arrive here, with the answers to your own questions.", + translations: { ja: 'エージェントからの質問・承認・作業の確認と、あなたの質問への回答がここに届きます。' }, + }, + 'tracker.inbox.answer': { defaultMessage: '{name} answered your question', translations: { ja: '{name} があなたの質問に回答' } }, + 'tracker.inbox.mention': { defaultMessage: '{name} mentioned you', translations: { ja: '{name} があなたをメンション' } }, + 'tracker.inbox.ack': { defaultMessage: 'Mark as read', translations: { ja: '既読にする' } }, + 'tracker.inbox.ackAll': { defaultMessage: 'Mark all updates as read', translations: { ja: 'お知らせをすべて既読にする' } }, + 'tracker.inbox.keys': { defaultMessage: 'J/K move · 1–6 choose · Enter send · O open · E mark read', translations: { ja: 'J/K 移動 · 1〜6 選択 · Enter 送信 · O 開く · E 既読' } }, + 'tracker.inbox.item': { defaultMessage: '{kind}: {title} on {identifier}', translations: { ja: '{identifier} の{kind}: {title}' } }, + 'tracker.palette.goInbox': { defaultMessage: 'Open the inbox', translations: { ja: '受信箱を開く' } }, + + // Filters and built-in views + 'tracker.filter.agentsFacet': { defaultMessage: 'Agent work', translations: { ja: 'エージェント' } }, + 'tracker.filter.agentWork': { defaultMessage: 'Filter by agent work', translations: { ja: 'エージェントの作業で絞り込む' } }, + 'tracker.filter.kindGroup': { defaultMessage: 'Assigned to', translations: { ja: '担当の種類' } }, + 'tracker.filter.kind.agent': { defaultMessage: 'Assigned to an agent', translations: { ja: 'エージェントが担当' } }, + 'tracker.filter.kind.person': { defaultMessage: 'Assigned to a person', translations: { ja: '人が担当' } }, + 'tracker.filter.workGroup': { defaultMessage: 'Work', translations: { ja: '作業' } }, + 'tracker.filter.run.active': { defaultMessage: 'An agent is working', translations: { ja: 'エージェントが作業中' } }, + 'tracker.filter.run.stalled': { defaultMessage: 'An agent is not responding', translations: { ja: 'エージェントが応答なし' } }, + 'tracker.filter.run.none': { defaultMessage: 'No agent work in progress', translations: { ja: 'エージェントの作業なし' } }, + 'tracker.filter.requestGroup': { defaultMessage: 'Requests', translations: { ja: '依頼' } }, + 'tracker.filter.request.open': { defaultMessage: 'Has open requests', translations: { ja: '未回答の依頼あり' } }, + 'tracker.filter.request.mine': { defaultMessage: 'Has a request I raised', translations: { ja: '自分が出した依頼あり' } }, + 'tracker.filter.agentGroup': { defaultMessage: 'Assigned agent', translations: { ja: '担当のエージェント' } }, + 'tracker.nav.atWork': { defaultMessage: 'Agents at work', translations: { ja: 'エージェントの作業中' } }, + 'tracker.nav.waiting': { defaultMessage: 'Waiting for people', translations: { ja: '人の確認待ち' } }, + 'tracker.atWork.emptyTitle': { defaultMessage: 'No agent is working right now', translations: { ja: 'いま作業中のエージェントはいません' } }, + 'tracker.atWork.emptyBody': { defaultMessage: 'Assign an issue to an agent to delegate it.', translations: { ja: '課題の担当をエージェントにすると、作業を任せられます。' } }, + 'tracker.waiting.emptyTitle': { defaultMessage: 'No open requests', translations: { ja: '未回答の依頼はありません' } }, + 'tracker.waiting.emptyBody': { defaultMessage: 'When an agent needs a decision from a person, its issue shows up here.', translations: { ja: 'エージェントが人の判断を求めると、その課題がここに並びます。' } }, + + // Comment mentions + 'tracker.comment.mentionList': { defaultMessage: 'Agents to mention', translations: { ja: 'メンションするエージェント' } }, + 'tracker.comment.mentionHint': { defaultMessage: 'Markdown supported · @ mentions an agent', translations: { ja: 'Markdown が使えます · @ でエージェントをメンション' } }, + + // Edit conflicts + 'tracker.issue.conflictTitle': { defaultMessage: 'Someone changed this issue while you were editing', translations: { ja: '編集中にほかの人がこの課題を更新しました' } }, + 'tracker.issue.conflictBody': { defaultMessage: 'Your text is kept. Load the latest version, check it, then save again.', translations: { ja: '入力した内容は残っています。最新の内容を読み込んで確認してから、もう一度保存してください。' } }, + 'tracker.issue.conflictReload': { defaultMessage: 'Load latest', translations: { ja: '最新を読み込む' } }, + + // Settings: agents + 'tracker.settings.agents': { defaultMessage: 'Agents', translations: { ja: 'エージェント' } }, + 'tracker.agents.lead': { + defaultMessage: 'Agents pick up issues assigned to them, report as they work and ask people when they need a decision. Each has one person responsible for what it does.', + translations: { ja: 'エージェントは担当になった課題に取り組み、作業の様子を報告し、判断が必要なときは人に依頼します。エージェントごとに、その作業に責任を持つ人を 1 人決めます。' }, + }, + 'tracker.agents.adminOnly': { defaultMessage: 'Only admins register, edit and disable agents.', translations: { ja: 'エージェントの登録・編集・無効化は管理者だけができます。' } }, + 'tracker.agents.register': { defaultMessage: 'Register agent', translations: { ja: 'エージェントを登録' } }, + 'tracker.agents.registered': { defaultMessage: '{name} registered', translations: { ja: '{name} を登録しました' } }, + 'tracker.agents.handle': { defaultMessage: 'Handle', translations: { ja: 'ハンドル' } }, + 'tracker.agents.handleHint': { + defaultMessage: 'Lowercase letters, digits and hyphens, starting with a letter. People mention it as @handle, and it is the external subject of its Access Keys. It cannot be changed later.', + translations: { ja: '英小文字・数字・ハイフン(先頭は英字)。@ハンドル でメンションでき、アクセスキーの external サブジェクトになります。あとから変更できません。' }, + }, + 'tracker.agents.handleFixed': { defaultMessage: 'The handle cannot be changed.', translations: { ja: 'ハンドルは変更できません。' } }, + 'tracker.agents.handleInvalid': { defaultMessage: 'Use 2–31 lowercase letters, digits or hyphens, starting with a letter.', translations: { ja: '英小文字・数字・ハイフンで 2〜31 文字(先頭は英字)にしてください。' } }, + 'tracker.agents.handleTaken': { defaultMessage: 'Another agent already has this handle.', translations: { ja: 'このハンドルはほかのエージェントが使っています。' } }, + 'tracker.agents.name': { defaultMessage: 'Display name', translations: { ja: '表示名' } }, + 'tracker.agents.owner': { defaultMessage: 'Responsible person', translations: { ja: '責任者' } }, + 'tracker.agents.ownerHint': { + defaultMessage: 'Accountable for what the agent does. Its requests go to this person when no one delegated the issue.', + translations: { ja: 'エージェントの作業に責任を持つ人です。任せた人がいない課題の依頼は、この人に届きます。' }, + }, + 'tracker.agents.ownerNone': { defaultMessage: 'Choose a person', translations: { ja: '人を選んでください' } }, + 'tracker.agents.description': { defaultMessage: 'What to delegate to it', translations: { ja: '任せる仕事' } }, + 'tracker.agents.descriptionHint': { defaultMessage: 'Shown next to the agent when someone picks an assignee.', translations: { ja: '担当者を選ぶときにエージェントの横に表示されます。' } }, + 'tracker.agents.lastSeen': { defaultMessage: 'Last seen {time}', translations: { ja: '最終接続 {time}' } }, + 'tracker.agents.neverSeen': { defaultMessage: 'Not connected yet', translations: { ja: 'まだ接続していません' } }, + 'tracker.agents.activeRuns': { defaultMessage: '{count} in progress', translations: { ja: '作業中 {count} 件' } }, + 'tracker.agents.medianWait': { defaultMessage: 'Waits {time} for a person (median)', translations: { ja: '人の回答まで {time}(中央値)' } }, + 'tracker.agents.noWait': { defaultMessage: 'No answered requests yet', translations: { ja: '回答された依頼はまだありません' } }, + 'tracker.agents.empty': { defaultMessage: 'No agents yet', translations: { ja: 'まだエージェントはいません' } }, + 'tracker.agents.disable': { defaultMessage: 'Disable', translations: { ja: '無効にする' } }, + 'tracker.agents.enable': { defaultMessage: 'Enable', translations: { ja: '有効にする' } }, + 'tracker.agents.disableLabel': { defaultMessage: 'Disable {name}', translations: { ja: '{name} を無効にする' } }, + 'tracker.agents.enableLabel': { defaultMessage: 'Enable {name}', translations: { ja: '{name} を有効にする' } }, + 'tracker.agents.editLabel': { defaultMessage: 'Edit agent {name}', translations: { ja: 'エージェント {name} を編集' } }, + 'tracker.agents.disableTitle': { defaultMessage: 'Disable {name}?', translations: { ja: '{name} を無効にしますか?' } }, + 'tracker.agents.disableBody': { + defaultMessage: + '{name} can no longer connect with its keys and is no longer offered as an assignee. Its {count} work items in progress are stopped now and their open requests withdrawn. Issues assigned to it keep it as their assignee.', + translations: { ja: '{name} はキーで接続できなくなり、担当者の候補にも出なくなります。進行中の作業 {count} 件はすぐに止まり、その未回答の依頼は取り下げられます。担当している課題の担当者はそのままです。' }, + }, + 'tracker.agents.keyTitle': { defaultMessage: 'Give it a key', translations: { ja: 'キーを発行する' } }, + 'tracker.agents.keyBody': { + defaultMessage: 'Run this with the apth CLI. The platform shows the key once; Tracker never receives or shows it. Hand the key to the agent, not to a person.', + translations: { ja: 'apth CLI で次のコマンドを実行します。キーはプラットフォームが一度だけ表示します。Tracker がキーを受け取ったり表示したりすることはありません。キーは人ではなくエージェントに渡してください。' }, + }, + 'tracker.agents.copy': { defaultMessage: 'Copy command', translations: { ja: 'コマンドをコピー' } }, + 'tracker.agents.copied': { defaultMessage: 'Command copied', translations: { ja: 'コマンドをコピーしました' } }, + 'tracker.agents.showKey': { defaultMessage: 'Key command for {name}', translations: { ja: '{name} のキー発行コマンド' } }, + + // Settings: completion policy + 'tracker.completion.title': { defaultMessage: 'Finishing agent work', translations: { ja: 'エージェントの作業の完了' } }, + 'tracker.completion.review': { defaultMessage: 'A person approves', translations: { ja: '人が承認して完了' } }, + 'tracker.completion.reviewHint': { + defaultMessage: 'When an agent reports its work done, the person who delegated it gets a review request. The issue is done only when they approve. Recommended.', + translations: { ja: 'エージェントが作業の完了を報告すると、任せた人に確認の依頼が届きます。その人が承認したときだけ課題が完了になります。おすすめ。' }, + }, + 'tracker.completion.direct': { defaultMessage: 'The agent finishes on its own', translations: { ja: 'エージェントが自分で完了' } }, + 'tracker.completion.directHint': { + defaultMessage: 'Agents may move an issue to a done status themselves. No one is asked to review their work.', + translations: { ja: 'エージェントが課題を完了の状態に自分で移せます。作業の確認はだれにも依頼されません。' }, + }, +}) diff --git a/web/src/copy/index.ts b/web/src/copy/index.ts index 2b190fe..03bf132 100644 --- a/web/src/copy/index.ts +++ b/web/src/copy/index.ts @@ -3,6 +3,7 @@ // Screens read it through `useText().t(id, values)` (src/i18n.tsx); no screen // hardcodes user-facing text. import type { DashboardMessageCatalog } from '@appthrust/platform-dashboard-i18n' +import { agentMessages } from './agents' import { commonMessages } from './common' import { epicMessages } from './epics' import { issueMessages } from './issues' @@ -11,7 +12,7 @@ import { reportMessages } from './report' import { settingsMessages } from './settings' import { sprintMessages } from './sprints' -export const catalogs: readonly DashboardMessageCatalog[] = [commonMessages, issueMessages, epicMessages, projectMessages, reportMessages, settingsMessages, sprintMessages] +export const catalogs: readonly DashboardMessageCatalog[] = [commonMessages, issueMessages, epicMessages, projectMessages, reportMessages, settingsMessages, sprintMessages, agentMessages] export type MessageId = | keyof typeof commonMessages @@ -21,3 +22,4 @@ export type MessageId = | keyof typeof reportMessages | keyof typeof settingsMessages | keyof typeof sprintMessages + | keyof typeof agentMessages diff --git a/web/src/dev/mock-tracker.test.ts b/web/src/dev/mock-tracker.test.ts index 6fb89d6..f39f811 100644 --- a/web/src/dev/mock-tracker.test.ts +++ b/web/src/dev/mock-tracker.test.ts @@ -1,17 +1,17 @@ import { beforeEach, describe, expect, test } from 'bun:test' -import type { Attachment, Burndown, Issue, IssuePage, IssueSummary, Label, Project, Sprint, Status, TimelineItem, Velocity, View } from '../api/tracker' +import type { Agent, Attachment, Burndown, InboxItem, Issue, IssuePage, IssueSummary, Label, Project, Run, Sprint, Status, TimelineItem, TrackerEvent, TrackerRequest, Velocity, View } from '../api/tracker' import { addDays, dayInZone } from '../model/sprints' import { MOCK_PEOPLE, trackerRoutes } from './mock-tracker' const BASE = '/api/tracker/v1' -async function call(method: string, path: string, body?: unknown) { +async function call(method: string, path: string, body?: unknown, headers: Record = {}) { const url = new URL(`${BASE}${path}`, 'http://mock.test') - const init: RequestInit = { method } + const init: RequestInit = { method, headers: { ...headers } } if (body instanceof FormData) init.body = body else if (body !== undefined) { init.body = JSON.stringify(body) - init.headers = { 'Content-Type': 'application/json' } + init.headers = { ...headers, 'Content-Type': 'application/json' } } const response = await trackerRoutes(new Request(url, init), url) if (!response) throw new Error(`unhandled ${method} ${path}`) @@ -35,8 +35,8 @@ beforeEach(async () => { describe('tracker mock: fixture shared with the server dev seed', () => { test('caller, workspace, statuses, labels, views and people', async () => { - expect((await call('GET', '/me')).body).toEqual({ ...MOCK_PEOPLE.alex, role: 'Admin', isAdmin: true }) - expect((await call('GET', '/workspace')).body).toMatchObject({ key: 'APT', issueCount: 40, sprintLengthWeeks: 1, timezone: 'Asia/Tokyo' }) + expect((await call('GET', '/me')).body).toEqual({ ...MOCK_PEOPLE.alex, kind: 'person', role: 'Admin', isAdmin: true }) + expect((await call('GET', '/workspace')).body).toMatchObject({ key: 'APT', issueCount: 42, sprintLengthWeeks: 1, timezone: 'Asia/Tokyo', agentCompletion: 'review' }) expect((await statuses()).map((status) => [status.name, status.category, status.color, status.position])).toEqual([ ['Backlog', 'backlog', 'gray', 0], ['Todo', 'unstarted', 'gray', 1], @@ -89,7 +89,8 @@ describe('tracker mock: fixture shared with the server dev seed', () => { describe('tracker mock: issues', () => { test('filter, sort and cursor paging; malformed parameters are 400 invalid', async () => { - expect((await list(filterQuery({ type: ['bug'] }))).items).toHaveLength(10) + // Ten seeded bugs plus APT-42, reported by astra. + expect((await list(filterQuery({ type: ['bug'] }))).items).toHaveLength(11) expect((await list(filterQuery({ assignee: ['me'] }))).items.every((issue) => issue.assignee?.sub === 'dev-alex')).toBe(true) expect((await list(filterQuery({ category: ['started'] }))).items).toHaveLength(16) expect((await list(filterQuery({ q: 'cluster' }))).items.map((issue) => issue.identifier).sort()).toEqual(['APT-10', 'APT-28', 'APT-3']) @@ -100,9 +101,9 @@ describe('tracker mock: issues', () => { seen.push(...page.items.map((issue) => issue.identifier)) cursor = page.nextCursor } while (cursor) - expect(seen).toHaveLength(40) + expect(seen).toHaveLength(42) expect(seen[0]).toBe('APT-1') - expect(new Set(seen).size).toBe(40) + expect(new Set(seen).size).toBe(42) const urgentFirst = (await list('?sort=priority')).items expect(urgentFirst.slice(0, 6).every((issue) => issue.priority === 'urgent')).toBe(true) for (const bad of ['?filter=%7Bnope', filterQuery({ colour: ['red'] }), filterQuery({ type: ['initiative'] }), filterQuery({ epic: ['APT-31'] }), filterQuery({ story: 'none' }), '?sort=title', '?limit=500']) { @@ -132,7 +133,7 @@ describe('tracker mock: issues', () => { expect((await call('POST', '/__mock/caller', { sub: 'dev-riley', name: 'Riley Park' })).status).toBe(200) expect((await list(filterQuery({ reporter: ['me'] }))).items).toEqual([]) const created = (await call('POST', '/issues', { title: 'First report', type: 'bug', report: { environment: 'craftsman', surface: 'dashboard' } })).body as Issue - expect(created.reporter).toEqual({ sub: 'dev-riley', name: 'Riley Park' }) + expect(created.reporter).toEqual({ sub: 'dev-riley', name: 'Riley Park', kind: 'person' }) expect((await list(filterQuery({ reporter: ['me'] }))).items.map((issue) => issue.identifier)).toEqual([created.identifier]) const subjects = Array.from({ length: 21 }, (_, i) => `dev-${i}`) @@ -159,9 +160,9 @@ describe('tracker mock: issues', () => { expect((await call('POST', '/issues', { title: 'x', type: 'task', report: { environment: 'local', surface: 'apth' } })).status).toBe(400) const created = await call('POST', '/issues', { title: ' Board drag fails ', type: 'bug', priority: 'high', report: { environment: 'craftsman', surface: 'dashboard', version: '0.1.0', steps: '' } }) expect(created.status).toBe(201) - expect(created.body).toMatchObject({ identifier: 'APT-41', title: 'Board drag fails', statusId: (await statusNamed('Backlog')).id, reporter: MOCK_PEOPLE.alex, report: { environment: 'craftsman', surface: 'dashboard', version: '0.1.0' }, estimate: null, sprint: null }) + expect(created.body).toMatchObject({ identifier: 'APT-43', title: 'Board drag fails', statusId: (await statusNamed('Backlog')).id, reporter: { ...MOCK_PEOPLE.alex, kind: 'person' }, report: { environment: 'craftsman', surface: 'dashboard', version: '0.1.0' }, estimate: null, sprint: null }) expect(created.body.report.steps).toBeUndefined() - expect((await call('GET', '/workspace')).body.issueCount).toBe(41) + expect((await call('GET', '/workspace')).body.issueCount).toBe(43) }) test('PATCH: one activity per changed field, completion time, links and cycle checks', async () => { @@ -210,7 +211,7 @@ describe('tracker mock: issues', () => { await as('dev-alex', 'Admin') expect((await call('DELETE', `/issues/${issue.id}`)).status).toBe(204) expect((await call('GET', '/issues/APT-4')).status).toBe(404) - expect((await list()).items).toHaveLength(39) + expect((await list()).items).toHaveLength(41) }) }) @@ -289,7 +290,7 @@ describe('tracker mock: epics and stories', () => { expect(inEpic.map((issue) => issue.number)).toContain(33) expect((await list(`${filterQuery({ story: [story.id] })}&limit=200`)).items.every((issue) => issue.story?.id === story.id)).toBe(true) const noEpic = (await list(`${filterQuery({ epic: ['none'] })}&limit=200`)).items - expect(noEpic.map((issue) => issue.number).sort((a, b) => a - b)).toEqual([5, 10, 15, 20, 25, 30, 31, 32, 37, 38, 39, 40]) + expect(noEpic.map((issue) => issue.number).sort((a, b) => a - b)).toEqual([5, 10, 15, 20, 25, 30, 31, 32, 37, 38, 39, 40, 41, 42]) expect((await list(`${filterQuery({ epic: [epic.id, 'none'] })}&limit=200`)).items).toHaveLength(inEpic.length + noEpic.length) expect((await list(filterQuery({ type: ['epic', 'story'] }))).items).toHaveLength(6) expect((await list(filterQuery({ parent: epic.id }))).items.map((issue) => issue.number).sort()).toEqual([33, 34]) @@ -401,14 +402,16 @@ describe('tracker mock: projects', () => { expect(items.map((project) => [project.name, project.color, project.archived, project.issueCount])).toEqual([ ['Builder Console', 'orange', false, 10], ['Dashboard', 'blue', false, 5], - ['Platform API', 'purple', false, 5], + // APT-41 and APT-42 (agents' reports) are in Platform API. + ['Platform API', 'purple', false, 7], ]) const byName = Object.fromEntries(items.map((project) => [project.name, project.id])) const order = [byName.Dashboard, byName['Platform API'], byName['Builder Console']] const all = (await list('?sort=number')).items for (const issue of all) { const seeded = issue.number <= 30 - expect(issue.projectId, issue.identifier).toBe(seeded && issue.number % 3 !== 0 ? order[((issue.number % 3) + (issue.number % 2)) % 3]! : null) + const agentReport = issue.number === 41 || issue.number === 42 + expect(issue.projectId, issue.identifier).toBe(agentReport ? byName['Platform API']! : seeded && issue.number % 3 !== 0 ? order[((issue.number % 3) + (issue.number % 2)) % 3]! : null) } const closed = new Set((await statuses()).filter((status) => status.category === 'completed' || status.category === 'canceled').map((status) => status.id)) for (const project of items) { @@ -603,7 +606,7 @@ describe('tracker mock: sprints fixture (API.md v0.1.10)', () => { test('four Done work items close the seed, and 17 work items carry a size across all five', async () => { const all = (await list('?sort=number&limit=200')).items const done = await statusNamed('Done') - expect(all.slice(36).map((issue) => [issue.number, issue.title, issue.type, issue.statusId === done.id, issue.parent, issue.projectId, issue.estimate])).toEqual([ + expect(all.slice(36, 40).map((issue) => [issue.number, issue.title, issue.type, issue.statusId === done.id, issue.parent, issue.projectId, issue.estimate])).toEqual([ [37, 'Speed up issue search', 'task', true, null, null, 'L'], [38, 'Add bulk status change', 'feature', true, null, null, 'XL'], [39, 'Tidy up the settings layout', 'task', true, null, null, 'XL'], @@ -748,7 +751,7 @@ describe('tracker mock: estimates and membership on issue writes', () => { expect(both).toHaveLength(10) const backlog = (await list(`${filterQuery({ sprint: ['none'] })}&limit=200`)).items expect(backlog.every((issue) => issue.sprint === null)).toBe(true) - expect(backlog).toHaveLength(40 - 3 * 3 - 7 - 3) + expect(backlog).toHaveLength(42 - 3 * 3 - 7 - 3) expect((await call('GET', `/issues${filterQuery({ sprint: ['Sprint 4'] })}`)).status).toBe(400) const bySize = (await list('?sort=estimate&limit=200')).items expect(bySize.slice(0, 6).every((issue) => issue.estimate === 'XL')).toBe(true) @@ -859,3 +862,295 @@ describe('tracker mock: sprint lifecycle', () => { expect((await call('PATCH', '/workspace', { sprintLengthWeeks: 1 })).status).toBe(403) }) }) + +// --- agents (API.md "Agents"; fixture `.tmp/agents-ui/fixture.md`) ------------------------------------- + +/** A call made with the named agent's Access Key assertion. */ +const agentCall = (handle: string, method: string, path: string, body?: unknown, headers: Record = {}) => call(method, path, body, { 'X-Mock-Agent': handle, ...headers }) +const issueNamed = async (identifier: string) => (await call('GET', `/issues/${identifier}`)).body as Issue +const agentsByHandle = async () => new Map(((await call('GET', '/agents?includeDisabled=true')).body.items as Agent[]).map((agent) => [agent.handle, agent])) +const inbox = async (handle?: string) => ((handle ? await agentCall(handle, 'GET', '/inbox') : await call('GET', '/inbox')).body.items as InboxItem[]) +const inboxTitles = (items: InboxItem[]) => items.map((item) => (item.kind === 'mention' ? `mention ${item.issue.identifier}` : item.kind === 'assignment' ? `assignment ${item.issue.identifier}` : `${item.kind} ${item.request.title}`)) +const MINUTE = 60_000 + +describe('tracker mock: agents fixture', () => { + test('four agents (one disabled) with derived counts; disabled ones only on request', async () => { + const active = (await call('GET', '/agents')).body.items as Agent[] + expect(active.map((agent) => agent.handle)).toEqual(['astra', 'claude', 'opus-ui']) + const all = await agentsByHandle() + expect([...all.values()].map((agent) => [agent.handle, agent.name, agent.owner.sub, agent.disabled, agent.activeRuns, agent.openRequests])).toEqual([ + ['astra', 'Astra', 'dev-sam', false, 1, 1], + ['claude', 'Claude', 'dev-jordan', false, 0, 1], + ['legacy-bot', 'Legacy bot', 'dev-alex', true, 0, 0], + ['opus-ui', 'Opus UI', 'dev-alex', false, 1, 1], + ]) + expect(all.get('astra')!.lastSeenAt).toEqual(expect.any(String)) + }) + + test('delegations, runs and request counts on the board', async () => { + const astra = (await agentsByHandle()).get('astra')! + const apt15 = await issueNamed('APT-15') + expect(apt15.assignee).toMatchObject({ sub: `agent:${astra.id}`, kind: 'agent', name: 'Astra', agent: { handle: 'astra', owner: { sub: 'dev-sam' }, disabled: false } }) + // The wire carries `kind` on every person, the delegator included. + const delegator: unknown = apt15.delegator + expect(delegator).toEqual({ ...MOCK_PEOPLE.alex, kind: 'person' }) + expect(apt15.activeRun).toMatchObject({ state: 'running', session: 'astra · lane-2', agent: { name: 'Astra' } }) + expect((await issueNamed('APT-27')).activeRun?.state).toBe('waiting') + expect((await issueNamed('APT-27')).openRequestCount).toBe(1) + expect((await issueNamed('APT-9')).activeRun?.state).toBe('stalled') + expect((await issueNamed('APT-16'))).toMatchObject({ activeRun: null, openRequestCount: 1 }) + expect((await issueNamed('APT-1')).openRequestCount).toBe(1) + expect((await issueNamed('APT-41')).reporter).toMatchObject({ kind: 'agent', name: 'Claude' }) + expect((await issueNamed('APT-42'))).toMatchObject({ reporter: { name: 'Astra' }, assignee: { name: 'Astra' }, delegator: MOCK_PEOPLE.sam }) + const numbers = async (filter: object) => (await list(`${filterQuery(filter)}&sort=number&limit=200`)).items.map((issue) => issue.number) + expect(await numbers({ run: ['active'] })).toEqual([15, 27]) + expect(await numbers({ run: ['stalled'] })).toEqual([9]) + expect(await numbers({ request: ['open'] })).toEqual([1, 16, 27]) + // `mine`: an open request the caller raised (Alex's only request, R6, is answered); astra raised the open review of APT-16. + expect(await numbers({ request: ['mine'] })).toEqual([]) + expect((await agentCall('astra', 'GET', `/issues${filterQuery({ request: ['mine'] })}`)).body.items.map((issue: IssueSummary) => issue.number)).toEqual([16]) + expect(await numbers({ assigneeKind: ['agent'] })).toEqual([4, 9, 13, 15, 16, 19, 21, 26, 27, 42]) + expect(await numbers({ agent: [astra.id] })).toEqual([4, 9, 15, 16, 19, 42]) + for (const bad of [{ run: ['live'] }, { request: ['all'] }, { assigneeKind: ['bot'] }, { agent: ['astra'] }]) expect((await call('GET', `/issues${filterQuery(bad)}`)).status).toBe(400) + // A run on the timeline sits at its start; requests at their creation. + const kinds = ((await call('GET', `/issues/${apt15.id}/timeline`)).body.items as TimelineItem[]).map((item) => item.kind) + expect(kinds).toEqual(['activity', 'activity', 'activity', 'run', 'request']) + }) + + test('inboxes: requests first, then answers and mentions; agents also get their actionable assignments', async () => { + expect(inboxTitles(await inbox())).toEqual([ + 'request Add APT-1 to the current sprint?', + 'request Review: CLI login expires too early', + "request Which label should the panel's close button use?", + 'answer Which open bugs look like duplicates of APT-22?', + ]) + await as('dev-sam') + expect(inboxTitles(await inbox())).toEqual(['request Add APT-1 to the current sprint?']) + // Assignments by priority (APT-42 medium; APT-4, APT-9, APT-19 low with APT-4 in the active sprint; APT-15 none), then number. + expect(inboxTitles(await inbox('astra'))).toEqual(['mention APT-22', 'answer Review: Platform API returns stale status', 'assignment APT-42', 'assignment APT-4', 'assignment APT-9', 'assignment APT-19', 'assignment APT-15']) + expect(inboxTitles(await inbox('opus-ui'))).toEqual(['assignment APT-26', 'assignment APT-13']) + expect(inboxTitles(await inbox('claude'))).toEqual(['assignment APT-21']) + }) +}) + +describe('tracker mock: agent keys', () => { + test('the handle is the key subject; scopes gate methods; agents act with role Viewer', async () => { + expect(await agentCall('nobody', 'GET', '/me')).toMatchObject({ status: 403, body: { error: 'key_subject' } }) + expect(await agentCall('legacy-bot', 'GET', '/issues')).toMatchObject({ status: 403, body: { error: 'key_subject' } }) + const me = (await agentCall('astra', 'GET', '/me')).body + expect(me).toMatchObject({ kind: 'agent', name: 'Astra', role: 'Viewer', isAdmin: false, scopes: ['tracker:read', 'tracker:write'], agent: { handle: 'astra' } }) + expect(await agentCall('astra', 'POST', '/issues', { title: 'x', type: 'task' }, { 'X-Mock-Scopes': 'tracker:read' })).toMatchObject({ status: 403, body: { error: 'insufficient_scope' } }) + expect(await agentCall('astra', 'GET', '/issues', undefined, { 'X-Mock-Scopes': 'tracker:write' })).toMatchObject({ status: 403, body: { error: 'insufficient_scope' } }) + expect((await agentCall('astra', 'GET', '/people')).body).toEqual({ items: [], source: 'unavailable' }) + expect((await agentCall('astra', 'POST', '/agents', { handle: 'x1', name: 'X', ownerSub: 'dev-alex' })).status).toBe(403) + expect((await agentCall('astra', 'PATCH', '/workspace', { agentCompletion: 'direct' })).status).toBe(403) + }) + + test('agents edit fields only as assignee or reporter, assign only themselves on their reports, never complete under review', async () => { + const done = await statusNamed('Done') + const apt2 = await issueNamed('APT-2') + expect((await agentCall('astra', 'PATCH', `/issues/${apt2.id}`, { priority: 'high' })).status).toBe(403) + // Commenting and raising questions work on any issue. + expect((await agentCall('astra', 'POST', `/issues/${apt2.id}/comments`, { body: 'Looks related to APT-15.' })).status).toBe(201) + const apt19 = await issueNamed('APT-19') + expect((await agentCall('astra', 'PATCH', `/issues/${apt19.id}`, { priority: 'high' })).body.priority).toBe('high') + expect((await agentCall('astra', 'PATCH', `/issues/${apt19.id}`, { statusId: done.id })).status).toBe(403) + const agents = await agentsByHandle() + // Self-assignment only on an issue the agent reported. + const own = (await agentCall('astra', 'POST', '/issues', { title: 'Follow-up from APT-15', type: 'task', assigneeSub: `agent:${agents.get('astra')!.id}` })).body as Issue + expect(own).toMatchObject({ assignee: { name: 'Astra' }, delegator: MOCK_PEOPLE.sam, reporter: { name: 'Astra' } }) + expect((await agentCall('astra', 'POST', '/issues', { title: 'x', type: 'task', assigneeSub: `agent:${agents.get('claude')!.id}` })).status).toBe(403) + expect((await agentCall('astra', 'PATCH', `/issues/${apt19.id}`, { assigneeSub: `agent:${agents.get('claude')!.id}` })).status).toBe(403) + // Under `direct` the agent may complete. + await call('PATCH', '/workspace', { agentCompletion: 'direct' }) + expect((await agentCall('astra', 'PATCH', `/issues/${apt19.id}`, { statusId: done.id })).body.statusId).toBe(done.id) + }) +}) + +describe('tracker mock: delegation, runs and requests', () => { + test('assign → run → question → answer → finish → review → approve completes the issue as the person', async () => { + const agents = await agentsByHandle() + const astraSub = `agent:${agents.get('astra')!.id}` + const apt2 = await issueNamed('APT-2') + expect((await call('PATCH', `/issues/${apt2.id}`, { assigneeSub: `agent:${agents.get('legacy-bot')!.id}` })).body.issues[0].path).toBe('assigneeSub') + expect((await agentCall('astra', 'POST', `/issues/${apt2.id}/runs`, {})).status).toBe(403) + const assigned = (await call('PATCH', `/issues/${apt2.id}`, { assigneeSub: astraSub })).body as Issue + expect(assigned).toMatchObject({ assignee: { sub: astraSub }, delegator: MOCK_PEOPLE.alex }) + expect(inboxTitles(await inbox('astra'))).toContain('assignment APT-2') + expect((await call('POST', `/issues/${apt2.id}/runs`, {})).status).toBe(403) + const started = await agentCall('astra', 'POST', `/issues/${apt2.id}/runs`, { session: 'astra · lane-3', note: 'reading the issue' }) + expect(started.status).toBe(201) + const run = started.body as Run + expect(run).toMatchObject({ state: 'running', session: 'astra · lane-3', note: 'reading the issue', reason: null, finishedAt: null }) + expect(Date.parse(run.leaseExpiresAt) - Date.parse(run.heartbeatAt)).toBe(10 * MINUTE) + expect((await agentCall('astra', 'POST', `/issues/${apt2.id}/runs`, {})).status).toBe(409) + expect((await agentCall('astra', 'POST', `/runs/${run.id}/heartbeat`, { note: 'running tests' })).body.note).toBe('running tests') + expect((await agentCall('claude', 'POST', `/runs/${run.id}/heartbeat`, {})).status).toBe(403) + // Only the run's own agent attaches a request to it, and only on the run's issue. + expect((await agentCall('claude', 'POST', `/issues/${apt2.id}/requests`, { kind: 'question', title: 'Mine?', runId: run.id })).status).toBe(403) + expect((await agentCall('astra', 'POST', `/issues/${(await issueNamed('APT-3')).id}/requests`, { kind: 'question', title: 'Here?', runId: run.id })).status).toBe(403) + const question = (await agentCall('astra', 'POST', `/issues/${apt2.id}/requests`, { kind: 'question', title: 'Which key?', options: ['J/K', 'Arrows'], runId: run.id })).body as TrackerRequest + expect(question).toMatchObject({ to: { sub: 'dev-alex' }, from: { sub: astraSub }, state: 'open', runId: run.id }) + expect((await issueNamed('APT-2')).activeRun?.state).toBe('waiting') + expect(inboxTitles(await inbox()).filter((title) => title.startsWith('request')).at(-1)).toBe('request Which key?') + expect((await call('POST', `/requests/${question.id}/answer`, { option: 'Tab' })).status).toBe(400) + await as('dev-sam') + expect((await call('POST', `/requests/${question.id}/answer`, { option: 'J/K' })).status).toBe(403) + await as('dev-alex', 'Admin') + expect((await call('POST', `/requests/${question.id}/answer`, { option: 'J/K', body: 'Like the list.' })).body).toMatchObject({ state: 'answered', answer: { option: 'J/K', body: 'Like the list.', by: { sub: 'dev-alex' } } }) + expect((await call('POST', `/requests/${question.id}/answer`, { option: 'J/K' })).status).toBe(409) + expect((await issueNamed('APT-2')).activeRun?.state).toBe('running') + expect(inboxTitles(await inbox('astra'))).toContain('answer Which key?') + await agentCall('astra', 'POST', '/inbox/ack', { answers: [question.id] }) + expect(inboxTitles(await inbox('astra'))).not.toContain('answer Which key?') + + const links = [{ kind: 'pr', url: 'https://github.com/appthrust/tracker/pull/150', title: 'Keyboard shortcuts' }] + expect((await agentCall('astra', 'POST', `/runs/${run.id}/finish`, { outcome: 'succeeded', summary: 'Done.', links: [{ kind: 'pr', url: 'http://x', title: 'x' }] })).status).toBe(400) + const finished = (await agentCall('astra', 'POST', `/runs/${run.id}/finish`, { outcome: 'succeeded', summary: 'Added **J/K**.', links })).body as Run + expect(finished).toMatchObject({ state: 'succeeded', summary: 'Added **J/K**.', links, finishedAt: expect.any(String) }) + expect((await agentCall('astra', 'POST', `/runs/${run.id}/heartbeat`, {})).status).toBe(409) + const review = (await call('GET', `/requests?state=open&issue=${apt2.id}`)).body.items[0] as TrackerRequest + expect(review).toMatchObject({ kind: 'review', to: { sub: 'dev-alex' }, title: `Review: ${apt2.title}`, body: 'Added **J/K**.', options: ['approve', 'reject'], runId: run.id }) + expect((await agentCall('astra', 'POST', `/requests/${review.id}/answer`, { option: 'approve' })).status).toBe(403) + const approved = await call('POST', `/requests/${review.id}/answer`, { option: 'approve' }) + expect(approved.status).toBe(200) + const after = await issueNamed('APT-2') + const done = await statusNamed('Done') + expect(after).toMatchObject({ statusId: done.id, completedAt: expect.any(String), activeRun: null, openRequestCount: 0 }) + const timeline = (await call('GET', `/issues/${apt2.id}/timeline`)).body.items as TimelineItem[] + const status = [...timeline].reverse().find((item) => item.kind === 'activity' && item.activity.field === 'status') + expect(status?.kind === 'activity' && status.activity.actor).toMatchObject({ sub: 'dev-alex', kind: 'person' }) + }) + + test('stalled runs are derived from the lease, refused heartbeats and closed by the next start', async () => { + const apt15 = await issueNamed('APT-15') + const run = apt15.activeRun! + expect((await call('POST', '/__mock/clock', { advanceMs: 11 * MINUTE })).status).toBe(200) + expect((await issueNamed('APT-15')).activeRun?.state).toBe('stalled') + expect((await call('GET', `/runs/${run.id}`)).body.state).toBe('stalled') + expect((await agentCall('astra', 'POST', `/runs/${run.id}/heartbeat`, {})).status).toBe(409) + expect((await agentCall('astra', 'POST', `/runs/${run.id}/finish`, { outcome: 'succeeded', summary: '' })).status).toBe(409) + // The waiting run of APT-27 stalled too: its question is ignored by "Actionable", so opus-ui may restart. + expect(inboxTitles(await inbox('opus-ui'))).toContain('assignment APT-27') + const fresh = await agentCall('opus-ui', 'POST', `/issues/${(await issueNamed('APT-27')).id}/runs`, {}) + expect(fresh.status).toBe(201) + const runs = (await call('GET', '/issues/APT-27/runs')).body.items as Run[] + expect(runs.map((candidate) => [candidate.state, candidate.reason])).toEqual([ + ['running', null], + ['failed', 'lease_expired'], + ]) + expect((await issueNamed('APT-27')).openRequestCount).toBe(0) + expect((await agentsByHandle()).get('astra')!.activeRuns).toBe(0) + // A person cancels a stalled run. + expect((await call('POST', `/runs/${run.id}/cancel`)).body).toMatchObject({ state: 'canceled', reason: 'canceled_by:dev-alex' }) + expect((await call('POST', `/runs/${run.id}/cancel`)).status).toBe(409) + }) + + test('reassigning away from an agent cancels its run and withdraws its requests; disabling cancels every run', async () => { + const apt27 = await issueNamed('APT-27') + const reassigned = (await call('PATCH', `/issues/${apt27.id}`, { assigneeSub: 'dev-sam' })).body as Issue + expect(reassigned).toMatchObject({ assignee: { sub: 'dev-sam', kind: 'person' }, delegator: null, activeRun: null, openRequestCount: 0 }) + const runs = (await call('GET', `/issues/${apt27.id}/runs`)).body.items as Run[] + expect(runs[0]).toMatchObject({ state: 'canceled', reason: 'reassigned' }) + expect(inboxTitles(await inbox())).not.toContain("request Which label should the panel's close button use?") + const fields = ((await call('GET', `/issues/${apt27.id}/timeline`)).body.items as TimelineItem[]).flatMap((item) => (item.kind === 'activity' ? [item.activity.field] : [])) + expect(fields.slice(-2)).toEqual(['assignee', 'delegator']) + + const astra = (await agentsByHandle()).get('astra')! + await as('dev-sam') + expect((await call('PATCH', `/agents/${astra.id}`, { disabled: true })).status).toBe(403) + await as('dev-alex', 'Admin') + expect((await call('PATCH', `/agents/${astra.id}`, { handle: 'astra2' })).body.issues[0].path).toBe('handle') + expect((await call('PATCH', `/agents/${astra.id}`, { disabled: true })).body).toMatchObject({ disabled: true, activeRuns: 0 }) + expect((await call('GET', '/issues/APT-15/runs')).body.items[0]).toMatchObject({ state: 'canceled', reason: 'canceled_by:dev-alex' }) + expect((await issueNamed('APT-15')).assignee?.agent?.disabled).toBe(true) + expect(await agentCall('astra', 'GET', '/inbox')).toMatchObject({ status: 403, body: { error: 'key_subject' } }) + }) + + test('approvals and reviews: people only; unaddressed ones by any person; an open approval blocks a successful finish', async () => { + const apt1 = await issueNamed('APT-1') + const approval = ((await call('GET', `/requests?issue=${apt1.id}`)).body.items as TrackerRequest[])[0]! + expect(approval).toMatchObject({ kind: 'approval', to: null, options: ['approve', 'reject'] }) + expect((await agentCall('astra', 'POST', `/requests/${approval.id}/answer`, { option: 'approve' })).status).toBe(403) + expect((await call('POST', `/requests/${approval.id}/answer`, { body: 'no option' })).body.issues[0].path).toBe('option') + await as('dev-jordan') + expect((await call('POST', `/requests/${approval.id}/answer`, { option: 'reject', body: 'Next sprint.' })).body.answer).toMatchObject({ option: 'reject', by: { sub: 'dev-jordan' } }) + expect(inboxTitles(await inbox('claude'))).toContain('answer Add APT-1 to the current sprint?') + + // The review of APT-16 is Alex's; Sam (not Admin) cannot answer it. + const review = ((await call('GET', '/requests?state=open&to=dev-alex')).body.items as TrackerRequest[]).find((request) => request.kind === 'review')! + await as('dev-sam') + expect((await call('POST', `/requests/${review.id}/answer`, { option: 'approve' })).status).toBe(403) + await as('dev-alex', 'Admin') + expect((await call('POST', `/requests/${review.id}/answer`, { option: 'reject', body: 'Add a test for the refresh path.' })).body.state).toBe('answered') + expect((await issueNamed('APT-16')).statusId).toBe((await statusNamed('In Review')).id) + + const apt15 = await issueNamed('APT-15') + const run = apt15.activeRun! + expect((await agentCall('astra', 'POST', `/issues/${apt15.id}/requests`, { kind: 'approval', title: 'Delete testdata?', options: ['yes'] })).status).toBe(400) + expect((await agentCall('astra', 'POST', `/issues/${apt15.id}/requests`, { kind: 'approval', title: 'Delete testdata?', to: `agent:${(await agentsByHandle()).get('claude')!.id}` })).status).toBe(400) + const ask = (await agentCall('astra', 'POST', `/issues/${apt15.id}/requests`, { kind: 'approval', title: 'Delete testdata?', runId: run.id })).body as TrackerRequest + expect(ask.to?.sub).toBe('dev-alex') + expect((await agentCall('astra', 'POST', `/runs/${run.id}/finish`, { outcome: 'succeeded', summary: 'x' })).status).toBe(409) + expect((await call('POST', `/requests/${ask.id}/withdraw`)).status).toBe(403) + expect((await agentCall('astra', 'POST', `/requests/${ask.id}/withdraw`)).body.state).toBe('withdrawn') + expect((await issueNamed('APT-15')).activeRun?.state).toBe('running') + }) + + test('Idempotency-Key replays the first response; another body is 409', async () => { + const apt3 = await issueNamed('APT-3') + const first = await call('POST', `/issues/${apt3.id}/comments`, { body: 'once' }, { 'Idempotency-Key': 'k-1' }) + const again = await call('POST', `/issues/${apt3.id}/comments`, { body: 'once' }, { 'Idempotency-Key': 'k-1' }) + expect(again).toMatchObject({ status: 201, body: { id: first.body.id } }) + expect(((await call('GET', `/issues/${apt3.id}/timeline`)).body.items as TimelineItem[]).filter((item) => item.kind === 'comment')).toHaveLength(1) + expect((await call('POST', `/issues/${apt3.id}/comments`, { body: 'twice' }, { 'Idempotency-Key': 'k-1' })).status).toBe(409) + // Keys are per actor. + expect((await agentCall('astra', 'POST', `/issues/${apt3.id}/comments`, { body: 'twice' }, { 'Idempotency-Key': 'k-1' })).status).toBe(201) + expect((await call('POST', `/issues/${apt3.id}/comments`, { body: 'x' }, { 'Idempotency-Key': 'k'.repeat(129) })).status).toBe(400) + }) + + test('expectedUpdatedAt: a stale edit is 409 conflict', async () => { + const apt3 = await issueNamed('APT-3') + expect((await call('PATCH', `/issues/${apt3.id}`, { title: 'Fresh', expectedUpdatedAt: apt3.updatedAt })).body.title).toBe('Fresh') + expect(await call('PATCH', `/issues/${apt3.id}`, { title: 'Stale', expectedUpdatedAt: apt3.updatedAt })).toMatchObject({ status: 409, body: { error: 'conflict' } }) + }) + + test('mentions: @handle of an active agent, one row per comment and agent, acknowledged by the agent', async () => { + const apt3 = await issueNamed('APT-3') + const comment = (await call('POST', `/issues/${apt3.id}/comments`, { body: '@claude and @claude, also @nobody and email@astra.dev' })).body + expect(comment.mentions.map((actor: { name: string }) => actor.name)).toEqual(['Claude']) + const mention = (await inbox('claude')).find((item) => item.kind === 'mention') + expect(mention).toMatchObject({ kind: 'mention', issue: { identifier: 'APT-3' }, comment: { id: comment.id } }) + await agentCall('claude', 'POST', '/inbox/ack', { mentions: [comment.id] }) + expect((await inbox('claude')).some((item) => item.kind === 'mention')).toBe(false) + }) + + test('events: ascending from a cursor, `after` omitted starts now', async () => { + const start = (await call('GET', '/events')).body + expect(start.items).toEqual([]) + const apt3 = await issueNamed('APT-3') + await call('PATCH', `/issues/${apt3.id}`, { priority: 'low', title: 'Renamed' }) + await call('POST', `/issues/${apt3.id}/comments`, { body: 'hi' }) + const page = (await call('GET', `/events?after=${start.next}`)).body as { items: TrackerEvent[]; next: number } + expect(page.items.map((event) => [event.type, event.issue?.identifier])).toEqual([ + ['issue.updated', 'APT-3'], + ['comment.created', 'APT-3'], + ]) + expect(page.items[0]!.data).toEqual({ fields: ['title', 'priority'] }) + expect(page.next).toBe(page.items[1]!.seq) + expect((await call('GET', `/events?after=${page.next}`)).body).toEqual({ items: [], next: page.next }) + expect((await call('GET', '/events?limit=501')).status).toBe(400) + }) + + test('agent registry: Admin registers with an immutable unique handle; the guide is Markdown', async () => { + expect((await call('POST', '/agents', { handle: 'Astra', name: 'X', ownerSub: 'dev-alex' })).body.issues[0].path).toBe('handle') + expect((await call('POST', '/agents', { handle: 'astra', name: 'X', ownerSub: 'dev-alex' })).status).toBe(409) + expect((await call('POST', '/agents', { handle: 'scout', name: 'Scout', ownerSub: 'agent:x' })).body.issues[0].path).toBe('ownerSub') + const created = await call('POST', '/agents', { handle: 'scout', name: 'Scout', description: 'Finds flaky tests.', ownerSub: 'dev-jordan' }) + expect(created).toMatchObject({ status: 201, body: { handle: 'scout', owner: { sub: 'dev-jordan', name: 'Jordan Lee' }, activeRuns: 0, openRequests: 0, lastSeenAt: null } }) + expect((await call('PATCH', `/agents/${created.body.id}`, { name: 'Scout 2', ownerSub: 'dev-sam' })).body).toMatchObject({ name: 'Scout 2', owner: { sub: 'dev-sam' } }) + const guide = await call('GET', '/agent-guide') + expect(guide.headers.get('Content-Type')).toContain('text/markdown') + expect(new TextDecoder().decode(guide.body)).toContain('POST /runs/{id}/heartbeat') + }) +}) diff --git a/web/src/dev/mock-tracker.ts b/web/src/dev/mock-tracker.ts index d5712d3..4ceaf17 100644 --- a/web/src/dev/mock-tracker.ts +++ b/web/src/dev/mock-tracker.ts @@ -13,37 +13,58 @@ // on its fourth day with a scope increase and a cancellation, and a planned // one; 17 work items carry a size. The exact fixture (shared authority with // the server seed) is `SPRINT_FIXTURE` below. +// Agents (API.md "Agents"): four registered agents (astra, opus-ui, claude, +// legacy-bot disabled), delegations, runs (running, waiting, stalled, +// succeeded), requests, a mention and two agent-reported issues (APT-41/42), +// all relative to the moment of seeding — the shared fixture is +// `.tmp/agents-ui/fixture.md`, mirrored by `seedAgents` below. Leases are +// real: ten minutes after a reset the live runs turn stalled. // The caller is Alex Chen as Team Admin; MOCK_ROLE=Editor (or Viewer) makes // them a non-admin. `POST /api/tracker/v1/__mock/caller {sub, role?}` switches // the signed-in person (role default Editor); a `sub` outside the seed needs a // `name` and signs in someone who has reported and been assigned nothing. +// A request with `X-Mock-Agent: ` acts as that agent's Access Key +// assertion instead (`X-Mock-Scopes: tracker:read,tracker:write`, the default +// being both): an unknown or disabled handle is 403 `key_subject`. +// `POST /api/tracker/v1/__mock/clock {advanceMs}` moves the mock's clock +// forward (leases expire without waiting). // `POST /api/tracker/v1/__mock/reset` reseeds all state (body // `{"projects":"none"}` reseeds without projects). // MOCK_PROJECTS=none starts with no projects (a workspace from before v0.2, // like the live install). MOCK_DIRECTORY=absent makes `GET /people` answer // `source: unavailable`. The issue cursor is base64url(offset), opaque to the SPA. +import { AsyncLocalStorage } from 'node:async_hooks' import type { Activity, ActivityField, + Actor, + Agent, + AgentCompletion, ApiError, Attachment, Burndown, Comment, + EventType, Filter, GroupBy, + InboxItem, Issue, IssueRef, IssueSummary, IssueType, Label, LabelColor, + Link, Me, Person, Priority, Progress, Project, Report, + RequestKind, + RequestState, Role, + Run, Size, Sort, Sprint, @@ -54,6 +75,8 @@ import type { StatusCategory, Tally, TimelineItem, + TrackerEvent, + TrackerRequest, Unit, Velocity, VelocityEntry, @@ -61,6 +84,36 @@ import type { ViewLayout, Workspace, } from '../api/tracker' +import { + ACCESS_KEY_SCOPES, + AGENT_COMPLETIONS, + AGENT_DESCRIPTION_MAX_BYTES, + AGENT_HANDLE_PATTERN, + AGENT_NAME_MAX, + agentIdOf, + agentSub, + canAnswer, + canCancelRun, + compareActionable, + DECISION_OPTIONS, + deriveRunState, + IDEMPOTENCY_KEY_MAX, + isActionable, + isAddressedTo, + isLiveRun, + isTerminalRun, + LEASE_MS, + LINK_TITLE_MAX, + maySetCompleted, + parseMentions, + REQUEST_BODY_MAX_BYTES, + REQUEST_OPTIONS_MAX, + REQUEST_TITLE_MAX, + RUN_LINKS_MAX, + RUN_SUMMARY_MAX_BYTES, + RUN_TEXT_MAX, + type StoredRunState, +} from '../model/agents' import { ATTACHMENT_MAX_BYTES, ATTACHMENT_TYPES, @@ -137,6 +190,10 @@ const FILTER_KEYS: Record = { epic: true, story: true, sprint: true, + assigneeKind: true, + agent: true, + run: true, + request: true, } const VELOCITY_LIMIT_DEFAULT = 8 const VELOCITY_LIMIT_MAX = 26 @@ -166,6 +223,9 @@ export const MOCK_PEOPLE = { jordan: { sub: 'dev-jordan', name: 'Jordan Lee' }, } as const satisfies Record +/** A person as an API Actor. */ +const personActor = (person: Person): Actor => ({ ...person, kind: 'person' }) + export const MOCK_WORKSPACE_ID = 'pj-mock' type StoredIssue = { @@ -176,8 +236,10 @@ type StoredIssue = { type: IssueType priority: Priority statusId: string - assignee: Person | null - reporter: Person + /** Agent actors are stored by `sub` and resolved at read time (name, owner and `disabled` stay current). */ + assignee: Actor | null + reporter: Actor + delegator: Person | null labelIds: string[] projectId: string | null parentId: string | null @@ -190,7 +252,30 @@ type StoredIssue = { estimate: Size | null sprintId: string | null } -type StoredComment = Comment & { deleted: boolean } +type StoredComment = Omit & { deleted: boolean } +type StoredAgent = { id: string; handle: string; name: string; description: string; owner: Person; disabled: boolean; createdAt: string; updatedAt: string; lastSeenAt: string | null } +/** `state` never holds `stalled`: it is derived from `leaseExpiresAt` on read, as on the server. */ +type StoredRun = Omit & { issueId: string; agentId: string; state: StoredRunState } +type StoredRequest = { + id: string + issueId: string + kind: RequestKind + fromSub: string + toSub: string | null + title: string + body: string + options: string[] + runId: string | null + state: RequestState + answer: { option: string | null; body: string; bySub: string; at: string } | null + createdAt: string + /** The requester acknowledged the answer in its inbox. */ + answerAcked: boolean +} +type StoredMention = { commentId: string; issueId: string; targetSub: string; acked: boolean } +type StoredIdempotency = { body: string; status: number; response: string; at: number } +/** Who a request acts as: the signed-in person, or an agent's Access Key assertion with its scopes. */ +type Caller = { actor: Actor; role: Role; agent: StoredAgent | null; scopes: readonly string[] } type StoredAttachment = Attachment & { bytes: Uint8Array; deleted: boolean } type StoredProject = { id: string; name: string; description: string; color: LabelColor; archivedAt: string | null; createdAt: string; updatedAt: string } type Block = { blockerId: string; blockedId: string } @@ -346,7 +431,7 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { const projects: StoredProject[] = withProjects ? PROJECT_SEED.map(([name, color]) => ({ id: ulid(T0, seq++), name, description: '', color, archivedAt: null, createdAt: at(0), updatedAt: at(0) })) : [] - const people = [MOCK_PEOPLE.alex, MOCK_PEOPLE.sam, MOCK_PEOPLE.jordan] + const people = [MOCK_PEOPLE.alex, MOCK_PEOPLE.sam, MOCK_PEOPLE.jordan].map(personActor) const issues: StoredIssue[] = [] const activities: Activity[] = [] SEED_TITLES.forEach((title, i) => { @@ -363,6 +448,7 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { statusId: status.id, assignee: people[(i + 1) % people.length]!, reporter: people[i % people.length]!, + delegator: null, labelIds: [labels[i % labels.length]!.id], projectId: projects[seedProjectIndex(i + 1) ?? -1]?.id ?? null, parentId: null, @@ -402,7 +488,8 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { priority: 'medium', statusId: status.id, assignee: null, - reporter: MOCK_PEOPLE.alex, + reporter: personActor(MOCK_PEOPLE.alex), + delegator: null, labelIds: [], projectId: null, parentId, @@ -449,13 +536,13 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { }) ) const views: (View & { ownerSub: string })[] = [ - { id: ulid(T0, seq++), name: 'Bugs', owner: MOCK_PEOPLE.alex, ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'list', groupBy: 'none', filter: { type: ['bug'] }, sort: 'updated', position: 0, createdAt: at(0), updatedAt: at(0) }, - { id: ulid(T0, seq++), name: 'My issues', owner: MOCK_PEOPLE.alex, ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'list', groupBy: 'none', filter: { assignee: ['me'] }, sort: 'updated', position: 1, createdAt: at(0), updatedAt: at(0) }, - { id: ulid(T0, seq++), name: 'By epic', owner: MOCK_PEOPLE.alex, ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'board', groupBy: 'epic', filter: {}, sort: 'updated', position: 2, createdAt: at(0), updatedAt: at(0) }, + { id: ulid(T0, seq++), name: 'Bugs', owner: personActor(MOCK_PEOPLE.alex), ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'list', groupBy: 'none', filter: { type: ['bug'] }, sort: 'updated', position: 0, createdAt: at(0), updatedAt: at(0) }, + { id: ulid(T0, seq++), name: 'My issues', owner: personActor(MOCK_PEOPLE.alex), ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'list', groupBy: 'none', filter: { assignee: ['me'] }, sort: 'updated', position: 1, createdAt: at(0), updatedAt: at(0) }, + { id: ulid(T0, seq++), name: 'By epic', owner: personActor(MOCK_PEOPLE.alex), ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'board', groupBy: 'epic', filter: {}, sort: 'updated', position: 2, createdAt: at(0), updatedAt: at(0) }, ] const role = process.env.MOCK_ROLE === 'Editor' || process.env.MOCK_ROLE === 'Viewer' ? (process.env.MOCK_ROLE as Role) : 'Admin' return { - workspace: { id: MOCK_WORKSPACE_ID, key: 'APT', name: MOCK_WORKSPACE_ID, sprintLengthWeeks: 1 as SprintLength, timezone: DEFAULT_TIMEZONE, createdAt: at(0), updatedAt: at(0) }, + workspace: { id: MOCK_WORKSPACE_ID, key: 'APT', name: MOCK_WORKSPACE_ID, sprintLengthWeeks: 1 as SprintLength, timezone: DEFAULT_TIMEZONE, agentCompletion: 'review' as AgentCompletion, createdAt: at(0), updatedAt: at(0) }, statuses, labels, projects, @@ -470,19 +557,223 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { caller: MOCK_PEOPLE.alex as Person, role, clock: T0 + 100 * HOUR, + /** Added to the wall clock (`POST /__mock/clock`). */ + offset: 0, seq: seq + 1000, + agents: [] as StoredAgent[], + runs: [] as StoredRun[], + requests: [] as StoredRequest[], + mentions: [] as StoredMention[], + events: [] as TrackerEvent[], + eventSeq: 0, + idempotency: new Map(), } } -let state = seedTracker() +type MockState = ReturnType + +/** One agent of the fixture (`.tmp/agents-ui/fixture.md`, "Agents"); times are offsets from the moment of seeding. */ +type AgentFixture = { handle: string; name: string; owner: Person; disabled: boolean; description: string; created: number; updated: number; seen: number } +const MINUTE = 60_000 +const DAY = 24 * HOUR +export const AGENT_FIXTURE = { + agents: [ + { handle: 'astra', name: 'Astra', owner: MOCK_PEOPLE.sam, disabled: false, description: 'Backend implementer. Go handlers, store queries, migrations and their tests. Delegate issues with a clear acceptance check.', created: -14 * DAY, updated: -14 * DAY, seen: -2 * MINUTE }, + { handle: 'opus-ui', name: 'Opus UI', owner: MOCK_PEOPLE.alex, disabled: false, description: 'UI implementer. React screens, copy and accessibility in the SPA. Delegate issues that include the expected screen or a screenshot.', created: -7 * DAY, updated: -7 * DAY, seen: -1 * MINUTE }, + { handle: 'claude', name: 'Claude', owner: MOCK_PEOPLE.jordan, disabled: false, description: 'Planner and triage. Reads new reports, finds duplicates, proposes priority and sprint. Does not change code.', created: -14 * DAY, updated: -14 * DAY, seen: -2 * HOUR }, + { handle: 'legacy-bot', name: 'Legacy bot', owner: MOCK_PEOPLE.alex, disabled: true, description: 'Old nightly triage script. Replaced by claude.', created: -60 * DAY, updated: -30 * DAY, seen: -32 * DAY }, + ] as AgentFixture[], + /** [issue number, agent handle, delegator, assigned at] */ + delegations: [ + [15, 'astra', MOCK_PEOPLE.alex, -40 * MINUTE], + [27, 'opus-ui', MOCK_PEOPLE.alex, -45 * MINUTE], + [9, 'astra', MOCK_PEOPLE.sam, -4 * HOUR], + [16, 'astra', MOCK_PEOPLE.alex, -3 * HOUR], + [4, 'astra', MOCK_PEOPLE.sam, -27 * HOUR], + [21, 'claude', MOCK_PEOPLE.alex, -4 * HOUR], + [13, 'opus-ui', MOCK_PEOPLE.alex, -1 * DAY], + [26, 'opus-ui', MOCK_PEOPLE.jordan, -1 * DAY], + [19, 'astra', MOCK_PEOPLE.sam, -2 * DAY], + ] as [number, string, Person, number][], + reviewSummary16: [ + 'The CLI refreshed its login only after a request failed with 401, so the first command after one hour always failed.', + '', + '- Refresh the token when less than 5 minutes of its lifetime remain.', + '- Retry once on 401 after a refresh.', + '- Added `TestLoginRefreshBeforeExpiry`.', + ].join('\n'), + reviewSummary4: 'Status reads now bypass the list cache after a status change. Added a regression test for the list endpoint.', +} + +/** + * The agents fixture (`.tmp/agents-ui/fixture.md`), applied after the rest of + * the seed: agents, delegations, APT-41/42 reported by agents, runs, requests, + * a comment with a mention. `at(offset)` is relative to the seeding instant. + */ +function seedAgents(seeded: MockState) { + const base = Math.max(Date.now(), seeded.clock) + const at = (offset: number) => new Date(base + offset).toISOString() + const id = (offset: number) => ulid(base + offset, seeded.seq++) + const issueNo = (number: number) => seeded.issues.find((issue) => issue.number === number)! + const agents = AGENT_FIXTURE.agents.map((fixture): StoredAgent => ({ + id: id(fixture.created), + handle: fixture.handle, + name: fixture.name, + description: fixture.description, + owner: fixture.owner, + disabled: fixture.disabled, + createdAt: at(fixture.created), + updatedAt: at(fixture.updated), + lastSeenAt: at(fixture.seen), + })) + seeded.agents = agents + const agent = (handle: string) => agents.find((candidate) => candidate.handle === handle)! + const stub = (handle: string): Actor => ({ sub: agentSub(agent(handle).id), name: agent(handle).name, kind: 'agent' }) + for (const [number, handle, delegator, offset] of AGENT_FIXTURE.delegations) { + const issue = issueNo(number) + const time = at(offset) + const actor = personActor(delegator) + seeded.activities.push({ id: id(offset), issueId: issue.id, actor, field: 'assignee', from: issue.assignee, to: stub(handle), createdAt: time }) + seeded.activities.push({ id: id(offset), issueId: issue.id, actor, field: 'delegator', from: null, to: delegator, createdAt: time }) + Object.assign(issue, { assignee: stub(handle), delegator, updatedAt: time }) + } + // APT-41 and APT-42: reported by agents, appended after the existing issues. + const backlog = seeded.statuses.find((status) => status.name === 'Backlog')! + const todo = seeded.statuses.find((status) => status.name === 'Todo')! + const platformApi = seeded.projects.find((project) => project.name === 'Platform API')?.id ?? null + const reported = (title: string, type: IssueType, priority: Priority, statusId: string, reporter: string, offset: number, description: string, extra: Partial) => { + const time = at(offset) + const issue: StoredIssue = { + id: id(offset), + number: seeded.issues.length + 1, + title, + description, + type, + priority, + statusId, + assignee: null, + reporter: stub(reporter), + delegator: null, + labelIds: [], + projectId: platformApi, + parentId: null, + dueOn: null, + report: null, + createdAt: time, + updatedAt: time, + completedAt: null, + deleted: false, + estimate: null, + sprintId: null, + ...extra, + } + seeded.issues.push(issue) + seeded.activities.push({ id: id(offset), issueId: issue.id, actor: issue.reporter, field: 'created', from: null, to: null, createdAt: time }) + return issue + } + const apt41 = reported('Three reports describe the same stale status', 'task', 'high', backlog.id, 'claude', -5 * HOUR, 'APT-4, APT-22 and APT-28 all show a status that lags behind the real one by one refresh. Proposal: keep APT-4 and close the other two as duplicates.', {}) + reported('Flaky test: lease renewal in store/runs_test', 'bug', 'medium', todo.id, 'astra', -3 * HOUR, 'TestHeartbeatRenewsLease fails about 1 in 30 runs on CI.', { + assignee: stub('astra'), + delegator: agent('astra').owner, + report: { environment: 'local', surface: 'platform-api', version: '0.1.13', steps: 'go test -count=30 ./cmd/server/internal/store -run TestHeartbeatRenewsLease', expected: 'All runs pass.', actual: 'One run fails with lease_expired.' }, + }) + const run = (number: number, handle: string, state: StoredRunState, session: string, note: string, started: number, heartbeat: number, finished: number | null, summary = '', links: Link[] = []): StoredRun => { + const stored: StoredRun = { + id: id(started), + issueId: issueNo(number).id, + agentId: agent(handle).id, + state, + reason: null, + session, + note, + summary, + links, + startedAt: at(started), + heartbeatAt: at(heartbeat), + leaseExpiresAt: at(heartbeat + LEASE_MS), + finishedAt: finished === null ? null : at(finished), + } + seeded.runs.push(stored) + return stored + } + const run15 = run(15, 'astra', 'running', 'astra · lane-2', 'running go test ./cmd/server/... after removing 14 unused fixtures', -35 * MINUTE, -2 * MINUTE, null) + const run27 = run(27, 'opus-ui', 'waiting', 'opus-ui · a11y pass', 'waiting for a decision on the close-button label', -40 * MINUTE, -1 * MINUTE, null) + run(9, 'astra', 'running', 'astra · lane-1', 'comparing the Gateway page with the current kubeconfig flow', -3 * HOUR, -52 * MINUTE, null) + const run16 = run(16, 'astra', 'succeeded', 'astra · lane-2', 'opening the pull request', -2 * HOUR, -25 * MINUTE, -25 * MINUTE, AGENT_FIXTURE.reviewSummary16, [ + { kind: 'pr', url: 'https://github.com/appthrust/tracker/pull/142', title: 'Refresh the CLI login before the token expires' }, + ]) + const run4 = run(4, 'astra', 'succeeded', 'astra · lane-1', 'opening the pull request', -26 * HOUR, -24 * HOUR, -24 * HOUR, AGENT_FIXTURE.reviewSummary4, [ + { kind: 'pr', url: 'https://github.com/appthrust/tracker/pull/138', title: 'Invalidate the status cache on change' }, + ]) + const subOf = (handle: string) => agentSub(agent(handle).id) + const request = (number: number, kind: RequestKind, fromSub: string, toSub: string | null, runId: string | null, title: string, created: number, extra: Partial = {}): StoredRequest => { + const stored: StoredRequest = { + id: id(created), + issueId: issueNo(number).id, + kind, + fromSub, + toSub, + title, + body: '', + options: kind === 'question' ? [] : [...DECISION_OPTIONS], + runId, + state: 'open', + answer: null, + createdAt: at(created), + answerAcked: false, + ...extra, + } + seeded.requests.push(stored) + return stored + } + request(27, 'question', subOf('opus-ui'), MOCK_PEOPLE.alex.sub, run27.id, "Which label should the panel's close button use?", -8 * MINUTE, { + body: 'The panel\'s close button has no visible text. "Close" matches the rest of the app; "Dismiss" is what the screen reader announces today.', + options: ['Close', 'Dismiss', 'Keep both: visible "Close", spoken "Dismiss"'], + }) + request(15, 'question', subOf('astra'), MOCK_PEOPLE.alex.sub, run15.id, 'Delete the fixtures under testdata/legacy too?', -28 * MINUTE, { + options: ['Yes, delete them', 'No, keep them'], + state: 'answered', + answer: { option: 'Yes, delete them', body: 'They are unused since 0.1.7.', bySub: MOCK_PEOPLE.alex.sub, at: at(-20 * MINUTE) }, + answerAcked: true, + }) + request(16, 'review', subOf('astra'), MOCK_PEOPLE.alex.sub, run16.id, `Review: ${issueNo(16).title}`, -25 * MINUTE, { body: run16.summary }) + request(4, 'review', subOf('astra'), MOCK_PEOPLE.sam.sub, run4.id, `Review: ${issueNo(4).title}`, -24 * HOUR, { + body: run4.summary, + state: 'answered', + answer: { option: 'reject', body: 'Still stale right after a status change: the 304 path keeps the old ETag. Please add a test for it.', bySub: MOCK_PEOPLE.sam.sub, at: at(-20 * HOUR) }, + }) + request(1, 'approval', subOf('claude'), null, null, 'Add APT-1 to the current sprint?', -90 * MINUTE, { body: 'Two people lost their filters on appthrust.dev this week. It is urgent but sits in the backlog without a sprint.' }) + request(21, 'question', MOCK_PEOPLE.alex.sub, subOf('claude'), null, 'Which open bugs look like duplicates of APT-22?', -3 * HOUR, { + state: 'answered', + answer: { option: null, body: 'APT-4 and APT-28 describe the same stale-cache symptom; I filed APT-41 to merge them.', bySub: subOf('claude'), at: at(-2 * HOUR) }, + }) + const comment = (number: number, author: Actor, offset: number, text: string) => { + const stored: StoredComment = { id: id(offset), issueId: issueNo(number).id, author, body: text, createdAt: at(offset), editedAt: null, deleted: false } + seeded.comments.push(stored) + return stored + } + const mention = comment(22, personActor(MOCK_PEOPLE.sam), -1 * HOUR, '@astra could you check whether the cursor encoding changed with APT-15? The skipped rows start after page 2.') + seeded.mentions.push({ commentId: mention.id, issueId: mention.issueId, targetSub: subOf('astra'), acked: false }) + comment(apt41.number, stub('claude'), -5 * HOUR, 'Filed from triage. Evidence: the three reports name the same endpoint and the same one-refresh lag.') + return seeded +} + +let state = seedAgents(seedTracker()) + +/** The mock's wall clock: real time plus the `__mock/clock` offset. */ +const wallClock = () => Date.now() + state.offset /** Strictly increasing wall-clock time, so two writes in one millisecond still order. */ function now(): string { - state.clock = Math.max(Date.now(), state.clock + 1) + state.clock = Math.max(wallClock(), state.clock + 1) return new Date(state.clock).toISOString() } const nextId = () => ulid(state.clock, state.seq++) +const callerContext = new AsyncLocalStorage() +/** The caller of the request being handled (`trackerRoutes` runs each request inside its own context, so concurrent requests never mix). */ +const who = (): Caller => callerContext.getStore() ?? { actor: personActor(state.caller), role: state.role, agent: null, scopes: ACCESS_KEY_SCOPES } + const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) const fail = (status: number, error: string, message: string, issues?: ApiError['issues']) => json({ error, message, ...(issues ? { issues } : {}) } satisfies ApiError, status) const notFound = () => fail(404, 'not_found', 'The requested resource was not found') @@ -500,7 +791,8 @@ async function body(request: Request): Promise | undefin } } -const isAdmin = () => state.role === 'Admin' +/** Signed-in Admins only: an agent's key acts with role Viewer (API.md "Access Keys"). */ +const isAdmin = () => who().agent === null && who().role === 'Admin' const bytes = (text: string) => new TextEncoder().encode(text).length const isStringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every((item) => typeof item === 'string') const live = () => state.issues.filter((issue) => !issue.deleted) @@ -627,8 +919,12 @@ function summary(issue: StoredIssue): IssueSummary { type: issue.type, priority: issue.priority, statusId: issue.statusId, - assignee: issue.assignee, - reporter: issue.reporter, + assignee: issue.assignee ? actorView(issue.assignee) : null, + reporter: actorView(issue.reporter), + // People on the wire carry `kind`, as the server writes every Person-valued field (delegator, owner). + delegator: issue.delegator ? personActor(issue.delegator) : null, + activeRun: activeRunOf(issue.id) ? runView(activeRunOf(issue.id)!) : null, + openRequestCount: state.requests.filter((request) => request.issueId === issue.id && request.state === 'open').length, labelIds: [...issue.labelIds], projectId: issue.projectId, parent: parent ? ref(parent) : null, @@ -672,8 +968,104 @@ function personFor(sub: string): Person { return Object.values(MOCK_PEOPLE).find((person) => person.sub === sub) ?? { sub, name: sub } } -function record(issue: StoredIssue, field: ActivityField, from: unknown, to: unknown, createdAt: string) { - state.activities.push({ id: nextId(), issueId: issue.id, actor: state.caller, field, from, to, createdAt }) +function record(issue: StoredIssue, field: ActivityField, from: unknown, to: unknown, createdAt: string, actor: Actor = who().actor) { + state.activities.push({ id: nextId(), issueId: issue.id, actor, field, from, to, createdAt }) +} + +// --- agents (API.md "Agents") -------------------------------------------------------- + +const agentById = (id: string | null) => (id ? state.agents.find((agent) => agent.id === id) : undefined) +const agentBySub = (sub: string) => agentById(agentIdOf(sub)) + +function agentActor(agent: StoredAgent): Actor { + return { sub: agentSub(agent.id), name: agent.name, kind: 'agent', agent: { id: agent.id, handle: agent.handle, owner: personActor(agent.owner), disabled: agent.disabled } } +} + +/** A stored actor as readers see it now: agents resolve to their current name, owner and state; people keep their stored name. */ +function actorView(actor: Actor): Actor { + const agent = agentBySub(actor.sub) + if (agent) return agentActor(agent) + const { agent: _agent, ...person } = actor + return { ...person, kind: 'person' } +} + +/** The Actor for a subject: an agent, else a person (seeded name or the subject itself). */ +function actorFor(sub: string): Actor { + const agent = agentBySub(sub) + return agent ? agentActor(agent) : personActor(personFor(sub)) +} + +function agentView(agent: StoredAgent): Agent { + const runs = state.runs.filter((run) => run.agentId === agent.id) + return { + ...agent, + owner: personActor(agent.owner), + activeRuns: runs.filter((run) => isLiveRun({ state: derived(run) })).length, + openRequests: state.requests.filter((request) => request.fromSub === agentSub(agent.id) && request.state === 'open').length, + } +} + +/** The run's state as readers see it (`stalled` once the lease has passed). */ +const derived = (run: StoredRun) => deriveRunState(run.state, run.leaseExpiresAt, wallClock()) +const isStalledRun = (run: StoredRun) => derived(run) === 'stalled' +/** The issue's non-terminal run (live or stalled), if any. */ +const activeRunOf = (issueId: string) => state.runs.find((run) => run.issueId === issueId && !isTerminalRun(run.state)) + +function runView(run: StoredRun): Run { + const { issueId, agentId, ...rest } = run + const issue = state.issues.find((candidate) => candidate.id === issueId)! + return { ...rest, issue: ref(issue), agent: agentActor(agentById(agentId)!), state: derived(run), links: run.links.map((link) => ({ ...link })) } +} + +function requestView(request: StoredRequest): TrackerRequest { + const issue = state.issues.find((candidate) => candidate.id === request.issueId)! + return { + id: request.id, + issue: ref(issue), + kind: request.kind, + from: actorFor(request.fromSub), + to: request.toSub === null ? null : actorFor(request.toSub), + title: request.title, + body: request.body, + options: [...request.options], + runId: request.runId, + state: request.state, + answer: request.answer ? { option: request.answer.option, body: request.answer.body, by: actorFor(request.answer.bySub), at: request.answer.at } : null, + createdAt: request.createdAt, + } +} + +function commentView({ deleted: _deleted, ...comment }: StoredComment): Comment { + return { ...comment, author: actorView(comment.author), mentions: state.mentions.filter((mention) => mention.commentId === comment.id).map((mention) => actorFor(mention.targetSub)) } +} + +/** Appends one Event in the transaction of the write it describes (`seq` from the workspace counter). */ +function emit(type: EventType, issue: StoredIssue | null, data: unknown, at: string, actor: Actor = who().actor) { + state.eventSeq += 1 + state.events.push({ seq: state.eventSeq, at, issue: issue ? ref(issue) : null, actor: actorView(actor), type, data }) +} + +/** Withdraws the run's open requests (whatever ends a run without success, and a successful finish for its questions). */ +function withdrawRunRequests(run: StoredRun, time: string, kinds: readonly RequestKind[] = ['question', 'approval', 'review']) { + const issue = issueById(run.issueId) ?? state.issues.find((candidate) => candidate.id === run.issueId)! + for (const request of state.requests.filter((candidate) => candidate.runId === run.id && candidate.state === 'open' && kinds.includes(candidate.kind))) { + request.state = 'withdrawn' + emit('request.withdrawn', issue, request.id, time) + } +} + +/** Ends a non-terminal run without success (`canceled` or `failed`) and withdraws its open requests. */ +function endRun(run: StoredRun, state_: 'canceled' | 'failed', reason: string, time: string) { + const issue = state.issues.find((candidate) => candidate.id === run.issueId)! + Object.assign(run, { state: state_, reason, finishedAt: time }) + withdrawRunRequests(run, time) + emit(state_ === 'canceled' ? 'run.canceled' : 'run.finished', issue, run.id, time) +} + +/** After a request on the run closes: a waiting run with no open request left is running again. */ +function resumeIfClear(runId: string | null) { + const run = state.runs.find((candidate) => candidate.id === runId) + if (run?.state === 'waiting' && !state.requests.some((request) => request.runId === run.id && request.state === 'open')) run.state = 'running' } function closedStatus(statusId: string): boolean { @@ -807,8 +1199,16 @@ function parseFilter(raw: string | null): Filter | Problem { } const enumProblem = (key: string, allowed: readonly string[]) => (filter[key] as string[] | undefined)?.some((value) => !allowed.includes(value)) ? { path: `filter.${key}`, message: `${key} must be one of ${allowed.join(', ')}` } : undefined - const problem = enumProblem('category', CATEGORIES) ?? enumProblem('type', ISSUE_TYPES) ?? enumProblem('priority', PRIORITIES) ?? enumProblem('surface', SURFACES) + const problem = + enumProblem('category', CATEGORIES) ?? + enumProblem('type', ISSUE_TYPES) ?? + enumProblem('priority', PRIORITIES) ?? + enumProblem('surface', SURFACES) ?? + enumProblem('assigneeKind', ['person', 'agent']) ?? + enumProblem('run', ['active', 'stalled', 'none']) ?? + enumProblem('request', ['open', 'mine']) if (problem) return problem + if ((filter.agent as string[] | undefined)?.some((value) => !ULID_PATTERN.test(value))) return { path: 'filter.agent', message: 'agent must list agent ids' } const reporter = filter.reporter as string[] | undefined if (reporter && (reporter.length > REPORTER_FILTER_MAX || reporter.some((value) => value.length === 0 || value.length > 4096))) return { path: 'filter.reporter', message: `reporter must list at most ${REPORTER_FILTER_MAX} subjects of 1 to 4096 characters` } @@ -840,13 +1240,43 @@ function listIssues(url: URL): Response { const descriptions = new Map(state.issues.map((issue) => [issue.id, issue.description])) const matching = live() .map(summary) - .filter((issue) => matchesFilter(issue, filter, { me: state.caller.sub, statuses: state.statuses, description: (candidate) => descriptions.get(candidate.id) ?? '', activeSprintId: activeSprint()?.id ?? null })) + .filter((issue) => + matchesFilter(issue, filter, { + me: who().actor.sub, + statuses: state.statuses, + description: (candidate) => descriptions.get(candidate.id) ?? '', + activeSprintId: activeSprint()?.id ?? null, + raisedOpenRequest: (candidate) => state.requests.some((stored) => stored.issueId === candidate.id && stored.state === 'open' && stored.fromSub === who().actor.sub), + }) + ) .sort(compareIssues(sort)) const page = matching.slice(offset, offset + limit) const next = offset + limit < matching.length ? Buffer.from(String(offset + limit), 'utf8').toString('base64url') : null return json({ items: page, nextCursor: next }) } +const personOf = ({ kind: _kind, agent: _agent, ...person }: Actor): Person => person + +/** + * `assigneeSub` on an issue write: a person's subject, or `agent:` of an + * active agent (unknown or disabled → 400). An agent assigns only itself, on + * issues it reported (403). Assigning an agent makes the delegator the person + * who assigned, or the assigning agent's owner. + */ +function resolveAssignee(sub: string, reporterSub: string): { assignee: Actor; delegator: Person | null } | Response { + const caller = who() + const id = agentIdOf(sub) + if (id === null) return { assignee: personActor(personFor(sub)), delegator: null } + const agent = agentById(id) + if (!agent) return invalid('assigneeSub', 'unknown agent') + if (agent.disabled) return invalid('assigneeSub', 'the agent is disabled') + if (caller.agent && (caller.agent.id !== agent.id || reporterSub !== caller.actor.sub)) return forbidden() + return { assignee: { sub, name: agent.name, kind: 'agent' }, delegator: caller.agent ? caller.agent.owner : personOf(caller.actor) } +} + +/** An agent setting a completed status under the `review` policy (403). */ +const completionRefused = (statusId: string) => who().agent !== null && categoryOf(statusId) === 'completed' && !maySetCompleted('agent', state.workspace.agentCompletion) + async function createIssue(request: Request): Promise { const input = await body(request) if (!input) return invalid('', 'A JSON object is required') @@ -864,6 +1294,9 @@ async function createIssue(request: Request): Promise { const statusId = typeof input.statusId === 'string' ? input.statusId : backlog.id if (!state.statuses.some((status) => status.id === statusId)) return invalid('statusId', 'unknown status') if (input.assigneeSub !== undefined && input.assigneeSub !== null && typeof input.assigneeSub !== 'string') return invalid('assigneeSub', 'assigneeSub must be a string') + if (completionRefused(statusId)) return forbidden() + const assigned = typeof input.assigneeSub === 'string' ? resolveAssignee(input.assigneeSub, who().actor.sub) : { assignee: null, delegator: null } + if (assigned instanceof Response) return assigned if (input.labelIds !== undefined && (!isStringArray(input.labelIds) || input.labelIds.some((id) => !state.labels.some((label) => label.id === id)))) return invalid('labelIds', 'unknown label') if (input.parentId !== undefined && input.parentId !== null && (typeof input.parentId !== 'string' || !issueById(input.parentId))) return invalid('parentId', 'unknown parent') const parent = issueById((input.parentId as string | null | undefined) ?? null) @@ -889,8 +1322,9 @@ async function createIssue(request: Request): Promise { type, priority: (input.priority as Priority | undefined) ?? 'none', statusId, - assignee: typeof input.assigneeSub === 'string' ? personFor(input.assigneeSub) : null, - reporter: state.caller, + assignee: assigned.assignee, + reporter: who().actor, + delegator: assigned.delegator, labelIds: [...new Set((input.labelIds as string[] | undefined) ?? [])], projectId: typeof input.projectId === 'string' ? input.projectId : null, parentId: (input.parentId as string | undefined) ?? null, @@ -905,6 +1339,7 @@ async function createIssue(request: Request): Promise { } state.issues.push(issue) record(issue, 'created', null, null, time) + emit('issue.created', issue, issue.id, time) writeLedger(issue.id, { sprintId: null, size: null, category: undefined, deleted: false }, standingOf(issue), time) return json(full(issue), 201) } @@ -912,9 +1347,16 @@ async function createIssue(request: Request): Promise { async function updateIssue(issue: StoredIssue, request: Request): Promise { const input = await body(request) if (!input) return invalid('', 'A JSON object is required') - const known = ['title', 'description', 'type', 'priority', 'statusId', 'assigneeSub', 'labelIds', 'parentId', 'blocks', 'dueOn', 'report', 'projectId', 'estimate', 'sprintId'] + const known = ['title', 'description', 'type', 'priority', 'statusId', 'assigneeSub', 'labelIds', 'parentId', 'blocks', 'dueOn', 'report', 'projectId', 'estimate', 'sprintId', 'expectedUpdatedAt'] const unknownKey = Object.keys(input).find((key) => !known.includes(key)) if (unknownKey) return invalid(unknownKey, `unknown field ${unknownKey}`) + // An agent edits an issue's fields only as its assignee or reporter. + const caller = who() + if (caller.agent && issue.assignee?.sub !== caller.actor.sub && issue.reporter.sub !== caller.actor.sub) return forbidden() + if ('expectedUpdatedAt' in input) { + if (typeof input.expectedUpdatedAt !== 'string') return invalid('expectedUpdatedAt', 'expectedUpdatedAt must be an RFC 3339 timestamp') + if (input.expectedUpdatedAt !== issue.updatedAt) return conflict('the issue changed since it was read; reload it and apply the change again') + } if ('title' in input) { const problem = titleProblem(input.title) if (problem) return invalid(problem.path, problem.message) @@ -923,7 +1365,11 @@ async function updateIssue(issue: StoredIssue, request: Request): Promise status.id === input.statusId)) return invalid('statusId', 'unknown status') + if ('statusId' in input && input.statusId !== issue.statusId && completionRefused(input.statusId as string)) return forbidden() if ('assigneeSub' in input && input.assigneeSub !== null && typeof input.assigneeSub !== 'string') return invalid('assigneeSub', 'assigneeSub must be a string or null') + const assigneeChanged = 'assigneeSub' in input && (input.assigneeSub ?? null) !== (issue.assignee?.sub ?? null) + const assigned = !assigneeChanged ? undefined : typeof input.assigneeSub === 'string' ? resolveAssignee(input.assigneeSub, issue.reporter.sub) : { assignee: null, delegator: null } + if (assigned instanceof Response) return assigned if ('labelIds' in input && (!isStringArray(input.labelIds) || input.labelIds.some((id) => !state.labels.some((label) => label.id === id)))) return invalid('labelIds', 'unknown label') if ('parentId' in input && input.parentId !== null) { if (typeof input.parentId !== 'string' || !issueById(input.parentId)) return invalid('parentId', 'unknown parent') @@ -977,10 +1423,10 @@ async function updateIssue(issue: StoredIssue, request: Request): Promise { record(issue, field, from, to, time) - changed = true + fields.push(field) } if ('title' in input && (input.title as string).trim() !== issue.title) { change('title', issue.title, (input.title as string).trim()) @@ -1007,10 +1453,16 @@ async function updateIssue(issue: StoredIssue, request: Request): Promise 0) { + issue.updatedAt = time + emit('issue.updated', issue, { fields: [...new Set(fields)] }, time) + } return json(full(issue)) } +/** An activity as readers see it: the actor, and assignee values, resolved to current agent names and state. */ +function activityView(activity: Activity): Activity { + const resolve = (value: unknown) => (activity.field === 'assignee' && value && typeof value === 'object' ? actorView(value as Actor) : value) + return { ...activity, actor: actorView(activity.actor), from: resolve(activity.from), to: resolve(activity.to) } +} + +/** Activities, comments, runs (at `startedAt`) and requests (at `createdAt`), ascending. */ function timeline(issue: StoredIssue): Response { - const items: TimelineItem[] = [ - ...state.activities.filter((activity) => activity.issueId === issue.id).map((activity): TimelineItem => ({ kind: 'activity', activity })), - ...state.comments - .filter((comment) => comment.issueId === issue.id && !comment.deleted) - .map(({ deleted: _deleted, ...comment }): TimelineItem => ({ kind: 'comment', comment })), + const stamped: [string, string, TimelineItem][] = [ + ...state.activities.filter((activity) => activity.issueId === issue.id).map((activity): [string, string, TimelineItem] => [activity.createdAt, activity.id, { kind: 'activity', activity: activityView(activity) }]), + ...state.comments.filter((comment) => comment.issueId === issue.id && !comment.deleted).map((comment): [string, string, TimelineItem] => [comment.createdAt, comment.id, { kind: 'comment', comment: commentView(comment) }]), + ...state.runs.filter((run) => run.issueId === issue.id).map((run): [string, string, TimelineItem] => [run.startedAt, run.id, { kind: 'run', run: runView(run) }]), + ...state.requests.filter((request) => request.issueId === issue.id).map((request): [string, string, TimelineItem] => [request.createdAt, request.id, { kind: 'request', request: requestView(request) }]), ] - const at = (item: TimelineItem) => (item.kind === 'activity' ? item.activity.createdAt : item.comment.createdAt) - const id = (item: TimelineItem) => (item.kind === 'activity' ? item.activity.id : item.comment.id) - items.sort((a, b) => at(a).localeCompare(at(b)) || id(a).localeCompare(id(b))) - return json({ items }) + stamped.sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1])) + return json({ items: stamped.map(([, , item]) => item) }) } async function attach(issue: StoredIssue, request: Request): Promise { @@ -1093,7 +1553,7 @@ async function attach(issue: StoredIssue, request: Request): Promise { mediaType, size: file.size, url: `${BASE}/attachments/${id}`, - uploader: state.caller, + uploader: who().actor, createdAt: now(), bytes: new Uint8Array(await file.arrayBuffer()), deleted: false, @@ -1105,7 +1565,7 @@ async function attach(issue: StoredIssue, request: Request): Promise { } function viewsVisible() { - return state.views.filter((view) => view.shared || view.ownerSub === state.caller.sub).sort((a, b) => a.position - b.position || a.createdAt.localeCompare(b.createdAt)) + return state.views.filter((view) => view.shared || view.ownerSub === who().actor.sub).sort((a, b) => a.position - b.position || a.createdAt.localeCompare(b.createdAt)) } function viewOut({ ownerSub: _ownerSub, ...view }: View & { ownerSub: string }): View { @@ -1273,6 +1733,8 @@ async function sprintRoutes(request: Request, url: URL, route: string): Promise< return json(burndownOf(sprint, scope.unit, scope.keep)) } if (method !== 'POST' || action === 'burndown') return notFound() + // Sprint start and close stay with people (API.md "Agents", Authorization). + if (who().agent) return forbidden() if (action === 'start') { if (sprintState(sprint) !== 'planned') return conflict('only a planned sprint can be started') if (activeSprint()) return conflict('another sprint is active; close it first') @@ -1299,15 +1761,447 @@ async function sprintRoutes(request: Request, url: URL, route: string): Promise< return undefined } +// --- agents, runs, requests, inbox, events (API.md "Agents") -------------------------------- + +const IDEMPOTENCY_TTL_MS = 24 * HOUR +const EVENTS_LIMIT_DEFAULT = 100 +const EVENTS_LIMIT_MAX = 500 +const REQUEST_OPTION_MAX = 200 + +const runById = (id: string | null) => (id ? state.runs.find((run) => run.id === id) : undefined) +const requestById = (id: string) => state.requests.find((request) => request.id === id) +/** The parts of a stored request the pure rules read. */ +const requestShape = (request: StoredRequest) => ({ kind: request.kind, state: request.state, from: { sub: request.fromSub }, to: request.toSub === null ? null : { sub: request.toSub } }) + +/** `domain.Actionable` for one agent over one live issue. */ +function actionableFor(issue: StoredIssue, agentSubject: string): boolean { + const run = activeRunOf(issue.id) + return isActionable({ + deleted: issue.deleted, + category: categoryOf(issue.statusId), + activeRun: run ? { state: derived(run), agent: { sub: agentSub(run.agentId) } } : null, + agentSub: agentSubject, + ownOpenRequest: state.requests.some((request) => request.issueId === issue.id && request.fromSub === agentSubject && request.state === 'open' && !(request.runId && runById(request.runId) && isStalledRun(runById(request.runId)!))), + openBlocker: state.blocks.some((block) => block.blockedId === issue.id && issueById(block.blockerId) !== undefined && !closedStatus(issueById(block.blockerId)!.statusId)), + }) +} + +/** The caller's queue: open requests for them (oldest first), then unacknowledged answers and mentions (newest first), then — for agents — actionable assignments. */ +function inboxOf(caller: Caller): InboxItem[] { + const me = caller.actor + const requests = state.requests + .filter((request) => issueById(request.issueId) && isAddressedTo(requestShape(request), me)) + .sort((a, b) => a.createdAt.localeCompare(b.createdAt)) + .map((request): InboxItem => ({ kind: 'request', request: requestView(request) })) + const answers = state.requests + .filter((request) => issueById(request.issueId) && request.fromSub === me.sub && request.state === 'answered' && !request.answerAcked) + .map((request): [string, InboxItem] => [request.answer!.at, { kind: 'answer', request: requestView(request) }]) + const mentions = state.mentions + .filter((mention) => mention.targetSub === me.sub && !mention.acked) + .flatMap((mention): [string, InboxItem][] => { + const comment = state.comments.find((candidate) => candidate.id === mention.commentId && !candidate.deleted) + const issue = issueById(mention.issueId) + return comment && issue ? [[comment.createdAt, { kind: 'mention', comment: commentView(comment), issue: ref(issue) }]] : [] + }) + const updates = [...answers, ...mentions].sort((a, b) => b[0].localeCompare(a[0])).map(([, item]) => item) + const assignments = caller.agent + ? live() + .filter((issue) => issue.assignee?.sub === me.sub && actionableFor(issue, me.sub)) + .map(summary) + .sort(compareActionable(activeSprint()?.id ?? null)) + .map((issue): InboxItem => ({ kind: 'assignment', issue })) + : [] + return [...requests, ...updates, ...assignments] +} + +function agentInputProblem(input: Record, creating: boolean): Problem | undefined { + const known = creating ? ['handle', 'name', 'description', 'ownerSub'] : ['name', 'description', 'ownerSub', 'disabled'] + if (!creating && 'handle' in input) return { path: 'handle', message: 'handle is immutable' } + const unknownKey = Object.keys(input).find((key) => !known.includes(key)) + if (unknownKey) return { path: unknownKey, message: `unknown field ${unknownKey}` } + if (creating && (typeof input.handle !== 'string' || !AGENT_HANDLE_PATTERN.test(input.handle))) return { path: 'handle', message: 'handle must match ^[a-z][a-z0-9-]{1,30}$' } + if ((creating || 'name' in input) && (typeof input.name !== 'string' || !input.name.trim() || Array.from(input.name.trim()).length > AGENT_NAME_MAX)) return { path: 'name', message: `name must be 1–${AGENT_NAME_MAX} characters` } + if ('description' in input && (typeof input.description !== 'string' || bytes(input.description) > AGENT_DESCRIPTION_MAX_BYTES)) return { path: 'description', message: `description must be at most ${AGENT_DESCRIPTION_MAX_BYTES} bytes` } + if ((creating || 'ownerSub' in input) && (typeof input.ownerSub !== 'string' || !input.ownerSub || agentIdOf(input.ownerSub) !== null)) return { path: 'ownerSub', message: 'ownerSub must name a person' } + if ('disabled' in input && typeof input.disabled !== 'boolean') return { path: 'disabled', message: 'disabled must be a boolean' } + return undefined +} + +const isHttpsUrl = (value: unknown) => { + if (typeof value !== 'string') return false + try { + return new URL(value).protocol === 'https:' + } catch { + return false + } +} + +function linksProblem(value: unknown): Problem | undefined { + if (value === undefined) return undefined + if (!Array.isArray(value) || value.length > RUN_LINKS_MAX) return { path: 'links', message: `links must be a list of at most ${RUN_LINKS_MAX}` } + for (const [index, link] of value.entries()) { + const candidate = link as Partial | null + if (!candidate || !['pr', 'commit', 'url'].includes(candidate.kind as string)) return { path: `links.${index}.kind`, message: 'kind must be pr, commit or url' } + if (!isHttpsUrl(candidate.url)) return { path: `links.${index}.url`, message: 'url must be an https URL' } + if (typeof candidate.title !== 'string' || Array.from(candidate.title).length > LINK_TITLE_MAX) return { path: `links.${index}.title`, message: `title must be at most ${LINK_TITLE_MAX} characters` } + } + return undefined +} + +const textProblem = (input: Record, key: string, max: number): Problem | undefined => + key in input && (typeof input[key] !== 'string' || Array.from(input[key] as string).length > max) ? { path: key, message: `${key} must be at most ${max} characters` } : undefined + +/** The agent protocol for an agent, generated from the routes it uses. */ +function agentGuide(): string { + const rows: [string, string][] = [ + ['GET /inbox', 'Your queue: requests addressed to you, answers to your requests, mentions, then the issues assigned to you that you can act on (an `assignment` carries `activeRun` when you already hold a live run: resume it, do not start again).'], + ['POST /inbox/ack', '`{ answers?: requestIds, mentions?: commentIds }` once you have read them.'], + ['POST /issues/{id}/runs', '`{ session?, note? }` starts a run on an issue assigned to you. The lease is 10 minutes.'], + ['POST /runs/{id}/heartbeat', '`{ note? }` renews the lease; say what you are doing in the note. A 409 means the run ended or stalled: stop and start a fresh run.'], + ['POST /issues/{id}/requests', '`{ kind: "question" | "approval", title, body?, options?, to?, runId? }`. Omit `to` to ask your delegator; `to: null` asks any person. With `runId` the run waits until every request is answered.'], + ['POST /runs/{id}/finish', '`{ outcome: "succeeded" | "failed", summary, links? }`. Under the review policy a success opens a review for your delegator; only their approval completes the issue.'], + ['POST /runs/{id}/cancel', 'Give up a run (yours, or a stalled one).'], + ['GET /events?after=', 'Every change in commit order; keep the last `next` as your cursor.'], + ] + return [ + '# Working in Tracker as an agent', + '', + `Exchange your Access Key for an assertion (\`apth access-keys exchange\`), then call \`${BASE}\` with \`Authorization: Bearer \`. \`GET\` needs \`tracker:read\`; every other method \`tracker:write\`. Send an \`Idempotency-Key\` header on every \`POST\` so a retry never acts twice.`, + '', + `Completion policy of this workspace: \`${state.workspace.agentCompletion}\`.`, + '', + '| Route | What it does |', + '| --- | --- |', + ...rows.map(([route, text]) => `| \`${route}\` | ${text} |`), + '', + ].join('\n') +} + +async function agentRoutes(request: Request, url: URL, route: string): Promise { + const caller = who() + let match: RegExpMatchArray | null + + if (route === 'GET /agent-guide') return new Response(agentGuide(), { headers: { 'Content-Type': 'text/markdown; charset=utf-8', 'Cache-Control': 'no-store' } }) + + // Agents + if (route === 'GET /agents') { + const includeDisabled = url.searchParams.get('includeDisabled') === 'true' + return json({ items: state.agents.filter((agent) => includeDisabled || !agent.disabled).sort((a, b) => a.handle.localeCompare(b.handle)).map(agentView) }) + } + if (route === 'POST /agents') { + if (!isAdmin()) return forbidden() + const input = await body(request) + if (!input) return invalid('', 'A JSON object is required') + const problem = agentInputProblem(input, true) + if (problem) return invalid(problem.path, problem.message) + if (state.agents.some((agent) => agent.handle === input.handle)) return conflict('an agent with this handle exists') + const time = now() + const agent: StoredAgent = { id: nextId(), handle: input.handle as string, name: (input.name as string).trim(), description: (input.description as string | undefined) ?? '', owner: personFor(input.ownerSub as string), disabled: false, createdAt: time, updatedAt: time, lastSeenAt: null } + state.agents.push(agent) + return json(agentView(agent), 201) + } + if ((match = route.match(/^PATCH \/agents\/([^/]+)$/))) { + const agent = agentById(decodeURIComponent(match[1]!)) + if (!agent) return notFound() + if (!isAdmin()) return forbidden() + const input = await body(request) + if (!input) return invalid('', 'A JSON object is required') + const problem = agentInputProblem(input, false) + if (problem) return invalid(problem.path, problem.message) + const time = now() + if (typeof input.name === 'string') agent.name = input.name.trim() + if (typeof input.description === 'string') agent.description = input.description + if (typeof input.ownerSub === 'string') agent.owner = personFor(input.ownerSub) + if (input.disabled === true && !agent.disabled) { + for (const run of state.runs.filter((candidate) => candidate.agentId === agent.id && !isTerminalRun(candidate.state))) endRun(run, 'canceled', `canceled_by:${caller.actor.sub}`, time) + } + if (typeof input.disabled === 'boolean') agent.disabled = input.disabled + agent.updatedAt = time + return json(agentView(agent)) + } + + // Inbox and events + if (route === 'GET /inbox') return json({ items: inboxOf(caller) }) + if (route === 'POST /inbox/ack') { + const input = await body(request) + if (!input) return invalid('', 'A JSON object is required') + for (const key of ['answers', 'mentions'] as const) if (key in input && !isStringArray(input[key])) return invalid(key, `${key} must list ids`) + for (const id of (input.answers as string[] | undefined) ?? []) { + const stored = requestById(id) + if (stored && stored.fromSub === caller.actor.sub && stored.state === 'answered') stored.answerAcked = true + } + for (const id of (input.mentions as string[] | undefined) ?? []) { + for (const mention of state.mentions) if (mention.commentId === id && mention.targetSub === caller.actor.sub) mention.acked = true + } + return noContent() + } + if (route === 'GET /events') { + const afterParam = url.searchParams.get('after') + const limitParam = url.searchParams.get('limit') + const limit = limitParam === null ? EVENTS_LIMIT_DEFAULT : Number(limitParam) + if (!Number.isInteger(limit) || limit < 1 || limit > EVENTS_LIMIT_MAX) return invalid('limit', `limit must be between 1 and ${EVENTS_LIMIT_MAX}`) + if (afterParam === null) return json({ items: [], next: state.eventSeq }) + const after = Number(afterParam) + if (!Number.isInteger(after) || after < 0) return invalid('after', 'after must be a sequence number') + const items = state.events.filter((event) => event.seq > after).slice(0, limit) + return json({ items, next: items.at(-1)?.seq ?? after }) + } + + // Runs + if ((match = route.match(/^(GET|POST) \/issues\/([^/]+)\/runs$/))) { + const [, method, rawId] = match + const issue = method === 'GET' ? findIssue(decodeURIComponent(rawId!)) : issueById(decodeURIComponent(rawId!)) + if (!issue) return notFound() + if (method === 'GET') return json({ items: state.runs.filter((run) => run.issueId === issue.id).sort((a, b) => b.startedAt.localeCompare(a.startedAt) || b.id.localeCompare(a.id)).map(runView) }) + if (!caller.agent || issue.assignee?.sub !== caller.actor.sub) return forbidden() + const input = (await body(request)) ?? {} + const problem = textProblem(input, 'session', RUN_TEXT_MAX) ?? textProblem(input, 'note', RUN_TEXT_MAX) + if (problem) return invalid(problem.path, problem.message) + const time = now() + const current = activeRunOf(issue.id) + if (current && !isStalledRun(current)) return conflict('another run is live on this issue') + // A stalled run is never revived: the next start closes it. + if (current) endRun(current, 'failed', 'lease_expired', time) + const run: StoredRun = { + id: nextId(), + issueId: issue.id, + agentId: caller.agent.id, + state: 'running', + reason: null, + session: (input.session as string | undefined) ?? '', + note: (input.note as string | undefined) ?? '', + summary: '', + links: [], + startedAt: time, + heartbeatAt: time, + leaseExpiresAt: new Date(Date.parse(time) + LEASE_MS).toISOString(), + finishedAt: null, + } + state.runs.push(run) + emit('run.started', issue, run.id, time) + return json(runView(run), 201) + } + if ((match = route.match(/^GET \/runs\/([^/]+)$/))) { + const run = runById(decodeURIComponent(match[1]!)) + return run && issueById(run.issueId) ? json(runView(run)) : notFound() + } + if ((match = route.match(/^POST \/runs\/([^/]+)\/(heartbeat|finish|cancel)$/))) { + const [, rawId, action] = match + const run = runById(decodeURIComponent(rawId!)) + const issue = run ? issueById(run.issueId) : undefined + if (!run || !issue) return notFound() + const own = caller.agent?.id === run.agentId + if (action === 'cancel') { + if (!canCancelRun({ agent: { sub: agentSub(run.agentId) }, state: derived(run) }, caller.actor)) return isTerminalRun(run.state) ? conflict('the run has ended') : forbidden() + endRun(run, 'canceled', `canceled_by:${caller.actor.sub}`, now()) + return json(runView(run)) + } + if (!own) return forbidden() + if (isTerminalRun(run.state)) return conflict('the run has ended') + if (isStalledRun(run)) return conflict('the run stalled (its lease passed); start a fresh run') + const input = (await body(request)) ?? {} + if (action === 'heartbeat') { + const problem = textProblem(input, 'note', RUN_TEXT_MAX) + if (problem) return invalid(problem.path, problem.message) + const time = now() + Object.assign(run, { heartbeatAt: time, leaseExpiresAt: new Date(Date.parse(time) + LEASE_MS).toISOString() }) + if (typeof input.note === 'string') run.note = input.note + return json(runView(run)) + } + if (input.outcome !== 'succeeded' && input.outcome !== 'failed') return invalid('outcome', 'outcome must be succeeded or failed') + if (typeof input.summary !== 'string' || bytes(input.summary) > RUN_SUMMARY_MAX_BYTES) return invalid('summary', `summary must be Markdown of at most ${RUN_SUMMARY_MAX_BYTES} bytes`) + const links = linksProblem(input.links) + if (links) return invalid(links.path, links.message) + if (input.outcome === 'succeeded' && state.requests.some((stored) => stored.runId === run.id && stored.kind === 'approval' && stored.state === 'open')) return conflict('an approval of this run is still open; resolve or withdraw it first') + const time = now() + Object.assign(run, { state: input.outcome, summary: input.summary, links: ((input.links as Link[] | undefined) ?? []).map(({ kind, url: href, title }) => ({ kind, url: href, title })), finishedAt: time }) + if (input.outcome === 'failed') withdrawRunRequests(run, time) + else withdrawRunRequests(run, time, ['question']) + emit('run.finished', issue, run.id, time) + if (input.outcome === 'succeeded' && state.workspace.agentCompletion === 'review') { + const review: StoredRequest = { + id: nextId(), + issueId: issue.id, + kind: 'review', + fromSub: caller.actor.sub, + toSub: issue.delegator?.sub ?? caller.agent!.owner.sub, + title: `Review: ${issue.title}`, + body: run.summary, + options: [...DECISION_OPTIONS], + runId: run.id, + state: 'open', + answer: null, + createdAt: time, + answerAcked: false, + } + state.requests.push(review) + emit('request.opened', issue, review.id, time) + } + return json(runView(run)) + } + + // Requests + if ((match = route.match(/^POST \/issues\/([^/]+)\/requests$/))) { + const issue = issueById(decodeURIComponent(match[1]!)) + if (!issue) return notFound() + const input = await body(request) + if (!input) return invalid('', 'A JSON object is required') + const unknownKey = Object.keys(input).find((key) => !['kind', 'title', 'body', 'options', 'to', 'runId'].includes(key)) + if (unknownKey) return invalid(unknownKey, `unknown field ${unknownKey}`) + if (input.kind !== 'question' && input.kind !== 'approval') return invalid('kind', 'kind must be question or approval') + if (typeof input.title !== 'string' || !input.title.trim() || Array.from(input.title.trim()).length > REQUEST_TITLE_MAX) return invalid('title', `title must be 1–${REQUEST_TITLE_MAX} characters`) + if (input.body !== undefined && (typeof input.body !== 'string' || bytes(input.body) > REQUEST_BODY_MAX_BYTES)) return invalid('body', `body must be Markdown of at most ${REQUEST_BODY_MAX_BYTES} bytes`) + let options: string[] = [] + if (input.kind === 'approval') { + if (input.options !== undefined && JSON.stringify(input.options) !== JSON.stringify(DECISION_OPTIONS)) return invalid('options', 'an approval has the fixed options approve and reject') + options = [...DECISION_OPTIONS] + } else if (input.options !== undefined) { + if (!isStringArray(input.options) || input.options.length > REQUEST_OPTIONS_MAX || input.options.some((option) => !option.trim() || Array.from(option).length > REQUEST_OPTION_MAX) || new Set(input.options).size !== input.options.length) + return invalid('options', `options must be at most ${REQUEST_OPTIONS_MAX} distinct texts of 1–${REQUEST_OPTION_MAX} characters`) + options = input.options + } + // `to` omitted: an agent asks its delegator here (else its owner); a person asks any person. + let toSub: string | null + if (input.to === undefined) toSub = caller.agent ? (issue.delegator?.sub ?? caller.agent.owner.sub) : null + else if (input.to === null) toSub = null + else if (typeof input.to !== 'string' || !input.to) return invalid('to', 'to must be a subject or null') + else toSub = input.to + if (toSub !== null) { + const target = agentBySub(toSub) + if (agentIdOf(toSub) !== null && (!target || target.disabled)) return invalid('to', 'to names no active agent') + if (target && input.kind === 'approval') return invalid('to', 'an approval is answered by people only') + if (toSub === caller.actor.sub) return invalid('to', 'a request goes to someone else') + } + let run: StoredRun | undefined + if (input.runId !== undefined) { + run = typeof input.runId === 'string' ? runById(input.runId) : undefined + if (!run) return invalid('runId', 'unknown run') + // Only the run's own agent attaches a request, and only to a run of this issue. + if (caller.agent?.id !== run.agentId || run.issueId !== issue.id) return forbidden() + if (isTerminalRun(run.state) || isStalledRun(run)) return conflict('the run is not live') + } + const time = now() + const stored: StoredRequest = { + id: nextId(), + issueId: issue.id, + kind: input.kind, + fromSub: caller.actor.sub, + toSub, + title: input.title.trim(), + body: (input.body as string | undefined) ?? '', + options, + runId: run?.id ?? null, + state: 'open', + answer: null, + createdAt: time, + answerAcked: false, + } + state.requests.push(stored) + if (run) run.state = 'waiting' + emit('request.opened', issue, stored.id, time) + return json(requestView(stored), 201) + } + if (route === 'GET /requests') { + const wanted = url.searchParams.get('state') + if (wanted !== null && !['open', 'answered', 'withdrawn'].includes(wanted)) return invalid('state', 'state must be open, answered or withdrawn') + const to = url.searchParams.get('to') + const toSub = to === 'me' ? caller.actor.sub : to + const issueKey = url.searchParams.get('issue') + const issue = issueKey ? findIssue(issueKey) : undefined + if (issueKey && !issue) return json({ items: [] }) + const items = state.requests + .filter((stored) => issueById(stored.issueId) && (wanted === null || stored.state === wanted) && (toSub === null || stored.toSub === toSub) && (!issue || stored.issueId === issue.id)) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)) + .map(requestView) + return json({ items }) + } + if ((match = route.match(/^GET \/requests\/([^/]+)$/))) { + const stored = requestById(decodeURIComponent(match[1]!)) + return stored && issueById(stored.issueId) ? json(requestView(stored)) : notFound() + } + if ((match = route.match(/^POST \/requests\/([^/]+)\/(answer|withdraw)$/))) { + const [, rawId, action] = match + const stored = requestById(decodeURIComponent(rawId!)) + const issue = stored ? issueById(stored.issueId) : undefined + if (!stored || !issue) return notFound() + if (action === 'withdraw') { + if (stored.fromSub !== caller.actor.sub) return forbidden() + if (stored.state !== 'open') return conflict('the request is no longer open') + const time = now() + stored.state = 'withdrawn' + emit('request.withdrawn', issue, stored.id, time) + resumeIfClear(stored.runId) + return json(requestView(stored)) + } + if (stored.state !== 'open') return conflict('the request is no longer open') + if (!canAnswer(requestShape(stored), { ...caller.actor, isAdmin: isAdmin() })) return forbidden() + const input = (await body(request)) ?? {} + if (input.option !== undefined && (typeof input.option !== 'string' || (stored.options.length > 0 ? !stored.options.includes(input.option) : true))) return invalid('option', stored.options.length > 0 ? `option must be one of ${stored.options.join(', ')}` : 'this request has no options') + if (input.body !== undefined && (typeof input.body !== 'string' || bytes(input.body) > REQUEST_BODY_MAX_BYTES)) return invalid('body', `body must be Markdown of at most ${REQUEST_BODY_MAX_BYTES} bytes`) + if (stored.kind !== 'question' && input.option === undefined) return invalid('option', 'choose approve or reject') + if (input.option === undefined && !(input.body as string | undefined)?.trim()) return invalid('body', 'an answer needs an option or a text') + const time = now() + stored.state = 'answered' + stored.answer = { option: (input.option as string | undefined) ?? null, body: (input.body as string | undefined) ?? '', bySub: caller.actor.sub, at: time } + emit('request.answered', issue, stored.id, time) + // Approving a review completes the issue as the person who approved, in the same write. + const done = orderStatuses(state.statuses).find((status) => status.category === 'completed') + if (stored.kind === 'review' && stored.answer.option === 'approve' && done && categoryOf(issue.statusId) !== 'completed') { + const before = standingOf(issue) + record(issue, 'status', issue.statusId, done.id, time) + Object.assign(issue, { statusId: done.id, completedAt: time, updatedAt: time }) + writeLedger(issue.id, before, standingOf(issue), time) + emit('issue.updated', issue, { fields: ['status'] }, time) + } + resumeIfClear(stored.runId) + return json(requestView(stored)) + } + return undefined +} + +/** The request's caller: the signed-in person, or — with `X-Mock-Agent` — that agent's key (403 `key_subject` unless an active agent has the handle; 403 `insufficient_scope` without the method's scope). */ +function callerOf(request: Request): Caller | Response { + const handle = request.headers.get('X-Mock-Agent') + if (handle === null) return { actor: personActor(state.caller), role: state.role, agent: null, scopes: ACCESS_KEY_SCOPES } + const agent = state.agents.find((candidate) => candidate.handle === handle && !candidate.disabled) + if (!agent) return fail(403, 'key_subject', "the key's external subject is not an active agent") + const scopes = (request.headers.get('X-Mock-Scopes') ?? ACCESS_KEY_SCOPES.join(',')).split(',').map((scope) => scope.trim()).filter(Boolean) + const needed = request.method === 'GET' ? 'tracker:read' : 'tracker:write' + if (!scopes.includes(needed)) return fail(403, 'insufficient_scope', `the key lacks ${needed}`) + agent.lastSeenAt = new Date(wallClock()).toISOString() + return { actor: agentActor(agent), role: 'Viewer', agent, scopes } +} + +/** `Idempotency-Key` on a POST (multipart attachment uploads excepted): the first response is kept 24 h per (actor, key) and replayed; the same key with another body → 409. */ +async function idempotent(request: Request, handle: () => Promise): Promise { + const multipart = (request.headers.get('Content-Type') ?? '').startsWith('multipart/form-data') + const key = request.method === 'POST' && !multipart ? request.headers.get('Idempotency-Key') : null + if (key === null) return handle() + if (!key || key.length > IDEMPOTENCY_KEY_MAX) return invalid('Idempotency-Key', `Idempotency-Key must be 1–${IDEMPOTENCY_KEY_MAX} characters`) + const sent = await request.clone().text() + const slot = `${who().actor.sub}\n${key}` + const at = wallClock() + const stored = state.idempotency.get(slot) + if (stored && at - stored.at < IDEMPOTENCY_TTL_MS) { + if (stored.body !== sent) return conflict('this Idempotency-Key was used with a different body') + return new Response(stored.status === 204 ? null : stored.response, { status: stored.status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } }) + } + const response = await handle() + if (!response) return response + // Expired rows go when a new one is written. + for (const [other, row] of state.idempotency) if (at - row.at >= IDEMPOTENCY_TTL_MS) state.idempotency.delete(other) + state.idempotency.set(slot, { body: sent, status: response.status, response: await response.clone().text(), at }) + return response +} + /** Handles `/api/tracker/v1/*`; undefined for any other path. */ export async function trackerRoutes(request: Request, url: URL): Promise { if (!url.pathname.startsWith(`${BASE}/`)) return undefined const route = `${request.method} ${url.pathname.slice(BASE.length)}` - let match: RegExpMatchArray | null if (route === 'POST /__mock/reset') { const input = await body(request) - state = seedTracker(input?.projects === 'none' ? { withProjects: false } : {}) + state = seedAgents(seedTracker(input?.projects === 'none' ? { withProjects: false } : {})) return json({ reset: true }) } if (route === 'POST /__mock/caller') { @@ -1320,12 +2214,27 @@ export async function trackerRoutes(request: Request, url: URL): Promise idempotent(request, () => routes(request, url, route))) +} - if (route === 'GET /me') return json({ ...state.caller, role: state.role, isAdmin: isAdmin() } satisfies Me) +async function routes(request: Request, url: URL, route: string): Promise { + let match: RegExpMatchArray | null + if (route === 'GET /me') { + const caller = who() + return json({ ...caller.actor, role: caller.role, isAdmin: isAdmin(), ...(caller.agent ? { scopes: [...caller.scopes] } : {}) } satisfies Me) + } // Workspace if (route === 'GET /workspace') return json(workspace()) @@ -1337,6 +2246,8 @@ export async function trackerRoutes(request: Request, url: URL): Promise 100)) return invalid('name', 'name must be 1–100 characters') if ('sprintLengthWeeks' in input && !SPRINT_LENGTHS.includes(input.sprintLengthWeeks as SprintLength)) return invalid('sprintLengthWeeks', 'sprintLengthWeeks must be 1 or 2') if ('timezone' in input && !isTimeZone(input.timezone)) return invalid('timezone', 'timezone must be an IANA time zone name') + if ('agentCompletion' in input && !AGENT_COMPLETIONS.includes(input.agentCompletion as AgentCompletion)) return invalid('agentCompletion', 'agentCompletion must be review or direct') + if (typeof input.agentCompletion === 'string') state.workspace.agentCompletion = input.agentCompletion as AgentCompletion if (typeof input.key === 'string') state.workspace.key = input.key if (typeof input.name === 'string') state.workspace.name = input.name.trim() if (typeof input.sprintLengthWeeks === 'number') state.workspace.sprintLengthWeeks = input.sprintLengthWeeks as SprintLength @@ -1488,6 +2399,7 @@ export async function trackerRoutes(request: Request, url: URL): Promise COMMENT_MAX_BYTES) return invalid('body', 'body must be at most 20 KiB') - const comment: StoredComment = { id: nextId(), issueId: issue.id, author: state.caller, body: input.body, createdAt: now(), editedAt: null, deleted: false } + const comment: StoredComment = { id: nextId(), issueId: issue.id, author: who().actor, body: input.body, createdAt: now(), editedAt: null, deleted: false } state.comments.push(comment) + // Mentions: one row per (comment, active agent) its `@handle`s name. + const handles = parseMentions(input.body, state.agents.filter((agent) => !agent.disabled).map((agent) => agent.handle)) + for (const handle of handles) state.mentions.push({ commentId: comment.id, issueId: issue.id, targetSub: agentSub(state.agents.find((agent) => agent.handle === handle)!.id), acked: false }) issue.updatedAt = comment.createdAt - const { deleted: _deleted, ...out } = comment - return json(out satisfies Comment, 201) + emit('comment.created', issue, comment.id, comment.createdAt) + return json(commentView(comment), 201) } if (method === 'POST' && sub === 'attachments') return attach(issue, request) return notFound() @@ -1518,7 +2433,7 @@ export async function trackerRoutes(request: Request, url: URL): Promise candidate.id === decodeURIComponent(rawId!) && !candidate.deleted) if (!comment || !issueById(comment.issueId)) return notFound() - const mine = comment.author.sub === state.caller.sub + const mine = comment.author.sub === who().actor.sub if (method === 'DELETE') { if (!mine && !isAdmin()) return forbidden() comment.deleted = true @@ -1530,8 +2445,7 @@ export async function trackerRoutes(request: Request, url: URL): Promise COMMENT_MAX_BYTES) return invalid('body', 'body must be at most 20 KiB') comment.body = input.body comment.editedAt = now() - const { deleted: _deleted, ...out } = comment - return json(out satisfies Comment) + return json(commentView(comment)) } // Attachments @@ -1549,7 +2463,7 @@ export async function trackerRoutes(request: Request, url: URL): Promise candidate.id === decodeURIComponent(rawId!)) if (!view) return notFound() - if (view.shared ? !isAdmin() : view.ownerSub !== state.caller.sub) return forbidden() + if (view.shared ? !isAdmin() : view.ownerSub !== who().actor.sub) return forbidden() if (method === 'DELETE') { state.views = state.views.filter((candidate) => candidate !== view) return noContent() @@ -1610,9 +2524,12 @@ export async function trackerRoutes(request: Request, url: URL): Promise !q || person.name.toLowerCase().includes(q) || person.sub.includes(q)) return json({ items: items.slice(0, PEOPLE_LIMIT), source: 'directory' }) diff --git a/web/src/features/agents/actor.tsx b/web/src/features/agents/actor.tsx new file mode 100644 index 0000000..c624b13 --- /dev/null +++ b/web/src/features/agents/actor.tsx @@ -0,0 +1,38 @@ +// Actors on screen: an agent is visibly not a person (the Avatar's robot +// square, never a photo) and always says who is responsible for it — in the +// badge's accessible name and tooltip where only the badge fits, and as +// visible text wherever the name is written out. +import type { Actor } from '../../api/tracker' +import { useText } from '../../i18n' +import { isAgent } from '../../model/agents' +import { Avatar, cn } from '../../ui' + +/** The badge of a person or an agent; agents carry "name, owned by …" as their accessible name and tooltip. */ +export function ActorAvatar({ actor, size = 'xs' }: { actor: Actor; size?: 'xs' | 'sm' | 'md' | 'lg' }) { + const { t } = useText() + const label = isAgent(actor) ? t('tracker.agent.avatarLabel', { name: actor.name, owner: actor.agent.owner.name }) : undefined + return +} + +/** "Astra [Agent] · Owned by Sam Rivera" (the owner line can be dropped where space is short), or a person's name. */ +export function ActorName({ actor, owner = true, className }: { actor: Actor; owner?: boolean; className?: string }) { + const { t } = useText() + if (!isAgent(actor)) return {actor.name} + return ( + + {actor.name} + + {owner ? {t('tracker.agent.ownedBy', { name: actor.agent.owner.name })} : null} + + ) +} + +/** The small "Agent" (or "Disabled") tag next to an agent's name. */ +export function AgentTag({ disabled = false }: { disabled?: boolean }) { + const { t } = useText() + return ( + + {disabled ? t('tracker.agent.disabled') : t('tracker.agent.badge')} + + ) +} diff --git a/web/src/features/agents/agents-settings.tsx b/web/src/features/agents/agents-settings.tsx new file mode 100644 index 0000000..a72fd2f --- /dev/null +++ b/web/src/features/agents/agents-settings.tsx @@ -0,0 +1,296 @@ +// `/settings/agents` and the workspace's completion policy. Everyone sees +// the agents (name, @handle, responsible person, what to delegate, last +// seen, work in progress, open requests and the median time their requests +// waited for a person, from the answered requests); Admins register (the +// handle is fixed from then on), edit, disable — with a confirmation that +// says the agent's work in progress is stopped — and copy the exact `apth` +// command that mints a key. The key is shown once by the platform, never by +// Tracker. Runs by outcome are not shown: no route lists runs across issues. +import { useQuery } from '@tanstack/react-query' +import { Bot, Check, Copy, KeyRound, Pencil, Plus, Power, PowerOff } from 'lucide-react' +import { useId, useMemo, useState, type FormEvent } from 'react' +import { peopleQuery, requestsQuery, useAgentMutations, useUpdateWorkspace } from '../../api/queries' +import { isTrackerError, type Agent, type AgentCompletion, type Person } from '../../api/tracker' +import { useText } from '../../i18n' +import { accessKeyCommand, AGENT_COMPLETIONS, AGENT_DESCRIPTION_MAX_BYTES, AGENT_HANDLE_PATTERN, AGENT_NAME_MAX, medianWaitMs } from '../../model/agents' +import { ActionError, Avatar, Button, cn, ConfirmDialog, Dialog, Field, formatDateTime, formatDuration, formatRelative, Notice, Section, SelectInput, showToast, TextArea, TextInput } from '../../ui' +import { useReference } from '../issues/use-reference' +import { AgentTag } from './actor' + +export function AgentSettings() { + const { t } = useText() + const { agents, me } = useReference() + const { update } = useAgentMutations() + const answered = useQuery(requestsQuery({ state: 'answered' })) + const [editing, setEditing] = useState(null) + const [disabling, setDisabling] = useState(null) + const [keyFor, setKeyFor] = useState(null) + const waits = useMemo(() => { + const byAgent = new Map() + for (const agent of agents) byAgent.set(agent.id, medianWaitMs((answered.data ?? []).filter((request) => request.from.sub === `agent:${agent.id}`))) + return byAgent + }, [agents, answered.data]) + const active = agents.filter((agent) => !agent.disabled) + const disabled = agents.filter((agent) => agent.disabled) + const row = (agent: Agent) => ( + setKeyFor((current) => (current === agent.id ? null : agent.id))} + onEdit={() => setEditing(agent)} + onDisable={() => (update.reset(), setDisabling(agent))} + onEnable={() => update.mutate({ id: agent.id, input: { disabled: false } })} + /> + ) + return ( +
+

{t('tracker.agents.lead')}

+ {!me.isAdmin ? : null} + {update.error && !disabling ? : null} +
} onClick={() => setEditing('new')}> + {t('tracker.agents.register')} + + ) : undefined + } + > + {active.length === 0 ? ( +

{t('tracker.agents.empty')}

+ ) : ( +
    {active.map(row)}
+ )} +
+ {disabled.length > 0 ? ( +
+
    {disabled.map(row)}
+
+ ) : null} + {editing ? setEditing(null)} onCreated={(agent) => setKeyFor(agent.id)} /> : null} + !open && setDisabling(null)} + title={t('tracker.agents.disableTitle', { name: disabling?.name ?? '' })} + body={t('tracker.agents.disableBody', { name: disabling?.name ?? '', count: disabling?.activeRuns ?? 0 })} + confirmLabel={t('tracker.agents.disable')} + tone="danger" + pending={update.isPending} + error={update.error} + onConfirm={() => disabling && update.mutate({ id: disabling.id, input: { disabled: true } }, { onSuccess: () => setDisabling(null) })} + /> +
+ ) +} + +function AgentRow({ agent, wait, showKey, onToggleKey, onEdit, onDisable, onEnable }: { agent: Agent; wait: number | null; showKey: boolean; onToggleKey: () => void; onEdit: () => void; onDisable: () => void; onEnable: () => void }) { + const { t, locale } = useText() + const { me } = useReference() + const keyId = useId() + return ( +
  • +
    + +
    +

    + {agent.name} + @{agent.handle} + +

    +

    {t('tracker.agent.ownedBy', { name: agent.owner.name })}

    + {agent.description ?

    {agent.description}

    : null} +

    + {agent.lastSeenAt ? ( + + ) : ( + {t('tracker.agents.neverSeen')} + )} + 0 && 'font-medium text-accent-strong')}>{t('tracker.agents.activeRuns', { count: agent.activeRuns })} + 0 && 'font-medium text-busy-ink')}>{t('tracker.run.openRequests', { count: agent.openRequests })} + {wait === null ? t('tracker.agents.noWait') : t('tracker.agents.medianWait', { time: formatDuration(wait, locale) })} +

    +
    + {me.isAdmin ? ( +
    + {!agent.disabled ? ( + + ) : null} + + {agent.disabled ? ( + + ) : ( + + )} +
    + ) : null} +
    + {showKey ? : null} +
  • + ) +} + +/** The exact `apth` command and a copy button; the key itself never passes through Tracker. */ +function KeyCommand({ id, agent }: { id: string; agent: Agent }) { + const { t } = useText() + const [copied, setCopied] = useState(false) + const command = accessKeyCommand(agent.handle) + return ( +
    +

    {t('tracker.agents.keyBody')}

    +
    + {command} + +
    +
    + ) +} + +/** Register (`agent` null) or edit an agent. The handle is entered once; editing shows it fixed. */ +function AgentDialog({ agent, onClose, onCreated }: { agent: Agent | null; onClose: () => void; onCreated: (agent: Agent) => void }) { + const { t } = useText() + const { me } = useReference() + const { create, update } = useAgentMutations() + const people = useQuery(peopleQuery('')) + const [handle, setHandle] = useState(agent?.handle ?? '') + const [name, setName] = useState(agent?.name ?? '') + const [ownerSub, setOwnerSub] = useState(agent?.owner.sub ?? me.sub) + const [description, setDescription] = useState(agent?.description ?? '') + const [submitted, setSubmitted] = useState(false) + const mutation = agent ? update : create + const owners = new Map() + for (const person of [{ sub: me.sub, name: me.name }, ...(agent ? [agent.owner] : []), ...(people.data?.items ?? [])]) owners.set(person.sub, person) + const handleError = !agent && !AGENT_HANDLE_PATTERN.test(handle) ? t('tracker.agents.handleInvalid') : isTrackerError(create.error, 'conflict') ? t('tracker.agents.handleTaken') : undefined + const nameError = !name.trim() ? t('tracker.form.required') : Array.from(name.trim()).length > AGENT_NAME_MAX ? t('tracker.form.tooLong', { max: AGENT_NAME_MAX }) : undefined + const descriptionError = new TextEncoder().encode(description).length > AGENT_DESCRIPTION_MAX_BYTES ? t('tracker.form.tooLong', { max: AGENT_DESCRIPTION_MAX_BYTES }) : undefined + const submit = (event: FormEvent) => { + event.preventDefault() + setSubmitted(true) + if ((handleError && !isTrackerError(create.error, 'conflict')) || nameError || descriptionError || !ownerSub) return + if (agent) { + update.mutate({ id: agent.id, input: { name: name.trim(), description, ownerSub } }, { onSuccess: onClose }) + return + } + create.mutate( + { handle, name: name.trim(), description, ownerSub }, + { + onSuccess: (created) => { + showToast({ tone: 'success', title: t('tracker.agents.registered', { name: created.name }) }) + onCreated(created) + onClose() + }, + } + ) + } + return ( + !open && onClose()} + title={agent ? t('tracker.agents.editLabel', { name: agent.name }) : t('tracker.agents.register')} + footer={ + <> + + + + } + > +
    + +
    + + @ + + { + setHandle(event.target.value.toLowerCase()) + create.reset() + }} + maxLength={31} + autoComplete="off" + spellCheck={false} + className="pl-7 font-mono" + /> +
    +
    + + setName(event.target.value)} maxLength={AGENT_NAME_MAX} /> + + + setOwnerSub(event.target.value)}> + {[...owners.values()].map((person) => ( + + ))} + + + +