oficina / equipo Public

feat: add custom specialists and template copies

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 7070cc2db38d66dbc3844d12fd37f9bcfab31a5b parent 2daa8f5
47 files changed, +2,185 −309
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +59 −0
  • internal/equipo/app.go +12 −2
  • internal/equipo/connection_selection.go +18 −27
  • internal/equipo/copy.go +120 −0
  • internal/equipo/handlers.go +10 −72
  • internal/equipo/icons/icons.go +1 −0
  • internal/equipo/library/application.go +62 −0
  • internal/equipo/library/budget_test.go +10 −0
  • internal/equipo/library/counts.go +119 −0
  • internal/equipo/library/handlers.go +255 −0
  • internal/equipo/library/legacy.go +47 −0
  • internal/equipo/library/legacy_handlers.go +36 −0
  • internal/equipo/library/navigation.go +51 −0
  • internal/equipo/library/references.go +44 −0
  • internal/equipo/library/selection.go +32 −0
  • internal/equipo/library/specialists.go +329 −0
  • internal/equipo/library/templates.go +169 −0
  • internal/equipo/library/views.go +89 −0
  • internal/equipo/library_handlers.go +61 −0
  • internal/equipo/migrations/0024_specialist_library.sql +15 −0
  • internal/equipo/migrations/schema.sql +2 −1
  • internal/equipo/models.go +3 −11
  • internal/equipo/navigation.go +4 −17
  • internal/equipo/planning/plans.go +7 −0
  • internal/equipo/planning/task_views.go +1 −0
  • internal/equipo/plans.go +3 −0
  • internal/equipo/render.go +3 −2
  • internal/equipo/runner_execution.go +1 −1
  • internal/equipo/specialist_library.go +29 −0
  • internal/equipo/specialists.go +9 −54
  • internal/equipo/store.go +5 −0
  • internal/equipo/task_counts.go +6 −58
  • internal/equipo/task_views.go +7 −49
  • internal/equipo/templates/chrome.html +2 −2
  • internal/equipo/templates/plan.html +1 −1
  • internal/equipo/templates/specialist.html +7 −3
  • internal/equipo/templates/specialist_form.html +28 −0
  • internal/equipo/templates/task_card.html +1 −1
  • internal/equipo/templates/template_diff.html +13 −0
  • internal/equipo/templates/template_library.html +14 −0
  • internal/equipotest/specialists_test.go +8 −8
  • internal/plan3test/specialist_catalog_test.go +83 −0
  • internal/plan3test/specialist_library_test.go +309 −0
  • internal/plan3test/specialist_migration_test.go +55 −0
  • internal/runner/provider/specialists.go +17 −0
  • internal/runner/provider/specialists_test.go +27 −0
  • internal/runnerproto/types.go +1 −0

CI failed — run details

diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index e389399a..ab2f50ce 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -3527,3 +3527,62 @@ Final supplemental checks: `CGO_ENABLED=0 go test ./internal/runner -run '^Test(
| Copy | PENDING, 122 new runtime entries plus draft documents and inherited pending copy |
| Live certification and Paul's usable acceptance | NOT RUN; follow LIVE-GATE-plan-3.md section 3a after controller review |
| Production release | DISABLED pending the copy and live gates |
+
+## Task 12
+
+Added the specialist library, version-pinned editable template copies, guarded explicit template diffs, archive/reference protection, migration 0024, shared HTML/application operations and custom category navigation/selection. Engineering/Review remain required. Current-member and creator/owner checks precede replay. Custom execution remains unavailable because this release has no certified custom tool grants; the manifest remains uncertified. All 60 new runtime copy entries are individually pending in copy.go.
+
+## Verification and TDD
+
+The five required tests were written before implementation. The first run of `CGO_ENABLED=0 go test ./internal/plan3test ./internal/runner/provider/... -run '^TestSpecialist(Library|Required|Tool|Scope|Template)' -count=1` exited 1: `no required module provides package amadan.net/oficina/equipo/internal/equipo/library`. The final identical command exits 0: plan3test 1.300s, provider 0.002s, Claude 0.083s and Codex 0.082s. Adapter packages compile in this command; they contain no tests matching the specialist prefix.
+
+A later error-path test was also run red: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestSpecialistScopeLookupFailure$' -count=1` exited 1 with “project query failure lost unavailable state”, because a database query error was mapped to not-found. The implementation now distinguishes missing records from failed queries. The final required command includes this test and passes.
+
+The named tests cover independent template copies and pinned origins; install/update retries; changed request bodies; required categories; arbitrary commands and native provider tools; separate team/project/certificate tool intersections; creator/owner authority; removed-member replay; foreign team/project denial; revision conflicts; audit rollback; unstarted-plan archive protection; retained started briefs; catalog changes between preview and acceptance; explicit selected fields; all four template groups and blank; authenticated scriptless forms; model/project selection limits; custom names/icons/counts; and the 0023-to-0024 upgrade. The migration test preserves settings, revisions and roles, compares fresh/upgraded schemas and checks repeat application.
+
+Other final checks (exit 0):
+
+- `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestSpecialist|TestSpecialists|TestConnectionSelection|TestRailCounts|TestTaskPagesUnknownCounts)' -count=1`: 6.731s. Existing specialist tests were adapted to compare slice-bearing records with `reflect.DeepEqual` and to omit both 0005 and its dependent 0024 from the pre-specialist upgrade fixture. The existing unavailable-read regression caught a normalization loss during extraction; that was restored before this passing run.
+- `CGO_ENABLED=0 go test ./internal/plan3test -run '^(TestPlanAuthorityReplay|TestPlanEditClaimRaceAtomic|TestPlanProjectCorrection.*|TestPlanApprovalPrecedence.*|TestConversationScriptlessPlanGuards|TestConversationScriptlessConnectionChoices|TestPlanWorkflow.*)$' -count=1`: 3.236s.
+- `make migration-check`: 0.150s for its targeted `TestMigrationModels` test.
+- `CGO_ENABLED=0 go test ./internal/equipo -run '^(TestConversationMigrationSnapshot|TestTemplateCopyKeys|TestRunnerCopyInventory)$' -count=1`: 1.303s.
+- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/library ./internal/equipo/planning ./internal/equipo/icons ./internal/runner/provider ./internal/runnerproto ./internal/plan3test ./internal/equipotest`.
+- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/library ./internal/equipo/planning ./internal/equipo/icons ./internal/runner/provider ./internal/runnerproto ./internal/plan3test ./internal/equipotest`.
+- `gofmt -l internal/equipo internal/plan3test internal/equipotest internal/runner/provider internal/runnerproto`: no output.
+- `git diff --check`: no output.
+- `make budget`: 32 directories within budget. The initial root count exceeded 10800; specialist settings, HTTP parsing, selection helpers, navigation and workload projections were extracted into library without raising ceilings.
+
+Only targeted tests ran. No full suite, `make ci`, browser server, provider session, sign-in or enrolment was used. Test runtimes above are targeted measurements, not full-package runtime claims.
+
+## Guard mutations
+
+Each guard was broken separately, the named test reached its failed assertion, and the original file was restored before the next mutation. All commands exited 1; none failed merely to compile. The required command passes after restoration.
+
+| Guard | Command | Exit | Failed assertion | Restoration |
+| --- | --- | --- | --- | --- |
+| copy isolation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistLibraryCatalogIsolation$ -count=1` | 1 | catalog changed installed copy | Restored |
+| required deletion | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistRequiredDefaults$ -count=1` | 1 | required default archived <nil> | Restored |
+| required conversion | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistRequiredDefaults$ -count=1` | 1 | required role converted <nil> | Restored |
+| edit authority | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistScopeAndPermissions$ -count=1` | 1 | other member edited specialist <nil> | Restored |
+| unstarted references | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistScopeArchiveReferences$ -count=1` | 1 | unstarted plan lost specialist <nil> | Restored |
+| accepted diff identity | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistLibraryCopies$ -count=1` | 1 | forged diff accepted <nil> | Restored |
+| current membership on replay | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistScopeAndPermissions$ -count=1` | 1 | removed creator replayed write <nil> | Restored |
+| atomic audit | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistLibraryRevisionAndAudit$ -count=1` | 1 | audit failure accepted | Restored |
+| project scope | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistScopeProjectAndModels$ -count=1` | 1 | specialist project set ignored <nil> | Restored |
+| tool project subset | `CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestSpecialistToolPolicy$/project$ -count=1` | 1 | tool authority widened | Restored |
+| tool certification | `CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestSpecialistToolPolicy$/certificate$ -count=1` | 1 | tool authority widened | Restored |
+| allowed models | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestSpecialistScopeProjectAndModels$ -count=1` | 1 | allowed model set ignored | Restored |
+
+## Measured size
+
+| Directory | Source lines | Test lines |
+| --- | ---: | ---: |
+| `internal/equipo` | 10798 | 437 |
+| `internal/equipo/library` | 1233 | 10 |
+| `internal/equipo/planning` | 1341 | 57 |
+| `internal/runner/provider` | 2746 | 1793 |
+| `internal/runnerproto` | 2304 | 60 |
+| `internal/plan3test` | 446 | 6662 |
+| `internal/equipotest` | 0 | 12998 |
+
+Full report and copy inventory: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-12-report.md`. Commit uses `--author "codex <codex~paul@keymail.dev>"` and subject `feat: add custom specialists and template copies`. No push, other agents, copy-review server, live provider work or full suites.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 93651346..6302b9d5 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -204,13 +204,23 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/runners/{id}/revoke", a.revokeRunner)
r.Post("/projects/{id}/connections", a.saveConnectionChoice)
r.Get("/settings", a.settings)
- r.Get("/specialists/{key}", a.specialist)
+ lh := a.libraryHandler()
+ r.Get("/specialists/{key}", lh.Detail)
+ r.Get("/templates", lh.Catalog)
+ r.Post("/templates/{id}/install", lh.Install)
+ r.Get("/specialists/new", lh.Form)
+ r.Post("/specialists", lh.Save)
+ r.Get("/specialists/{key}/edit", lh.Form)
+ r.Post("/specialists/{key}/edit", lh.Save)
+ r.Post("/specialists/{key}/archive", lh.Archive)
+ r.Get("/specialists/{key}/template-diff", lh.Diff)
+ r.Post("/specialists/{key}/template-update", lh.Apply)
r.Post("/accounts", a.saveAccount)
r.Post("/projects", a.saveProject)
r.Post("/projects/{id}", a.saveProject)
r.Post("/team/members", a.saveMember)
r.Post("/team/budgets", a.saveBudgets)
- r.Post("/specialists/{key}", a.saveSpecialist)
+ r.Post("/specialists/{key}", lh.SaveLegacy)
r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ErrorPage(w, r, http.StatusNotFound, "") }))
})
return a, nil
diff --git a/internal/equipo/connection_selection.go b/internal/equipo/connection_selection.go
index ada2f327..419086fc 100644
--- a/internal/equipo/connection_selection.go
+++ b/internal/equipo/connection_selection.go
@@ -1,6 +1,7 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/taskplan"
"context"
"errors"
@@ -29,36 +30,11 @@ func (s *Store) eligible(tx *gorm.DB, c connectionRecord, r ConnectionReport, no
}
func specialistAllows(sp Specialist, r ConnectionReport) bool {
- return sp.ModelSelection == "best_fit" || sp.ModelSelection == "fixed" && sp.Provider == r.Provider && sp.ModelFamily == r.Family && sp.Model == r.Model
+ return library.ModelAllowed(sp, r.Provider, r.Family, r.Model) && (sp.ModelSelection == "best_fit" || sp.ModelSelection == "fixed" && sp.Provider == r.Provider && sp.ModelFamily == r.Family && sp.Model == r.Model)
}
func knownFamily(s string) bool { return s == "claude" || s == "gpt" }
func specialistAt(tx *gorm.DB, key string) (Specialist, error) {
- var sp Specialist
- if err := tx.Where("key = ?", key).First(&sp).Error; err != nil {
- return sp, storeError(err)
- }
- if sp.MaxConcurrent <= 0 {
- return sp, ErrUnavailable
- }
- // Containment-pending attempts occupy capacity even after stop is requested.
- capabilities := []string{key}
- if key == "engineering" {
- capabilities = []string{"reproduce", "implement", "reconcile"}
- }
- if key == "review" {
- capabilities = []string{"review", "verify"}
- }
- var live int64
- if key == "product" {
- capabilities = []string{"scope", "research"}
- }
- if err := tx.Table("attempts").Joins("JOIN steps ON steps.id = attempts.step_id").Where("attempts.containment = ? AND (steps.capability IN ? OR EXISTS (SELECT 1 FROM runner_assignments ra WHERE ra.attempt_id=attempts.id AND json_extract(ra.brief,'$.step.SpecialistKey')=?))", "pending", capabilities, key).Count(&live).Error; err != nil {
- return sp, storeError(err)
- }
- if live >= int64(sp.MaxConcurrent) {
- return sp, ErrUnavailable
- }
- return sp, nil
+ return library.ExecutionSpecialist(tx, key, ErrUnavailable, storeError)
}
// SelectConnection is an instance eligibility snapshot. It creates neither a
@@ -102,6 +78,21 @@ func (s *Store) selectStepConnection(tx *gorm.DB, person string, projectID int64
if err != nil {
return err
}
+ if !library.ProjectAllowed(sp, projectID) {
+ return ErrForbidden
+ }
+ var instance Team
+ if err := tx.First(&instance).Error; err != nil {
+ return err
+ }
+ if sp.TeamID != instance.ID {
+ return ErrNotFound
+ }
+ // Custom profiles are not certified in this release. Empty tool sets
+ // are not an implicit grant of the action's tools.
+ if sp.Role == "" {
+ return ErrUnavailable
+ }
if specialist == "review" && !knownFamily(excludedFamily) {
return ErrUnavailable
}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 43febed9..db5012bf 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -48,6 +48,126 @@ const BootLog = "Equipo could not start."
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
var pageCopy = map[string]string{
+ // COPY REVIEW REQUIRED: specialists.new
+ "specialists.new": "New specialist",
+ // COPY REVIEW REQUIRED: specialists.name
+ "specialists.name": "Name",
+ // COPY REVIEW REQUIRED: specialists.icon
+ "specialists.icon": "Icon",
+ // COPY REVIEW REQUIRED: specialists.instructions
+ "specialists.instructions": "Standing instructions",
+ // COPY REVIEW REQUIRED: specialists.models
+ "specialists.models": "Allowed models",
+ // COPY REVIEW REQUIRED: specialists.tools
+ "specialists.tools": "Allowed tools",
+ // COPY REVIEW REQUIRED: specialists.projects
+ "specialists.projects": "Projects",
+ // COPY REVIEW REQUIRED: specialists.required
+ "specialists.required": "Required specialist",
+ // COPY REVIEW REQUIRED: specialists.archive
+ "specialists.archive": "Archive specialist",
+ // COPY REVIEW REQUIRED: specialists.edit
+ "specialists.edit": "Edit specialist",
+ // COPY REVIEW REQUIRED: specialists.archived
+ "specialists.archived": "Archived",
+ // COPY REVIEW REQUIRED: specialists.unavailable
+ "specialists.unavailable": "Execution is unavailable until the tool profile is certified.",
+ // COPY REVIEW REQUIRED: templates.title
+ "templates.title": "Template library",
+ // COPY REVIEW REQUIRED: templates.install
+ "templates.install": "Add to team",
+ // COPY REVIEW REQUIRED: templates.diff
+ "templates.diff": "Compare template",
+ // COPY REVIEW REQUIRED: templates.apply
+ "templates.apply": "Apply selected fields",
+ // COPY REVIEW REQUIRED: templates.old
+ "templates.old": "Installed template",
+ // COPY REVIEW REQUIRED: templates.current
+ "templates.current": "Your copy",
+ // COPY REVIEW REQUIRED: templates.suggested
+ "templates.suggested": "Suggested values",
+ // COPY REVIEW REQUIRED: templates.version
+ "templates.version": "Template version",
+ // COPY REVIEW REQUIRED: templates.group.quality
+ "templates.group.quality": "Quality",
+ // COPY REVIEW REQUIRED: templates.group.safety
+ "templates.group.safety": "Safety",
+ // COPY REVIEW REQUIRED: templates.group.running
+ "templates.group.running": "Running things",
+ // COPY REVIEW REQUIRED: templates.group.words
+ "templates.group.words": "Words and reach",
+ // COPY REVIEW REQUIRED: templates.qa.name
+ "templates.qa.name": "QA and testing",
+ // COPY REVIEW REQUIRED: templates.qa.description
+ "templates.qa.description": "Find gaps in tests and check behaviour against the requirements.",
+ // COPY REVIEW REQUIRED: templates.qa.instructions
+ "templates.qa.instructions": "Check the requirements and existing tests. Report gaps with evidence and propose tests. Do not treat a model response as test evidence.",
+ // COPY REVIEW REQUIRED: templates.accessibility.name
+ "templates.accessibility.name": "Accessibility",
+ // COPY REVIEW REQUIRED: templates.accessibility.description
+ "templates.accessibility.description": "Check whether people can use the interface with different access needs.",
+ // COPY REVIEW REQUIRED: templates.accessibility.instructions
+ "templates.accessibility.instructions": "Check semantics, keyboard use and accessible names. Describe the evidence and any checks that still need a person.",
+ // COPY REVIEW REQUIRED: templates.performance.name
+ "templates.performance.name": "Performance",
+ // COPY REVIEW REQUIRED: templates.performance.description
+ "templates.performance.description": "Find slow paths and propose measured improvements.",
+ // COPY REVIEW REQUIRED: templates.performance.instructions
+ "templates.performance.instructions": "Use supplied measurements to identify slow paths. Explain uncertainty and propose repeatable checks before recommending changes.",
+ // COPY REVIEW REQUIRED: templates.security.name
+ "templates.security.name": "Security",
+ // COPY REVIEW REQUIRED: templates.security.description
+ "templates.security.description": "Review code and project material for security risks.",
+ // COPY REVIEW REQUIRED: templates.security.instructions
+ "templates.security.instructions": "Review the supplied code and material for security risks. Cite evidence. Do not access systems or credentials outside the task.",
+ // COPY REVIEW REQUIRED: templates.privacy.name
+ "templates.privacy.name": "Privacy",
+ // COPY REVIEW REQUIRED: templates.privacy.description
+ "templates.privacy.description": "Review how the project handles personal information.",
+ // COPY REVIEW REQUIRED: templates.privacy.instructions
+ "templates.privacy.instructions": "Identify personal information in the supplied project material. Propose ways to limit collection and access without inspecting private records.",
+ // COPY REVIEW REQUIRED: templates.ops.name
+ "templates.ops.name": "Ops",
+ // COPY REVIEW REQUIRED: templates.ops.description
+ "templates.ops.description": "Review operational plans and suggest reliable ways to run the project.",
+ // COPY REVIEW REQUIRED: templates.ops.instructions
+ "templates.ops.instructions": "Review supplied operational material and propose checks. Do not change infrastructure, deploy, spend money or move funds.",
+ // COPY REVIEW REQUIRED: templates.data.name
+ "templates.data.name": "Data",
+ // COPY REVIEW REQUIRED: templates.data.description
+ "templates.data.description": "Review data definitions and propose checks for data quality.",
+ // COPY REVIEW REQUIRED: templates.data.instructions
+ "templates.data.instructions": "Review supplied data definitions and propose quality checks. Do not access live private data, change infrastructure, spend money or move funds.",
+ // COPY REVIEW REQUIRED: templates.support.name
+ "templates.support.name": "Support",
+ // COPY REVIEW REQUIRED: templates.support.description
+ "templates.support.description": "Use project material to investigate reported problems.",
+ // COPY REVIEW REQUIRED: templates.support.instructions
+ "templates.support.instructions": "Investigate reported problems using supplied project material. Cite sources and prepare suggestions for a person. Do not contact customers.",
+ // COPY REVIEW REQUIRED: templates.docs.name
+ "templates.docs.name": "Docs",
+ // COPY REVIEW REQUIRED: templates.docs.description
+ "templates.docs.description": "Help people understand and use the project.",
+ // COPY REVIEW REQUIRED: templates.docs.instructions
+ "templates.docs.instructions": "Check supplied documentation against project behaviour. Propose clear instructions and examples, with evidence for technical claims.",
+ // COPY REVIEW REQUIRED: templates.localisation.name
+ "templates.localisation.name": "Localisation",
+ // COPY REVIEW REQUIRED: templates.localisation.description
+ "templates.localisation.description": "Review language and regional conventions.",
+ // COPY REVIEW REQUIRED: templates.localisation.instructions
+ "templates.localisation.instructions": "Review supplied text for language and regional conventions. Preserve meaning and identify wording that needs a fluent speaker to review.",
+ // COPY REVIEW REQUIRED: templates.seo.name
+ "templates.seo.name": "SEO",
+ // COPY REVIEW REQUIRED: templates.seo.description
+ "templates.seo.description": "Review how people can find and understand published pages.",
+ // COPY REVIEW REQUIRED: templates.seo.instructions
+ "templates.seo.instructions": "Review supplied pages and metadata. Propose clear descriptions and useful structure. Do not publish changes or promise search rankings.",
+ // COPY REVIEW REQUIRED: templates.blank.name
+ "templates.blank.name": "Blank specialist",
+ // COPY REVIEW REQUIRED: templates.blank.description
+ "templates.blank.description": "Start with your own name and standing instructions.",
+ // COPY REVIEW REQUIRED: templates.blank.instructions
+ "templates.blank.instructions": "Follow the task instructions within the team and project permissions. Ask a person when evidence or authority is missing.",
// COPY REVIEW REQUIRED: plan.connection
"plan.connection": "Connection",
// COPY REVIEW REQUIRED: plan.current_selection
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go
index a77ddaa3..b8ea377a 100644
--- a/internal/equipo/handlers.go
+++ b/internal/equipo/handlers.go
@@ -9,6 +9,7 @@ import (
"strings"
"amadan.net/oficina/equipo/internal/equipo/conversation"
+ "amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/equipo/planning"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/rastrillo/rastrillo/auth"
@@ -26,6 +27,9 @@ type budgetForm struct {
Fields []budgetField
}
type pageData struct {
+ Specialists []Specialist
+ Library library.View
+ SpecialistNames map[string]string
Conversation conversation.Page
Coordinator conversation.CoordinatorPage
Plan planning.Page
@@ -73,6 +77,12 @@ func (a *application) page(r *http.Request, key string) (pageData, error) {
return pageData{}, storeError(err)
}
data := pageData{Live: a.live.View(r), Topic: jobTopic(instance.ID, 0), CollectionTopic: jobTopic(instance.ID, 0), Nav: Navigation(), Key: key, Title: "nav." + key, Address: id.Address, TeamName: instance.Name, Owner: member.Active && member.Role == RoleOwner}
+ rows, e := a.store.Specialists(r.Context())
+ if e != nil {
+ return pageData{}, e
+ }
+ data.Specialists = rows
+ data.Nav, data.SpecialistNames = library.WithSpecialists(rows)
if err := a.fillCounts(r, &data); err != nil {
return pageData{}, err
}
@@ -279,50 +289,6 @@ func (a *application) settings(w http.ResponseWriter, r *http.Request) {
data.BudgetForms = budgetForms(data.Budget, data.Groups)
a.renderLive(w, r, "settings", data)
}
-func (a *application) specialist(w http.ResponseWriter, r *http.Request) {
- key := chi.URLParam(r, "key")
- if !validSpecialistKey(key) {
- a.failure(w, r, ErrNotFound)
- return
- }
- data, err := a.page(r, key)
- if err != nil {
- a.failure(w, r, err)
- return
- }
- specialists, err := a.store.Specialists(r.Context())
- if err != nil {
- a.failure(w, r, err)
- return
- }
- for _, s := range specialists {
- if s.Key == key {
- data.Specialist = s
- work, e := a.store.SpecialistWork(r.Context(), Actor{Address: data.Address}, key)
- if e != nil {
- a.failure(w, r, e)
- return
- }
- data.Work = work
- data.Tasks = work.Tasks
- if e = a.fillCounts(r, &data); e != nil {
- a.failure(w, r, e)
- return
- }
- a.renderLive(w, r, "specialist", data)
- return
- }
- }
- a.failure(w, r, ErrNotFound)
-}
-func validSpecialistKey(key string) bool {
- for _, k := range []string{"product", "design", "copy", "engineering", "review"} {
- if key == k {
- return true
- }
- }
- return false
-}
// Reject unknown and duplicate fields, including submitted identity. Role on the
// roster form describes the target member; the actor always comes from auth.From.
@@ -449,34 +415,6 @@ func (a *application) saveMember(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/people", http.StatusSeeOther)
}
-func (a *application) saveSpecialist(w http.ResponseWriter, r *http.Request) {
- key := chi.URLParam(r, "key")
- if !validSpecialistKey(key) {
- a.failure(w, r, ErrNotFound)
- return
- }
- actor, err := a.writeForm(w, r, "revision", "model_selection", "provider", "model_family", "model", "standing_instructions", "max_concurrent")
- if err != nil {
- a.failure(w, r, err)
- return
- }
- revision, err := number(r, "revision")
- if err != nil {
- a.failure(w, r, err)
- return
- }
- concurrent, err := number(r, "max_concurrent")
- if err != nil || int64(int(concurrent)) != concurrent {
- a.failure(w, r, ErrInvalid)
- return
- }
- err = a.store.SaveSpecialist(r.Context(), actor, Specialist{Key: key, Revision: revision, ModelSelection: r.PostForm.Get("model_selection"), Provider: r.PostForm.Get("provider"), ModelFamily: r.PostForm.Get("model_family"), Model: r.PostForm.Get("model"), StandingInstructions: r.PostForm.Get("standing_instructions"), MaxConcurrent: int(concurrent)})
- if err != nil {
- a.failure(w, r, err)
- return
- }
- http.Redirect(w, r, "/specialists/"+key, http.StatusSeeOther)
-}
func limitFields(prefix string, p team.PeriodLimits, set bool) []budgetField {
fields := []budgetField{{Name: prefix + "calls", CopyKey: "budget.calls"}, {Name: prefix + "input", CopyKey: "budget.input"}, {Name: prefix + "output", CopyKey: "budget.output"}, {Name: prefix + "seconds", CopyKey: "budget.seconds"}}
diff --git a/internal/equipo/icons/icons.go b/internal/equipo/icons/icons.go
index 3acd20e5..86ffd107 100644
--- a/internal/equipo/icons/icons.go
+++ b/internal/equipo/icons/icons.go
@@ -20,6 +20,7 @@ package icons
import "html/template"
var icons = map[string]template.HTML{
+ "shield": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true" viewBox="0 0 24 24"><path d="M12 3 3 7v5c0 5 9 9 9 9s9-4 9-9V7z"/></svg>`,
"users": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /> <path d="M16 3.128a4 4 0 0 1 0 7.744" /> <path d="M22 21v-2a4 4 0 0 0-3-3.87" /> <circle cx="9" cy="7" r="4" /></svg>`,
"message-circle": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`,
"inbox": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>`,
diff --git a/internal/equipo/library/application.go b/internal/equipo/library/application.go
new file mode 100644
index 00000000..2270ca87
--- /dev/null
+++ b/internal/equipo/library/application.go
@@ -0,0 +1,62 @@
+package library
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "context"
+ "gorm.io/gorm"
+)
+
+type Application struct {
+ Write func(context.Context, func(*gorm.DB) error) error
+ Read func(context.Context, kernel.Actor, func(*gorm.DB) error) error
+ At func(*gorm.DB) *Store
+ Normalize func(string) string
+}
+
+func (s *Application) read(ctx context.Context, a kernel.Actor, fn func(*Store) error) error {
+ return s.Read(ctx, a, func(tx *gorm.DB) error { return fn(s.At(tx)) })
+}
+func (s *Application) libraryWrite(ctx context.Context, fn func(*Store) error) error {
+ return s.Write(ctx, func(tx *gorm.DB) error { return fn(s.At(tx)) })
+}
+func (s *Application) CreateSpecialist(ctx context.Context, a kernel.Actor, in SpecialistInput, m kernel.Mutation) (row Specialist, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.Create(a, in, m); return err })
+ return
+}
+func (s *Application) UpdateSpecialist(ctx context.Context, a kernel.Actor, in SpecialistInput, m kernel.Mutation) (row Specialist, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.Update(a, in, m); return err })
+ return
+}
+func (s *Application) DeleteSpecialist(ctx context.Context, a kernel.Actor, key string, m kernel.Mutation) error {
+ a.Address = s.Normalize(a.Address)
+ return s.libraryWrite(ctx, func(l *Store) error { return l.Delete(a, key, m) })
+}
+func (s *Application) Specialist(ctx context.Context, a kernel.Actor, key string) (row Specialist, err error) {
+ err = s.read(ctx, a, func(l *Store) error { row, err = l.Get(a, key); return err })
+ return
+}
+func (s *Application) SpecialistTemplates(ctx context.Context, a kernel.Actor) (rows []Template, err error) {
+ err = s.read(ctx, a, func(l *Store) error { rows, err = l.Templates(a); return err })
+ return
+}
+func (s *Application) InstallSpecialistTemplate(ctx context.Context, a kernel.Actor, ref TemplateRef, m kernel.Mutation) (row Specialist, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.Install(a, ref, m); return err })
+ return
+}
+func (s *Application) SpecialistTemplateDiff(ctx context.Context, a kernel.Actor, key string, ref TemplateRef) (diff TemplateDiff, err error) {
+ err = s.read(ctx, a, func(l *Store) error { diff, err = l.Diff(a, key, ref); return err })
+ return
+}
+func (s *Application) ApplySpecialistTemplate(ctx context.Context, a kernel.Actor, key string, diff TemplateDiff, selected []string, m kernel.Mutation) (row Specialist, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.Apply(a, key, diff, selected, m); return err })
+ return
+}
+
+func (s *Application) ListSpecialists(ctx context.Context, a kernel.Actor) (rows []Specialist, err error) {
+ err = s.read(ctx, a, func(l *Store) error { rows, err = l.List(a); return err })
+ return
+}
diff --git a/internal/equipo/library/budget_test.go b/internal/equipo/library/budget_test.go
new file mode 100644
index 00000000..12ed619c
--- /dev/null
+++ b/internal/equipo/library/budget_test.go
@@ -0,0 +1,10 @@
+package library
+
+import (
+ "os"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/equipo/library/counts.go b/internal/equipo/library/counts.go
new file mode 100644
index 00000000..ba128b61
--- /dev/null
+++ b/internal/equipo/library/counts.go
@@ -0,0 +1,119 @@
+package library
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/planning"
+ "gorm.io/gorm"
+ "time"
+)
+
+func VisibleTasks(tx *gorm.DB, teamID string, since time.Time) *gorm.DB {
+ // Unknown finish dates remain visible. Both job and person transitions matter.
+ return tx.Model(&planning.Task{}).Joins("LEFT JOIN jobs visible_job ON visible_job.id=tasks.job_id AND visible_job.account=tasks.team_id").Where("tasks.team_id=?", teamID).Where(`
+ (tasks.state NOT IN ('failed','cancelled','merged') AND COALESCE(visible_job.state,'') NOT IN ('failed','cancelled'))
+ OR MAX(COALESCE(julianday(visible_job.updated_at),0),COALESCE((SELECT MAX(julianday(at)) FROM audit_events WHERE record_id=tasks.id AND kind IN ('task.cancel','task.merge')),0)) IN (0)
+ OR MAX(COALESCE(julianday(visible_job.updated_at),0),COALESCE((SELECT MAX(julianday(at)) FROM audit_events WHERE record_id=tasks.id AND kind IN ('task.cancel','task.merge')),0))>=julianday(?)`, since).Select("tasks.*")
+}
+
+func Counts(tx *gorm.DB, teamID string, now time.Time) (map[string]planning.SpecialistWorkView, error) {
+ out := map[string]planning.SpecialistWorkView{}
+ err := func() error {
+ for _, key := range DefaultKeys {
+ v := planning.SpecialistWorkView{CountsKnown: true, UsageKnown: true}
+ if key != "engineering" && key != "review" {
+ out[key] = v
+ continue
+ }
+ caps := []string{"reproduce", "implement"}
+ if key == "review" {
+ caps = []string{"review", "verify"}
+ }
+ var counts struct {
+ Working, Queued, Finished, Waiting int
+ Unknown int64
+ Calls, Input, Output int64
+ }
+ // One row per task before aggregation avoids multiplying usage by attempts.
+ err := tx.Raw(`WITH visible AS (?), classified AS (
+ SELECT t.id,t.job_id,
+ CASE WHEN t.state IN ('failed','cancelled','merged') OR j.state IN ('failed','cancelled') THEN 'finished'
+ WHEN (SELECT count(*) FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='succeeded')=2 THEN CASE WHEN (SELECT MAX(julianday(att.updated_at)) FROM attempts att JOIN steps st ON st.id=att.step_id JOIN runner_assignments a ON a.attempt_id=att.id WHERE a.task_id=t.id AND st.capability IN ?)<julianday(?) THEN 'hidden' ELSE 'finished' END
+ WHEN EXISTS(SELECT 1 FROM questions q JOIN runner_assignments a ON a.id=q.assignment_id JOIN attempts att ON att.id=a.attempt_id WHERE q.task_id=t.id AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence AND a.step_key IN ? AND julianday(a.lease_deadline)>julianday(?) AND julianday(att.lease_deadline)>julianday(?)) THEN 'waiting'
+ WHEN EXISTS(SELECT 1 FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='running') THEN 'working'
+ ELSE 'queued' END bucket
+ FROM visible t LEFT JOIN jobs j ON j.id=t.job_id
+ ) SELECT COALESCE(SUM(bucket='working'),0) working,COALESCE(SUM(bucket='queued'),0) queued,
+ COALESCE(SUM(bucket='finished'),0) finished,COALESCE(SUM(bucket='waiting'),0) waiting,COALESCE(SUM(job_id=0),0) unknown
+ FROM classified`, VisibleTasks(tx, teamID, weekStart(now)), caps, caps, weekStart(now), caps, now, now, caps).Scan(&counts).Error
+ if err != nil {
+ return err
+ }
+ v.Working, v.Queued, v.Finished, v.Waiting = counts.Working, counts.Queued, counts.Finished, counts.Waiting
+ unprepared := counts.Unknown > 0
+ err = tx.Raw(`SELECT COALESCE(SUM(CASE WHEN r.state='open' THEN r.r_calls ELSE r.s_calls END),0) calls,
+ COALESCE(SUM(r.s_input),0) input, COALESCE(SUM(r.s_output),0) output,
+ COALESCE(SUM(r.state='open' OR r.settled_by='unknown'),0) unknown
+ FROM reservations r JOIN steps st ON st.id=r.step_id JOIN (?) t ON t.job_id=r.job_id
+ WHERE st.capability IN ? AND julianday(r.created_at)>=julianday(?)`, VisibleTasks(tx, teamID, weekStart(now)), caps, weekStart(now)).Scan(&counts).Error
+ if err != nil {
+ return err
+ }
+ v.CountedTurns, v.InputTokens, v.OutputTokens = counts.Calls, counts.Input, counts.Output
+ v.UsageKnown = counts.Unknown == 0 && !unprepared
+ out[key] = v
+ }
+ return nil
+ }()
+ if err == nil {
+ err = additionalCounts(tx, teamID, now, out)
+ }
+ return out, err
+}
+
+func additionalCounts(tx *gorm.DB, teamID string, now time.Time, out map[string]planning.SpecialistWorkView) error {
+ var keys []string
+ if err := tx.Model(&Specialist{}).Where("team_id=? AND key NOT IN ?", teamID, []string{"engineering", "review"}).Pluck("key", &keys).Error; err != nil {
+ return err
+ }
+ for _, key := range keys {
+ var result struct {
+ Working, Queued, Finished, Waiting int
+ Unknown, Calls, Input, Output int64
+ }
+ // Classify once per task; plan step identities, not display labels, join work.
+ err := tx.Raw(`WITH selected AS (
+ SELECT t.id,t.job_id,t.state,st.key,st.state step_state,
+ (SELECT MAX(julianday(a.updated_at)) FROM attempts a WHERE a.step_id=st.id) ended,
+ EXISTS(SELECT 1 FROM questions q JOIN runner_assignments a ON a.id=q.assignment_id JOIN attempts att ON att.id=a.attempt_id
+ WHERE q.task_id=t.id AND a.step_key=st.key AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence
+ AND julianday(a.lease_deadline)>julianday(?) AND julianday(att.lease_deadline)>julianday(?)) waiting
+ FROM (?) t JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.plan_revision,
+ json_each(p.plan,'$.Steps') ps
+ LEFT JOIN steps st ON st.job_id=t.job_id AND st.key=json_extract(ps.value,'$.Key')
+ WHERE json_extract(ps.value,'$.Specialist')=?
+ ), grouped AS (
+ SELECT id,job_id,CASE WHEN state IN ('failed','cancelled','merged') THEN 'finished'
+ WHEN SUM(step_state='succeeded')=count(*) THEN CASE WHEN MAX(ended)<julianday(?) THEN 'hidden' ELSE 'finished' END
+ WHEN SUM(waiting)>0 THEN 'waiting' WHEN SUM(step_state='running')>0 THEN 'working' ELSE 'queued' END bucket FROM selected GROUP BY id,job_id,state
+ ) SELECT COALESCE(SUM(bucket='working'),0) working,COALESCE(SUM(bucket='queued'),0) queued,
+ COALESCE(SUM(bucket='finished'),0) finished,COALESCE(SUM(bucket='waiting'),0) waiting,COALESCE(SUM(job_id=0),0) unknown FROM grouped`, now, now, VisibleTasks(tx, teamID, weekStart(now)), key, weekStart(now)).Scan(&result).Error
+ if err != nil {
+ return err
+ }
+ v := planning.SpecialistWorkView{CountsKnown: true, UsageKnown: result.Unknown == 0, Working: result.Working, Queued: result.Queued, Finished: result.Finished, Waiting: result.Waiting}
+ err = tx.Raw(`SELECT COALESCE(SUM(CASE WHEN r.state='open' THEN r.r_calls ELSE r.s_calls END),0) calls,
+ COALESCE(SUM(r.s_input),0) input,COALESCE(SUM(r.s_output),0) output,COALESCE(SUM(r.state='open' OR r.settled_by='unknown'),0) unknown
+ FROM reservations r JOIN steps st ON st.id=r.step_id JOIN tasks t ON t.job_id=r.job_id
+ JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.plan_revision
+ WHERE t.team_id=? AND julianday(r.created_at)>=julianday(?) AND EXISTS(
+ SELECT 1 FROM json_each(p.plan,'$.Steps') ps WHERE json_extract(ps.value,'$.Key')=st.key AND json_extract(ps.value,'$.Specialist')=?)`, teamID, weekStart(now), key).Scan(&result).Error
+ if err != nil {
+ return err
+ }
+ v.UsageKnown = v.UsageKnown && result.Unknown == 0
+ v.CountedTurns = result.Calls
+ v.InputTokens = result.Input
+ v.OutputTokens = result.Output
+ out[key] = v
+ }
+ return nil
+}
diff --git a/internal/equipo/library/handlers.go b/internal/equipo/library/handlers.go
new file mode 100644
index 00000000..dcd2543d
--- /dev/null
+++ b/internal/equipo/library/handlers.go
@@ -0,0 +1,255 @@
+package library
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "net/http"
+ "slices"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "github.com/go-chi/chi/v5"
+)
+
+type Operations interface {
+ SaveSpecialist(context.Context, kernel.Actor, Specialist) error
+ Specialist(context.Context, kernel.Actor, string) (Specialist, error)
+ CreateSpecialist(context.Context, kernel.Actor, SpecialistInput, kernel.Mutation) (Specialist, error)
+ UpdateSpecialist(context.Context, kernel.Actor, SpecialistInput, kernel.Mutation) (Specialist, error)
+ DeleteSpecialist(context.Context, kernel.Actor, string, kernel.Mutation) error
+ SpecialistTemplates(context.Context, kernel.Actor) ([]Template, error)
+ InstallSpecialistTemplate(context.Context, kernel.Actor, TemplateRef, kernel.Mutation) (Specialist, error)
+ SpecialistTemplateDiff(context.Context, kernel.Actor, string, TemplateRef) (TemplateDiff, error)
+ ApplySpecialistTemplate(context.Context, kernel.Actor, string, TemplateDiff, []string, kernel.Mutation) (Specialist, error)
+}
+type FieldDiff struct{ Key, CopyKey, Old, Current, Suggested string }
+type ProjectOption struct {
+ ID int64
+ Name string
+ Selected bool
+}
+type View struct {
+ Specialist Specialist
+ Templates []Template
+ Icons []string
+ Models []ModelRef
+ Projects []ProjectOption
+ Diff TemplateDiff
+ Fields []FieldDiff
+ DiffJSON, RequestID string
+}
+type Handler struct {
+ LegacyForm func(http.ResponseWriter, *http.Request, ...string) (kernel.Actor, error)
+ Number func(*http.Request, string) (int64, error)
+ NotFound error
+ Store Operations
+ Actor func(*http.Request) (kernel.Actor, error)
+ Render func(http.ResponseWriter, *http.Request, string, View)
+ Failure func(http.ResponseWriter, *http.Request, error)
+ Invalid error
+}
+
+func (h *Handler) Catalog(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ rows, err := h.Store.SpecialistTemplates(r.Context(), a)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ h.Render(w, r, "template_library", View{Templates: rows, RequestID: rand.Text()})
+}
+func (h *Handler) Form(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ row := Specialist{MaxConcurrent: 1, Icon: "plus"}
+ if key := chi.URLParam(r, "key"); key != "" {
+ row, err = h.Store.Specialist(r.Context(), a, key)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ }
+ iconIDs := []string{"lightbulb", "pencil", "type", "code", "check-circle", "shield", "sliders", "plus"}
+ if !slices.Contains(iconIDs, row.Icon) {
+ iconIDs = append(iconIDs, row.Icon)
+ }
+ h.Render(w, r, "specialist_form", View{Specialist: row, Icons: iconIDs, Models: append(slices.Clone(row.AllowedModels), ModelRef{}), RequestID: rand.Text()})
+}
+func (h *Handler) form(w http.ResponseWriter, r *http.Request, allowed ...string) (kernel.Actor, kernel.Mutation, error) {
+ a, err := h.Actor(r)
+ if err != nil {
+ return a, kernel.Mutation{}, err
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
+ if r.ParseForm() != nil {
+ return a, kernel.Mutation{}, h.Invalid
+ }
+ for key, v := range r.PostForm {
+ modelField := false
+ if strings.HasPrefix(key, "model.") {
+ parts := strings.Split(key, ".")
+ if len(parts) == 3 {
+ n, e := strconv.Atoi(parts[1])
+ modelField = e == nil && n >= 0 && n <= 100 && slices.Contains([]string{"provider", "family", "name"}, parts[2]) && slices.Contains(allowed, "models")
+ }
+ }
+ if (!slices.Contains(allowed, key) || key == "models") && !modelField || len(v) != 1 && key != "field" && key != "project" {
+ return a, kernel.Mutation{}, h.Invalid
+ }
+ }
+ revision := int64(0)
+ if v := r.PostForm.Get("revision"); v != "" {
+ revision, err = strconv.ParseInt(v, 10, 64)
+ if err != nil {
+ return a, kernel.Mutation{}, h.Invalid
+ }
+ }
+ m := kernel.Mutation{RequestID: r.PostForm.Get("request_id"), Revision: revision}
+ if !m.Valid() {
+ return a, m, h.Invalid
+ }
+ return a, m, nil
+}
+func (h *Handler) Save(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "revision", "name", "icon", "instructions", "max_concurrent", "models", "project")
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ max, err := strconv.Atoi(r.PostForm.Get("max_concurrent"))
+ if err != nil {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ in := SpecialistInput{Key: chi.URLParam(r, "key"), Name: r.PostForm.Get("name"), Icon: r.PostForm.Get("icon"), Instructions: r.PostForm.Get("instructions"), MaxConcurrent: max}
+ for i := 0; i <= 100; i++ {
+ prefix := "model." + strconv.Itoa(i) + "."
+ model := ModelRef{r.PostForm.Get(prefix + "provider"), r.PostForm.Get(prefix + "family"), r.PostForm.Get(prefix + "name")}
+ if model != (ModelRef{}) {
+ in.AllowedModels = append(in.AllowedModels, model)
+ }
+ }
+ for _, v := range r.PostForm["project"] {
+ id, e := strconv.ParseInt(v, 10, 64)
+ if e != nil {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ in.ProjectIDs = append(in.ProjectIDs, id)
+ }
+ var row Specialist
+ if in.Key == "" {
+ row, err = h.Store.CreateSpecialist(r.Context(), a, in, m)
+ } else {
+ row, err = h.Store.UpdateSpecialist(r.Context(), a, in, m)
+ }
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/specialists/"+row.Key, http.StatusSeeOther)
+}
+func (h *Handler) Archive(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "revision")
+ if err == nil {
+ err = h.Store.DeleteSpecialist(r.Context(), a, chi.URLParam(r, "key"), m)
+ }
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/work", http.StatusSeeOther)
+}
+func (h *Handler) Install(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "version")
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ version, err := strconv.ParseInt(r.PostForm.Get("version"), 10, 64)
+ if err != nil {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ row, err := h.Store.InstallSpecialistTemplate(r.Context(), a, TemplateRef{chi.URLParam(r, "id"), version}, m)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/specialists/"+row.Key+"/edit", http.StatusSeeOther)
+}
+func (h *Handler) Diff(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ key := chi.URLParam(r, "key")
+ row, err := h.Store.Specialist(r.Context(), a, key)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ version := row.TemplateVersion
+ if v := r.URL.Query().Get("version"); v != "" {
+ version, err = strconv.ParseInt(v, 10, 64)
+ if err != nil {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ }
+ diff, err := h.Store.SpecialistTemplateDiff(r.Context(), a, key, TemplateRef{row.TemplateID, version})
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ view := View{Specialist: row, Diff: diff, RequestID: rand.Text()}
+ raw, _ := json.Marshal(diff)
+ view.DiffJSON = string(raw)
+ labels := map[string]string{"name": "specialists.name", "icon": "specialists.icon", "instructions": "specialists.instructions", "allowed_models": "specialists.models", "tools": "specialists.tools", "project_ids": "specialists.projects", "max_concurrent": "specialist.concurrent"}
+ for _, field := range []string{"name", "icon", "instructions", "allowed_models", "tools", "project_ids", "max_concurrent"} {
+ view.Fields = append(view.Fields, FieldDiff{field, labels[field], string(diff.Old[field]), string(diff.Current[field]), string(diff.Suggested[field])})
+ }
+ h.Render(w, r, "template_diff", view)
+}
+func (h *Handler) Apply(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "revision", "diff", "field")
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ var diff TemplateDiff
+ if json.Unmarshal([]byte(r.PostForm.Get("diff")), &diff) != nil {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ row, err := h.Store.ApplySpecialistTemplate(r.Context(), a, chi.URLParam(r, "key"), diff, r.PostForm["field"], m)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/specialists/"+row.Key, http.StatusSeeOther)
+}
+
+func (h *Handler) Detail(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ row, err := h.Store.Specialist(r.Context(), a, chi.URLParam(r, "key"))
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ h.Render(w, r, "specialist", View{Specialist: row, RequestID: rand.Text()})
+}
diff --git a/internal/equipo/library/legacy.go b/internal/equipo/library/legacy.go
new file mode 100644
index 00000000..4aa553f0
--- /dev/null
+++ b/internal/equipo/library/legacy.go
@@ -0,0 +1,47 @@
+package library
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "slices"
+ "strings"
+)
+
+func (s *Store) SaveLegacy(actor kernel.Actor, specialist Specialist) error {
+ if !slices.Contains(DefaultKeys, specialist.Key) || specialist.MaxConcurrent <= 0 || specialist.Revision < 0 {
+ return s.deps.Invalid
+ }
+ if specialist.ModelSelection != "best_fit" && specialist.ModelSelection != "fixed" {
+ return s.deps.Invalid
+ }
+ specialist.Provider = strings.TrimSpace(specialist.Provider)
+ specialist.ModelFamily = strings.TrimSpace(specialist.ModelFamily)
+ specialist.Model = strings.TrimSpace(specialist.Model)
+ if specialist.ModelSelection == "fixed" && (specialist.Provider == "" || specialist.ModelFamily == "" || specialist.Model == "") {
+ return s.deps.Invalid
+ }
+ tx := s.tx
+ access, err := s.deps.Authorize(tx, actor)
+ if err != nil {
+ return err
+ }
+ if !access.Owner {
+ return s.deps.Forbidden
+ }
+ var old Specialist
+ if err := tx.Where("key = ? AND team_id=? AND archived=?", specialist.Key, access.TeamID, false).First(&old).Error; err != nil {
+ return err
+ }
+ if old.Revision != specialist.Revision {
+ return s.deps.Conflict
+ }
+ specialist.Revision++
+ result := tx.Model(&Specialist{}).Where("key = ? AND revision = ?", specialist.Key, old.Revision).
+ Select("ModelSelection", "Provider", "ModelFamily", "Model", "StandingInstructions", "MaxConcurrent", "Revision").Updates(&specialist)
+ if result.Error != nil {
+ return result.Error
+ }
+ if result.RowsAffected != 1 {
+ return s.deps.Conflict
+ }
+ return s.deps.Audit(tx, actor, "specialist.save", specialist.Key)
+}
diff --git a/internal/equipo/library/legacy_handlers.go b/internal/equipo/library/legacy_handlers.go
new file mode 100644
index 00000000..55715c59
--- /dev/null
+++ b/internal/equipo/library/legacy_handlers.go
@@ -0,0 +1,36 @@
+package library
+
+import (
+ "github.com/go-chi/chi/v5"
+ "net/http"
+ "slices"
+)
+
+func (h *Handler) SaveLegacy(w http.ResponseWriter, r *http.Request) {
+ key := chi.URLParam(r, "key")
+ if !slices.Contains(DefaultKeys, key) {
+ h.Failure(w, r, h.NotFound)
+ return
+ }
+ actor, err := h.LegacyForm(w, r, "revision", "model_selection", "provider", "model_family", "model", "standing_instructions", "max_concurrent")
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ revision, err := h.Number(r, "revision")
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ concurrent, err := h.Number(r, "max_concurrent")
+ if err != nil || int64(int(concurrent)) != concurrent {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ err = h.Store.SaveSpecialist(r.Context(), actor, Specialist{Key: key, Revision: revision, ModelSelection: r.PostForm.Get("model_selection"), Provider: r.PostForm.Get("provider"), ModelFamily: r.PostForm.Get("model_family"), Model: r.PostForm.Get("model"), StandingInstructions: r.PostForm.Get("standing_instructions"), MaxConcurrent: int(concurrent)})
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/specialists/"+key, http.StatusSeeOther)
+}
diff --git a/internal/equipo/library/navigation.go b/internal/equipo/library/navigation.go
new file mode 100644
index 00000000..0935b9fe
--- /dev/null
+++ b/internal/equipo/library/navigation.go
@@ -0,0 +1,51 @@
+package library
+
+type NavItem struct{ Key, Group, Href, CopyKey, Icon string }
+
+func Navigation() []NavItem {
+ return []NavItem{
+ {"conversation", "", "/conversation", "nav.conversation", "message-circle"},
+ {"needs-you", "", "/needs-you", "nav.needs-you", "inbox"},
+ {"journey", "", "/journey", "nav.journey", "route"},
+ {"projects", "", "/projects", "nav.projects", "folder"},
+ {"product", "specialists", "/specialists/product", "nav.product", "lightbulb"},
+ {"design", "specialists", "/specialists/design", "nav.design", "pencil"},
+ {"copy", "specialists", "/specialists/copy", "nav.copy", "type"},
+ {"engineering", "specialists", "/specialists/engineering", "nav.engineering", "code"},
+ {"review", "specialists", "/specialists/review", "nav.review", "check-circle"},
+ {"templates", "specialists", "/templates", "templates.title", "plus"},
+ {"connections", "team", "/connections", "nav.connections", "plug"},
+ {"people", "team", "/people", "nav.people", "users"},
+ {"settings", "team", "/settings", "nav.settings", "sliders"},
+ }
+}
+
+func WithSpecialists(rows []Specialist) ([]NavItem, map[string]string) {
+ nav := []NavItem{}
+ active := map[string]bool{}
+ for _, row := range rows {
+ active[row.Key] = true
+ }
+ for _, item := range Navigation() {
+ if item.Group != "specialists" || item.Key == "templates" || active[item.Key] {
+ nav = append(nav, item)
+ }
+ }
+ names := map[string]string{}
+ for _, row := range rows {
+ names[row.Key] = row.Name
+ }
+ for i, item := range nav {
+ if item.Key == "templates" {
+ custom := []NavItem{}
+ for _, row := range rows {
+ if row.Role == "" {
+ custom = append(custom, NavItem{row.Key, "specialists", "/specialists/" + row.Key, "", row.Icon})
+ }
+ }
+ nav = append(nav[:i], append(custom, nav[i:]...)...)
+ break
+ }
+ }
+ return nav, names
+}
diff --git a/internal/equipo/library/references.go b/internal/equipo/library/references.go
new file mode 100644
index 00000000..836194b7
--- /dev/null
+++ b/internal/equipo/library/references.go
@@ -0,0 +1,44 @@
+package library
+
+import (
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "gorm.io/gorm"
+ "slices"
+)
+
+func UnstartedReference(tx *gorm.DB, key string) (bool, error) {
+ var n int64
+ err := tx.Raw(`SELECT count(*) FROM tasks t JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.plan_revision, json_each(p.plan,'$.Steps') st
+ WHERE json_extract(st.value,'$.Specialist')=? AND t.state NOT IN ('cancelled','failed','merged','replaced')
+ AND NOT EXISTS (SELECT 1 FROM steps s WHERE s.job_id=t.job_id AND s.key=json_extract(st.value,'$.Key') AND (s.attempts>0 OR s.state IN ('succeeded','cancelled')))
+ AND NOT EXISTS (SELECT 1 FROM runner_assignments a WHERE a.task_id=t.id AND a.step_key=json_extract(st.value,'$.Key') AND a.claim_request<>'')`, key).Scan(&n).Error
+ return n > 0, err
+}
+
+// ValidatePlan checks only mutable selections. Started steps retain their saved
+// specialist and runner brief even after the library entry is archived.
+func (s *Store) ValidatePlan(teamID string, p taskplan.Plan, started map[string]bool) error {
+ for _, st := range p.Steps {
+ if started[st.Key] || st.Action == "person" || st.Action == "checks" || st.Action == "publish" {
+ continue
+ }
+ key := st.Specialist
+ if key == "" {
+ key = "engineering"
+ }
+ row, err := s.get(Access{TeamID: teamID}, key)
+ if err != nil {
+ return err
+ }
+ if row.Archived || len(row.ProjectIDs) > 0 && !slices.Contains(row.ProjectIDs, p.ProjectID) {
+ return s.deps.Forbidden
+ }
+ }
+ return nil
+}
+func ModelAllowed(row Specialist, provider, family, model string) bool {
+ return len(row.AllowedModels) == 0 || slices.Contains(row.AllowedModels, ModelRef{provider, family, model})
+}
+func ProjectAllowed(row Specialist, project int64) bool {
+ return len(row.ProjectIDs) == 0 || slices.Contains(row.ProjectIDs, project)
+}
diff --git a/internal/equipo/library/selection.go b/internal/equipo/library/selection.go
new file mode 100644
index 00000000..4ea1df1b
--- /dev/null
+++ b/internal/equipo/library/selection.go
@@ -0,0 +1,32 @@
+package library
+
+import "gorm.io/gorm"
+
+func ExecutionSpecialist(tx *gorm.DB, key string, unavailable error, normalize func(error) error) (Specialist, error) {
+ var sp Specialist
+ if err := tx.Where("key = ?", key).First(&sp).Error; err != nil {
+ return sp, normalize(err)
+ }
+ if sp.Archived || sp.MaxConcurrent <= 0 {
+ return sp, unavailable
+ }
+ // Containment-pending attempts occupy capacity even after stop is requested.
+ capabilities := []string{key}
+ if key == "engineering" {
+ capabilities = []string{"reproduce", "implement", "reconcile"}
+ }
+ if key == "review" {
+ capabilities = []string{"review", "verify"}
+ }
+ var live int64
+ if key == "product" {
+ capabilities = []string{"scope", "research"}
+ }
+ if err := tx.Table("attempts").Joins("JOIN steps ON steps.id = attempts.step_id").Where("attempts.containment = ? AND (steps.capability IN ? OR EXISTS (SELECT 1 FROM runner_assignments ra WHERE ra.attempt_id=attempts.id AND json_extract(ra.brief,'$.step.SpecialistKey')=?))", "pending", capabilities, key).Count(&live).Error; err != nil {
+ return sp, normalize(err)
+ }
+ if live >= int64(sp.MaxConcurrent) {
+ return sp, unavailable
+ }
+ return sp, nil
+}
diff --git a/internal/equipo/library/specialists.go b/internal/equipo/library/specialists.go
new file mode 100644
index 00000000..6dafdd9a
--- /dev/null
+++ b/internal/equipo/library/specialists.go
@@ -0,0 +1,329 @@
+package library
+
+import (
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/equipo/icons"
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+type ModelRef struct{ Provider, Family, Model string }
+type SpecialistInput struct {
+ Key, Name, Icon, Instructions string
+ AllowedModels []ModelRef
+ Tools []string
+ ProjectIDs []int64
+ MaxConcurrent int
+}
+type Specialist struct {
+ Key string `gorm:"primaryKey"`
+ ModelSelection, Provider, ModelFamily, Model, StandingInstructions string
+ MaxConcurrent int
+ Revision int64
+ TeamID string `gorm:"not null;default:''"`
+ Creator string `gorm:"not null;default:''"`
+ Name string `gorm:"not null;default:''"`
+ Icon string `gorm:"not null;default:''"`
+ Role string `gorm:"not null;default:''"`
+ Required bool `gorm:"not null;default:false"`
+ Archived bool `gorm:"not null;default:false"`
+ AllowedModels []ModelRef `gorm:"serializer:json;not null;default:'[]'"`
+ Tools []string `gorm:"serializer:json;not null;default:'[]'"`
+ ProjectIDs []int64 `gorm:"serializer:json;not null;default:'[]'"`
+ TemplateID string `gorm:"not null;default:''"`
+ TemplateVersion int64 `gorm:"not null;default:0"`
+ TemplateBase string `gorm:"not null;default:'{}'"`
+}
+type request struct {
+ TeamID, Principal, Operation, Resource, RequestID string `gorm:"primaryKey"`
+ InputHash, Result string
+}
+
+func (request) TableName() string { return "specialist_requests" }
+
+var Models = []any{&Specialist{}, &request{}}
+var DefaultKeys = []string{"product", "design", "copy", "engineering", "review"}
+var DefaultIcons = []string{"lightbulb", "pencil", "type", "code", "check-circle"}
+
+type Access struct {
+ TeamID string
+ Owner bool
+}
+type Dependencies struct {
+ Authorize func(*gorm.DB, kernel.Actor) (Access, error)
+ Audit func(*gorm.DB, kernel.Actor, string, string) error
+ Referenced func(*gorm.DB, string) (bool, error)
+ Copy func(string) string
+ Catalog func() []Template
+ Invalid, Forbidden, NotFound, Conflict error
+}
+type Store struct {
+ tx *gorm.DB
+ deps Dependencies
+}
+
+func New(tx *gorm.DB, d Dependencies) *Store { return &Store{tx: tx, deps: d} }
+func Seed(tx *gorm.DB, teamID string) (int64, error) {
+ rows := []Specialist{}
+ for i, key := range DefaultKeys {
+ rows = append(rows, Specialist{Key: key, TeamID: teamID, Role: key, Icon: DefaultIcons[i], Required: key == "engineering" || key == "review", ModelSelection: "best_fit", MaxConcurrent: 1, Revision: 1, AllowedModels: []ModelRef{}, Tools: []string{}, ProjectIDs: []int64{}})
+ }
+ r := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "key"}}, DoNothing: true}).Create(&rows)
+ return r.RowsAffected, r.Error
+}
+func Input(s Specialist) SpecialistInput {
+ return SpecialistInput{Key: s.Key, Name: s.Name, Icon: s.Icon, Instructions: s.StandingInstructions, AllowedModels: slices.Clone(s.AllowedModels), Tools: slices.Clone(s.Tools), ProjectIDs: slices.Clone(s.ProjectIDs), MaxConcurrent: s.MaxConcurrent}
+}
+func (s *Store) Get(actor kernel.Actor, key string) (Specialist, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Specialist{}, err
+ }
+ return s.get(a, key)
+}
+func (s *Store) get(a Access, key string) (Specialist, error) {
+ var row Specialist
+ err := s.tx.Where("key=? AND team_id=?", key, a.TeamID).First(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ err = s.deps.NotFound
+ }
+ return row, err
+}
+func (s *Store) List(actor kernel.Actor) ([]Specialist, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return nil, err
+ }
+ var rows []Specialist
+ err = s.tx.Where("team_id=? AND archived=?", a.TeamID, false).Order("key").Find(&rows).Error
+ return rows, err
+}
+func (s *Store) editor(actor kernel.Actor, key string) (Access, Specialist, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return a, Specialist{}, err
+ }
+ row, err := s.get(a, key)
+ if err != nil {
+ return a, row, err
+ }
+ if !a.Owner && row.Creator != actor.Address {
+ return a, row, s.deps.Forbidden
+ }
+ return a, row, nil
+}
+func (s *Store) validate(in SpecialistInput) error {
+ if (strings.TrimSpace(in.Name) == "" && !slices.Contains(DefaultKeys, in.Key)) || len(in.Name) > 120 || !utf8.ValidString(in.Name) || len(in.Instructions) > 16384 || !utf8.ValidString(in.Instructions) || in.MaxConcurrent < 1 || in.MaxConcurrent > 100 || len(in.AllowedModels) > 100 || len(in.Tools) > 32 || len(in.ProjectIDs) > 100 {
+ return s.deps.Invalid
+ }
+ seen := map[ModelRef]bool{}
+ for _, m := range in.AllowedModels {
+ if (m.Provider != "codex" || m.Family != "gpt") && (m.Provider != "claude" || m.Family != "claude") || strings.TrimSpace(m.Model) == "" || len(m.Model) > 128 || !utf8.ValidString(m.Model) || seen[m] {
+ return s.deps.Invalid
+ }
+ seen[m] = true
+ }
+ ids := map[int64]bool{}
+ for _, id := range in.ProjectIDs {
+ if id <= 0 || ids[id] {
+ return s.deps.Invalid
+ }
+ ids[id] = true
+ }
+ if icons.Icon(in.Icon) == "" {
+ return s.deps.Invalid
+ }
+ // Custom executable profiles have no owner grants or certificates in this release.
+ if provider.ValidateSpecialistTools(in.Tools, nil, nil, nil) != nil {
+ return s.deps.Forbidden
+ }
+ for _, id := range in.ProjectIDs {
+ var p kernel.Project
+ if err := s.tx.First(&p, id).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return s.deps.NotFound
+ }
+ return err
+ }
+ }
+ return nil
+}
+func (s *Store) replay(a Access, actor kernel.Actor, op, key string, m kernel.Mutation, input any) (request, Specialist, bool, error) {
+ var result Specialist
+ if !m.Valid() {
+ return request{}, result, false, s.deps.Invalid
+ }
+ hash, err := kernel.InputHash(struct {
+ Input any
+ Revision int64
+ }{input, m.Revision})
+ if err != nil {
+ return request{}, result, false, err
+ }
+ q := request{TeamID: a.TeamID, Principal: actor.Address, Operation: op, Resource: key, RequestID: m.RequestID, InputHash: hash}
+ var old request
+ err = s.tx.Where("team_id=? AND principal=? AND operation=? AND resource=? AND request_id=?", q.TeamID, q.Principal, op, key, m.RequestID).First(&old).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return q, result, false, nil
+ }
+ if err != nil {
+ return q, result, false, err
+ }
+ if old.InputHash != hash {
+ return q, result, true, s.deps.Conflict
+ }
+ err = json.Unmarshal([]byte(old.Result), &result)
+ return q, result, true, err
+}
+func (s *Store) save(actor kernel.Actor, q request, row Specialist) (Specialist, error) {
+ if err := s.deps.Audit(s.tx, actor, q.Operation, row.Key); err != nil {
+ return Specialist{}, err
+ }
+ raw, err := json.Marshal(row)
+ if err != nil {
+ return Specialist{}, err
+ }
+ q.Result = string(raw)
+ return row, s.tx.Create(&q).Error
+}
+func (s *Store) Create(actor kernel.Actor, in SpecialistInput, m kernel.Mutation) (Specialist, error) {
+ return s.create(actor, in, TemplateRef{}, m)
+}
+func (s *Store) create(actor kernel.Actor, in SpecialistInput, ref TemplateRef, m kernel.Mutation) (Specialist, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Specialist{}, err
+ }
+ q, old, replay, err := s.replay(a, actor, "specialist.create", "", m, struct {
+ Input SpecialistInput
+ Template TemplateRef
+ }{in, ref})
+ if err != nil || replay {
+ return old, err
+ }
+ if in.Key != "" || m.Revision != 0 {
+ return Specialist{}, s.deps.Invalid
+ }
+ return s.insert(a, actor, in, ref, q)
+}
+func (s *Store) insert(a Access, actor kernel.Actor, in SpecialistInput, ref TemplateRef, q request) (Specialist, error) {
+ if err := s.validate(in); err != nil {
+ return Specialist{}, err
+ }
+ row := Specialist{Key: rand.Text(), TeamID: a.TeamID, Creator: actor.Address, ModelSelection: "best_fit", Revision: 1, TemplateID: ref.ID, TemplateVersion: ref.Version, TemplateBase: "{}"}
+ assign(&row, in)
+ if ref.ID != "" {
+ raw, _ := json.Marshal(fields(row))
+ row.TemplateBase = string(raw)
+ }
+ if err := s.tx.Create(&row).Error; err != nil {
+ return Specialist{}, err
+ }
+ return s.save(actor, q, row)
+}
+func assign(row *Specialist, in SpecialistInput) {
+ row.Name = in.Name
+ row.Icon = in.Icon
+ row.StandingInstructions = in.Instructions
+ row.MaxConcurrent = in.MaxConcurrent
+ row.AllowedModels = append([]ModelRef{}, in.AllowedModels...)
+ row.Tools = append([]string{}, in.Tools...)
+ row.ProjectIDs = append([]int64{}, in.ProjectIDs...)
+}
+func (s *Store) Update(actor kernel.Actor, in SpecialistInput, m kernel.Mutation) (Specialist, error) {
+ a, row, err := s.editor(actor, in.Key)
+ if err != nil {
+ return Specialist{}, err
+ }
+ q, old, replay, err := s.replay(a, actor, "specialist.update", in.Key, m, in)
+ if err != nil || replay {
+ return old, err
+ }
+ return s.update(actor, row, in, m, q)
+}
+func (s *Store) update(actor kernel.Actor, row Specialist, in SpecialistInput, m kernel.Mutation, q request) (Specialist, error) {
+ if row.Archived || m.Revision != row.Revision {
+ return Specialist{}, s.deps.Conflict
+ }
+ // Required categories keep their server-owned role and identity. Instructions
+ // cannot change the action profile, independent review or final person.
+ if row.Required && (in.Name != row.Name || in.Icon != row.Icon || len(in.Tools) != 0 || len(in.ProjectIDs) != 0) {
+ return Specialist{}, s.deps.Forbidden
+ }
+ if err := s.validate(in); err != nil {
+ return Specialist{}, err
+ }
+ assign(&row, in)
+ row.Revision++
+ r := s.tx.Model(&Specialist{}).Where("key=? AND team_id=? AND revision=?", row.Key, row.TeamID, m.Revision).Select("Name", "Icon", "StandingInstructions", "MaxConcurrent", "AllowedModels", "Tools", "ProjectIDs", "Revision", "TemplateID", "TemplateVersion", "TemplateBase").Updates(&row)
+ if r.Error != nil {
+ return Specialist{}, r.Error
+ }
+ if r.RowsAffected != 1 {
+ return Specialist{}, s.deps.Conflict
+ }
+ return s.save(actor, q, row)
+}
+func (s *Store) Delete(actor kernel.Actor, key string, m kernel.Mutation) error {
+ a, row, err := s.editor(actor, key)
+ if err != nil {
+ return err
+ }
+ if row.Required {
+ return s.deps.Forbidden
+ }
+ q, _, replay, err := s.replay(a, actor, "specialist.archive", key, m, key)
+ if err != nil || replay {
+ return err
+ }
+ if row.Archived || row.Revision != m.Revision {
+ return s.deps.Conflict
+ }
+ used, err := s.deps.Referenced(s.tx, key)
+ if err != nil {
+ return err
+ }
+ if used {
+ return s.deps.Conflict
+ }
+ row.Archived = true
+ row.Revision++
+ r := s.tx.Model(&Specialist{}).Where("key=? AND team_id=? AND revision=?", key, a.TeamID, m.Revision).Select("Archived", "Revision").Updates(&row)
+ if r.Error != nil {
+ return r.Error
+ }
+ if r.RowsAffected != 1 {
+ return s.deps.Conflict
+ }
+ _, err = s.save(actor, q, row)
+ return err
+}
+
+func ListInstance(tx *gorm.DB) ([]Specialist, error) {
+ var rows []Specialist
+ if err := tx.Where("archived=? AND team_id=(SELECT id FROM teams LIMIT 1)", false).Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ slices.SortFunc(rows, func(a, b Specialist) int {
+ ai, bi := slices.Index(DefaultKeys, a.Key), slices.Index(DefaultKeys, b.Key)
+ if ai < 0 {
+ ai = len(DefaultKeys)
+ }
+ if bi < 0 {
+ bi = len(DefaultKeys)
+ }
+ if ai != bi {
+ return ai - bi
+ }
+ return strings.Compare(a.Key, b.Key)
+ })
+ return rows, nil
+}
diff --git a/internal/equipo/library/templates.go b/internal/equipo/library/templates.go
new file mode 100644
index 00000000..bf7b8207
--- /dev/null
+++ b/internal/equipo/library/templates.go
@@ -0,0 +1,169 @@
+package library
+
+import (
+ "encoding/json"
+ "reflect"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+)
+
+type TemplateRef struct {
+ ID string
+ Version int64
+}
+type TemplateDiff struct {
+ From, To TemplateRef
+ CurrentRevision int64
+ Old, Current, Suggested map[string]json.RawMessage
+}
+type Template struct {
+ Ref TemplateRef
+ Group, GroupKey, NameKey, DescriptionKey, InstructionsKey, Icon string
+}
+
+func Catalog() []Template {
+ rows := []Template{}
+ for _, g := range []struct {
+ group, icon string
+ ids []string
+ }{
+ {"quality", "check-circle", []string{"qa", "accessibility", "performance"}},
+ {"safety", "shield", []string{"security", "privacy"}},
+ {"running", "sliders", []string{"ops", "data", "support"}},
+ {"words", "type", []string{"docs", "localisation", "seo"}},
+ {"", "plus", []string{"blank"}},
+ } {
+ for _, id := range g.ids {
+ key := "templates." + id
+ groupKey := ""
+ if g.group != "" {
+ groupKey = "templates.group." + g.group
+ }
+ rows = append(rows, Template{Ref: TemplateRef{id, 1}, Group: g.group, GroupKey: groupKey, NameKey: key + ".name", DescriptionKey: key + ".description", InstructionsKey: key + ".instructions", Icon: g.icon})
+ }
+ }
+ return rows
+}
+func (s *Store) Templates(actor kernel.Actor) ([]Template, error) {
+ if _, err := s.deps.Authorize(s.tx, actor); err != nil {
+ return nil, err
+ }
+ return s.deps.Catalog(), nil
+}
+func (s *Store) template(ref TemplateRef) (SpecialistInput, error) {
+ for _, t := range s.deps.Catalog() {
+ if t.Ref == ref {
+ return SpecialistInput{Name: s.deps.Copy(t.NameKey), Icon: t.Icon, Instructions: s.deps.Copy(t.InstructionsKey), MaxConcurrent: 1}, nil
+ }
+ }
+ return SpecialistInput{}, s.deps.NotFound
+}
+func (s *Store) Install(actor kernel.Actor, ref TemplateRef, m kernel.Mutation) (Specialist, error) {
+ // Replay is keyed by the pinned reference, not text that a later binary might
+ // resolve differently. Authorization is always checked first.
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Specialist{}, err
+ }
+ q, row, replay, err := s.replay(a, actor, "specialist.install", ref.ID, m, ref)
+ if err != nil || replay {
+ return row, err
+ }
+ in, err := s.template(ref)
+ if err != nil {
+ return Specialist{}, err
+ }
+ if m.Revision != 0 {
+ return Specialist{}, s.deps.Invalid
+ }
+ return s.insert(a, actor, in, ref, q)
+}
+func fields(row Specialist) map[string]json.RawMessage {
+ result := map[string]json.RawMessage{}
+ for k, v := range map[string]any{"name": row.Name, "icon": row.Icon, "instructions": row.StandingInstructions, "allowed_models": row.AllowedModels, "tools": row.Tools, "project_ids": row.ProjectIDs, "max_concurrent": row.MaxConcurrent} {
+ raw, _ := json.Marshal(v)
+ result[k] = raw
+ }
+ return result
+}
+func (s *Store) Diff(actor kernel.Actor, key string, target TemplateRef) (TemplateDiff, error) {
+ row, err := s.Get(actor, key)
+ if err != nil {
+ return TemplateDiff{}, err
+ }
+ if row.TemplateID == "" || row.TemplateID != target.ID || target.Version < row.TemplateVersion {
+ return TemplateDiff{}, s.deps.Invalid
+ }
+ in, err := s.template(target)
+ if err != nil {
+ return TemplateDiff{}, err
+ }
+ var old map[string]json.RawMessage
+ if err = json.Unmarshal([]byte(row.TemplateBase), &old); err != nil {
+ return TemplateDiff{}, err
+ }
+ var suggested Specialist
+ assign(&suggested, in)
+ return TemplateDiff{From: TemplateRef{row.TemplateID, row.TemplateVersion}, To: target, CurrentRevision: row.Revision, Old: old, Current: fields(row), Suggested: fields(suggested)}, nil
+}
+func (s *Store) Apply(actor kernel.Actor, key string, diff TemplateDiff, selected []string, m kernel.Mutation) (Specialist, error) {
+ a, row, err := s.editor(actor, key)
+ if err != nil {
+ return Specialist{}, err
+ }
+ q, saved, replay, err := s.replay(a, actor, "specialist.template_update", key, m, struct {
+ Diff TemplateDiff
+ Selected []string
+ }{diff, selected})
+ if err != nil || replay {
+ return saved, err
+ }
+ current, err := s.Diff(actor, key, diff.To)
+ if err != nil {
+ return Specialist{}, err
+ }
+ if m.Revision != diff.CurrentRevision || !equalDiff(current, diff) {
+ return Specialist{}, s.deps.Conflict
+ }
+ if len(selected) == 0 {
+ return Specialist{}, s.deps.Invalid
+ }
+ values := fields(row)
+ seen := []string{}
+ for _, key := range selected {
+ v, ok := diff.Suggested[key]
+ if !ok || slices.Contains(seen, key) {
+ return Specialist{}, s.deps.Invalid
+ }
+ seen = append(seen, key)
+ values[key] = v
+ }
+ in := Input(row)
+ for key, dst := range map[string]any{"name": &in.Name, "icon": &in.Icon, "instructions": &in.Instructions, "allowed_models": &in.AllowedModels, "tools": &in.Tools, "project_ids": &in.ProjectIDs, "max_concurrent": &in.MaxConcurrent} {
+ if err = json.Unmarshal(values[key], dst); err != nil {
+ return Specialist{}, s.deps.Invalid
+ }
+ }
+ row.TemplateVersion = diff.To.Version
+ raw, _ := json.Marshal(diff.Suggested)
+ row.TemplateBase = string(raw)
+ return s.update(actor, row, in, m, q)
+}
+func equalDiff(a, b TemplateDiff) bool {
+ if a.From != b.From || a.To != b.To || a.CurrentRevision != b.CurrentRevision {
+ return false
+ }
+ for _, pair := range [][2]map[string]json.RawMessage{{a.Old, b.Old}, {a.Current, b.Current}, {a.Suggested, b.Suggested}} {
+ if len(pair[0]) != len(pair[1]) {
+ return false
+ }
+ for key, v := range pair[0] {
+ var x, y any
+ if json.Unmarshal(v, &x) != nil || json.Unmarshal(pair[1][key], &y) != nil || !reflect.DeepEqual(x, y) {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/internal/equipo/library/views.go b/internal/equipo/library/views.go
new file mode 100644
index 00000000..c75818fc
--- /dev/null
+++ b/internal/equipo/library/views.go
@@ -0,0 +1,89 @@
+package library
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/equipo/planning"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "encoding/json"
+ "errors"
+ "gorm.io/gorm"
+ "time"
+)
+
+func Work(views []planning.TaskViewData, key string, now time.Time) planning.SpecialistWorkView {
+ out := planning.SpecialistWorkView{CountsKnown: true, UsageKnown: true}
+ for _, v := range views {
+ includes, running, waiting, finished := false, false, false, true
+ var ended time.Time
+ for _, step := range v.Steps {
+ if step.Category == key {
+ includes = true
+ running = running || step.State == "running"
+ waiting = waiting || step.State == "waiting"
+ finished = finished && step.State == "succeeded"
+ if step.FinishedAt.After(ended) {
+ ended = step.FinishedAt
+ }
+ out.UsageKnown = out.UsageKnown && step.UsageKnown
+ out.CountedTurns += step.CountedTurns
+ out.InputTokens += step.InputTokens
+ out.OutputTokens += step.OutputTokens
+ }
+ }
+ if !includes {
+ continue
+ }
+ switch {
+ case v.Group == "finished":
+ out.Finished++
+ case finished:
+ if !ended.IsZero() && ended.Before(weekStart(now)) {
+ continue
+ }
+ out.Finished++
+ v.Group = "finished"
+ case waiting:
+ out.Waiting++
+ v.Group = "needs-person"
+ case running:
+ out.Working++
+ v.Group = "running"
+ default:
+ out.Queued++
+ v.Group = "queued"
+ }
+ out.Tasks = append(out.Tasks, v)
+ }
+ return out
+}
+func weekStart(now time.Time) time.Time { return kernel.WeekStart(now) }
+
+func DecorateCard(tx *gorm.DB, teamID, taskID string, card *planning.StepCard) error {
+ if card.Category == "person" || card.Category == "runner" || card.Category == "" {
+ return nil
+ }
+ var row Specialist
+ err := tx.Where("team_id=? AND key=?", teamID, card.Category).First(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ card.CategoryName, card.CategoryIcon = row.Name, row.Icon
+ var saved []struct{ Brief string }
+ if err = tx.Table("runner_assignments").Select("brief").Where("task_id=? AND step_key=? AND claim_request<>''", taskID, card.Key).Order("id").Find(&saved).Error; err != nil {
+ return err
+ }
+ for _, snapshot := range saved {
+ var brief runnerproto.RunnerBrief
+ if err = json.Unmarshal([]byte(snapshot.Brief), &brief); err != nil {
+ return err
+ }
+ if brief.Step.SpecialistIcon != "" {
+ card.CategoryName, card.CategoryIcon = brief.Step.SpecialistName, brief.Step.SpecialistIcon
+ break
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/library_handlers.go b/internal/equipo/library_handlers.go
new file mode 100644
index 00000000..de2d7b56
--- /dev/null
+++ b/internal/equipo/library_handlers.go
@@ -0,0 +1,61 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "amadan.net/rastrillo/rastrillo/auth"
+ "net/http"
+ "slices"
+)
+
+func (a *application) libraryHandler() *library.Handler {
+ return &library.Handler{Store: a.store, Invalid: ErrInvalid, Failure: a.failure, LegacyForm: a.writeForm, Number: number, NotFound: ErrNotFound,
+ Actor: func(r *http.Request) (Actor, error) {
+ id, ok := auth.From(r)
+ if !ok {
+ return Actor{}, ErrForbidden
+ }
+ return Actor{Address: id.Address}, nil
+ },
+ Render: func(w http.ResponseWriter, r *http.Request, name string, v library.View) {
+ data, err := a.page(r, "templates")
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ data.Title = "templates.title"
+ if name == "specialist_form" {
+ data.Title = "specialists.new"
+ if v.Specialist.Key != "" {
+ data.Title = "specialists.edit"
+ if !data.Owner && v.Specialist.Creator != data.Address {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ }
+ groups, err := a.store.Projects(r.Context())
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ for _, g := range groups {
+ for _, p := range g.Projects {
+ v.Projects = append(v.Projects, library.ProjectOption{ID: p.Project.ID, Name: p.Project.Name, Selected: slices.Contains(v.Specialist.ProjectIDs, p.Project.ID)})
+ }
+ }
+ }
+ if name == "specialist" {
+ data.Key = v.Specialist.Key
+ data.Title = "nav." + v.Specialist.Key
+ data.Specialist = v.Specialist
+ data.Owner = data.Owner || v.Specialist.Creator == data.Address
+ data.Work, err = a.store.SpecialistWork(r.Context(), Actor{Address: data.Address}, data.Key)
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ data.Tasks = data.Work.Tasks
+ }
+ data.Library = v
+ a.renderLive(w, r, name, data)
+ }}
+}
diff --git a/internal/equipo/migrations/0024_specialist_library.sql b/internal/equipo/migrations/0024_specialist_library.sql
new file mode 100644
index 00000000..728ca182
--- /dev/null
+++ b/internal/equipo/migrations/0024_specialist_library.sql
@@ -0,0 +1,15 @@
+ALTER TABLE specialists ADD COLUMN team_id text NOT NULL DEFAULT "";
+ALTER TABLE specialists ADD COLUMN creator text NOT NULL DEFAULT "";
+ALTER TABLE specialists ADD COLUMN name text NOT NULL DEFAULT "";
+ALTER TABLE specialists ADD COLUMN icon text NOT NULL DEFAULT "";
+ALTER TABLE specialists ADD COLUMN role text NOT NULL DEFAULT "";
+ALTER TABLE specialists ADD COLUMN required numeric NOT NULL DEFAULT false;
+ALTER TABLE specialists ADD COLUMN archived numeric NOT NULL DEFAULT false;
+ALTER TABLE specialists ADD COLUMN allowed_models text NOT NULL DEFAULT "[]";
+ALTER TABLE specialists ADD COLUMN tools text NOT NULL DEFAULT "[]";
+ALTER TABLE specialists ADD COLUMN project_ids text NOT NULL DEFAULT "[]";
+ALTER TABLE specialists ADD COLUMN template_id text NOT NULL DEFAULT "";
+ALTER TABLE specialists ADD COLUMN template_version integer NOT NULL DEFAULT 0;
+ALTER TABLE specialists ADD COLUMN template_base text NOT NULL DEFAULT "{}";
+UPDATE specialists SET team_id=COALESCE((SELECT id FROM teams LIMIT 1),''), role=key, required=key IN ('engineering','review'), icon=CASE key WHEN 'product' THEN 'lightbulb' WHEN 'design' THEN 'pencil' WHEN 'copy' THEN 'type' WHEN 'engineering' THEN 'code' WHEN 'review' THEN 'check-circle' ELSE 'plus' END;
+CREATE TABLE specialist_requests (team_id text, principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY (team_id,principal,operation,resource,request_id));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 17990489..373085d4 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -154,7 +154,7 @@ CREATE TABLE service (
quarantine_why TEXT NOT NULL
);
-CREATE TABLE specialists (key text, model_selection text, provider text, model_family text, model text, standing_instructions text, max_concurrent integer, revision integer, PRIMARY KEY (key));
+CREATE TABLE specialists (key text, model_selection text, provider text, model_family text, model text, standing_instructions text, max_concurrent integer, revision integer, team_id text NOT NULL DEFAULT "",creator text NOT NULL DEFAULT "",name text NOT NULL DEFAULT "",icon text NOT NULL DEFAULT "",role text NOT NULL DEFAULT "",required numeric NOT NULL DEFAULT false,archived numeric NOT NULL DEFAULT false,allowed_models text NOT NULL DEFAULT "[]",tools text NOT NULL DEFAULT "[]",project_ids text NOT NULL DEFAULT "[]",template_id text NOT NULL DEFAULT "",template_version integer NOT NULL DEFAULT 0,template_base text NOT NULL DEFAULT "{}", PRIMARY KEY (key));
CREATE TABLE steps (
id INTEGER PRIMARY KEY,
@@ -385,3 +385,4 @@ CREATE TABLE personal_preferences (id text PRIMARY KEY, text text, status text,
CREATE TABLE personal_settings (team_id text, person text, landing text, revision integer, PRIMARY KEY (team_id,person));
CREATE TABLE person_api_requests (principal text NOT NULL, operation text NOT NULL, resource text NOT NULL, request_id text NOT NULL, input_hash text NOT NULL, result text NOT NULL, created_at datetime NOT NULL, expires_at datetime NOT NULL, PRIMARY KEY (principal,operation,resource,request_id));
CREATE INDEX person_api_requests_expiry ON person_api_requests(expires_at);
+CREATE TABLE specialist_requests (team_id text, principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY (team_id,principal,operation,resource,request_id));
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index 31af676a..e06b8e92 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -1,6 +1,7 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
"time"
"amadan.net/oficina/equipo/internal/equipo/conversation"
@@ -9,7 +10,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/planning"
)
-var Models = append(append(append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...), planning.Models...), personapi.Models...)
+var Models = append(append(append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...), planning.Models...), append(personapi.Models, library.Models...)...)
type Role string
@@ -73,13 +74,4 @@ type projectRequest struct {
Result string
}
-type Specialist struct {
- Key string `gorm:"primaryKey"`
- ModelSelection string
- Provider string
- ModelFamily string
- Model string
- StandingInstructions string
- MaxConcurrent int
- Revision int64
-}
+type Specialist = library.Specialist
diff --git a/internal/equipo/navigation.go b/internal/equipo/navigation.go
index c4667e85..46a0d7b2 100644
--- a/internal/equipo/navigation.go
+++ b/internal/equipo/navigation.go
@@ -1,20 +1,7 @@
package equipo
-type NavItem struct{ Key, Group, Href, CopyKey, Icon string }
+import "amadan.net/oficina/equipo/internal/equipo/library"
-func Navigation() []NavItem {
- return []NavItem{
- {"conversation", "", "/conversation", "nav.conversation", "message-circle"},
- {"needs-you", "", "/needs-you", "nav.needs-you", "inbox"},
- {"journey", "", "/journey", "nav.journey", "route"},
- {"projects", "", "/projects", "nav.projects", "folder"},
- {"product", "specialists", "/specialists/product", "nav.product", "lightbulb"},
- {"design", "specialists", "/specialists/design", "nav.design", "pencil"},
- {"copy", "specialists", "/specialists/copy", "nav.copy", "type"},
- {"engineering", "specialists", "/specialists/engineering", "nav.engineering", "code"},
- {"review", "specialists", "/specialists/review", "nav.review", "check-circle"},
- {"connections", "team", "/connections", "nav.connections", "plug"},
- {"people", "team", "/people", "nav.people", "users"},
- {"settings", "team", "/settings", "nav.settings", "sliders"},
- }
-}
+type NavItem = library.NavItem
+
+func Navigation() []NavItem { return library.Navigation() }
diff --git a/internal/equipo/planning/plans.go b/internal/equipo/planning/plans.go
index b1fe501c..6580421c 100644
--- a/internal/equipo/planning/plans.go
+++ b/internal/equipo/planning/plans.go
@@ -59,6 +59,7 @@ type Access struct {
ProjectRevision int64
}
type Dependencies struct {
+ Specialists func(*gorm.DB, string, taskplan.Plan, map[string]bool) error
DecisionOwner func(*gorm.DB, kernel.Actor, int64, string) (int64, error)
Access func(*gorm.DB, kernel.Actor, int64) (Access, error)
Project func(*gorm.DB, int64) error
@@ -196,6 +197,9 @@ func (s *Store) propose(actor kernel.Actor, requester string, p taskplan.Plan, m
if err != nil || replayed {
return result, err
}
+ if err = s.deps.Specialists(s.tx, a.TeamID, p, nil); err != nil {
+ return result, err
+ }
t := Task{ID: rand.Text(), Requester: requester, RequestID: rand.Text(), Description: p.Steps[0].Instructions, ProjectID: p.ProjectID, Revision: 1, PlanRevision: 1, Kind: p.Kind, TeamID: a.TeamID, MergeOwner: a.MergeOwner, State: "proposed"}
t.ReviewRef = "equipo/" + t.ID
if err = s.tx.Create(&t).Error; err != nil {
@@ -266,6 +270,9 @@ func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (ta
if err = taskplan.ValidateEdit(before, p, started); err != nil {
return result, s.deps.Invalid
}
+ if err = s.deps.Specialists(s.tx, t.TeamID, p, started); err != nil {
+ return result, err
+ }
if t.JobID != 0 && !checkpoint {
change, err := GraphChange(p, steps)
if err != nil {
diff --git a/internal/equipo/planning/task_views.go b/internal/equipo/planning/task_views.go
index 394ad1f9..5c910bd5 100644
--- a/internal/equipo/planning/task_views.go
+++ b/internal/equipo/planning/task_views.go
@@ -8,6 +8,7 @@ import (
)
type StepCard struct {
+ CategoryName, CategoryIcon string
FinishedAt time.Time
Key, Category, State, Model, Account, Actual, Person, Action, Reason string
Isolation team.IsolationSnapshot
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go
index 45961bbe..0f0cc6d5 100644
--- a/internal/equipo/plans.go
+++ b/internal/equipo/plans.go
@@ -19,6 +19,9 @@ const (
func (s *Store) planningAt(tx *gorm.DB) *planning.Store {
deps := planning.Dependencies{
+ Specialists: func(tx *gorm.DB, teamID string, p taskplan.Plan, started map[string]bool) error {
+ return s.libraryAt(tx).ValidatePlan(teamID, p, started)
+ },
DecisionOwner: renderedDecisionOwner,
Access: func(tx *gorm.DB, a Actor, id int64) (planning.Access, error) {
p, err := bugAuthority(tx, a, id)
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index be8014fe..7d7e4e60 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -10,6 +10,7 @@ import (
"amadan.net/rastrillo/rastrillo/ui"
"amadan.net/oficina/equipo/internal/equipo/icons"
+ "amadan.net/oficina/equipo/internal/equipo/library"
)
//go:embed templates static
@@ -26,10 +27,10 @@ var assets = rastrillo.NewAssets(appFS)
var pages = map[string]*template.Template{}
func init() {
- for _, name := range []string{"conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} {
+ for _, name := range []string{"specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} {
page := template.Must(template.New("layout").
Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
- Funcs(template.FuncMap{"asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
+ Funcs(template.FuncMap{"projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
"kindKey": func(k ProjectKind) string { return "kind." + string(k) },
"ownerKey": func(k string) string { return "owner." + k },
"roleKey": func(k Role) string { return "role." + string(k) },
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go
index 0b7f120f..c6f048c8 100644
--- a/internal/equipo/runner_execution.go
+++ b/internal/equipo/runner_execution.go
@@ -579,7 +579,7 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest
if err != nil {
return err
}
- brief := RunnerBrief{ProjectRevision: project.Revision, BudgetRevision: budget.Revision, Step: runnerproto.StepBrief{PlanRevision: task.PlanRevision, StepKey: a.StepKey, Action: resolved.Action, SpecialistKey: executionSpecialist(resolved), SpecialistRevision: sp.Revision}, AttemptDeadline: e.store.runnerClock.Now().UTC().Add(time.Duration(policy.AttemptSeconds) * time.Second), Policy: policy, Target: team.TargetBinding{Kind: team.TargetRepository, Repository: project.Repository, DefaultRef: project.DefaultBranch, Ref: task.ReviewRef, BaseRevision: task.BaseCommit}, Instructions: task.Description, StandingInstructions: sp.StandingInstructions, ConfirmedPreferences: []string{}, Selection: value.Selection, ArtifactHashes: []string{}}
+ brief := RunnerBrief{ProjectRevision: project.Revision, BudgetRevision: budget.Revision, Step: runnerproto.StepBrief{PlanRevision: task.PlanRevision, StepKey: a.StepKey, Action: resolved.Action, SpecialistKey: executionSpecialist(resolved), SpecialistRevision: sp.Revision, SpecialistName: sp.Name, SpecialistIcon: sp.Icon}, AttemptDeadline: e.store.runnerClock.Now().UTC().Add(time.Duration(policy.AttemptSeconds) * time.Second), Policy: policy, Target: team.TargetBinding{Kind: team.TargetRepository, Repository: project.Repository, DefaultRef: project.DefaultBranch, Ref: task.ReviewRef, BaseRevision: task.BaseCommit}, Instructions: task.Description, StandingInstructions: sp.StandingInstructions, ConfirmedPreferences: []string{}, Selection: value.Selection, ArtifactHashes: []string{}}
plan, err := e.store.planningAt(tx).Plan(task)
if err != nil {
return err
diff --git a/internal/equipo/specialist_library.go b/internal/equipo/specialist_library.go
new file mode 100644
index 00000000..5562e4a4
--- /dev/null
+++ b/internal/equipo/specialist_library.go
@@ -0,0 +1,29 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "gorm.io/gorm"
+)
+
+type SpecialistInput = library.SpecialistInput
+type ModelRef = library.ModelRef
+type TemplateRef = library.TemplateRef
+type TemplateDiff = library.TemplateDiff
+
+func (s *Store) libraryAt(tx *gorm.DB) *library.Store {
+ return library.New(tx, library.Dependencies{
+ Authorize: func(tx *gorm.DB, a Actor) (library.Access, error) {
+ m, err := currentRunnerMember(tx, a.Address)
+ if err != nil {
+ return library.Access{}, err
+ }
+ var t Team
+ err = tx.First(&t).Error
+ return library.Access{TeamID: t.ID, Owner: m.Role == RoleOwner}, err
+ },
+ Audit: appendAudit, Copy: copyText, Catalog: library.Catalog,
+
+ Referenced: library.UnstartedReference,
+ Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict,
+ })
+}
diff --git a/internal/equipo/specialists.go b/internal/equipo/specialists.go
index 6efcbf8d..727c297a 100644
--- a/internal/equipo/specialists.go
+++ b/internal/equipo/specialists.go
@@ -2,71 +2,26 @@ package equipo
import (
"context"
- "slices"
- "strings"
+ "amadan.net/oficina/equipo/internal/equipo/library"
"gorm.io/gorm"
- "gorm.io/gorm/clause"
)
-var specialistKeys = [...]string{"product", "design", "copy", "engineering", "review"}
-
func seedSpecialists(tx *gorm.DB) (int64, error) {
- rows := make([]Specialist, 0, len(specialistKeys))
- for _, key := range specialistKeys {
- rows = append(rows, Specialist{Key: key, ModelSelection: "best_fit", MaxConcurrent: 1, Revision: 1})
+ var t Team
+ if err := tx.First(&t).Error; err != nil {
+ return 0, err
}
- result := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "key"}}, DoNothing: true}).Create(&rows)
- return result.RowsAffected, storeError(result.Error)
+ return library.Seed(tx, t.ID)
}
-
func (s *Store) Specialists(ctx context.Context) ([]Specialist, error) {
if s == nil || s.db == nil {
return nil, ErrUnavailable
}
- var rows []Specialist
- if err := s.db.G.WithContext(ctx).Find(&rows).Error; err != nil {
- return nil, storeError(err)
- }
- slices.SortFunc(rows, func(a, b Specialist) int {
- return slices.Index(specialistKeys[:], a.Key) - slices.Index(specialistKeys[:], b.Key)
- })
- return rows, nil
+ rows, err := library.ListInstance(s.db.G.WithContext(ctx))
+ return rows, storeError(err)
}
-func (s *Store) SaveSpecialist(ctx context.Context, actor Actor, specialist Specialist) error {
- if !slices.Contains(specialistKeys[:], specialist.Key) || specialist.MaxConcurrent <= 0 || specialist.Revision < 0 {
- return ErrInvalid
- }
- if specialist.ModelSelection != "best_fit" && specialist.ModelSelection != "fixed" {
- return ErrInvalid
- }
- specialist.Provider = strings.TrimSpace(specialist.Provider)
- specialist.ModelFamily = strings.TrimSpace(specialist.ModelFamily)
- specialist.Model = strings.TrimSpace(specialist.Model)
- if specialist.ModelSelection == "fixed" && (specialist.Provider == "" || specialist.ModelFamily == "" || specialist.Model == "") {
- return ErrInvalid
- }
- return s.write(ctx, func(tx *gorm.DB) error {
- if err := requireOwner(tx, actor); err != nil {
- return err
- }
- var old Specialist
- if err := tx.Where("key = ?", specialist.Key).First(&old).Error; err != nil {
- return storeError(err)
- }
- if old.Revision != specialist.Revision {
- return ErrConflict
- }
- specialist.Revision++
- result := tx.Model(&Specialist{}).Where("key = ? AND revision = ?", specialist.Key, old.Revision).
- Select("ModelSelection", "Provider", "ModelFamily", "Model", "StandingInstructions", "MaxConcurrent", "Revision").Updates(&specialist)
- if result.Error != nil {
- return storeError(result.Error)
- }
- if result.RowsAffected != 1 {
- return ErrConflict
- }
- return appendAudit(tx, actor, "specialist.save", specialist.Key)
- })
+func (s *Store) SaveSpecialist(ctx context.Context, actor Actor, row Specialist) error {
+ return s.write(ctx, func(tx *gorm.DB) error { return s.libraryAt(tx).SaveLegacy(actor, row) })
}
diff --git a/internal/equipo/store.go b/internal/equipo/store.go
index dd3bfa6a..b3f15af0 100644
--- a/internal/equipo/store.go
+++ b/internal/equipo/store.go
@@ -10,6 +10,7 @@ import (
"gorm.io/gorm"
"gorm.io/plugin/dbresolver"
+ "amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/equipo/personapi"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/rastrillo/rastrillo/db"
@@ -46,6 +47,7 @@ func (e *refusal) Unwrap() error { return e.kind }
// Store grants no access by itself. Mutators must check the trusted Actor
// against the current roster and append an AuditEvent in their transaction.
type Store struct {
+ *library.Application
personBearer personapi.VerifyPersonBearer
personCookie func(*http.Request) (personapi.PersonPrincipal, error)
personOrigin string
@@ -72,6 +74,9 @@ func NewStore(d *db.DB, options ...StoreOption) *Store {
for _, option := range options {
option(s)
}
+ s.Application = &library.Application{Write: s.write, At: s.libraryAt, Normalize: normalizeAddress, Read: func(ctx context.Context, a Actor, fn func(*gorm.DB) error) error {
+ return s.readTeam(ctx, a, func(tx *gorm.DB, _ Team) error { return fn(tx) })
+ }}
return s
}
diff --git a/internal/equipo/task_counts.go b/internal/equipo/task_counts.go
index 52d7fcdf..b70d84b6 100644
--- a/internal/equipo/task_counts.go
+++ b/internal/equipo/task_counts.go
@@ -1,68 +1,16 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
"context"
- "time"
-
"gorm.io/gorm"
+ "time"
)
func visibleTasks(tx *gorm.DB, teamID string, since time.Time) *gorm.DB {
- // Unknown finish dates remain visible. Both job and person transitions matter.
- return tx.Model(&Task{}).Joins("LEFT JOIN jobs visible_job ON visible_job.id=tasks.job_id AND visible_job.account=tasks.team_id").Where("tasks.team_id=?", teamID).Where(`
- (tasks.state NOT IN ('failed','cancelled','merged') AND COALESCE(visible_job.state,'') NOT IN ('failed','cancelled'))
- OR MAX(COALESCE(julianday(visible_job.updated_at),0),COALESCE((SELECT MAX(julianday(at)) FROM audit_events WHERE record_id=tasks.id AND kind IN ('task.cancel','task.merge')),0)) IN (0)
- OR MAX(COALESCE(julianday(visible_job.updated_at),0),COALESCE((SELECT MAX(julianday(at)) FROM audit_events WHERE record_id=tasks.id AND kind IN ('task.cancel','task.merge')),0))>=julianday(?)`, since).Select("tasks.*")
+ return library.VisibleTasks(tx, teamID, since)
}
-
-func (s *Store) SpecialistCounts(ctx context.Context, actor Actor) (map[string]SpecialistWorkView, error) {
- out := map[string]SpecialistWorkView{}
- err := s.readTeam(ctx, actor, func(tx *gorm.DB, instance Team) error {
- for _, key := range specialistKeys {
- v := SpecialistWorkView{CountsKnown: true, UsageKnown: true}
- if key != "engineering" && key != "review" {
- out[key] = v
- continue
- }
- caps := []string{"reproduce", "implement"}
- if key == "review" {
- caps = []string{"review", "verify"}
- }
- var counts struct {
- Working, Queued, Finished, Waiting int
- Unknown int64
- Calls, Input, Output int64
- }
- // One row per task before aggregation avoids multiplying usage by attempts.
- err := tx.Raw(`WITH visible AS (?), classified AS (
- SELECT t.id,t.job_id,
- CASE WHEN t.state IN ('failed','cancelled','merged') OR j.state IN ('failed','cancelled') THEN 'finished'
- WHEN (SELECT count(*) FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='succeeded')=2 THEN CASE WHEN (SELECT MAX(julianday(att.updated_at)) FROM attempts att JOIN steps st ON st.id=att.step_id JOIN runner_assignments a ON a.attempt_id=att.id WHERE a.task_id=t.id AND st.capability IN ?)<julianday(?) THEN 'hidden' ELSE 'finished' END
- WHEN EXISTS(SELECT 1 FROM questions q JOIN runner_assignments a ON a.id=q.assignment_id JOIN attempts att ON att.id=a.attempt_id WHERE q.task_id=t.id AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence AND a.step_key IN ? AND julianday(a.lease_deadline)>julianday(?) AND julianday(att.lease_deadline)>julianday(?)) THEN 'waiting'
- WHEN EXISTS(SELECT 1 FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='running') THEN 'working'
- ELSE 'queued' END bucket
- FROM visible t LEFT JOIN jobs j ON j.id=t.job_id
- ) SELECT COALESCE(SUM(bucket='working'),0) working,COALESCE(SUM(bucket='queued'),0) queued,
- COALESCE(SUM(bucket='finished'),0) finished,COALESCE(SUM(bucket='waiting'),0) waiting,COALESCE(SUM(job_id=0),0) unknown
- FROM classified`, visibleTasks(tx, instance.ID, weekStart(s.runnerClock.Now())), caps, caps, weekStart(s.runnerClock.Now()), caps, s.runnerClock.Now(), s.runnerClock.Now(), caps).Scan(&counts).Error
- if err != nil {
- return storeError(err)
- }
- v.Working, v.Queued, v.Finished, v.Waiting = counts.Working, counts.Queued, counts.Finished, counts.Waiting
- unprepared := counts.Unknown > 0
- err = tx.Raw(`SELECT COALESCE(SUM(CASE WHEN r.state='open' THEN r.r_calls ELSE r.s_calls END),0) calls,
- COALESCE(SUM(r.s_input),0) input, COALESCE(SUM(r.s_output),0) output,
- COALESCE(SUM(r.state='open' OR r.settled_by='unknown'),0) unknown
- FROM reservations r JOIN steps st ON st.id=r.step_id JOIN (?) t ON t.job_id=r.job_id
- WHERE st.capability IN ? AND julianday(r.created_at)>=julianday(?)`, visibleTasks(tx, instance.ID, weekStart(s.runnerClock.Now())), caps, weekStart(s.runnerClock.Now())).Scan(&counts).Error
- if err != nil {
- return storeError(err)
- }
- v.CountedTurns, v.InputTokens, v.OutputTokens = counts.Calls, counts.Input, counts.Output
- v.UsageKnown = counts.Unknown == 0 && !unprepared
- out[key] = v
- }
- return nil
- })
- return out, err
+func (s *Store) SpecialistCounts(ctx context.Context, actor Actor) (out map[string]SpecialistWorkView, err error) {
+ err = s.readTeam(ctx, actor, func(tx *gorm.DB, t Team) error { out, err = library.Counts(tx, t.ID, s.runnerClock.Now()); return err })
+ return
}
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go
index 8b4cc637..f7c732d8 100644
--- a/internal/equipo/task_views.go
+++ b/internal/equipo/task_views.go
@@ -1,6 +1,7 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
"context"
"database/sql"
"encoding/json"
@@ -90,61 +91,15 @@ func (s *Store) Journey(ctx context.Context, actor Actor) ([]TaskViewData, error
}
return views, nil
}
-func specialistWork(views []TaskViewData, key string, now time.Time) SpecialistWorkView {
- out := SpecialistWorkView{CountsKnown: true, UsageKnown: true}
- for _, v := range views {
- includes, running, waiting, finished := false, false, false, true
- var ended time.Time
- for _, step := range v.Steps {
- if step.Category == key {
- includes = true
- running = running || step.State == "running"
- waiting = waiting || step.State == "waiting"
- finished = finished && step.State == "succeeded"
- if step.FinishedAt.After(ended) {
- ended = step.FinishedAt
- }
- out.UsageKnown = out.UsageKnown && step.UsageKnown
- out.CountedTurns += step.CountedTurns
- out.InputTokens += step.InputTokens
- out.OutputTokens += step.OutputTokens
- }
- }
- if !includes {
- continue
- }
- switch {
- case v.Group == "finished":
- out.Finished++
- case finished:
- if !ended.IsZero() && ended.Before(weekStart(now)) {
- continue
- }
- out.Finished++
- v.Group = "finished"
- case waiting:
- out.Waiting++
- v.Group = "needs-person"
- case running:
- out.Working++
- v.Group = "running"
- default:
- out.Queued++
- v.Group = "queued"
- }
- out.Tasks = append(out.Tasks, v)
- }
- return out
-}
func (s *Store) SpecialistWork(ctx context.Context, actor Actor, key string) (SpecialistWorkView, error) {
- if !validSpecialistKey(key) {
- return SpecialistWorkView{}, ErrNotFound
+ if _, err := s.Specialist(ctx, actor, key); err != nil {
+ return SpecialistWorkView{}, err
}
views, err := s.Journey(ctx, actor)
if err != nil {
return SpecialistWorkView{}, err
}
- return specialistWork(views, key, s.runnerClock.Now()), nil
+ return library.Work(views, key, s.runnerClock.Now()), nil
}
func exposed(iso team.IsolationSnapshot) bool { return iso.Status == "unconfined" || iso.RunnerTainted }
func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, error) {
@@ -266,6 +221,9 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e
if person != "" {
card.Category = "person"
}
+ if err = library.DecorateCard(tx, task.TeamID, task.ID, &card); err != nil {
+ return v, err
+ }
sel := eng
if plan.Specialist == "review" {
sel = review
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html
index e4186692..8c6a3180 100644
--- a/internal/equipo/templates/chrome.html
+++ b/internal/equipo/templates/chrome.html
@@ -5,10 +5,10 @@
{{define "nav"}}
{{template "region:rail" .}}{{end}}
{{define "region:rail"}}<nav rst-shell-nav id="rail" {{.Live.Attrs .CollectionTopic}}>
-{{$counts := .Counts}}{{$key := .Key}}{{$group := ""}}
+{{$names := .SpecialistNames}}{{$counts := .Counts}}{{$key := .Key}}{{$group := ""}}
{{range .Nav}}
{{if ne .Group $group}}{{if .Group}}<p equipo-nav-group>{{copy (printf "nav.%s" .Group)}}</p>{{end}}{{$group = .Group}}{{end}}
-<a id="nav-{{.Key}}" href="{{.Href}}"{{if eq .Key $key}} aria-current="page"{{end}}>{{icon .Icon}}<span>{{copy .CopyKey}}{{if eq .Group "specialists"}}{{with index $counts .Key}}{{if .CountsKnown}}<small equipo-count>{{.Working}} · {{.Queued}} {{copy "activity.queued"}} · {{.Waiting}} {{copy "task.state.waiting"}}</small>{{else}}<small equipo-count>{{copy "counts.unavailable"}}</small>{{end}}{{end}}{{end}}</span></a>
+<a id="nav-{{.Key}}" href="{{.Href}}"{{if eq .Key $key}} aria-current="page"{{end}}>{{icon .Icon}}<span>{{if index $names .Key}}{{index $names .Key}}{{else}}{{copy .CopyKey}}{{end}}{{if eq .Group "specialists"}}{{with index $counts .Key}}{{if .CountsKnown}}<small equipo-count>{{.Working}} · {{.Queued}} {{copy "activity.queued"}} · {{.Waiting}} {{copy "task.state.waiting"}}</small>{{else}}<small equipo-count>{{copy "counts.unavailable"}}</small>{{end}}{{end}}{{end}}</span></a>
{{end}}
</nav>{{end}}
{{define "region:notice"}}<div id="notice" role="status"></div>{{end}}
diff --git a/internal/equipo/templates/plan.html b/internal/equipo/templates/plan.html
index b9c19795..77f85724 100644
--- a/internal/equipo/templates/plan.html
+++ b/internal/equipo/templates/plan.html
@@ -24,7 +24,7 @@
</fieldset>
{{end}}
{{if lt (len .Steps) 16}}<details><summary>{{copy "plan.add_step"}}</summary><fieldset>{{$i := len .Steps}}
-<label>{{copy "plan.step_key"}}<input rst-input name="step_{{$i}}_key"></label><label>{{copy "plan.specialist"}}<select rst-input name="step_{{$i}}_specialist"><option value=""></option>{{range .Steps}}{{if .Specialist}}<option value="{{.Specialist}}">{{copy (printf "nav.%s" .Specialist)}}</option>{{end}}{{end}}<option value="product">{{copy "nav.product"}}</option><option value="design">{{copy "nav.design"}}</option><option value="copy">{{copy "nav.copy"}}</option></select></label>
+<label>{{copy "plan.step_key"}}<input rst-input name="step_{{$i}}_key"></label><label>{{copy "plan.specialist"}}<select rst-input name="step_{{$i}}_specialist"><option value=""></option>{{range $.Specialists}}{{if projectAllows . $.Plan.Plan.ProjectID}}<option value="{{.Key}}">{{if .Name}}{{.Name}}{{else}}{{copy (printf "nav.%s" .Key)}}{{end}}</option>{{end}}{{end}}</select></label>
<label>{{copy "plan.action"}}<select rst-input name="step_{{$i}}_action"><option value="investigate">{{copy "plan.action.investigate"}}</option><option value="recommend">{{copy "plan.action.recommend"}}</option><option value="implement">{{copy "plan.action.implement"}}</option><option value="copy">{{copy "plan.action.copy"}}</option><option value="design">{{copy "plan.action.design"}}</option></select></label>
<label>{{copy "plan.position"}}<input rst-input name="step_{{$i}}_position" type="number" min="1" max="16"></label><label>{{copy "plan.instructions"}}<textarea rst-input name="step_{{$i}}_instructions"></textarea></label>
</fieldset></details>{{end}}
diff --git a/internal/equipo/templates/specialist.html b/internal/equipo/templates/specialist.html
index fb69b827..21d63ef4 100644
--- a/internal/equipo/templates/specialist.html
+++ b/internal/equipo/templates/specialist.html
@@ -1,7 +1,11 @@
{{define "content"}}
-<h1>{{copy .Title}}</h1>
+<h1>{{icon .Specialist.Icon}}{{if .Specialist.Name}}{{.Specialist.Name}}{{else}}{{copy .Title}}{{end}}</h1>
+{{if .Specialist.Required}}<p>{{copy "specialists.required"}}</p>{{end}}
+{{if .Specialist.Archived}}<p>{{copy "specialists.archived"}}</p>{{end}}
+{{if .Owner}}<p><a href="/specialists/{{.Specialist.Key}}/edit">{{copy "specialists.edit"}}</a></p>{{end}}
+{{if .Specialist.TemplateID}}<p><a href="/specialists/{{.Specialist.Key}}/template-diff">{{copy "templates.diff"}}</a></p>{{end}}
{{template "region:activity" .}}
-<section equipo-card><h2>{{copy "nav.settings"}}</h2>
+{{if .Specialist.Role}}<section equipo-card><h2>{{copy "nav.settings"}}</h2>
<form method="post" action="/specialists/{{.Specialist.Key}}" equipo-form>
<fieldset{{if not .Owner}} disabled{{end}}>
<input type="hidden" name="revision" value="{{.Specialist.Revision}}">
@@ -12,7 +16,7 @@
<label>{{copy "specialist.concurrent"}}<input rst-input name="max_concurrent" type="number" min="1" step="1" value="{{.Specialist.MaxConcurrent}}" required></label>
<label>{{copy "specialist.instructions"}}<textarea rst-input name="standing_instructions" rows="5">{{.Specialist.StandingInstructions}}</textarea></label>
{{if .Owner}}<button rst-btn="primary" type="submit">{{copy "form.save"}}</button>{{end}}
-</fieldset></form></section>
+</fieldset></form></section>{{end}}
{{end}}
{{define "region:activity"}}<div id="activity" {{.Live.Attrs .Topic}}><p>{{copy "activity.working"}}: {{.Work.Working}} · {{copy "activity.queued"}}: {{.Work.Queued}} · {{copy "activity.finished"}}: {{.Work.Finished}}</p>{{if .Work.UsageKnown}}<p>{{copy "usage.counted_turns"}}: {{.Work.CountedTurns}}</p><p>{{copy "usage.tokens"}}: {{.Work.InputTokens}} / {{.Work.OutputTokens}}</p>{{else}}<p>{{copy "usage.unknown"}}</p>{{end}}{{template "task-groups" .}}</div>{{end}}
diff --git a/internal/equipo/templates/specialist_form.html b/internal/equipo/templates/specialist_form.html
new file mode 100644
index 00000000..d9b87149
--- /dev/null
+++ b/internal/equipo/templates/specialist_form.html
@@ -0,0 +1,28 @@
+{{define "up"}}/templates{{end}}
+{{define "content"}}
+<h1>{{copy .Title}}</h1>
+{{$sp := .Library.Specialist}}
+{{if $sp.Required}}<p>{{copy "specialists.required"}}</p>{{end}}
+<form method="post" action="{{if $sp.Key}}/specialists/{{$sp.Key}}/edit{{else}}/specialists{{end}}" equipo-form>
+<input type="hidden" name="request_id" value="{{.Library.RequestID}}">
+<input type="hidden" name="revision" value="{{$sp.Revision}}">
+{{if $sp.Required}}<p>{{copy (printf "nav.%s" $sp.Key)}}</p><input type="hidden" name="name" value="{{$sp.Name}}">{{else}}<label>{{copy "specialists.name"}}<input rst-input name="name" value="{{$sp.Name}}" maxlength="120" required></label>{{end}}
+<label>{{copy "specialists.icon"}}<select rst-input name="icon">{{range .Library.Icons}}<option value="{{.}}"{{if eq . $sp.Icon}} selected{{end}}>{{.}}</option>{{end}}</select></label>
+<label>{{copy "specialists.instructions"}}<textarea rst-input name="instructions" rows="6" maxlength="16384">{{$sp.StandingInstructions}}</textarea></label>
+<label>{{copy "specialist.concurrent"}}<input rst-input name="max_concurrent" type="number" min="1" max="100" value="{{$sp.MaxConcurrent}}" required></label>
+<fieldset><legend>{{copy "specialists.models"}}</legend>
+{{range $i,$model := .Library.Models}}
+<label>{{copy "specialist.provider"}}<input rst-input name="model.{{$i}}.provider" value="{{$model.Provider}}"></label>
+<label>{{copy "specialist.family"}}<input rst-input name="model.{{$i}}.family" value="{{$model.Family}}"></label>
+<label>{{copy "specialist.model"}}<input rst-input name="model.{{$i}}.name" value="{{$model.Model}}"></label>
+{{end}}</fieldset>
+<fieldset><legend>{{copy "specialists.projects"}}</legend>
+{{range .Library.Projects}}<label><input type="checkbox" name="project" value="{{.ID}}"{{if .Selected}} checked{{end}}>{{.Name}}</label>{{end}}
+</fieldset>
+<h2>{{copy "specialists.tools"}}</h2><p>{{copy "specialists.unavailable"}}</p>
+<button rst-btn="primary" type="submit">{{copy "form.save"}}</button>
+</form>
+{{if $sp.Key}}{{if not $sp.Required}}{{if not $sp.Archived}}
+<form method="post" action="/specialists/{{$sp.Key}}/archive"><input type="hidden" name="request_id" value="{{.Library.RequestID}}-archive"><input type="hidden" name="revision" value="{{$sp.Revision}}"><button rst-btn type="submit">{{copy "specialists.archive"}}</button></form>
+{{end}}{{end}}{{end}}
+{{end}}
diff --git a/internal/equipo/templates/task_card.html b/internal/equipo/templates/task_card.html
index adcc5e78..f743f21a 100644
--- a/internal/equipo/templates/task_card.html
+++ b/internal/equipo/templates/task_card.html
@@ -1,7 +1,7 @@
{{define "task-card"}}
<article equipo-task data-task="{{.Task.ID}}">
<div equipo-card><h3><a href="/tasks/{{.Task.ID}}">{{.Task.Description}}</a></h3><p equipo-secondary>{{.Project.Name}}</p><a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a> <a href="/tasks/{{.Task.ID}}/plan">{{copy "plan.edit"}}</a><p>{{copy .StateKey}}</p>{{if .Unconfined}}<p equipo-isolation>{{copy "isolation.unconfined"}}</p>{{end}}{{template "trial-label" .Isolation}}</div>
-<ol equipo-steps>{{range .Steps}}<li equipo-step data-step="{{.Key}}"><strong>{{copy (printf "nav.%s" .Category)}}</strong><span>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-value>{{.Model}} {{.Account}}{{.Person}}</span><span equipo-secondary title="{{.Reason}}">{{.Reason}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span>{{if .Unconfined}}<span equipo-isolation>{{copy "isolation.unconfined"}}</span>{{end}}{{template "trial-label" .Isolation}}</li>{{end}}</ol>
+<ol equipo-steps>{{range .Steps}}<li equipo-step data-step="{{.Key}}"><strong>{{if .CategoryIcon}}{{icon .CategoryIcon}}{{end}}{{if .CategoryName}}{{.CategoryName}}{{else}}{{copy (printf "nav.%s" .Category)}}{{end}}</strong><span>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-value>{{.Model}} {{.Account}}{{.Person}}</span><span equipo-secondary title="{{.Reason}}">{{.Reason}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span>{{if .Unconfined}}<span equipo-isolation>{{copy "isolation.unconfined"}}</span>{{end}}{{template "trial-label" .Isolation}}</li>{{end}}</ol>
</article>
{{end}}
{{define "task-groups"}}{{range $group := taskGroups}}<section><h2>{{copy (printf "task.group.%s" $group)}}</h2>{{range $.Tasks}}{{if eq .Group $group}}{{template "task-card" .}}{{end}}{{end}}</section>{{end}}{{if not .Tasks}}<p data-empty-state="{{.Key}}.empty">{{copy "task.empty"}}</p>{{end}}{{end}}
diff --git a/internal/equipo/templates/template_diff.html b/internal/equipo/templates/template_diff.html
new file mode 100644
index 00000000..6cb7289f
--- /dev/null
+++ b/internal/equipo/templates/template_diff.html
@@ -0,0 +1,13 @@
+{{define "content"}}
+<h1>{{copy "templates.diff"}}</h1>
+<form method="post" action="/specialists/{{.Library.Specialist.Key}}/template-update" equipo-form>
+<input type="hidden" name="request_id" value="{{.Library.RequestID}}">
+<input type="hidden" name="revision" value="{{.Library.Diff.CurrentRevision}}">
+<input type="hidden" name="diff" value="{{.Library.DiffJSON}}">
+{{range .Library.Fields}}<section equipo-card>
+<label><input type="checkbox" name="field" value="{{.Key}}">{{copy .CopyKey}}</label>
+<dl><dt>{{copy "templates.old"}}</dt><dd>{{.Old}}</dd><dt>{{copy "templates.current"}}</dt><dd>{{.Current}}</dd><dt>{{copy "templates.suggested"}}</dt><dd>{{.Suggested}}</dd></dl>
+</section>{{end}}
+<button rst-btn="primary" type="submit">{{copy "templates.apply"}}</button>
+</form>
+{{end}}
diff --git a/internal/equipo/templates/template_library.html b/internal/equipo/templates/template_library.html
new file mode 100644
index 00000000..19c14435
--- /dev/null
+++ b/internal/equipo/templates/template_library.html
@@ -0,0 +1,14 @@
+{{define "content"}}
+<h1>{{copy "templates.title"}}</h1>
+<p><a rst-btn href="/specialists/new">{{icon "plus"}}{{copy "specialists.new"}}</a></p>
+{{$group := ""}}{{$request := .Library.RequestID}}
+{{range .Library.Templates}}
+{{if ne .Group $group}}{{if .GroupKey}}<h2>{{copy .GroupKey}}</h2>{{end}}{{$group = .Group}}{{end}}
+<section equipo-card><h3>{{icon .Icon}}{{copy .NameKey}}</h3><p>{{copy .DescriptionKey}}</p>
+<form method="post" action="/templates/{{.Ref.ID}}/install">
+<input type="hidden" name="request_id" value="{{$request}}-{{.Ref.ID}}">
+<input type="hidden" name="version" value="{{.Ref.Version}}">
+<button rst-btn type="submit">{{copy "templates.install"}}</button>
+</form></section>
+{{end}}
+{{end}}
diff --git a/internal/equipotest/specialists_test.go b/internal/equipotest/specialists_test.go
index 44afb72f..e570237f 100644
--- a/internal/equipotest/specialists_test.go
+++ b/internal/equipotest/specialists_test.go
@@ -68,8 +68,8 @@ func TestSpecialistsSeedOnce(t *testing.T) {
s := equipo.NewStore(d)
before := specialists(t, s)
for _, row := range before {
- want := equipo.Specialist{Key: row.Key, ModelSelection: "best_fit", MaxConcurrent: 1, Revision: 1}
- if row != want {
+ want := equipo.Specialist{Key: row.Key, ModelSelection: "best_fit", MaxConcurrent: 1, Revision: 1, TeamID: row.TeamID, Role: row.Key, Icon: row.Icon, Required: row.Key == "engineering" || row.Key == "review", AllowedModels: []equipo.ModelRef{}, Tools: []string{}, ProjectIDs: []int64{}, TemplateBase: "{}"}
+ if !reflect.DeepEqual(row, want) {
t.Fatalf("wrong default: %+v", row)
}
}
@@ -124,7 +124,7 @@ func TestSpecialistsSeedExistingTeam(t *testing.T) {
t.Fatal(err)
}
rows := specialists(t, s)
- if partial && rows[0] != before {
+ if partial && !reflect.DeepEqual(rows[0], before) {
t.Fatal("backfill overwrote existing settings")
}
if scalar(t, d, "SELECT count(*) FROM teams") != 1 || scalar(t, d, "SELECT count(*) FROM members") != 1 {
@@ -139,7 +139,7 @@ func TestSpecialistsUpgrade(t *testing.T) {
d, logger := foundationDB(t)
previous := &migrate.Set{}
for _, migration := range equipo.BootSchema.All() {
- if migration.ID != "equipo/0005_specialists" {
+ if migration.ID != "equipo/0005_specialists" && migration.ID != "equipo/0024_specialist_library" {
previous.Add(migration)
}
}
@@ -254,7 +254,7 @@ func TestSpecialistSettings(t *testing.T) {
}
})
}
- if got := specialists(t, s)[0]; got != old {
+ if got := specialists(t, s)[0]; !reflect.DeepEqual(got, old) {
t.Fatal("invalid settings persisted")
}
v := old
@@ -264,7 +264,7 @@ func TestSpecialistSettings(t *testing.T) {
t.Fatal(err)
}
v.Revision++
- if got := specialists(t, s)[0]; got != v {
+ if got := specialists(t, s)[0]; !reflect.DeepEqual(got, v) {
t.Fatalf("saved settings: %+v", got)
}
if scalar(t, d, "SELECT count(*) FROM audit_events WHERE actor = ? AND kind = 'specialist.save' AND record_id = 'product'", ownerAddress) != 1 {
@@ -278,7 +278,7 @@ func TestSpecialistSettings(t *testing.T) {
t.Fatalf("stale settings: %v", err)
}
}
- if got := specialists(t, s)[0]; got != v || scalar(t, d, "SELECT count(*) FROM audit_events WHERE kind = 'specialist.save'") != 1 {
+ if got := specialists(t, s)[0]; !reflect.DeepEqual(got, v) || scalar(t, d, "SELECT count(*) FROM audit_events WHERE kind = 'specialist.save'") != 1 {
t.Fatal("stale write changed data or audit")
}
v.ModelSelection, v.Provider, v.ModelFamily, v.Model, v.StandingInstructions = "best_fit", "", "", "", ""
@@ -287,7 +287,7 @@ func TestSpecialistSettings(t *testing.T) {
t.Fatal(err)
}
v.Revision++
- if got := specialists(t, s)[0]; got != v {
+ if got := specialists(t, s)[0]; !reflect.DeepEqual(got, v) {
t.Fatal("empty fields did not clear saved values")
}
}
diff --git a/internal/plan3test/specialist_catalog_test.go b/internal/plan3test/specialist_catalog_test.go
new file mode 100644
index 00000000..cff7bf5f
--- /dev/null
+++ b/internal/plan3test/specialist_catalog_test.go
@@ -0,0 +1,83 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "errors"
+ "gorm.io/gorm"
+ "testing"
+)
+
+func TestSpecialistLibraryCatalogIsolation(t *testing.T) {
+ f := newFixture(t)
+ copyValue := "Shipped version one"
+ templates := []library.Template{{Ref: library.TemplateRef{ID: "qa", Version: 1}, NameKey: "name", InstructionsKey: "instructions", Icon: "check-circle"}}
+ deps := library.Dependencies{
+ Authorize: func(_ *gorm.DB, _ equipo.Actor) (library.Access, error) {
+ return library.Access{TeamID: f.TeamID, Owner: true}, nil
+ },
+ Audit: func(_ *gorm.DB, _ equipo.Actor, _, _ string) error { return nil },
+ Copy: func(string) string { return copyValue }, Catalog: func() []library.Template { return templates },
+ Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Conflict: equipo.ErrConflict, NotFound: equipo.ErrNotFound,
+ }
+ must(t, f.DB.G.Transaction(func(tx *gorm.DB) error {
+ s := library.New(tx, deps)
+ a, err := s.Install(owner, templates[0].Ref, equipo.Mutation{RequestID: "one"})
+ if err != nil {
+ return err
+ }
+ b, err := s.Install(owner, templates[0].Ref, equipo.Mutation{RequestID: "two"})
+ if err != nil {
+ return err
+ }
+ templates = append(templates, templates[0])
+ templates[1].Ref.Version = 2
+ copyValue = "Shipped version two"
+ after, err := s.Get(owner, a.Key)
+ if err != nil {
+ return err
+ }
+ if after.Name != a.Name {
+ t.Fatal("catalog changed installed copy")
+ }
+ after, err = s.Get(owner, b.Key)
+ if err != nil {
+ return err
+ }
+ if after.Name != b.Name {
+ t.Fatal("catalog changed second copy")
+ }
+ diff, err := s.Diff(owner, a.Key, templates[1].Ref)
+ if err != nil {
+ return err
+ }
+ copyValue = "Changed after preview"
+ if _, err = s.Apply(owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "changed", Revision: a.Revision}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("later catalog silently changed accepted diff", err)
+ }
+ copyValue = "Shipped version two"
+ after, err = s.Apply(owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "accept", Revision: a.Revision})
+ if err != nil {
+ return err
+ }
+ if after.Name != copyValue || after.StandingInstructions != a.StandingInstructions || after.TemplateVersion != 2 {
+ t.Fatal("explicit update lost provenance or changed unselected field", after)
+ }
+ copyValue = "Later release"
+ replay, err := s.Apply(owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "accept", Revision: a.Revision})
+ if err != nil {
+ return err
+ }
+ if replay.Name != after.Name || replay.Revision != after.Revision {
+ t.Fatal("retry changed accepted diff")
+ }
+ replay, err = s.Install(owner, templates[0].Ref, equipo.Mutation{RequestID: "one"})
+ if err != nil {
+ return err
+ }
+ if replay.Name != a.Name {
+ t.Fatal("catalog change altered install retry")
+ }
+ return nil
+ }))
+}
diff --git a/internal/plan3test/specialist_library_test.go b/internal/plan3test/specialist_library_test.go
new file mode 100644
index 00000000..7902df4b
--- /dev/null
+++ b/internal/plan3test/specialist_library_test.go
@@ -0,0 +1,309 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "errors"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/library"
+)
+
+func specialistInput(name string) equipo.SpecialistInput {
+ return equipo.SpecialistInput{Name: name, Icon: "check-circle", Instructions: "Check the supplied evidence.", MaxConcurrent: 1}
+}
+func TestSpecialistLibraryCopies(t *testing.T) {
+ f := newFixture(t)
+ ref := equipo.TemplateRef{ID: "qa", Version: 1}
+ a, err := f.Store.InstallSpecialistTemplate(ctx, owner, ref, equipo.Mutation{RequestID: "a"})
+ must(t, err)
+ b, err := f.Store.InstallSpecialistTemplate(ctx, owner, ref, equipo.Mutation{RequestID: "b"})
+ must(t, err)
+ if a.Key == b.Key || a.TemplateID != "qa" || a.TemplateVersion != 1 || a.Creator != owner.Address {
+ t.Fatal("copies lack independent identity or provenance")
+ }
+ retry, err := f.Store.InstallSpecialistTemplate(ctx, owner, ref, equipo.Mutation{RequestID: "a"})
+ must(t, err)
+ if retry.Key != a.Key {
+ t.Fatal("retry duplicated copy")
+ }
+ in := library.Input(a)
+ in.Name = "Our QA"
+ in.Instructions = "Our own instructions."
+ a, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: a.Revision})
+ must(t, err)
+ b2, err := f.Store.Specialist(ctx, owner, b.Key)
+ must(t, err)
+ if !reflect.DeepEqual(b, b2) {
+ t.Fatal("editing one copy changed another")
+ }
+ diff, err := f.Store.SpecialistTemplateDiff(ctx, owner, a.Key, ref)
+ must(t, err)
+ if string(diff.Current["name"]) != `"Our QA"` || string(diff.Old["name"]) == string(diff.Current["name"]) || diff.CurrentRevision != a.Revision {
+ t.Fatal("diff lost old/current values", diff)
+ }
+ a, err = f.Store.ApplySpecialistTemplate(ctx, owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "apply", Revision: a.Revision})
+ must(t, err)
+ if a.Name != b.Name || a.StandingInstructions != "Our own instructions." {
+ t.Fatal("selected fields not respected")
+ }
+ _, err = f.Store.ApplySpecialistTemplate(ctx, owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "stale", Revision: diff.CurrentRevision})
+ if !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("stale diff accepted", err)
+ }
+ diff, err = f.Store.SpecialistTemplateDiff(ctx, owner, a.Key, ref)
+ must(t, err)
+ diff.Suggested["name"] = []byte(`"forged"`)
+ _, err = f.Store.ApplySpecialistTemplate(ctx, owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "forged", Revision: a.Revision})
+ if !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("forged diff accepted", err)
+ }
+}
+func TestSpecialistRequiredDefaults(t *testing.T) {
+ f := newFixture(t)
+ for _, key := range []string{"engineering", "review"} {
+ row, err := f.Store.Specialist(ctx, owner, key)
+ must(t, err)
+ if !row.Required || row.Role != key {
+ t.Fatal("required default lost role", row)
+ }
+ err = f.Store.DeleteSpecialist(ctx, owner, key, equipo.Mutation{RequestID: key, Revision: row.Revision})
+ if !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("required default archived", err)
+ }
+ in := library.Input(row)
+ in.Name = "Different role"
+ _, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "convert-" + key, Revision: row.Revision})
+ if !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("required role converted", err)
+ }
+ }
+}
+func TestSpecialistToolPolicy(t *testing.T) {
+ f := newFixture(t)
+ for _, tools := range [][]string{{"sh -c deploy"}, {"Bash"}, {"submit_candidate"}, {"submit_answer", "ask_person"}} {
+ in := specialistInput("Unsafe")
+ in.Tools = tools
+ if _, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: strings.Join(tools, ",")}); err == nil {
+ t.Fatal("uncertified or arbitrary tools accepted", tools)
+ }
+ }
+ row, err := f.Store.CreateSpecialist(ctx, owner, specialistInput("Safe"), equipo.Mutation{RequestID: "safe"})
+ must(t, err)
+ if _, err = f.Store.SelectConnection(ctx, owner.Address, 1, row.Key, ""); err == nil {
+ t.Fatal("unavailable tool profile dispatched")
+ }
+}
+func TestSpecialistScopeAndPermissions(t *testing.T) {
+ f := newFixture(t)
+ f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address)
+ row, err := f.Store.CreateSpecialist(ctx, peer, specialistInput("Team QA"), equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ in := library.Input(row)
+ in.Instructions = "Changed"
+ row, err = f.Store.UpdateSpecialist(ctx, peer, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision})
+ must(t, err)
+ outsider := equipo.Actor{Address: "outsider@example.com"}
+ must(t, f.Store.SetMember(ctx, owner, outsider.Address, equipo.RoleMember, true, 0))
+ in = library.Input(row)
+ if _, err = f.Store.UpdateSpecialist(ctx, outsider, in, equipo.Mutation{RequestID: "steal", Revision: row.Revision}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("other member edited specialist", err)
+ }
+ if err = f.Store.DeleteSpecialist(ctx, outsider, row.Key, equipo.Mutation{RequestID: "steal-delete", Revision: row.Revision}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("other member deleted specialist", err)
+ }
+ in.ProjectIDs = []int64{99999}
+ if _, err = f.Store.UpdateSpecialist(ctx, peer, in, equipo.Mutation{RequestID: "foreign-project", Revision: row.Revision}); err == nil {
+ t.Fatal("foreign project accepted")
+ }
+ f.exec(t, "UPDATE specialists SET team_id='other-team' WHERE key=?", row.Key)
+ if _, err = f.Store.Specialist(ctx, owner, row.Key); !errors.Is(err, equipo.ErrNotFound) {
+ t.Fatal("foreign specialist visible", err)
+ }
+ f.exec(t, "UPDATE specialists SET team_id=? WHERE key=?", f.TeamID, row.Key)
+ f.exec(t, "UPDATE members SET active=0 WHERE address=?", peer.Address)
+ if _, err = f.Store.CreateSpecialist(ctx, peer, specialistInput("Team QA"), equipo.Mutation{RequestID: "create"}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("removed creator replayed write", err)
+ }
+ must(t, f.Store.DeleteSpecialist(ctx, owner, row.Key, equipo.Mutation{RequestID: "archive", Revision: row.Revision}))
+ archived, err := f.Store.Specialist(ctx, owner, row.Key)
+ must(t, err)
+ if !archived.Archived {
+ t.Fatal("history deleted instead of archived")
+ }
+}
+func TestSpecialistTemplateGroups(t *testing.T) {
+ f := newFixture(t)
+ rows, err := f.Store.SpecialistTemplates(ctx, owner)
+ must(t, err)
+ expected := map[string]string{"qa": "quality", "accessibility": "quality", "performance": "quality", "security": "safety", "privacy": "safety", "ops": "running", "data": "running", "support": "running", "docs": "words", "localisation": "words", "seo": "words", "blank": ""}
+ if len(rows) != len(expected) {
+ t.Fatal("catalog missing templates", len(rows))
+ }
+ for _, row := range rows {
+ group, ok := expected[row.Ref.ID]
+ if !ok || row.Group != group || row.NameKey == "" || row.Icon == "" || row.InstructionsKey == "" {
+ t.Fatal("missing group/name/icon/instructions", row)
+ }
+ }
+ w := f.get(t, owner, "/templates")
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "QA and testing") || !strings.Contains(w.Body.String(), "<svg") {
+ t.Fatal("template display", w.Code, w.Body.String())
+ }
+}
+
+func TestSpecialistScopeArchiveReferences(t *testing.T) {
+ f := newFixture(t)
+ base := f.createTask(t)
+ row, err := f.Store.CreateSpecialist(ctx, owner, specialistInput("My specialist"), equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ p := taskplan.BugPlan("", base.ProjectID)
+ p.Revision = 0
+ p.Steps[0].Specialist = row.Key
+ p, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"})
+ must(t, err)
+ if err = f.Store.DeleteSpecialist(ctx, owner, row.Key, equipo.Mutation{RequestID: "archive", Revision: row.Revision}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("unstarted plan lost specialist", err)
+ }
+ snapshot := `{"StandingInstructions":"Check the supplied evidence.","step":{"SpecialistKey":"` + row.Key + `","SpecialistRevision":1}}`
+ f.exec(t, "INSERT INTO runner_assignments(id,task_id,step_key,claim_request,brief) VALUES(?,?,?,?,?)", "saved-step", p.TaskID, "reproduce", "claimed", snapshot)
+ in := library.Input(row)
+ in.Instructions = "Future work instructions."
+ row, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision})
+ must(t, err)
+ var got string
+ must(t, f.DB.Writer().QueryRow("SELECT brief FROM runner_assignments WHERE id='saved-step'").Scan(&got))
+ if got != snapshot {
+ t.Fatal("started snapshot rewritten")
+ }
+ must(t, f.Store.DeleteSpecialist(ctx, owner, row.Key, equipo.Mutation{RequestID: "archive", Revision: row.Revision}))
+ must(t, f.DB.Writer().QueryRow("SELECT brief FROM runner_assignments WHERE id='saved-step'").Scan(&got))
+ if got != snapshot {
+ t.Fatal("archiving changed started snapshot")
+ }
+ next := taskplan.BugPlan("", base.ProjectID)
+ next.Revision = 0
+ next.Steps[0].Specialist = row.Key
+ if _, err = f.Store.ProposePlan(ctx, owner, next, equipo.Mutation{RequestID: "archived-plan"}); err == nil {
+ t.Fatal("archived specialist offered to new plan")
+ }
+}
+func TestSpecialistLibraryRevisionAndAudit(t *testing.T) {
+ f := newFixture(t)
+ in := specialistInput("Original")
+ row, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ in.Name = "Changed"
+ if _, err = f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "create"}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("changed request accepted", err)
+ }
+ in = library.Input(row)
+ in.Name = "New"
+ edited, err := f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision})
+ must(t, err)
+ replay, err := f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision})
+ must(t, err)
+ if edited.Revision != replay.Revision {
+ t.Fatal("retry advanced revision")
+ }
+ if _, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "stale", Revision: row.Revision}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("stale update accepted", err)
+ }
+ f.exec(t, `CREATE TRIGGER reject_library_audit BEFORE INSERT ON audit_events WHEN NEW.kind='specialist.update' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END`)
+ in.Name = "Must roll back"
+ if _, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "rollback", Revision: edited.Revision}); err == nil {
+ t.Fatal("audit failure accepted")
+ }
+ got, err := f.Store.Specialist(ctx, owner, row.Key)
+ must(t, err)
+ if got.Name != edited.Name || got.Revision != edited.Revision {
+ t.Fatal("audit failure did not roll back")
+ }
+}
+func TestSpecialistTemplateForms(t *testing.T) {
+ f := newFixture(t)
+ f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address)
+ post := func(actor equipo.Actor, path string, values url.Values) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", path, strings.NewReader(values.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.Header.Set("Origin", origin)
+ r.AddCookie(f.Cookies[actor.Address])
+ w := httptest.NewRecorder()
+ f.Handler.ServeHTTP(w, r)
+ return w
+ }
+ values := url.Values{"request_id": {"web-create"}, "revision": {"0"}, "name": {"Web QA"}, "icon": {"check-circle"}, "instructions": {"Check evidence."}, "max_concurrent": {"1"}}
+ w := post(peer, "/specialists", values)
+ if w.Code != 303 {
+ t.Fatal("active member could not create", w.Code, w.Body.String())
+ }
+ key := strings.TrimPrefix(w.Header().Get("Location"), "/specialists/")
+ for _, path := range []string{"/specialists/" + key, "/specialists/" + key + "/edit", "/work"} {
+ w = f.get(t, peer, path)
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "Web QA") {
+ t.Fatal("custom specialist missing from page", path, w.Code)
+ }
+ }
+ values.Set("actor", owner.Address)
+ values.Set("request_id", "forged")
+ if w = post(peer, "/specialists", values); w.Code != 422 {
+ t.Fatal("submitted actor accepted", w.Code)
+ }
+ values.Del("actor")
+ values["name"] = []string{"one", "two"}
+ if w = post(peer, "/specialists", values); w.Code != 422 {
+ t.Fatal("duplicate field accepted", w.Code)
+ }
+}
+
+func TestSpecialistScopeProjectAndModels(t *testing.T) {
+ f := newFixture(t)
+ base := f.createTask(t)
+ other := equipo.Project{Name: "Other", Repository: "amadan.net/test/other", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1}
+ must(t, f.DB.G.Create(&other).Error)
+ must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: other.ID, Decision: "merge", Address: owner.Address}).Error)
+ in := specialistInput("Project QA")
+ in.ProjectIDs = []int64{base.ProjectID}
+ in.AllowedModels = []equipo.ModelRef{{Provider: "codex", Family: "gpt", Model: "fixture-model"}}
+ row, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "project-qa"})
+ must(t, err)
+ if library.ModelAllowed(row, "codex", "gpt", "another-model") || !library.ModelAllowed(row, "codex", "gpt", "fixture-model") {
+ t.Fatal("allowed model set ignored")
+ }
+ p := taskplan.BugPlan("", other.ID)
+ p.Revision = 0
+ p.Steps[0].Specialist = row.Key
+ if _, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "other-project"}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("specialist project set ignored", err)
+ }
+ p.ProjectID = base.ProjectID
+ p, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "allowed-project"})
+ must(t, err)
+ counts, err := f.Store.SpecialistCounts(ctx, owner)
+ must(t, err)
+ if counts[row.Key].Queued != 1 || !counts[row.Key].CountsKnown || counts[row.Key].UsageKnown {
+ t.Fatal("custom counts lost unknown usage", counts[row.Key])
+ }
+ view, err := f.Store.TaskView(ctx, owner, p.TaskID)
+ must(t, err)
+ if view.Steps[0].CategoryName != row.Name || view.Steps[0].CategoryIcon != row.Icon {
+ t.Fatal("custom category lost icon/name")
+ }
+}
+
+func TestSpecialistScopeLookupFailure(t *testing.T) {
+ f := newFixture(t)
+ f.exec(t, "DROP TABLE projects")
+ in := specialistInput("Must not save")
+ in.ProjectIDs = []int64{1}
+ if _, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "lookup"}); !errors.Is(err, equipo.ErrUnavailable) {
+ t.Fatal("project query failure lost unavailable state", err)
+ }
+ if f.count(t, "SELECT count(*) FROM specialists WHERE creator<>''") != 0 {
+ t.Fatal("lookup failure saved record")
+ }
+}
diff --git a/internal/plan3test/specialist_migration_test.go b/internal/plan3test/specialist_migration_test.go
new file mode 100644
index 00000000..b0ff3068
--- /dev/null
+++ b/internal/plan3test/specialist_migration_test.go
@@ -0,0 +1,55 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "testing"
+)
+
+func TestSpecialistLibraryMigration(t *testing.T) {
+ d, err := db.Open(filepath.Join(t.TempDir(), "library.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ must(t, err)
+ t.Cleanup(func() { must(t, d.Close()) })
+ old := &migrate.Set{}
+ for _, m := range equipo.BootSchema.All() {
+ if m.ID != "equipo/0024_specialist_library" {
+ old.Add(m)
+ }
+ }
+ _, err = migrate.Apply(ctx, d, old)
+ must(t, err)
+ f := &fixture{DB: d, Store: equipo.NewStore(d), TeamID: "saved-team"}
+ f.exec(t, "INSERT INTO teams(id,name,roster_epoch) VALUES('saved-team','Saved team',4)")
+ f.exec(t, "INSERT INTO members(address,role,revision,active) VALUES(?,'owner',3,1)", owner.Address)
+ f.exec(t, "INSERT INTO specialists(key,model_selection,standing_instructions,max_concurrent,revision) VALUES('engineering','best_fit','Saved instructions',3,7)")
+ result, err := migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, err)
+ if len(result.Applied) != 1 || result.Applied[0] != "equipo/0024_specialist_library" {
+ t.Fatal(result.Applied)
+ }
+ row, err := f.Store.Specialist(ctx, owner, "engineering")
+ must(t, err)
+ if row.TeamID != f.TeamID || !row.Required || row.Role != "engineering" || row.StandingInstructions != "Saved instructions" || row.Revision != 7 || row.MaxConcurrent != 3 {
+ t.Fatal("migration changed saved settings", row)
+ }
+ if f.count(t, "SELECT count(*) FROM specialist_requests") != 0 {
+ t.Fatal("migration fabricated requests")
+ }
+ fresh := newFixture(t)
+ upgraded, err := migrate.Read(ctx, d.Writer())
+ must(t, err)
+ clean, err := migrate.Read(ctx, fresh.DB.Writer())
+ must(t, err)
+ if !upgraded.Equal(clean) {
+ t.Fatal(upgraded.Diff(clean))
+ }
+ result, err = migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, err)
+ if len(result.Applied) != 0 {
+ t.Fatal("migration repeated")
+ }
+}
diff --git a/internal/runner/provider/specialists.go b/internal/runner/provider/specialists.go
new file mode 100644
index 00000000..357c9ded
--- /dev/null
+++ b/internal/runner/provider/specialists.go
@@ -0,0 +1,17 @@
+package provider
+
+import "slices"
+
+// ValidateSpecialistTools intersects a specialist's request with independently
+// supplied team, project and certified tool sets. Text is never a command.
+func ValidateSpecialistTools(requested, team, project, certified []string) error {
+ catalog := []string{"submit_reproduction", "submit_acceptance", "submit_answer", "submit_candidate", "submit_review", "submit_render", "ask_person"}
+ seen := []string{}
+ for _, tool := range requested {
+ if !slices.Contains(catalog, tool) || slices.Contains(seen, tool) || !slices.Contains(team, tool) || !slices.Contains(project, tool) || !slices.Contains(certified, tool) {
+ return ErrPolicy
+ }
+ seen = append(seen, tool)
+ }
+ return nil
+}
diff --git a/internal/runner/provider/specialists_test.go b/internal/runner/provider/specialists_test.go
new file mode 100644
index 00000000..b4c3b8ca
--- /dev/null
+++ b/internal/runner/provider/specialists_test.go
@@ -0,0 +1,27 @@
+package provider
+
+import "testing"
+
+func TestSpecialistToolPolicy(t *testing.T) {
+ allowed := []string{"submit_answer", "ask_person"}
+ if err := ValidateSpecialistTools(allowed, allowed, allowed, allowed); err != nil {
+ t.Fatal("certified subset denied", err)
+ }
+ for _, tc := range []struct {
+ name string
+ requested, team, project, certified []string
+ }{
+ {"command", []string{"sh -c deploy"}, []string{"sh -c deploy"}, []string{"sh -c deploy"}, []string{"sh -c deploy"}},
+ {"provider_tool", []string{"Bash"}, []string{"Bash"}, []string{"Bash"}, []string{"Bash"}},
+ {"team", allowed, []string{"ask_person"}, allowed, allowed},
+ {"project", allowed, allowed, []string{"ask_person"}, allowed},
+ {"certificate", allowed, allowed, allowed, []string{"ask_person"}},
+ {"duplicate", []string{"ask_person", "ask_person"}, allowed, allowed, allowed},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if ValidateSpecialistTools(tc.requested, tc.team, tc.project, tc.certified) == nil {
+ t.Fatal("tool authority widened")
+ }
+ })
+ }
+}
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index 6051000b..aa0719f5 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -151,6 +151,7 @@ type Assignment struct {
}
type StepBrief struct {
+ SpecialistName, SpecialistIcon string
PlanRevision int64
StepKey, SpecialistKey, Action string
SpecialistRevision int64