oficina / equipo Public

feat: add editable playbooks and project defaults

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev ef117ffaf0692f4fb009911f95b9d4e2db0e1a14 parent 7070cc2
39 files changed, +2,179 −98
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +64 −0
  • internal/coordinator/tools.go +5 −1
  • internal/coordinator/types.go +6 −4
  • internal/equipo/app.go +1 −11
  • internal/equipo/copy.go +62 −0
  • internal/equipo/library/application.go +22 −0
  • internal/equipo/library/handlers.go +52 −2
  • internal/equipo/library/navigation.go +1 −0
  • internal/equipo/library/playbook_application.go +61 −0
  • internal/equipo/library/playbook_defaults.go +251 −0
  • internal/equipo/library/playbook_handlers.go +264 −0
  • internal/equipo/library/playbook_suggestions.go +70 −0
  • internal/equipo/library/playbook_templates.go +140 −0
  • internal/equipo/library/playbook_views.go +109 −0
  • internal/equipo/library/playbooks.go +279 −0
  • internal/equipo/library/references.go +3 −0
  • internal/equipo/library/specialists.go +3 −1
  • internal/equipo/library/views.go +24 −0
  • internal/equipo/library_handlers.go +6 −43
  • internal/equipo/migrations/0025_playbooks.sql +6 −0
  • internal/equipo/migrations/schema.sql +6 −0
  • internal/equipo/planning/plans.go +22 −1
  • internal/equipo/planning/views.go +8 −0
  • internal/equipo/plans.go +7 −30
  • internal/equipo/render.go +1 −1
  • internal/equipo/specialist_library.go +4 −1
  • internal/equipo/store.go +6 −0
  • internal/equipo/templates/conversation_card.html +2 −1
  • internal/equipo/templates/plan.html +2 −1
  • internal/equipo/templates/playbook_diff.html +15 −0
  • internal/equipo/templates/playbook_form.html +19 −0
  • internal/equipo/templates/playbooks.html +11 −0
  • internal/equipo/templates/template_library.html +1 −1
  • internal/plan3test/playbooks_catalog_test.go +68 −0
  • internal/plan3test/playbooks_forms_test.go +96 −0
  • internal/plan3test/playbooks_migration_test.go +55 −0
  • internal/plan3test/playbooks_test.go +336 −0
  • internal/taskplan/playbooks.go +55 −0
  • internal/taskplan/playbooks_test.go +36 −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 ab2f50ce..d14188b0 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -3586,3 +3586,67 @@ Each guard was broken separately, the named test reached its failed assertion, a
| `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.
+
+## Task 13
+
+Implemented editable, revisioned playbooks, owner-managed defaults, immutable task copies, private suggestion saves and explicit template updates. Library writes recheck the current roster and creator/owner permissions in the transaction, scope request replay by team/person/operation/resource, and commit audit with data and history. Saved playbooks use Task 2 validation and retain review/checks/person; investigation execution stops at research/person. Recommendations cannot instantiate publishing playbooks, including through an earlier snapshot.
+
+Project+kind, compatible project-wide, kind-wide and shipped kind defaults are resolved in order. The default slot has a composite primary key and its own revision. Project-wide choices of another kind are skipped rather than changing the request's kind or evidence contract. New legacy bug submissions and coordinator proposals use the resolver. Plans display the pinned playbook name/revision and changed step keys.
+
+Added 0025 playbooks and the model/schema mirror. Existing tasks, plan revisions and audits survive upgrade. No core schema or evidence predicate changed. Root stays within its existing budget through feature extraction. API routes remain Task 20's work; the application operations needed by them are available.
+
+### TDD and corrective checks
+
+The five required integration tests were written before implementation. The required red command was:
+
+`CGO_ENABLED=0 go test ./internal/taskplan ./internal/plan3test -run '^TestPlaybook' -count=1`
+
+Exit 1: `library.PlaybookInput`, `library.PlaybookFields`, `InstallPlaybookTemplate`, `SavePlaybook`, `ResolvePlaybook` and related application methods were undefined. At that point taskplan had no matching test; the integration package failed to build. The same command passes after implementation and all guard restorations.
+
+Further failing tests identified integration work before its fix:
+
+| Command | Red result (exit 1) | Fix and green result |
+| --- | --- | --- |
+| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlaybookHTTP$' -count=1` | page unavailable /playbooks 404 | Added routes, forms and rendering; passes in the final required command. |
+| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlaybook(PlanProvenance|CoordinatorDefault)$' -count=1` | proposal snapshot replaced by later revision; runner.invalid | Resolve existing task provenance before the current library row; allow default-backed proposals through the coordinator's typed schema; both pass. |
+| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlaybookLegacyBugDefault$' -count=1` | bug creation ignored default | Seed new bug plans through the same resolver; passes. |
+| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlaybookRecommendationCannotReuseSnapshot$' -count=1` | recommendation reused publishing snapshot | Reject recommendation instantiation before looking up an earlier snapshot; passes. |
+
+The first `make budget` failed with root source at 10,874 against its existing 10,800 ceiling. Intermediate extraction checks found 10,840 and 10,810. Moving specialist routes, form projection and rendering preparation into library, and embedding planning's existing application facade, restored the existing budget. Specialist, plan, form and legacy bug regressions pass after that extraction.
+
+### Final verification
+
+All final commands below exited 0. These are targeted timings, not full-suite measurements.
+
+- `CGO_ENABLED=0 go test ./internal/taskplan ./internal/plan3test -run '^TestPlaybook' -count=1`: taskplan 0.002s; plan3test 2.050s. Covers all five named tests, catalog version acceptance, provenance, coordinator/default integration, migration, permissions, rollback, scriptless forms and recommendation snapshot refusal.
+- `CGO_ENABLED=0 go test ./internal/plan3test -run '^(TestPlan|TestSpecialist|TestConversationScriptlessPlanGuards|TestCoordinator(Tool|ProjectInference|SuggestionOnly))' -count=1`: 9.031s.
+- `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestBug(Submission|FormCannotChooseAuthority|Preparation|PreparedRetryIsImmutable|StartGuards|WorkOwner)|TestFixedBugPlan)' -count=1`: 33.388s.
+- `CGO_ENABLED=0 go test ./internal/coordinator -run '^TestCoordinatorTool' -count=1`: 0.002s.
+- `CGO_ENABLED=0 go test ./internal/equipo -run '^(TestConversationMigrationSnapshot|TestTemplateCopyKeys|TestRunnerCopyInventory)$' -count=1`: 2.543s.
+- `CGO_ENABLED=0 go vet ./internal/taskplan ./internal/coordinator ./internal/equipo/library ./internal/equipo/planning ./internal/equipo ./internal/plan3test`.
+- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/taskplan ./internal/coordinator ./internal/equipo/library ./internal/equipo/planning ./internal/equipo ./internal/plan3test`.
+- `gofmt -l internal/taskplan internal/coordinator internal/equipo/library internal/equipo/planning internal/equipo internal/plan3test`: no output.
+- `git diff --check`.
+- `make migration-check`: TestMigrationModels passed, 0.161s.
+- `make budget`: all 32 directories within their existing budgets. No budget was raised.
+
+### Guard mutations
+
+Ten guards were broken one at a time and restored. The required-tail mutation was repeated after strengthening the test isolation; all 15 combinations of template and mandatory action failed. No mutation was left in the working tree.
+
+| Guard broken | Targeted command | Exit | Observed failure | Restoration |
+| --- | --- | --- | --- | --- |
+| required_tail | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookMandatorySteps$ -count=1` | 1 | All 15 template/action subtests: mandatory tail removed; recommendation instantiated publishing playbook | Restored before the next mutation |
+| default_precedence | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookDefaultPrecedence$ -count=1` | 1 | precedence: kind-wide chosen ahead of the project-wide default | Restored before the next mutation |
+| immutable_snapshot | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookSnapshot$ -count=1` | 1 | playbooks_test.go:104: snapshot changed after library edit | Restored before the next mutation |
+| person_suggestion | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookSuggestionNeedsPerson$ -count=1` | 1 | playbooks_test.go:128: another person saved private suggestion | Restored before the next mutation |
+| creator_owner | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookAuthorityAndRollback$ -count=1` | 1 | playbooks_test.go:212: noncreator edited <nil> | Restored before the next mutation |
+| default_owner | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookDefaultPrecedence$ -count=1` | 1 | playbooks_test.go:82: member controlled default <nil> | Restored before the next mutation |
+| template_diff | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookTemplates$ -count=1` | 1 | playbooks_test.go:168: forged template diff accepted <nil> | Restored before the next mutation |
+| archived_specialist | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookTemplates$ -count=1` | 1 | playbooks_test.go:197: archived specialist accepted | Restored before the next mutation |
+| current_roster | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookAuthorityAndRollback$ -count=1` | 1 | playbooks_test.go:240: revoked replay accepted <nil> | Restored before the next mutation |
+| request_body | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlaybookAuthorityAndRollback$ -count=1` | 1 | playbooks_test.go:236: changed retry accepted <nil> | Restored before the next mutation |
+
+### Copy and handoff
+
+31 new runtime entries are individually marked `COPY REVIEW REQUIRED` in `internal/equipo/copy.go`; the full inventory is in `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-13-report.md`. The commit subject is `feat: add editable playbooks and project defaults`, with author `codex <codex~paul@keymail.dev>`. No push, merge, deployment, live provider run, sign-in, enrolment, agent delegation or copy-review server. No `.claude/HANDOFF.md`. The existing live-release blockers remain.
diff --git a/internal/coordinator/tools.go b/internal/coordinator/tools.go
index 969cb4f5..3b94962e 100644
--- a/internal/coordinator/tools.go
+++ b/internal/coordinator/tools.go
@@ -65,7 +65,11 @@ func Validate(call CoordinatorToolCall) (any, error) {
if p.ProjectID == 0 {
p.ProjectID = 1
}
- valid = Text(a.MessageID, 256) && a.Plan.ProjectID >= 0 && taskplan.Validate(p) == nil
+ defaultPlan := len(p.Steps) == 0 && (taskplan.Publication(p.Kind) || p.Kind == taskplan.Investigation)
+ valid = Text(a.MessageID, 256) && a.Plan.ProjectID >= 0 && (taskplan.Validate(p) == nil || defaultPlan) && len(p.PlaybookID) <= 256 && p.PlaybookRevision >= 0
+ if p.Kind == taskplan.Recommendation && (p.PlaybookID != "" || p.PlaybookRevision != 0) {
+ valid = false
+ }
for _, s := range a.Plan.Steps {
valid = valid && len(s.Instructions) <= 8192
}
diff --git a/internal/coordinator/types.go b/internal/coordinator/types.go
index a81d1e07..3d6aadfe 100644
--- a/internal/coordinator/types.go
+++ b/internal/coordinator/types.go
@@ -28,13 +28,15 @@ type PlanStep struct {
DependsOn []string `json:"depends_on,omitempty"`
}
type Plan struct {
- Kind taskplan.Kind `json:"kind"`
- ProjectID int64 `json:"project_id"`
- Steps []PlanStep `json:"steps"`
+ PlaybookID string `json:"playbook_id,omitempty"`
+ PlaybookRevision int64 `json:"playbook_revision,omitempty"`
+ Kind taskplan.Kind `json:"kind"`
+ ProjectID int64 `json:"project_id"`
+ Steps []PlanStep `json:"steps"`
}
func (p Plan) TaskPlan() taskplan.Plan {
- out := taskplan.Plan{Kind: p.Kind, ProjectID: p.ProjectID}
+ out := taskplan.Plan{Kind: p.Kind, ProjectID: p.ProjectID, PlaybookID: p.PlaybookID, PlaybookRevision: p.PlaybookRevision}
for _, s := range p.Steps {
out.Steps = append(out.Steps, taskplan.Step{Key: s.Key, Specialist: s.Specialist, Action: s.Action, Instructions: s.Instructions, DependsOn: s.DependsOn})
}
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 6302b9d5..1ee7093a 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -205,22 +205,12 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/projects/{id}/connections", a.saveConnectionChoice)
r.Get("/settings", a.settings)
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)
+ lh.Routes(r)
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}", 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/copy.go b/internal/equipo/copy.go
index db5012bf..29afab38 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -72,6 +72,68 @@ var pageCopy = map[string]string{
"specialists.archived": "Archived",
// COPY REVIEW REQUIRED: specialists.unavailable
"specialists.unavailable": "Execution is unavailable until the tool profile is certified.",
+ // COPY REVIEW REQUIRED: playbooks.all_projects
+ "playbooks.all_projects": "All projects",
+ // COPY REVIEW REQUIRED: playbooks.all_kinds
+ "playbooks.all_kinds": "All compatible task kinds",
+ // COPY REVIEW REQUIRED: playbooks.archive
+ "playbooks.archive": "Archive playbook",
+ // COPY REVIEW REQUIRED: task.kind.bug
+ "task.kind.bug": "Bug",
+ // COPY REVIEW REQUIRED: task.kind.feature
+ "task.kind.feature": "Feature",
+ // COPY REVIEW REQUIRED: task.kind.rendered_change
+ "task.kind.rendered_change": "Website change",
+ // COPY REVIEW REQUIRED: task.kind.investigation
+ "task.kind.investigation": "Investigation",
+ // COPY REVIEW REQUIRED: playbooks.title
+ "playbooks.title": "Playbooks",
+ // COPY REVIEW REQUIRED: playbooks.new
+ "playbooks.new": "New playbook",
+ // COPY REVIEW REQUIRED: playbooks.default
+ "playbooks.default": "Default playbook",
+ // COPY REVIEW REQUIRED: playbooks.kind
+ "playbooks.kind": "Task kind",
+ // COPY REVIEW REQUIRED: playbooks.steps
+ "playbooks.steps": "Steps",
+ // COPY REVIEW REQUIRED: playbooks.used
+ "playbooks.used": "Tasks using this playbook",
+ // COPY REVIEW REQUIRED: playbooks.suggested
+ "playbooks.suggested": "Suggested playbook",
+ // COPY REVIEW REQUIRED: playbooks.save_suggestion
+ "playbooks.save_suggestion": "Save playbook suggestion",
+ // COPY REVIEW REQUIRED: playbooks.update_available
+ "playbooks.update_available": "Review template changes",
+ // COPY REVIEW REQUIRED: templates.playbook_bug.name
+ "templates.playbook_bug.name": "Bug",
+ // COPY REVIEW REQUIRED: templates.playbook_bug.description
+ "templates.playbook_bug.description": "Reproduce a bug, fix it and prepare a reviewed change.",
+ // COPY REVIEW REQUIRED: templates.playbook_bug.instructions
+ "templates.playbook_bug.instructions": "Reproduce the reported problem before making a repository change.",
+ // COPY REVIEW REQUIRED: templates.playbook_website.name
+ "templates.playbook_website.name": "Website change",
+ // COPY REVIEW REQUIRED: templates.playbook_website.description
+ "templates.playbook_website.description": "Prepare copy and design changes for a person to review.",
+ // COPY REVIEW REQUIRED: templates.playbook_website.instructions
+ "templates.playbook_website.instructions": "Prepare the website design change for review and rendered approval.",
+ // COPY REVIEW REQUIRED: templates.playbook_infra.name
+ "templates.playbook_infra.name": "Infra change",
+ // COPY REVIEW REQUIRED: templates.playbook_infra.description
+ "templates.playbook_infra.description": "Prepare infrastructure code changes in the repository. Production operations are excluded.",
+ // COPY REVIEW REQUIRED: templates.playbook_infra.instructions
+ "templates.playbook_infra.instructions": "Plan repository changes only. Do not change production infrastructure, deploy or run production operations.",
+ // COPY REVIEW REQUIRED: templates.playbook_investigation.name
+ "templates.playbook_investigation.name": "Investigation",
+ // COPY REVIEW REQUIRED: templates.playbook_investigation.description
+ "templates.playbook_investigation.description": "Research a problem and stop for a person to decide what happens next.",
+ // COPY REVIEW REQUIRED: templates.playbook_investigation.instructions
+ "templates.playbook_investigation.instructions": "Research the problem using supplied project material. Stop at the person checkpoint before planning any publishing work.",
+ // COPY REVIEW REQUIRED: templates.playbook_blank.name
+ "templates.playbook_blank.name": "Blank playbook",
+ // COPY REVIEW REQUIRED: templates.playbook_blank.description
+ "templates.playbook_blank.description": "Start with independent review, checks and a person at the end.",
+ // COPY REVIEW REQUIRED: templates.playbook_blank.instructions
+ "templates.playbook_blank.instructions": "Review the repository change independently before checks and a person decision.",
// COPY REVIEW REQUIRED: templates.title
"templates.title": "Template library",
// COPY REVIEW REQUIRED: templates.install
diff --git a/internal/equipo/library/application.go b/internal/equipo/library/application.go
index 2270ca87..4d7136b2 100644
--- a/internal/equipo/library/application.go
+++ b/internal/equipo/library/application.go
@@ -4,6 +4,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/kernel"
"context"
"gorm.io/gorm"
+ "slices"
)
type Application struct {
@@ -60,3 +61,24 @@ func (s *Application) ListSpecialists(ctx context.Context, a kernel.Actor) (rows
err = s.read(ctx, a, func(l *Store) error { rows, err = l.List(a); return err })
return
}
+
+func (s *Application) SpecialistFormProjects(ctx context.Context, a kernel.Actor, row Specialist) (out []ProjectOption, err error) {
+ err = s.read(ctx, a, func(l *Store) error {
+ access, e := l.deps.Authorize(l.tx, a)
+ if e != nil {
+ return e
+ }
+ if row.Key != "" && !access.Owner && row.Creator != a.Address {
+ return l.deps.Forbidden
+ }
+ var projects []kernel.Project
+ if e = l.tx.Order("name,id").Find(&projects).Error; e != nil {
+ return e
+ }
+ for _, p := range projects {
+ out = append(out, ProjectOption{ID: p.ID, Name: p.Name, Selected: slices.Contains(row.ProjectIDs, p.ID)})
+ }
+ return nil
+ })
+ return
+}
diff --git a/internal/equipo/library/handlers.go b/internal/equipo/library/handlers.go
index dcd2543d..cd93b849 100644
--- a/internal/equipo/library/handlers.go
+++ b/internal/equipo/library/handlers.go
@@ -10,10 +10,15 @@ import (
"strings"
"amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/equipo/planning"
+ "amadan.net/rastrillo/rastrillo/auth"
"github.com/go-chi/chi/v5"
)
type Operations interface {
+ SpecialistFormProjects(context.Context, kernel.Actor, Specialist) ([]ProjectOption, error)
+ SpecialistWork(context.Context, kernel.Actor, string) (planning.SpecialistWorkView, error)
+ PlaybookOperations
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)
@@ -31,6 +36,16 @@ type ProjectOption struct {
Selected bool
}
type View struct {
+ PlaybookEditable bool
+ Work planning.SpecialistWorkView
+ PlaybookPage, Owner bool
+ Playbook Playbook
+ Playbooks []PlaybookView
+ Defaults []PlaybookDefault
+ PlaybookTemplates []Template
+ PlaybookSteps []PlaybookStepView
+ Specialists []Specialist
+ SuggestionID string
Specialist Specialist
Templates []Template
Icons []string
@@ -82,7 +97,12 @@ func (h *Handler) Form(w http.ResponseWriter, r *http.Request) {
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()})
+ projects, err := h.Store.SpecialistFormProjects(r.Context(), a, row)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ h.Render(w, r, "specialist_form", View{Specialist: row, Projects: projects, 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)
@@ -251,5 +271,35 @@ func (h *Handler) Detail(w http.ResponseWriter, r *http.Request) {
h.Failure(w, r, err)
return
}
- h.Render(w, r, "specialist", View{Specialist: row, RequestID: rand.Text()})
+ work, err := h.Store.SpecialistWork(r.Context(), a, row.Key)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ h.Render(w, r, "specialist", View{Specialist: row, Work: work, RequestID: rand.Text()})
+}
+
+func (h *Handler) Routes(r chi.Router) {
+ h.PlaybookRoutes(r)
+ r.Get("/specialists/{key}", h.Detail)
+ r.Get("/templates", h.Catalog)
+ r.Post("/templates/{id}/install", h.Install)
+ r.Get("/specialists/new", h.Form)
+ r.Post("/specialists", h.Save)
+ r.Get("/specialists/{key}/edit", h.Form)
+ r.Post("/specialists/{key}/edit", h.Save)
+ r.Post("/specialists/{key}/archive", h.Archive)
+ r.Get("/specialists/{key}/template-diff", h.Diff)
+ r.Post("/specialists/{key}/template-update", h.Apply)
+ r.Post("/specialists/{key}", h.SaveLegacy)
+}
+
+func SessionActor(forbidden error) func(*http.Request) (kernel.Actor, error) {
+ return func(r *http.Request) (kernel.Actor, error) {
+ id, ok := auth.From(r)
+ if !ok {
+ return kernel.Actor{}, forbidden
+ }
+ return kernel.Actor{Address: id.Address}, nil
+ }
}
diff --git a/internal/equipo/library/navigation.go b/internal/equipo/library/navigation.go
index 0935b9fe..dbf353a0 100644
--- a/internal/equipo/library/navigation.go
+++ b/internal/equipo/library/navigation.go
@@ -13,6 +13,7 @@ func Navigation() []NavItem {
{"copy", "specialists", "/specialists/copy", "nav.copy", "type"},
{"engineering", "specialists", "/specialists/engineering", "nav.engineering", "code"},
{"review", "specialists", "/specialists/review", "nav.review", "check-circle"},
+ {"playbooks", "", "/playbooks", "playbooks.title", "route"},
{"templates", "specialists", "/templates", "templates.title", "plus"},
{"connections", "team", "/connections", "nav.connections", "plug"},
{"people", "team", "/people", "nav.people", "users"},
diff --git a/internal/equipo/library/playbook_application.go b/internal/equipo/library/playbook_application.go
new file mode 100644
index 00000000..35f480d8
--- /dev/null
+++ b/internal/equipo/library/playbook_application.go
@@ -0,0 +1,61 @@
+package library
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "context"
+)
+
+func (s *Application) SavePlaybook(ctx context.Context, a kernel.Actor, in PlaybookInput, m kernel.Mutation) (row Playbook, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.SavePlaybook(a, in, m); return err })
+ return
+}
+func (s *Application) DeletePlaybook(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) error {
+ a.Address = s.Normalize(a.Address)
+ return s.libraryWrite(ctx, func(l *Store) error { return l.DeletePlaybook(a, id, m) })
+}
+func (s *Application) SetPlaybookDefault(ctx context.Context, a kernel.Actor, project int64, kind taskplan.Kind, id string, m kernel.Mutation) error {
+ a.Address = s.Normalize(a.Address)
+ return s.libraryWrite(ctx, func(l *Store) error { return l.SetPlaybookDefault(a, project, kind, id, m) })
+}
+func (s *Application) InstantiatePlaybook(ctx context.Context, a kernel.Actor, id, task string) (p taskplan.Plan, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { p, err = l.InstantiatePlaybook(a, id, task); return err })
+ return
+}
+func (s *Application) ResolvePlaybook(ctx context.Context, a kernel.Actor, project int64, kind taskplan.Kind) (row Playbook, err error) {
+ err = s.read(ctx, a, func(l *Store) error { row, err = l.ResolvePlaybook(a, project, kind); return err })
+ return
+}
+func (s *Application) Playbook(ctx context.Context, a kernel.Actor, id string) (row Playbook, err error) {
+ err = s.read(ctx, a, func(l *Store) error { row, err = l.Playbook(a, id); return err })
+ return
+}
+func (s *Application) Playbooks(ctx context.Context, a kernel.Actor) (rows []Playbook, err error) {
+ err = s.read(ctx, a, func(l *Store) error { rows, err = l.Playbooks(a); return err })
+ return
+}
+func (s *Application) InstallPlaybookTemplate(ctx context.Context, a kernel.Actor, ref TemplateRef, m kernel.Mutation) (row Playbook, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.InstallPlaybookTemplate(a, ref, m); return err })
+ return
+}
+func (s *Application) PlaybookTemplateDiff(ctx context.Context, a kernel.Actor, id string, ref TemplateRef) (diff TemplateDiff, err error) {
+ err = s.read(ctx, a, func(l *Store) error { diff, err = l.PlaybookTemplateDiff(a, id, ref); return err })
+ return
+}
+func (s *Application) ApplyPlaybookTemplate(ctx context.Context, a kernel.Actor, id string, diff TemplateDiff, fields []string, m kernel.Mutation) (row Playbook, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.ApplyPlaybookTemplate(a, id, diff, fields, m); return err })
+ return
+}
+func (s *Application) SavePlaybookSuggestion(ctx context.Context, a kernel.Actor, id string, in PlaybookInput, m kernel.Mutation) (row Playbook, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.libraryWrite(ctx, func(l *Store) error { row, err = l.SavePlaybookSuggestion(a, id, in, m); return err })
+ return
+}
+func (s *Application) PlaybookSuggestion(ctx context.Context, a kernel.Actor, id string) (raw string, revision int64, err error) {
+ err = s.read(ctx, a, func(l *Store) error { raw, revision, err = l.PlaybookSuggestion(a, id); return err })
+ return
+}
diff --git a/internal/equipo/library/playbook_defaults.go b/internal/equipo/library/playbook_defaults.go
new file mode 100644
index 00000000..db7ff34e
--- /dev/null
+++ b/internal/equipo/library/playbook_defaults.go
@@ -0,0 +1,251 @@
+package library
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/equipo/planning"
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "gorm.io/gorm"
+)
+
+func playbookKind(k taskplan.Kind) bool {
+ return taskplan.Publication(k) || k == taskplan.Investigation
+}
+func (s *Store) SetPlaybookDefault(actor kernel.Actor, project int64, kind taskplan.Kind, id string, m kernel.Mutation) error {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return err
+ }
+ if !a.Owner {
+ return s.deps.Forbidden
+ }
+ if project < 0 || kind != "" && !playbookKind(kind) || project == 0 && kind == "" {
+ return s.deps.Invalid
+ }
+ q, _, replay, err := s.playbookReplay(a, actor, "playbook.default", fmt.Sprintf("%d/%s", project, kind), m, id)
+ if err != nil || replay {
+ return err
+ }
+ if project > 0 {
+ var p kernel.Project
+ if err = s.tx.First(&p, project).Error; err != nil {
+ return err
+ }
+ }
+ if id != "" {
+ row, e := s.playbook(a, id)
+ if e != nil {
+ return e
+ }
+ if row.Archived || kind != "" && row.Kind != kind || len(row.ProjectIDs) > 0 && (project == 0 || !slices.Contains(row.ProjectIDs, project)) {
+ return s.deps.Invalid
+ }
+ if err = s.validatePlaybook(a, PlaybookFields(row)); err != nil {
+ return err
+ }
+ }
+ row := PlaybookDefault{TeamID: a.TeamID, ProjectID: project, Kind: kind}
+ err = s.tx.Where("team_id=? AND project_id=? AND kind=?", a.TeamID, project, kind).First(&row).Error
+ fresh := errors.Is(err, gorm.ErrRecordNotFound)
+ if err != nil && !fresh {
+ return err
+ }
+ if m.Revision != row.Revision {
+ return s.deps.Conflict
+ }
+ row.PlaybookID = id
+ row.Revision++
+ if fresh {
+ err = s.tx.Create(&row).Error
+ } else {
+ err = s.tx.Model(&PlaybookDefault{}).Where("team_id=? AND project_id=? AND kind=? AND revision=?", a.TeamID, project, kind, m.Revision).Select("PlaybookID", "Revision").Updates(&row).Error
+ }
+ if err != nil {
+ return err
+ }
+ _, err = s.finishPlaybook(actor, q, Playbook{ID: q.Resource, Revision: row.Revision})
+ return err
+}
+func (s *Store) ResolvePlaybook(actor kernel.Actor, project int64, kind taskplan.Kind) (Playbook, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Playbook{}, err
+ }
+ if project <= 0 || !playbookKind(kind) {
+ return Playbook{}, s.deps.Invalid
+ }
+ var p kernel.Project
+ if err = s.tx.First(&p, project).Error; err != nil {
+ return Playbook{}, err
+ }
+ for _, scope := range []struct {
+ project int64
+ kind taskplan.Kind
+ }{{project, kind}, {project, ""}, {0, kind}} {
+ var d PlaybookDefault
+ err = s.tx.Where("team_id=? AND project_id=? AND kind=?", a.TeamID, scope.project, scope.kind).First(&d).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ continue
+ }
+ if err != nil {
+ return Playbook{}, err
+ }
+ if d.PlaybookID == "" {
+ continue
+ }
+ row, e := s.playbook(a, d.PlaybookID)
+ if e != nil {
+ return row, e
+ }
+ // A project-wide choice supplies only compatible kinds. It cannot turn a
+ // recommendation or an investigation into publishing work.
+ if row.Kind != kind {
+ continue
+ }
+ return row, s.usablePlaybook(a, row, project)
+ }
+ id := map[taskplan.Kind]string{taskplan.Bug: "playbook_bug", taskplan.Feature: "playbook_infra", taskplan.RenderedChange: "playbook_website", taskplan.Investigation: "playbook_investigation"}[kind]
+ row, err := s.playbookTemplate(TemplateRef{id, 1})
+ if err != nil {
+ return row, err
+ }
+ return row, s.usablePlaybook(a, row, project)
+}
+func (s *Store) usablePlaybook(a Access, row Playbook, project int64) error {
+ if row.Archived || len(row.ProjectIDs) > 0 && !slices.Contains(row.ProjectIDs, project) {
+ return s.deps.Forbidden
+ }
+ if err := s.validatePlaybook(a, PlaybookFields(row)); err != nil {
+ return err
+ }
+ return s.ValidatePlan(a.TeamID, taskplan.Plan{Kind: row.Kind, ProjectID: project, Steps: row.Steps}, nil)
+}
+func (s *Store) resolvePlaybookID(a Access, id string) (Playbook, error) {
+ if strings.HasPrefix(id, "template:") {
+ for _, t := range s.playbookCatalog() {
+ row, err := s.playbookTemplate(t.Ref)
+ if err != nil {
+ return row, err
+ }
+ if row.ID == id {
+ return row, nil
+ }
+ }
+ return Playbook{}, s.deps.NotFound
+ }
+ return s.playbook(a, id)
+}
+func playbookPlan(row Playbook, taskID string, project, revision int64) taskplan.Plan {
+ return taskplan.Plan{TaskID: taskID, ProjectID: project, Revision: revision, Kind: row.Kind, PlaybookID: row.ID, PlaybookRevision: row.Revision, Steps: taskplan.PlaybookSteps(row.Kind, row.Steps)}
+}
+func (s *Store) InstantiatePlaybook(actor kernel.Actor, id, taskID string) (taskplan.Plan, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return taskplan.Plan{}, err
+ }
+ var task planning.Task
+ if err = s.tx.Where("id=? AND team_id=?", taskID, a.TeamID).First(&task).Error; err != nil {
+ return taskplan.Plan{}, err
+ }
+ if s.deps.TaskAccess == nil {
+ return taskplan.Plan{}, s.deps.Forbidden
+ }
+ if err = s.deps.TaskAccess(s.tx, actor, task.ProjectID); err != nil {
+ return taskplan.Plan{}, err
+ }
+ if task.Kind == taskplan.Recommendation {
+ return taskplan.Plan{}, s.deps.Invalid
+ }
+ var snap PlaybookSnapshot
+ err = s.tx.Where("task_id=? AND playbook_id=?", taskID, id).First(&snap).Error
+ if err == nil {
+ var p taskplan.Plan
+ err = json.Unmarshal([]byte(snap.Plan), &p)
+ return p, err
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return taskplan.Plan{}, err
+ }
+ if task.PlanRevision > 0 {
+ var saved planning.Revision
+ if err = s.tx.Where("task_id=? AND revision=?", task.ID, task.PlanRevision).First(&saved).Error; err != nil {
+ return taskplan.Plan{}, err
+ }
+ var p taskplan.Plan
+ if err = json.Unmarshal([]byte(saved.Plan), &p); err != nil {
+ return p, err
+ }
+ if p.PlaybookID == id {
+ row, e := s.playbookVersion(a.TeamID, id, p.PlaybookRevision)
+ if e != nil {
+ return p, e
+ }
+ baseline := playbookPlan(row, taskID, task.ProjectID, task.PlanRevision)
+ raw, _ := json.Marshal(baseline)
+ if err = s.tx.Create(&PlaybookSnapshot{TaskID: taskID, PlaybookID: id, Plan: string(raw)}).Error; err != nil {
+ return taskplan.Plan{}, err
+ }
+ return baseline, s.deps.Audit(s.tx, actor, "playbook.instantiate", taskID)
+ }
+ }
+ row, err := s.resolvePlaybookID(a, id)
+ if err != nil {
+ return taskplan.Plan{}, err
+ }
+ if err = s.usablePlaybook(a, row, task.ProjectID); err != nil {
+ return taskplan.Plan{}, err
+ }
+ p := playbookPlan(row, taskID, task.ProjectID, task.PlanRevision)
+ raw, _ := json.Marshal(p)
+ if err = s.tx.Create(&PlaybookSnapshot{TaskID: taskID, PlaybookID: id, Plan: string(raw)}).Error; err != nil {
+ return taskplan.Plan{}, err
+ }
+ return p, s.deps.Audit(s.tx, actor, "playbook.instantiate", taskID)
+}
+
+// ResolvePlan runs inside the proposal transaction, after request replay. Supplied
+// steps remain task-specific changes against the pinned library revision.
+func (s *Store) ResolvePlan(actor kernel.Actor, p taskplan.Plan) (taskplan.Plan, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return p, err
+ }
+ if p.Kind == taskplan.Recommendation {
+ if p.PlaybookID != "" || p.PlaybookRevision != 0 {
+ return p, s.deps.Invalid
+ }
+ return p, nil
+ }
+ if p.PlaybookID == "" && len(p.Steps) > 0 {
+ if p.PlaybookRevision != 0 {
+ return p, s.deps.Invalid
+ }
+ return p, nil
+ }
+ var row Playbook
+ if p.PlaybookID == "" {
+ row, err = s.ResolvePlaybook(actor, p.ProjectID, p.Kind)
+ } else {
+ row, err = s.resolvePlaybookID(a, p.PlaybookID)
+ }
+ if err != nil {
+ return p, err
+ }
+ if row.Kind != p.Kind || p.PlaybookRevision != 0 && p.PlaybookRevision != row.Revision {
+ return p, s.deps.Conflict
+ }
+ if err = s.usablePlaybook(a, row, p.ProjectID); err != nil {
+ return p, err
+ }
+ p.PlaybookID = row.ID
+ p.PlaybookRevision = row.Revision
+ if len(p.Steps) == 0 {
+ p.Steps = taskplan.PlaybookSteps(row.Kind, row.Steps)
+ }
+ return p, nil
+}
diff --git a/internal/equipo/library/playbook_handlers.go b/internal/equipo/library/playbook_handlers.go
new file mode 100644
index 00000000..ec29141d
--- /dev/null
+++ b/internal/equipo/library/playbook_handlers.go
@@ -0,0 +1,264 @@
+package library
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "net/http"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "github.com/go-chi/chi/v5"
+)
+
+type PlaybookOperations interface {
+ PlaybookPage(context.Context, kernel.Actor) (View, error)
+ Playbook(context.Context, kernel.Actor, string) (Playbook, error)
+ SavePlaybook(context.Context, kernel.Actor, PlaybookInput, kernel.Mutation) (Playbook, error)
+ DeletePlaybook(context.Context, kernel.Actor, string, kernel.Mutation) error
+ SetPlaybookDefault(context.Context, kernel.Actor, int64, taskplan.Kind, string, kernel.Mutation) error
+ InstallPlaybookTemplate(context.Context, kernel.Actor, TemplateRef, kernel.Mutation) (Playbook, error)
+ PlaybookTemplateDiff(context.Context, kernel.Actor, string, TemplateRef) (TemplateDiff, error)
+ ApplyPlaybookTemplate(context.Context, kernel.Actor, string, TemplateDiff, []string, kernel.Mutation) (Playbook, error)
+ PlaybookSuggestion(context.Context, kernel.Actor, string) (string, int64, error)
+ SavePlaybookSuggestion(context.Context, kernel.Actor, string, PlaybookInput, kernel.Mutation) (Playbook, error)
+}
+
+func (h *Handler) PlaybookRoutes(r chi.Router) {
+ r.Get("/playbooks", h.Playbooks)
+ r.Get("/playbooks/new", h.PlaybookForm)
+ r.Post("/playbooks", h.SavePlaybook)
+ r.Get("/playbooks/{id}", h.PlaybookForm)
+ r.Get("/playbooks/{id}/edit", h.PlaybookForm)
+ r.Post("/playbooks/{id}/edit", h.SavePlaybook)
+ r.Post("/playbooks/{id}/archive", h.ArchivePlaybook)
+ r.Post("/playbooks/defaults", h.PlaybookDefault)
+ r.Post("/playbook-templates/{id}/install", h.InstallPlaybook)
+ r.Get("/playbooks/{id}/template-diff", h.PlaybookDiff)
+ r.Post("/playbooks/{id}/template-update", h.ApplyPlaybook)
+ r.Get("/playbook-suggestions/{suggestion}", h.PlaybookForm)
+ r.Post("/playbook-suggestions/{suggestion}", h.SavePlaybook)
+}
+func (h *Handler) Playbooks(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ v, err := h.Store.PlaybookPage(r.Context(), a)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ v.RequestID = rand.Text()
+ h.Render(w, r, "playbooks", v)
+}
+func (h *Handler) PlaybookForm(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ v, err := h.Store.PlaybookPage(r.Context(), a)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ v.RequestID = rand.Text()
+ v.Playbook = Playbook{Kind: taskplan.Feature, Steps: taskplan.BugPlan("", 1).Steps[2:]}
+ if id := chi.URLParam(r, "id"); id != "" {
+ v.Playbook, err = h.Store.Playbook(r.Context(), a, id)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ if v.Playbook.Archived {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ }
+ v.PlaybookEditable = v.Playbook.ID == "" || v.Owner || v.Playbook.Creator == a.Address
+ v.SuggestionID = chi.URLParam(r, "suggestion")
+ if v.SuggestionID != "" {
+ raw, revision, e := h.Store.PlaybookSuggestion(r.Context(), a, v.SuggestionID)
+ if e != nil {
+ h.Failure(w, r, e)
+ return
+ }
+ name, instructions := suggestionDraft(raw)
+ v.Playbook.Name = name
+ v.Playbook.Revision = revision
+ v.Playbook.Kind = taskplan.Investigation
+ v.Playbook.Steps = append([]taskplan.Step{{Key: "research", Specialist: "engineering", Action: "investigate", Instructions: instructions}}, taskplan.BugPlan("", 1).Steps[2:4]...)
+ v.Playbook.Steps = append(v.Playbook.Steps, taskplan.Step{Key: "merge", Action: "person", Required: true})
+ }
+ for i, st := range v.Playbook.Steps {
+ v.PlaybookSteps = append(v.PlaybookSteps, PlaybookStepView{st, i, i + 1})
+ }
+ for i := range v.Projects {
+ v.Projects[i].Selected = slices.Contains(v.Playbook.ProjectIDs, v.Projects[i].ID)
+ }
+ h.Render(w, r, "playbook_form", v)
+}
+func (h *Handler) SavePlaybook(w http.ResponseWriter, r *http.Request) {
+ allowed := []string{"request_id", "revision", "name", "kind", "project", "template_id", "template_version", "step_count"}
+ for i := 0; i <= taskplan.MaxSteps; i++ {
+ for _, field := range []string{"key", "specialist", "action", "instructions", "position", "remove", "depends"} {
+ allowed = append(allowed, "step_"+strconv.Itoa(i)+"_"+field)
+ }
+ }
+ a, m, err := h.form(w, r, allowed...)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ in, err := h.decodePlaybook(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ var row Playbook
+ if id := chi.URLParam(r, "suggestion"); id != "" {
+ row, err = h.Store.SavePlaybookSuggestion(r.Context(), a, id, in, m)
+ } else {
+ row, err = h.Store.SavePlaybook(r.Context(), a, in, m)
+ }
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/playbooks/"+row.ID+"/edit", http.StatusSeeOther)
+}
+func (h *Handler) decodePlaybook(r *http.Request) (PlaybookInput, error) {
+ v := r.PostForm
+ in := PlaybookInput{ID: chi.URLParam(r, "id"), Name: v.Get("name"), Kind: taskplan.Kind(v.Get("kind")), Template: TemplateRef{ID: v.Get("template_id")}}
+ var err error
+ in.Template.Version, err = strconv.ParseInt(v.Get("template_version"), 10, 64)
+ if err != nil {
+ return in, h.Invalid
+ }
+ n, err := strconv.Atoi(v.Get("step_count"))
+ if err != nil || n < 1 || n > taskplan.MaxSteps {
+ return in, h.Invalid
+ }
+ steps := []PlaybookStepView{}
+ seen := map[int]bool{}
+ for i := 0; i <= n; i++ {
+ prefix := "step_" + strconv.Itoa(i) + "_"
+ if i == n && v.Get(prefix+"key") == "" {
+ break
+ }
+ if v.Get(prefix+"remove") == "1" {
+ continue
+ }
+ pos, e := strconv.Atoi(v.Get(prefix + "position"))
+ if e != nil || pos < 1 || pos > taskplan.MaxSteps || seen[pos] {
+ return in, h.Invalid
+ }
+ seen[pos] = true
+ st := taskplan.Step{Key: v.Get(prefix + "key"), Specialist: v.Get(prefix + "specialist"), Action: v.Get(prefix + "action"), Instructions: v.Get(prefix + "instructions")}
+ if deps := v.Get(prefix + "depends"); deps != "" {
+ st.DependsOn = strings.Split(deps, ",")
+ }
+ steps = append(steps, PlaybookStepView{Step: st, Position: pos})
+ }
+ sort.Slice(steps, func(i, j int) bool { return steps[i].Position < steps[j].Position })
+ for _, st := range steps {
+ in.Steps = append(in.Steps, st.Step)
+ }
+ for _, v := range v["project"] {
+ id, e := strconv.ParseInt(v, 10, 64)
+ if e != nil {
+ return in, h.Invalid
+ }
+ in.ProjectIDs = append(in.ProjectIDs, id)
+ }
+ return in, nil
+}
+func (h *Handler) ArchivePlaybook(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "revision")
+ if err == nil {
+ err = h.Store.DeletePlaybook(r.Context(), a, chi.URLParam(r, "id"), m)
+ }
+ h.playbookFinish(w, r, err)
+}
+func (h *Handler) PlaybookDefault(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "revision", "project_id", "kind", "playbook_id")
+ if err == nil {
+ project, e := strconv.ParseInt(r.PostForm.Get("project_id"), 10, 64)
+ if e != nil {
+ err = h.Invalid
+ } else {
+ err = h.Store.SetPlaybookDefault(r.Context(), a, project, taskplan.Kind(r.PostForm.Get("kind")), r.PostForm.Get("playbook_id"), m)
+ }
+ }
+ h.playbookFinish(w, r, err)
+}
+func (h *Handler) playbookFinish(w http.ResponseWriter, r *http.Request, err error) {
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/playbooks", http.StatusSeeOther)
+}
+func (h *Handler) InstallPlaybook(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "version")
+ if err == nil {
+ version, e := strconv.ParseInt(r.PostForm.Get("version"), 10, 64)
+ if e != nil {
+ err = h.Invalid
+ } else {
+ _, err = h.Store.InstallPlaybookTemplate(r.Context(), a, TemplateRef{chi.URLParam(r, "id"), version}, m)
+ }
+ }
+ h.playbookFinish(w, r, err)
+}
+func (h *Handler) PlaybookDiff(w http.ResponseWriter, r *http.Request) {
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ row, err := h.Store.Playbook(r.Context(), a, chi.URLParam(r, "id"))
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ target := row.Template
+ if v := r.URL.Query().Get("version"); v != "" {
+ target.Version, err = strconv.ParseInt(v, 10, 64)
+ if err != nil {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ }
+ diff, err := h.Store.PlaybookTemplateDiff(r.Context(), a, row.ID, target)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ v := View{PlaybookPage: true, Playbook: row, Diff: diff, RequestID: rand.Text()}
+ raw, _ := json.Marshal(diff)
+ v.DiffJSON = string(raw)
+ for _, field := range []struct{ key, label string }{{"name", "specialists.name"}, {"kind", "playbooks.kind"}, {"steps", "playbooks.steps"}, {"project_ids", "specialists.projects"}} {
+ v.Fields = append(v.Fields, FieldDiff{field.key, field.label, string(diff.Old[field.key]), string(diff.Current[field.key]), string(diff.Suggested[field.key])})
+ }
+ h.Render(w, r, "playbook_diff", v)
+}
+func (h *Handler) ApplyPlaybook(w http.ResponseWriter, r *http.Request) {
+ a, m, err := h.form(w, r, "request_id", "revision", "diff", "field")
+ if err == nil {
+ var diff TemplateDiff
+ if runnerproto.DecodeLimit(strings.NewReader(r.PostForm.Get("diff")), &diff, 64<<10) != nil {
+ err = h.Invalid
+ } else {
+ _, err = h.Store.ApplyPlaybookTemplate(r.Context(), a, chi.URLParam(r, "id"), diff, r.PostForm["field"], m)
+ }
+ }
+ h.playbookFinish(w, r, err)
+}
diff --git a/internal/equipo/library/playbook_suggestions.go b/internal/equipo/library/playbook_suggestions.go
new file mode 100644
index 00000000..6f39a96e
--- /dev/null
+++ b/internal/equipo/library/playbook_suggestions.go
@@ -0,0 +1,70 @@
+package library
+
+import (
+ "encoding/json"
+ "errors"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "gorm.io/gorm"
+)
+
+type PlaybookSuggestion struct {
+ ID string `gorm:"primaryKey"`
+ PlaybookID string
+}
+
+func (s *Store) PlaybookSuggestion(actor kernel.Actor, id string) (string, int64, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return "", 0, err
+ }
+ var row struct {
+ Body string
+ Revision int64
+ }
+ err = s.tx.Table("conversation_messages m").Select("m.body,m.revision").Joins("JOIN conversations c ON c.id=m.conversation_id").Joins("JOIN conversation_cards card ON card.resource_id=m.id AND card.stream_id=c.id").Where("m.id=? AND c.person=? AND c.team_id=? AND m.author_kind='coordinator' AND card.kind='suggest_playbook'", id, actor.Address, a.TeamID).Take(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ err = s.deps.NotFound
+ }
+ return row.Body, row.Revision, err
+}
+func (s *Store) SavePlaybookSuggestion(actor kernel.Actor, id string, in PlaybookInput, m kernel.Mutation) (Playbook, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Playbook{}, err
+ }
+ _, rev, err := s.PlaybookSuggestion(actor, id)
+ if err != nil {
+ return Playbook{}, err
+ }
+ q, old, replay, err := s.playbookReplay(a, actor, "playbook.suggestion_save", id, m, in)
+ if err != nil || replay {
+ return old, err
+ }
+ if rev != m.Revision {
+ return Playbook{}, s.deps.Conflict
+ }
+ if in.ID != "" || in.Template != (TemplateRef{}) {
+ return Playbook{}, s.deps.Invalid
+ }
+ var saved PlaybookSuggestion
+ err = s.tx.Where("id=?", id).First(&saved).Error
+ if err == nil {
+ return Playbook{}, s.deps.Conflict
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return Playbook{}, err
+ }
+ row, err := s.writePlaybook(a, actor, Playbook{}, in, kernel.Mutation{RequestID: m.RequestID}, q)
+ if err != nil {
+ return Playbook{}, err
+ }
+ return row, s.tx.Create(&PlaybookSuggestion{ID: id, PlaybookID: row.ID}).Error
+}
+func suggestionDraft(raw string) (name, instructions string) {
+ var v struct {
+ Draft struct{ Name, Instructions string }
+ }
+ _ = json.Unmarshal([]byte(raw), &v)
+ return v.Draft.Name, v.Draft.Instructions
+}
diff --git a/internal/equipo/library/playbook_templates.go b/internal/equipo/library/playbook_templates.go
new file mode 100644
index 00000000..cf13c305
--- /dev/null
+++ b/internal/equipo/library/playbook_templates.go
@@ -0,0 +1,140 @@
+package library
+
+import (
+ "encoding/json"
+ "slices"
+ "strconv"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/taskplan"
+)
+
+// PlaybookCatalog returns fresh version-pinned definitions on each call.
+func PlaybookCatalog() []Template {
+ rows := []Template{}
+ for _, id := range []string{"bug", "website", "infra", "investigation", "blank"} {
+ rows = append(rows, Template{Ref: TemplateRef{"playbook_" + id, 1}, Group: "playbooks", GroupKey: "playbooks.title", NameKey: "templates.playbook_" + id + ".name", DescriptionKey: "templates.playbook_" + id + ".description", InstructionsKey: "templates.playbook_" + id + ".instructions", Icon: "route"})
+ }
+ return rows
+}
+func (s *Store) playbookCatalog() []Template {
+ if s.deps.PlaybookCatalog != nil {
+ return s.deps.PlaybookCatalog()
+ }
+ return PlaybookCatalog()
+}
+func (s *Store) playbookTemplate(ref TemplateRef) (Playbook, error) {
+ for _, t := range s.playbookCatalog() {
+ if t.Ref == ref {
+ p := taskplan.BugPlan("", 1)
+ switch ref.ID {
+ case "playbook_bug":
+ case "playbook_website":
+ p.Kind = taskplan.RenderedChange
+ p.Steps = append([]taskplan.Step{{Key: "design", Specialist: "design", Action: "design"}, {Key: "copy", Specialist: "copy", Action: "copy"}}, p.Steps[1:]...)
+ case "playbook_infra":
+ p.Kind = taskplan.Feature
+ p.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"}
+ case "playbook_investigation":
+ p.Kind = taskplan.Investigation
+ p.Steps = append([]taskplan.Step{{Key: "research", Specialist: "engineering", Action: "investigate"}}, p.Steps[2:4]...)
+ p.Steps = append(p.Steps, taskplan.Step{Key: "merge", Action: "person", Required: true})
+ case "playbook_blank":
+ p.Kind = taskplan.Feature
+ p.Steps = p.Steps[2:]
+ default:
+ return Playbook{}, s.deps.NotFound
+ }
+ p.Steps[0].Instructions = s.deps.Copy(t.InstructionsKey)
+ row := Playbook{ID: "template:" + ref.ID + ":" + strconv.FormatInt(ref.Version, 10), Name: s.deps.Copy(t.NameKey), Kind: p.Kind, Steps: p.Steps, ProjectIDs: []int64{}, Template: ref, Revision: ref.Version}
+ return row, nil
+ }
+ }
+ return Playbook{}, s.deps.NotFound
+}
+func playbookValues(row Playbook) map[string]json.RawMessage {
+ values := map[string]json.RawMessage{}
+ for k, v := range map[string]any{"name": row.Name, "kind": row.Kind, "steps": row.Steps, "project_ids": row.ProjectIDs} {
+ raw, _ := json.Marshal(v)
+ values[k] = raw
+ }
+ return values
+}
+func (s *Store) InstallPlaybookTemplate(actor kernel.Actor, ref TemplateRef, m kernel.Mutation) (Playbook, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Playbook{}, err
+ }
+ q, old, replay, err := s.playbookReplay(a, actor, "playbook.install", ref.ID, m, ref)
+ if err != nil || replay {
+ return old, err
+ }
+ row, err := s.playbookTemplate(ref)
+ if err != nil {
+ return Playbook{}, err
+ }
+ in := PlaybookFields(row)
+ in.ID = ""
+ return s.writePlaybook(a, actor, Playbook{Template: ref}, in, m, q)
+}
+func (s *Store) PlaybookTemplateDiff(actor kernel.Actor, id string, target TemplateRef) (TemplateDiff, error) {
+ row, err := s.Playbook(actor, id)
+ if err != nil {
+ return TemplateDiff{}, err
+ }
+ if row.Archived || row.Template.ID == "" || row.Template.ID != target.ID || target.Version < row.Template.Version {
+ return TemplateDiff{}, s.deps.Invalid
+ }
+ next, err := s.playbookTemplate(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
+ }
+ return TemplateDiff{From: row.Template, To: target, CurrentRevision: row.Revision, Old: old, Current: playbookValues(row), Suggested: playbookValues(next)}, nil
+}
+func (s *Store) ApplyPlaybookTemplate(actor kernel.Actor, id string, diff TemplateDiff, selected []string, m kernel.Mutation) (Playbook, error) {
+ a, row, err := s.playbookEditor(actor, id)
+ if err != nil {
+ return Playbook{}, err
+ }
+ q, old, replay, err := s.playbookReplay(a, actor, "playbook.template_update", id, m, struct {
+ Diff TemplateDiff
+ Selected []string
+ }{diff, selected})
+ if err != nil || replay {
+ return old, err
+ }
+ current, err := s.PlaybookTemplateDiff(actor, id, diff.To)
+ if err != nil {
+ return Playbook{}, err
+ }
+ if m.Revision != diff.CurrentRevision || !equalDiff(current, diff) {
+ return Playbook{}, s.deps.Conflict
+ }
+ if len(selected) == 0 {
+ return Playbook{}, s.deps.Invalid
+ }
+ values := playbookValues(row)
+ seen := []string{}
+ for _, k := range selected {
+ v, ok := diff.Suggested[k]
+ if !ok || slices.Contains(seen, k) {
+ return Playbook{}, s.deps.Invalid
+ }
+ seen = append(seen, k)
+ values[k] = v
+ }
+ in := PlaybookFields(row)
+ for k, dst := range map[string]any{"name": &in.Name, "kind": &in.Kind, "steps": &in.Steps, "project_ids": &in.ProjectIDs} {
+ if json.Unmarshal(values[k], dst) != nil {
+ return Playbook{}, s.deps.Invalid
+ }
+ }
+ row.Template = diff.To
+ raw, _ := json.Marshal(diff.Suggested)
+ row.TemplateBase = string(raw)
+ return s.writePlaybook(a, actor, row, in, m, q)
+}
diff --git a/internal/equipo/library/playbook_views.go b/internal/equipo/library/playbook_views.go
new file mode 100644
index 00000000..a2406fa8
--- /dev/null
+++ b/internal/equipo/library/playbook_views.go
@@ -0,0 +1,109 @@
+package library
+
+import (
+ "context"
+ "encoding/json"
+ "reflect"
+ "sort"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/taskplan"
+)
+
+type PlaybookView struct {
+ Playbook
+ Used int64
+}
+type PlaybookStepView struct {
+ taskplan.Step
+ Index, Position int
+}
+
+func (s *Application) PlaybookPage(ctx context.Context, a kernel.Actor) (v View, err error) {
+ err = s.read(ctx, a, func(l *Store) error {
+ access, e := l.deps.Authorize(l.tx, a)
+ if e != nil {
+ return e
+ }
+ v.PlaybookPage = true
+ v.Owner = access.Owner
+ rows, e := l.Playbooks(a)
+ if e != nil {
+ return e
+ }
+ for _, row := range rows {
+ var n int64
+ if e = l.tx.Table("tasks t").Joins("JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.plan_revision").Where("t.team_id=? AND json_extract(p.plan,'$.PlaybookID')=?", access.TeamID, row.ID).Count(&n).Error; e != nil {
+ return e
+ }
+ v.Playbooks = append(v.Playbooks, PlaybookView{row, n})
+ }
+ if e = l.tx.Where("team_id=?", access.TeamID).Order("project_id,kind").Find(&v.Defaults).Error; e != nil {
+ return e
+ }
+ var projects []kernel.Project
+ if e = l.tx.Order("name,id").Find(&projects).Error; e != nil {
+ return e
+ }
+ for _, p := range projects {
+ v.Projects = append(v.Projects, ProjectOption{ID: p.ID, Name: p.Name})
+ }
+ v.PlaybookTemplates = l.playbookCatalog()
+ v.Specialists, e = l.List(a)
+ return e
+ })
+ return
+}
+func (s *Store) playbookVersion(teamID, id string, revision int64) (Playbook, error) {
+ row, err := s.resolvePlaybookID(Access{TeamID: teamID}, id)
+ if err != nil {
+ return row, err
+ }
+ if row.Creator == "" && row.TeamID == "" {
+ if row.Revision != revision {
+ return row, s.deps.Invalid
+ }
+ return row, nil
+ }
+ var saved PlaybookRevision
+ if err = s.tx.Where("id=? AND revision=?", id, revision).First(&saved).Error; err != nil {
+ return row, err
+ }
+ err = json.Unmarshal([]byte(saved.Value), &row)
+ return row, err
+}
+func (s *Store) PlanDetails(teamID string, p taskplan.Plan) (string, []string, error) {
+ if p.PlaybookID == "" {
+ if p.PlaybookRevision != 0 {
+ return "", nil, s.deps.Invalid
+ }
+ return "", nil, nil
+ }
+ if p.Kind == taskplan.Recommendation {
+ return "", nil, s.deps.Invalid
+ }
+ row, err := s.playbookVersion(teamID, p.PlaybookID, p.PlaybookRevision)
+ if err != nil {
+ return "", nil, err
+ }
+ changed := []string{}
+ before := map[string]taskplan.Step{}
+ baseline := taskplan.PlaybookSteps(row.Kind, row.Steps)
+ for _, st := range baseline {
+ before[st.Key] = st
+ }
+ for i, st := range p.Steps {
+ old, ok := before[st.Key]
+ if !ok || !reflect.DeepEqual(st, old) || i >= len(baseline) || baseline[i].Key != st.Key {
+ changed = append(changed, st.Key)
+ }
+ delete(before, st.Key)
+ }
+ removed := []string{}
+ for k := range before {
+ removed = append(removed, k)
+ }
+ sort.Strings(removed)
+ changed = append(changed, removed...)
+ return row.Name, changed, nil
+}
diff --git a/internal/equipo/library/playbooks.go b/internal/equipo/library/playbooks.go
new file mode 100644
index 00000000..11a8d9ff
--- /dev/null
+++ b/internal/equipo/library/playbooks.go
@@ -0,0 +1,279 @@
+package library
+
+import (
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "gorm.io/gorm"
+)
+
+type PlaybookInput struct {
+ ID, Name string
+ Kind taskplan.Kind
+ Steps []taskplan.Step
+ ProjectIDs []int64
+ Template TemplateRef
+}
+type Playbook struct {
+ ID string `gorm:"primaryKey"`
+ TeamID, Creator, Name string
+ Kind taskplan.Kind
+ Steps []taskplan.Step `gorm:"serializer:json"`
+ ProjectIDs []int64 `gorm:"serializer:json"`
+ Template TemplateRef `gorm:"embedded;embeddedPrefix:template_"`
+ TemplateBase string
+ Revision int64
+ Archived bool
+}
+type PlaybookRevision struct {
+ ID string `gorm:"primaryKey"`
+ Revision int64 `gorm:"primaryKey;autoIncrement:false"`
+ Value string
+}
+type PlaybookDefault struct {
+ TeamID string `gorm:"primaryKey"`
+ ProjectID int64 `gorm:"primaryKey;autoIncrement:false"`
+ Kind taskplan.Kind `gorm:"primaryKey"`
+ PlaybookID string
+ Revision int64
+}
+type PlaybookSnapshot struct {
+ TaskID string `gorm:"primaryKey"`
+ PlaybookID string `gorm:"primaryKey"`
+ Plan string
+}
+type playbookRequest request
+
+func (playbookRequest) TableName() string { return "playbook_requests" }
+
+func PlaybookFields(row Playbook) PlaybookInput {
+ steps := slices.Clone(row.Steps)
+ for i := range steps {
+ steps[i].DependsOn = slices.Clone(steps[i].DependsOn)
+ }
+ return PlaybookInput{ID: row.ID, Name: row.Name, Kind: row.Kind, Steps: steps, ProjectIDs: slices.Clone(row.ProjectIDs), Template: row.Template}
+}
+func (s *Store) Playbook(actor kernel.Actor, id string) (Playbook, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Playbook{}, err
+ }
+ return s.playbook(a, id)
+}
+func (s *Store) playbook(a Access, id string) (Playbook, error) {
+ var row Playbook
+ err := s.tx.Where("id=? AND team_id=?", id, a.TeamID).First(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ err = s.deps.NotFound
+ }
+ return row, err
+}
+func (s *Store) Playbooks(actor kernel.Actor) ([]Playbook, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return nil, err
+ }
+ var rows []Playbook
+ err = s.tx.Where("team_id=? AND archived=?", a.TeamID, false).Order("name,id").Find(&rows).Error
+ return rows, err
+}
+func (s *Store) playbookEditor(actor kernel.Actor, id string) (Access, Playbook, error) {
+ a, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return a, Playbook{}, err
+ }
+ if id == "" {
+ return a, Playbook{}, nil
+ }
+ row, err := s.playbook(a, id)
+ 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) validatePlaybook(a Access, in PlaybookInput) error {
+ if strings.TrimSpace(in.Name) == "" || len(in.Name) > 120 || !utf8.ValidString(in.Name) || len(in.ProjectIDs) > 100 || taskplan.ValidatePlaybook(in.Kind, in.Steps) != nil {
+ return s.deps.Invalid
+ }
+ ids := map[int64]bool{}
+ for _, id := range in.ProjectIDs {
+ if id <= 0 || ids[id] {
+ return s.deps.Invalid
+ }
+ ids[id] = true
+ var p kernel.Project
+ if err := s.tx.First(&p, id).Error; err != nil {
+ return err
+ }
+ }
+ for _, st := range in.Steps {
+ // A shared playbook cannot capture a person's account selection.
+ if st.ConnectionID != "" || st.Model != "" || st.SelectionReason != "" {
+ return s.deps.Invalid
+ }
+ if st.Action == "person" || st.Action == "checks" || st.Action == "publish" {
+ if st.Specialist != "" {
+ return s.deps.Invalid
+ }
+ continue
+ }
+ key := st.Specialist
+ if key == "" {
+ key = "engineering"
+ }
+ sp, err := s.get(a, key)
+ if err != nil {
+ return err
+ }
+ if sp.Archived {
+ return s.deps.Forbidden
+ }
+ if len(sp.ProjectIDs) > 0 {
+ if len(in.ProjectIDs) == 0 {
+ return s.deps.Forbidden
+ }
+ for _, id := range in.ProjectIDs {
+ if !slices.Contains(sp.ProjectIDs, id) {
+ return s.deps.Forbidden
+ }
+ }
+ }
+ }
+ return nil
+}
+func (s *Store) playbookReplay(a Access, actor kernel.Actor, op, id string, m kernel.Mutation, input any) (playbookRequest, Playbook, bool, error) {
+ var result Playbook
+ if !m.Valid() {
+ return playbookRequest{}, result, false, s.deps.Invalid
+ }
+ hash, err := kernel.InputHash(struct {
+ Input any
+ Revision int64
+ }{input, m.Revision})
+ if err != nil {
+ return playbookRequest{}, result, false, err
+ }
+ q := playbookRequest{TeamID: a.TeamID, Principal: actor.Address, Operation: op, Resource: id, RequestID: m.RequestID, InputHash: hash}
+ var old playbookRequest
+ err = s.tx.Where("team_id=? AND principal=? AND operation=? AND resource=? AND request_id=?", a.TeamID, actor.Address, op, id, 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) finishPlaybook(actor kernel.Actor, q playbookRequest, row Playbook) (Playbook, error) {
+ if err := s.deps.Audit(s.tx, actor, q.Operation, row.ID); err != nil {
+ return Playbook{}, err
+ }
+ raw, err := json.Marshal(row)
+ if err != nil {
+ return Playbook{}, err
+ }
+ q.Result = string(raw)
+ return row, s.tx.Create(&q).Error
+}
+func (s *Store) SavePlaybook(actor kernel.Actor, in PlaybookInput, m kernel.Mutation) (Playbook, error) {
+ a, row, err := s.playbookEditor(actor, in.ID)
+ if err != nil {
+ return Playbook{}, err
+ }
+ q, old, replay, err := s.playbookReplay(a, actor, "playbook.save", in.ID, m, in)
+ if err != nil || replay {
+ return old, err
+ }
+ // Provenance is assigned only by an explicit install or accepted update.
+ if in.Template != row.Template {
+ return Playbook{}, s.deps.Invalid
+ }
+ return s.writePlaybook(a, actor, row, in, m, q)
+}
+func (s *Store) writePlaybook(a Access, actor kernel.Actor, row Playbook, in PlaybookInput, m kernel.Mutation, q playbookRequest) (Playbook, error) {
+ if row.Archived || m.Revision != row.Revision {
+ return Playbook{}, s.deps.Conflict
+ }
+ if err := s.validatePlaybook(a, in); err != nil {
+ return Playbook{}, err
+ }
+ fresh := row.ID == ""
+ if fresh {
+ row.ID = rand.Text()
+ row.Creator = actor.Address
+ row.TeamID = a.TeamID
+ }
+ row.Name = in.Name
+ row.Kind = in.Kind
+ row.Steps = PlaybookFields(Playbook{Steps: in.Steps}).Steps
+ row.ProjectIDs = append([]int64{}, in.ProjectIDs...)
+ row.Revision++
+ for i := range row.Steps {
+ row.Steps[i].Required = slices.Contains([]string{"review", "checks", "person"}, row.Steps[i].Action)
+ }
+ if fresh && row.Template.ID != "" {
+ raw, _ := json.Marshal(playbookValues(row))
+ row.TemplateBase = string(raw)
+ }
+ var err error
+ if fresh {
+ err = s.tx.Create(&row).Error
+ } else {
+ r := s.tx.Model(&Playbook{}).Where("id=? AND team_id=? AND revision=?", row.ID, a.TeamID, m.Revision).Select("Name", "Kind", "Steps", "ProjectIDs", "Revision", "TemplateID", "TemplateVersion", "TemplateBase").Updates(&row)
+ err = r.Error
+ if err == nil && r.RowsAffected != 1 {
+ err = s.deps.Conflict
+ }
+ }
+ if err != nil {
+ return Playbook{}, err
+ }
+ raw, _ := json.Marshal(row)
+ if err = s.tx.Create(&PlaybookRevision{ID: row.ID, Revision: row.Revision, Value: string(raw)}).Error; err != nil {
+ return Playbook{}, err
+ }
+ return s.finishPlaybook(actor, q, row)
+}
+func (s *Store) DeletePlaybook(actor kernel.Actor, id string, m kernel.Mutation) error {
+ a, row, err := s.playbookEditor(actor, id)
+ if err != nil {
+ return err
+ }
+ if id == "" {
+ return s.deps.Invalid
+ }
+ q, _, replay, err := s.playbookReplay(a, actor, "playbook.archive", id, m, id)
+ if err != nil || replay {
+ return err
+ }
+ if row.Archived || row.Revision != m.Revision {
+ return s.deps.Conflict
+ }
+ var n int64
+ if err = s.tx.Model(&PlaybookDefault{}).Where("team_id=? AND playbook_id=?", a.TeamID, id).Count(&n).Error; err != nil {
+ return err
+ }
+ if n > 0 {
+ return s.deps.Conflict
+ }
+ row.Archived = true
+ row.Revision++
+ if err = s.tx.Model(&Playbook{}).Where("id=? AND team_id=? AND revision=?", id, a.TeamID, m.Revision).Select("Archived", "Revision").Updates(&row).Error; err != nil {
+ return err
+ }
+ _, err = s.finishPlaybook(actor, q, row)
+ return err
+}
diff --git a/internal/equipo/library/references.go b/internal/equipo/library/references.go
index 836194b7..26f72c3a 100644
--- a/internal/equipo/library/references.go
+++ b/internal/equipo/library/references.go
@@ -18,6 +18,9 @@ func UnstartedReference(tx *gorm.DB, key string) (bool, error) {
// 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 {
+ if _, _, err := s.PlanDetails(teamID, p); err != nil {
+ return err
+ }
for _, st := range p.Steps {
if started[st.Key] || st.Action == "person" || st.Action == "checks" || st.Action == "publish" {
continue
diff --git a/internal/equipo/library/specialists.go b/internal/equipo/library/specialists.go
index 6dafdd9a..98bcfa2b 100644
--- a/internal/equipo/library/specialists.go
+++ b/internal/equipo/library/specialists.go
@@ -49,7 +49,7 @@ type request struct {
func (request) TableName() string { return "specialist_requests" }
-var Models = []any{&Specialist{}, &request{}}
+var Models = []any{&Specialist{}, &request{}, &Playbook{}, &PlaybookRevision{}, &PlaybookDefault{}, &PlaybookSnapshot{}, &playbookRequest{}, &PlaybookSuggestion{}}
var DefaultKeys = []string{"product", "design", "copy", "engineering", "review"}
var DefaultIcons = []string{"lightbulb", "pencil", "type", "code", "check-circle"}
@@ -63,6 +63,8 @@ type Dependencies struct {
Referenced func(*gorm.DB, string) (bool, error)
Copy func(string) string
Catalog func() []Template
+ PlaybookCatalog func() []Template
+ TaskAccess func(*gorm.DB, kernel.Actor, int64) error
Invalid, Forbidden, NotFound, Conflict error
}
type Store struct {
diff --git a/internal/equipo/library/views.go b/internal/equipo/library/views.go
index c75818fc..b85f215e 100644
--- a/internal/equipo/library/views.go
+++ b/internal/equipo/library/views.go
@@ -87,3 +87,27 @@ func DecorateCard(tx *gorm.DB, teamID, taskID string, card *planning.StepCard) e
}
return nil
}
+
+func PageTitle(name string, v View) string {
+ if v.PlaybookPage {
+ return "playbooks.title"
+ }
+ switch name {
+ case "specialist_form":
+ if v.Specialist.Key != "" {
+ return "specialists.edit"
+ }
+ return "specialists.new"
+ case "specialist":
+ return "nav." + v.Specialist.Key
+ default:
+ return "templates.title"
+ }
+}
+
+func PageNav(v View) string {
+ if v.PlaybookPage {
+ return "playbooks"
+ }
+ return "templates"
+}
diff --git a/internal/equipo/library_handlers.go b/internal/equipo/library_handlers.go
index de2d7b56..faf316e8 100644
--- a/internal/equipo/library_handlers.go
+++ b/internal/equipo/library_handlers.go
@@ -2,59 +2,22 @@ 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
- },
+ Actor: library.SessionActor(ErrForbidden),
Render: func(w http.ResponseWriter, r *http.Request, name string, v library.View) {
- data, err := a.page(r, "templates")
+ data, err := a.page(r, library.PageNav(v))
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.Title = library.PageTitle(name, v)
+ data.Key, data.Specialist = v.Specialist.Key, v.Specialist
+ data.Owner = data.Owner || v.Specialist.Creator == data.Address
+ data.Work, data.Tasks = v.Work, v.Work.Tasks
data.Library = v
a.renderLive(w, r, name, data)
}}
diff --git a/internal/equipo/migrations/0025_playbooks.sql b/internal/equipo/migrations/0025_playbooks.sql
new file mode 100644
index 00000000..001240bb
--- /dev/null
+++ b/internal/equipo/migrations/0025_playbooks.sql
@@ -0,0 +1,6 @@
+CREATE TABLE playbooks (id text, team_id text, creator text, name text, kind text, steps text, project_ids text, template_id text, template_version integer, template_base text, revision integer, archived numeric, PRIMARY KEY (id));
+CREATE TABLE playbook_revisions (id text, revision integer, value text, PRIMARY KEY (id,revision));
+CREATE TABLE playbook_defaults (team_id text, project_id integer, kind text, playbook_id text, revision integer, PRIMARY KEY (team_id,project_id,kind));
+CREATE TABLE playbook_snapshots (task_id text, playbook_id text, plan text, PRIMARY KEY (task_id,playbook_id));
+CREATE TABLE playbook_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));
+CREATE TABLE playbook_suggestions (id text, playbook_id text, PRIMARY KEY (id));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 373085d4..5e3ec9f0 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -386,3 +386,9 @@ CREATE TABLE personal_settings (team_id text, person text, landing text, revisio
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));
+CREATE TABLE playbooks (id text, team_id text, creator text, name text, kind text, steps text, project_ids text, template_id text, template_version integer, template_base text, revision integer, archived numeric, PRIMARY KEY (id));
+CREATE TABLE playbook_revisions (id text, revision integer, value text, PRIMARY KEY (id,revision));
+CREATE TABLE playbook_defaults (team_id text, project_id integer, kind text, playbook_id text, revision integer, PRIMARY KEY (team_id,project_id,kind));
+CREATE TABLE playbook_snapshots (task_id text, playbook_id text, plan text, PRIMARY KEY (task_id,playbook_id));
+CREATE TABLE playbook_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));
+CREATE TABLE playbook_suggestions (id text, playbook_id text, PRIMARY KEY (id));
diff --git a/internal/equipo/planning/plans.go b/internal/equipo/planning/plans.go
index 6580421c..f13479b4 100644
--- a/internal/equipo/planning/plans.go
+++ b/internal/equipo/planning/plans.go
@@ -59,6 +59,8 @@ type Access struct {
ProjectRevision int64
}
type Dependencies struct {
+ PlaybookDetails func(*gorm.DB, string, taskplan.Plan) (string, []string, error)
+ ResolvePlaybook func(*gorm.DB, kernel.Actor, taskplan.Plan) (taskplan.Plan, error)
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)
@@ -186,7 +188,7 @@ func (s *Store) propose(actor kernel.Actor, requester string, p taskplan.Plan, m
if err != nil {
return taskplan.Plan{}, err
}
- if p.TaskID != "" || p.Revision != 0 || m.Revision != 0 || taskplan.Validate(p) != nil {
+ if p.TaskID != "" || p.Revision != 0 || m.Revision != 0 {
return taskplan.Plan{}, s.deps.Invalid
}
var result taskplan.Plan
@@ -197,6 +199,15 @@ func (s *Store) propose(actor kernel.Actor, requester string, p taskplan.Plan, m
if err != nil || replayed {
return result, err
}
+ if s.deps.ResolvePlaybook != nil {
+ p, err = s.deps.ResolvePlaybook(s.tx, actor, p)
+ if err != nil {
+ return result, err
+ }
+ }
+ if taskplan.Validate(p) != nil {
+ return result, s.deps.Invalid
+ }
if err = s.deps.Specialists(s.tx, a.TeamID, p, nil); err != nil {
return result, err
}
@@ -320,6 +331,16 @@ func (s *Store) Seed(t Task, actor kernel.Actor) error {
return nil
}
p := taskplan.BugPlan(t.ID, t.ProjectID)
+ if s.deps.ResolvePlaybook != nil {
+ var err error
+ p, err = s.deps.ResolvePlaybook(s.tx, actor, taskplan.Plan{TaskID: t.ID, Revision: 1, ProjectID: t.ProjectID, Kind: taskplan.Bug})
+ if err != nil {
+ return err
+ }
+ if taskplan.Validate(p) != nil {
+ return s.deps.Invalid
+ }
+ }
t.PlanRevision = 1
t.Kind = taskplan.Bug
if err := s.history(&t, p, actor, nil); err != nil {
diff --git a/internal/equipo/planning/views.go b/internal/equipo/planning/views.go
index 136e0cc3..7d971875 100644
--- a/internal/equipo/planning/views.go
+++ b/internal/equipo/planning/views.go
@@ -22,6 +22,8 @@ type StepView struct {
Locked bool
}
type Page struct {
+ PlaybookName string
+ PlaybookChanges []string
Connections []ConnectionOption
Task Task
Plan taskplan.Plan
@@ -43,6 +45,12 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) {
if err != nil {
return
}
+ if s.deps.PlaybookDetails != nil {
+ out.PlaybookName, out.PlaybookChanges, err = s.deps.PlaybookDetails(s.tx, out.Task.TeamID, out.Plan)
+ if err != nil {
+ return
+ }
+ }
_, accessErr := s.deps.Access(s.tx, a, out.Task.ProjectID)
out.CanEdit = accessErr == nil
out.Owner = s.deps.Member(s.tx, a, true) == nil
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go
index 0f0cc6d5..73e4b55a 100644
--- a/internal/equipo/plans.go
+++ b/internal/equipo/plans.go
@@ -5,7 +5,6 @@ import (
"amadan.net/oficina/equipo/internal/equipo/planning"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/taskplan"
- "context"
"encoding/json"
"gorm.io/gorm"
)
@@ -19,6 +18,12 @@ const (
func (s *Store) planningAt(tx *gorm.DB) *planning.Store {
deps := planning.Dependencies{
+ PlaybookDetails: func(tx *gorm.DB, teamID string, p taskplan.Plan) (string, []string, error) {
+ return s.libraryAt(tx).PlanDetails(teamID, p)
+ },
+ ResolvePlaybook: func(tx *gorm.DB, a Actor, p taskplan.Plan) (taskplan.Plan, error) {
+ return s.libraryAt(tx).ResolvePlan(a, p)
+ },
Specialists: func(tx *gorm.DB, teamID string, p taskplan.Plan, started map[string]bool) error {
return s.libraryAt(tx).ValidatePlan(teamID, p, started)
},
@@ -101,36 +106,8 @@ func (s *Store) planReady(tx *gorm.DB, t Task, p taskplan.Plan) error {
return err
}
func (s *Store) planningApplication() *planning.Application {
- return &planning.Application{Write: s.write, At: s.planningAt, Normalize: normalizeAddress}
-}
-func (s *Store) ProposePlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) {
- return s.planningApplication().ProposePlan(ctx, actor, p, m)
-}
-func (s *Store) EditPlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) {
- return s.planningApplication().EditPlan(ctx, actor, p, m)
-}
-func (s *Store) ApprovePlan(ctx context.Context, actor Actor, id string, m Mutation) (Task, error) {
- return s.planningApplication().ApprovePlan(ctx, actor, id, m)
-}
-func (s *Store) CorrectTaskProject(ctx context.Context, actor Actor, id string, project int64, m Mutation) (Task, error) {
- return s.planningApplication().CorrectTaskProject(ctx, actor, id, project, m)
+ return s.PlanApplication
}
-func (s *Store) SetProjectApproval(ctx context.Context, actor Actor, project int64, mode ApprovalMode, m Mutation) error {
- return s.planningApplication().SetProjectApproval(ctx, actor, project, mode, m)
-}
-func (s *Store) SetApprovalOverride(ctx context.Context, actor Actor, project int64, mode *ApprovalMode, m Mutation) error {
- return s.planningApplication().SetApprovalOverride(ctx, actor, project, mode, m)
-}
-func (s *Store) PlanApproval(ctx context.Context, actor Actor, project int64) (ApprovalMode, error) {
- return s.planningApplication().PlanApproval(ctx, actor, project)
-}
-func (s *Store) CheckPlanDispatch(ctx context.Context, actor Actor, id string) error {
- return s.planningApplication().CheckPlanDispatch(ctx, actor, id)
-}
-func (s *Store) TaskPlan(ctx context.Context, actor Actor, id string) (taskplan.Plan, error) {
- return s.planningApplication().TaskPlan(ctx, actor, id)
-}
-
func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error {
if err := s.planningAt(tx).CheckDispatch(Actor{Address: t.Requester}, t.ID); err != nil {
return err
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index 7d7e4e60..9bb6e13e 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -27,7 +27,7 @@ var assets = rastrillo.NewAssets(appFS)
var pages = map[string]*template.Template{}
func init() {
- 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"} {
+ for _, name := range []string{"playbooks", "playbook_form", "playbook_diff", "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{"projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
diff --git a/internal/equipo/specialist_library.go b/internal/equipo/specialist_library.go
index 5562e4a4..81a5415e 100644
--- a/internal/equipo/specialist_library.go
+++ b/internal/equipo/specialist_library.go
@@ -9,6 +9,8 @@ type SpecialistInput = library.SpecialistInput
type ModelRef = library.ModelRef
type TemplateRef = library.TemplateRef
type TemplateDiff = library.TemplateDiff
+type PlaybookInput = library.PlaybookInput
+type Playbook = library.Playbook
func (s *Store) libraryAt(tx *gorm.DB) *library.Store {
return library.New(tx, library.Dependencies{
@@ -21,7 +23,8 @@ func (s *Store) libraryAt(tx *gorm.DB) *library.Store {
err = tx.First(&t).Error
return library.Access{TeamID: t.ID, Owner: m.Role == RoleOwner}, err
},
- Audit: appendAudit, Copy: copyText, Catalog: library.Catalog,
+ TaskAccess: func(tx *gorm.DB, a Actor, id int64) error { _, err := bugAuthority(tx, a, id); return err },
+ Audit: appendAudit, Copy: copyText, Catalog: library.Catalog,
Referenced: library.UnstartedReference,
Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict,
diff --git a/internal/equipo/store.go b/internal/equipo/store.go
index b3f15af0..d651db15 100644
--- a/internal/equipo/store.go
+++ b/internal/equipo/store.go
@@ -12,6 +12,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/equipo/planning"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/rastrillo/rastrillo/db"
"net/http"
@@ -44,9 +45,13 @@ type refusal struct {
func (e *refusal) Error() string { return e.message }
func (e *refusal) Unwrap() error { return e.kind }
+type PlanApplication = planning.Application
+
// 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 {
+ *PlanApplication
*library.Application
personBearer personapi.VerifyPersonBearer
personCookie func(*http.Request) (personapi.PersonPrincipal, error)
@@ -74,6 +79,7 @@ func NewStore(d *db.DB, options ...StoreOption) *Store {
for _, option := range options {
option(s)
}
+ s.PlanApplication = &planning.Application{Write: s.write, At: s.planningAt, Normalize: normalizeAddress}
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) })
}}
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html
index b75d4294..a8c02b9e 100644
--- a/internal/equipo/templates/conversation_card.html
+++ b/internal/equipo/templates/conversation_card.html
@@ -25,7 +25,7 @@
<h2><a href="/tasks/{{.Task.ID}}/plan">{{.Task.Description}}</a></h2>
<p equipo-secondary>{{copy "plan.project"}}: {{.Project}}</p>
<p><span equipo-badge>{{copy "plan.revision"}} {{.Plan.Revision}}</span> <span equipo-badge>{{if eq .Task.ApprovalRevision .Plan.Revision}}{{copy "plan.approved"}}{{else}}{{copy "plan.proposed"}}{{end}}</span></p>
-{{if .Plan.PlaybookID}}<p equipo-secondary>{{copy "plan.playbook"}}: {{.Plan.PlaybookID}} <span equipo-value>{{.Plan.PlaybookRevision}}</span></p>{{end}}
+{{if .Plan.PlaybookID}}<p equipo-secondary>{{copy "plan.playbook"}}: {{.PlaybookName}} <span equipo-value>{{.Plan.PlaybookRevision}}</span></p>{{end}}
<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step><strong>{{if .Specialist}}{{copy (printf "nav.%s" .Specialist)}}{{else}}{{copy (printf "plan.action.%s" .Action)}}{{end}}</strong><span equipo-secondary>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><span equipo-value>{{.Model}} {{.Account}}</span>{{if .SelectionReason}}<span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span>{{end}}{{if .Actual}}<span equipo-secondary>{{copy "task.actual"}}: {{.Actual}}</span>{{end}}</li>{{end}}</ol>
<a href="/tasks/{{.Task.ID}}/plan#project">{{copy "plan.correct_project"}}</a> <a href="/tasks/{{.Task.ID}}/plan">{{copy "plan.edit"}}</a> <a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a>
{{end}}
@@ -39,6 +39,7 @@
{{if .WaitingTaskURL}}<p>{{copy "coordinator.waiting_label"}} <a href="{{.WaitingTaskURL}}">{{.WaitingLabel}}</a></p>{{else}}<p>{{copy .CopyKey}}</p>{{end}}
{{if .ActionKeys}}<div equipo-actions><form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="retry"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="turn_id" value="{{.ResourceID}}"><button rst-btn type="submit">{{copy "coordinator.retry"}}</button></form><form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="reset"><input type="hidden" name="request_id" value="{{.ResetID}}"><input type="hidden" name="revision" value="{{.BindingRevision}}"><button rst-btn type="submit">{{copy "coordinator.reset"}}</button></form></div>{{end}}
{{end}}
+{{if eq .Kind "suggest_playbook"}}<a href="/playbook-suggestions/{{.ResourceID}}">{{copy "playbooks.save_suggestion"}}</a>{{end}}
{{if eq .Kind "suggest_preference"}}<a href="/preferences">{{copy "preferences.title"}}</a>{{end}}
</article>
{{end}}
diff --git a/internal/equipo/templates/plan.html b/internal/equipo/templates/plan.html
index 77f85724..75f94103 100644
--- a/internal/equipo/templates/plan.html
+++ b/internal/equipo/templates/plan.html
@@ -7,7 +7,8 @@
<a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a>
{{if .Task.ReplacementID}}<a href="/tasks/{{.Task.ReplacementID}}/plan">{{copy "plan.replacement"}}</a>{{end}}
{{if eq .Plan.Kind "investigation"}}<p equipo-note>{{copy "plan.investigation_checkpoint"}}</p>{{end}}
-<p equipo-secondary>{{copy "plan.playbook"}}: {{if .Plan.PlaybookID}}{{.Plan.PlaybookID}} <span equipo-value>{{.Plan.PlaybookRevision}}</span>{{else}}{{copy "plan.custom"}}{{end}}</p>
+<p equipo-secondary>{{copy "plan.playbook"}}: {{if .Plan.PlaybookID}}{{.PlaybookName}} <span equipo-value>{{.Plan.PlaybookRevision}}</span>{{else}}{{copy "plan.custom"}}{{end}}</p>
+{{if .PlaybookChanges}}<section equipo-card><h2>{{copy "plan.changes"}}</h2><ul>{{range .PlaybookChanges}}<li data-playbook-change="{{.}}">{{.}}</li>{{end}}</ul></section>{{end}}
{{if .CanEdit}}
<form id="plan-editor" method="post" action="/tasks/{{.Task.ID}}/plan" equipo-form>
<input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Plan.Revision}}"><input type="hidden" name="kind" value="{{.Plan.Kind}}"><input type="hidden" name="project_id" value="{{.Plan.ProjectID}}"><input type="hidden" name="playbook_id" value="{{.Plan.PlaybookID}}"><input type="hidden" name="playbook_revision" value="{{.Plan.PlaybookRevision}}"><input type="hidden" name="step_count" value="{{len .Steps}}">
diff --git a/internal/equipo/templates/playbook_diff.html b/internal/equipo/templates/playbook_diff.html
new file mode 100644
index 00000000..94ac04b2
--- /dev/null
+++ b/internal/equipo/templates/playbook_diff.html
@@ -0,0 +1,15 @@
+{{define "title"}}{{copy "templates.diff"}}{{end}}
+{{define "up"}}/playbooks{{end}}
+{{define "content"}}
+<h1>{{copy "templates.diff"}}</h1>
+<form method="post" action="/playbooks/{{.Library.Playbook.ID}}/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/playbook_form.html b/internal/equipo/templates/playbook_form.html
new file mode 100644
index 00000000..95c5a1e4
--- /dev/null
+++ b/internal/equipo/templates/playbook_form.html
@@ -0,0 +1,19 @@
+{{define "title"}}{{copy "playbooks.title"}}{{end}}
+{{define "up"}}/playbooks{{end}}
+{{define "content"}}
+<h1>{{if .Library.SuggestionID}}{{copy "playbooks.suggested"}}{{else}}{{copy "playbooks.title"}}{{end}}</h1>
+{{with .Library}}<form method="post" action="{{if .SuggestionID}}/playbook-suggestions/{{.SuggestionID}}{{else if .Playbook.ID}}/playbooks/{{.Playbook.ID}}/edit{{else}}/playbooks{{end}}" equipo-form>
+<input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Playbook.Revision}}"><input type="hidden" name="template_id" value="{{.Playbook.Template.ID}}"><input type="hidden" name="template_version" value="{{.Playbook.Template.Version}}"><input type="hidden" name="step_count" value="{{len .Playbook.Steps}}">
+<fieldset {{if not .PlaybookEditable}}disabled{{end}}>
+<label>{{copy "specialists.name"}}<input rst-input name="name" required maxlength="120" value="{{.Playbook.Name}}"></label>
+<label>{{copy "playbooks.kind"}}<select rst-input name="kind"><option value="bug" {{if eq .Playbook.Kind "bug"}}selected{{end}}>{{copy "task.kind.bug"}}</option><option value="feature" {{if eq .Playbook.Kind "feature"}}selected{{end}}>{{copy "task.kind.feature"}}</option><option value="rendered_change" {{if eq .Playbook.Kind "rendered_change"}}selected{{end}}>{{copy "task.kind.rendered_change"}}</option><option value="investigation" {{if eq .Playbook.Kind "investigation"}}selected{{end}}>{{copy "task.kind.investigation"}}</option></select></label>
+<fieldset><legend>{{copy "specialists.projects"}}</legend>{{range .Projects}}<label><input type="checkbox" name="project" value="{{.ID}}" {{if .Selected}}checked{{end}}>{{.Name}}</label>{{end}}</fieldset>
+<h2>{{copy "playbooks.steps"}}</h2>
+{{range .PlaybookSteps}}<fieldset><legend>{{copy (printf "plan.action.%s" .Action)}}</legend><input type="hidden" name="step_{{.Index}}_key" value="{{.Key}}"><input type="hidden" name="step_{{.Index}}_action" value="{{.Action}}"><input type="hidden" name="step_{{.Index}}_depends" value="{{range $i,$v := .DependsOn}}{{if $i}},{{end}}{{$v}}{{end}}">
+{{if .Required}}<span equipo-badge>{{copy "plan.required_step"}}</span><input type="hidden" name="step_{{.Index}}_specialist" value="{{.Specialist}}">{{else}}<label>{{copy "plan.specialist"}}<select rst-input name="step_{{.Index}}_specialist">{{$key := .Specialist}}<option value=""></option>{{range $.Library.Specialists}}<option value="{{.Key}}" {{if eq .Key $key}}selected{{end}}>{{if .Name}}{{.Name}}{{else}}{{copy (printf "nav.%s" .Key)}}{{end}}</option>{{end}}</select></label><label><input type="checkbox" name="step_{{.Index}}_remove" value="1">{{copy "plan.remove_step"}}</label>{{end}}
+<label>{{copy "plan.position"}}<input rst-input type="number" min="1" max="16" name="step_{{.Index}}_position" value="{{.Position}}" required></label><label>{{copy "plan.instructions"}}<textarea rst-input name="step_{{.Index}}_instructions" rows="3" maxlength="16384">{{.Instructions}}</textarea></label>
+</fieldset>{{end}}
+{{if lt (len .Playbook.Steps) 16}}<details><summary>{{copy "plan.add_step"}}</summary><fieldset>{{$i := len .Playbook.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 .Specialists}}<option value="{{.Key}}">{{if .Name}}{{.Name}}{{else}}{{copy (printf "nav.%s" .Key)}}{{end}}</option>{{end}}</select></label><label>{{copy "plan.action"}}<select rst-input name="step_{{$i}}_action"><option value="scope">{{copy "plan.action.scope"}}</option><option value="reproduce">{{copy "plan.action.reproduce"}}</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><option value="investigate">{{copy "plan.action.investigate"}}</option></select></label><label>{{copy "plan.position"}}<input rst-input type="number" min="1" max="16" name="step_{{$i}}_position"></label><label>{{copy "plan.instructions"}}<textarea rst-input name="step_{{$i}}_instructions"></textarea></label></fieldset></details>{{end}}
+</fieldset>{{if .PlaybookEditable}}<button rst-btn="primary" type="submit">{{if .SuggestionID}}{{copy "playbooks.save_suggestion"}}{{else}}{{copy "form.save"}}{{end}}</button>{{end}}</form>
+{{if and .Playbook.ID .PlaybookEditable}}<form method="post" action="/playbooks/{{.Playbook.ID}}/archive"><input type="hidden" name="request_id" value="{{.RequestID}}-archive"><input type="hidden" name="revision" value="{{.Playbook.Revision}}"><button rst-btn type="submit">{{copy "playbooks.archive"}}</button></form>{{if .Playbook.Template.ID}}<a href="/playbooks/{{.Playbook.ID}}/template-diff">{{copy "playbooks.update_available"}}</a>{{end}}{{end}}
+{{end}}{{end}}
diff --git a/internal/equipo/templates/playbooks.html b/internal/equipo/templates/playbooks.html
new file mode 100644
index 00000000..9443d5f0
--- /dev/null
+++ b/internal/equipo/templates/playbooks.html
@@ -0,0 +1,11 @@
+{{define "title"}}{{copy "playbooks.title"}}{{end}}
+{{define "up"}}/work{{end}}
+{{define "content"}}
+<h1>{{copy "playbooks.title"}}</h1><a rst-btn href="/playbooks/new">{{copy "playbooks.new"}}</a>
+{{range .Library.Playbooks}}<section equipo-card><h2><a href="/playbooks/{{.ID}}/edit">{{.Name}}</a></h2><span equipo-badge>{{copy (printf "task.kind.%s" .Kind)}}</span><p>{{copy "playbooks.used"}}: <span equipo-value>{{.Used}}</span></p>{{if .Template.ID}}<a href="/playbooks/{{.ID}}/template-diff">{{copy "playbooks.update_available"}}</a>{{end}}</section>{{end}}
+<h2>{{copy "templates.title"}}</h2>
+{{range .Library.PlaybookTemplates}}<section equipo-card><h3>{{copy .NameKey}}</h3><p>{{copy .DescriptionKey}}</p><form method="post" action="/playbook-templates/{{.Ref.ID}}/install"><input type="hidden" name="request_id" value="{{$.Library.RequestID}}-{{.Ref.ID}}"><input type="hidden" name="version" value="{{.Ref.Version}}"><button rst-btn type="submit">{{copy "templates.install"}}</button></form></section>{{end}}
+{{if .Library.Owner}}<section equipo-card><h2>{{copy "playbooks.default"}}</h2>
+{{range .Library.Defaults}}<form method="post" action="/playbooks/defaults" equipo-form><input type="hidden" name="request_id" value="{{$.Library.RequestID}}-{{.ProjectID}}-{{.Kind}}"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="project_id" value="{{.ProjectID}}"><input type="hidden" name="kind" value="{{.Kind}}"><p>{{if .ProjectID}}{{$id := .ProjectID}}{{range $.Library.Projects}}{{if eq .ID $id}}{{.Name}}{{end}}{{end}}{{else}}{{copy "playbooks.all_projects"}}{{end}} / {{if .Kind}}{{copy (printf "task.kind.%s" .Kind)}}{{else}}{{copy "playbooks.all_kinds"}}{{end}}</p><label>{{copy "playbooks.default"}}<select rst-input name="playbook_id">{{$id := .PlaybookID}}<option value="">{{copy "plan.inherit"}}</option>{{range $.Library.Playbooks}}<option value="{{.ID}}" {{if eq .ID $id}}selected{{end}}>{{.Name}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{end}}
+<form method="post" action="/playbooks/defaults" equipo-form><input type="hidden" name="request_id" value="{{.Library.RequestID}}-default"><input type="hidden" name="revision" value="0"><label>{{copy "plan.project"}}<select rst-input name="project_id"><option value="0">{{copy "playbooks.all_projects"}}</option>{{range .Library.Projects}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select></label><label>{{copy "playbooks.kind"}}<select rst-input name="kind"><option value="">{{copy "playbooks.all_kinds"}}</option><option value="bug">{{copy "task.kind.bug"}}</option><option value="feature">{{copy "task.kind.feature"}}</option><option value="rendered_change">{{copy "task.kind.rendered_change"}}</option><option value="investigation">{{copy "task.kind.investigation"}}</option></select></label><label>{{copy "playbooks.default"}}<select rst-input name="playbook_id">{{range .Library.Playbooks}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form></section>{{end}}
+{{end}}
diff --git a/internal/equipo/templates/template_library.html b/internal/equipo/templates/template_library.html
index 19c14435..a7b606d4 100644
--- a/internal/equipo/templates/template_library.html
+++ b/internal/equipo/templates/template_library.html
@@ -1,5 +1,5 @@
{{define "content"}}
-<h1>{{copy "templates.title"}}</h1>
+<h1>{{copy "templates.title"}}</h1><a href="/playbooks">{{copy "playbooks.title"}}</a>
<p><a rst-btn href="/specialists/new">{{icon "plus"}}{{copy "specialists.new"}}</a></p>
{{$group := ""}}{{$request := .Library.RequestID}}
{{range .Library.Templates}}
diff --git a/internal/plan3test/playbooks_catalog_test.go b/internal/plan3test/playbooks_catalog_test.go
new file mode 100644
index 00000000..e11ce175
--- /dev/null
+++ b/internal/plan3test/playbooks_catalog_test.go
@@ -0,0 +1,68 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "errors"
+ "gorm.io/gorm"
+ "testing"
+)
+
+func TestPlaybookTemplatesVersionAcceptance(t *testing.T) {
+ f := newFixture(t)
+ templates := library.PlaybookCatalog()
+ copyValue := "Version one"
+ 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 }, PlaybookCatalog: 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)
+ row, err := s.InstallPlaybookTemplate(owner, templates[0].Ref, equipo.Mutation{RequestID: "install"})
+ if err != nil {
+ return err
+ }
+ templates = append(templates, templates[0])
+ templates[len(templates)-1].Ref.Version = 2
+ copyValue = "Version two"
+ current, err := s.Playbook(owner, row.ID)
+ if err != nil {
+ return err
+ }
+ if current.Name != row.Name {
+ t.Fatal("catalog changed copy")
+ }
+ diff, err := s.PlaybookTemplateDiff(owner, row.ID, templates[len(templates)-1].Ref)
+ if err != nil {
+ return err
+ }
+ copyValue = "Changed after preview"
+ if _, err = s.ApplyPlaybookTemplate(owner, row.ID, diff, []string{"name"}, equipo.Mutation{RequestID: "changed", Revision: 1}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("changed offered update accepted", err)
+ }
+ copyValue = "Version two"
+ updated, err := s.ApplyPlaybookTemplate(owner, row.ID, diff, []string{"name"}, equipo.Mutation{RequestID: "apply", Revision: 1})
+ if err != nil {
+ return err
+ }
+ current, err = s.Playbook(owner, row.ID)
+ if err != nil {
+ return err
+ }
+ if current.Name != "Version two" || current.Template.Version != 2 || current.Steps[0].Instructions != row.Steps[0].Instructions {
+ t.Fatal("update changed unselected fields or lost version", current)
+ }
+ copyValue = "Later release"
+ retry, err := s.ApplyPlaybookTemplate(owner, row.ID, diff, []string{"name"}, equipo.Mutation{RequestID: "apply", Revision: 1})
+ if err != nil {
+ return err
+ }
+ if retry.Revision != updated.Revision || retry.Name != updated.Name {
+ t.Fatal("retry changed accepted update")
+ }
+ return nil
+ }))
+}
diff --git a/internal/plan3test/playbooks_forms_test.go b/internal/plan3test/playbooks_forms_test.go
new file mode 100644
index 00000000..52dd7f4b
--- /dev/null
+++ b/internal/plan3test/playbooks_forms_test.go
@@ -0,0 +1,96 @@
+package plan3test
+
+import (
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "amadan.net/oficina/equipo/internal/taskplan"
+)
+
+func playbookForm(in library.PlaybookInput, request string, revision int64) url.Values {
+ v := actionForm(request, revision)
+ v.Set("name", in.Name)
+ v.Set("kind", string(in.Kind))
+ v.Set("template_id", in.Template.ID)
+ v.Set("template_version", strconv.FormatInt(in.Template.Version, 10))
+ v.Set("step_count", strconv.Itoa(len(in.Steps)))
+ for i, st := range in.Steps {
+ prefix := "step_" + strconv.Itoa(i) + "_"
+ for key, value := range map[string]string{"key": st.Key, "specialist": st.Specialist, "action": st.Action, "instructions": st.Instructions, "position": strconv.Itoa(i + 1), "depends": strings.Join(st.DependsOn, ",")} {
+ v.Set(prefix+key, value)
+ }
+ }
+ for _, id := range in.ProjectIDs {
+ v.Add("project", strconv.FormatInt(id, 10))
+ }
+ return v
+}
+func TestPlaybookForms(t *testing.T) {
+ f := newFixture(t)
+ base := f.createTask(t)
+ w := formPost(t, f, owner, "/playbooks", playbookForm(playbookInput("Browser saved"), "browser", 0))
+ expectHTTP(t, w, 303)
+ path := w.Header().Get("Location")
+ id := strings.TrimSuffix(strings.TrimPrefix(path, "/playbooks/"), "/edit")
+ row, err := f.Store.Playbook(ctx, owner, id)
+ must(t, err)
+ in := library.PlaybookFields(row)
+ in.Steps[0].Instructions = "Browser edit"
+ expectHTTP(t, formPost(t, f, owner, path, playbookForm(in, "edit", 1)), 303)
+ expectHTTP(t, formPost(t, f, owner, path, playbookForm(in, "edit", 1)), 303)
+ expectHTTP(t, formPost(t, f, owner, path, playbookForm(in, "stale", 1)), 409)
+ v := actionForm("default", 0)
+ v.Set("project_id", strconv.FormatInt(base.ProjectID, 10))
+ v.Set("kind", "bug")
+ v.Set("playbook_id", row.ID)
+ expectHTTP(t, formPost(t, f, owner, "/playbooks/defaults", v), 303)
+ f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address)
+ w = f.get(t, peer, "/playbooks/"+id)
+ expectHTTP(t, w, 200)
+ if !strings.Contains(w.Body.String(), "<fieldset disabled>") || strings.Contains(w.Body.String(), "/archive") {
+ t.Fatal("noncreator has editing controls")
+ }
+ expectHTTP(t, formPost(t, f, peer, path, playbookForm(in, "steal", 2)), 403)
+ expectHTTP(t, formPost(t, f, owner, "/playbooks/"+id+"/archive", actionForm("default-archive", 2)), 409)
+ v = actionForm("install", 0)
+ v.Del("revision")
+ v.Set("version", "1")
+ expectHTTP(t, formPost(t, f, owner, "/playbook-templates/playbook_bug/install", v), 303)
+ var installed library.Playbook
+ must(t, f.DB.G.Where("template_id='playbook_bug'").First(&installed).Error)
+ expectHTTP(t, f.get(t, owner, "/playbooks/"+installed.ID+"/template-diff"), 200)
+ // Recommendations retain their no-publication exception even with defaults.
+ recommendation := taskplan.Plan{ProjectID: base.ProjectID, Kind: taskplan.Recommendation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}}}
+ p, err := f.Store.ProposePlan(ctx, owner, recommendation, equipo.Mutation{RequestID: "recommend"})
+ must(t, err)
+ if p.PlaybookID != "" {
+ t.Fatal("recommendation acquired publishing playbook")
+ }
+ if _, err = f.Store.InstantiatePlaybook(ctx, owner, id, p.TaskID); err == nil {
+ t.Fatal("recommendation accepted publishing playbook")
+ }
+}
+
+func TestPlaybookRecommendationCannotReuseSnapshot(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ row, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Saved bug"), equipo.Mutation{RequestID: "save"})
+ must(t, err)
+ _, err = f.Store.InstantiatePlaybook(ctx, owner, row.ID, task.ID)
+ must(t, err)
+ p, err := f.Store.TaskPlan(ctx, owner, task.ID)
+ must(t, err)
+ p.Kind = taskplan.Recommendation
+ p.PlaybookID = ""
+ p.PlaybookRevision = 0
+ p.Steps = []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}}
+ _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "recommend", Revision: p.Revision})
+ must(t, err)
+ if _, err = f.Store.InstantiatePlaybook(ctx, owner, row.ID, task.ID); err == nil {
+ t.Fatal("recommendation reused publishing snapshot")
+ }
+}
diff --git a/internal/plan3test/playbooks_migration_test.go b/internal/plan3test/playbooks_migration_test.go
new file mode 100644
index 00000000..81608995
--- /dev/null
+++ b/internal/plan3test/playbooks_migration_test.go
@@ -0,0 +1,55 @@
+package plan3test
+
+import (
+ "io"
+ "log/slog"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+func TestPlaybookMigration(t *testing.T) {
+ d, err := db.Open(filepath.Join(t.TempDir(), "playbooks.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/0025_playbooks" {
+ old.Add(m)
+ }
+ }
+ _, err = migrate.Apply(ctx, d, old)
+ must(t, err)
+ f := &fixture{DB: d}
+ f.exec(t, "INSERT INTO teams(id,name,roster_epoch) VALUES('saved','Saved',2)")
+ f.exec(t, "INSERT INTO tasks(id,requester,request_id,team_id,revision,plan_revision,kind) VALUES('old','person','request','saved',5,2,'investigation')")
+ f.exec(t, "INSERT INTO plan_revisions(task_id,revision,plan,actor_kind,actor,changed_keys) VALUES('old',2,'saved plan','person','person','[]')")
+ f.exec(t, "INSERT INTO audit_events(actor,kind,record_id) VALUES('person','old.audit','old')")
+ result, err := migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, err)
+ if len(result.Applied) != 1 || result.Applied[0] != "equipo/0025_playbooks" {
+ t.Fatal(result.Applied)
+ }
+ if f.count(t, "SELECT revision FROM tasks WHERE id='old'") != 5 || f.count(t, "SELECT count(*) FROM plan_revisions WHERE plan='saved plan'") != 1 || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='old.audit'") != 1 {
+ t.Fatal("migration changed history")
+ }
+ if f.count(t, "SELECT count(*) FROM playbooks") != 0 {
+ t.Fatal("migration silently installed templates")
+ }
+ 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/plan3test/playbooks_test.go b/internal/plan3test/playbooks_test.go
new file mode 100644
index 00000000..55bb1c71
--- /dev/null
+++ b/internal/plan3test/playbooks_test.go
@@ -0,0 +1,336 @@
+package plan3test
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "amadan.net/oficina/equipo/internal/taskplan"
+)
+
+func playbookInput(name string) library.PlaybookInput {
+ return library.PlaybookInput{Name: name, Kind: taskplan.Bug, Steps: taskplan.BugPlan("", 1).Steps}
+}
+func TestPlaybookMandatorySteps(t *testing.T) {
+ f := newFixture(t)
+ for _, ref := range []string{"playbook_bug", "playbook_website", "playbook_infra", "playbook_investigation", "playbook_blank"} {
+ row, err := f.Store.InstallPlaybookTemplate(ctx, owner, equipo.TemplateRef{ID: ref, Version: 1}, equipo.Mutation{RequestID: ref})
+ must(t, err)
+ for _, action := range []string{"review", "checks", "person"} {
+ t.Run(ref+"/"+action, func(t *testing.T) {
+ in := library.PlaybookFields(row)
+ in.Steps = nil
+ for _, st := range row.Steps {
+ if st.Action != action {
+ in.Steps = append(in.Steps, st)
+ }
+ }
+ current, err := f.Store.Playbook(ctx, owner, row.ID)
+ must(t, err)
+ if _, err := f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: ref + action, Revision: current.Revision}); err == nil {
+ t.Fatal("mandatory tail removed")
+ }
+ })
+ }
+ }
+ in := playbookInput("Not a publishing playbook")
+ in.Kind = taskplan.Recommendation
+ if _, err := f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "recommendation"}); err == nil {
+ t.Fatal("recommendation instantiated publishing playbook")
+ }
+}
+func TestPlaybookDefaultPrecedence(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ kind, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Kind"), equipo.Mutation{RequestID: "kind"})
+ must(t, err)
+ wide, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Project"), equipo.Mutation{RequestID: "wide"})
+ must(t, err)
+ exact, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Exact"), equipo.Mutation{RequestID: "exact"})
+ must(t, err)
+ check := func(want string) {
+ t.Helper()
+ got, e := f.Store.ResolvePlaybook(ctx, owner, task.ProjectID, taskplan.Bug)
+ must(t, e)
+ if got.ID != want {
+ t.Fatalf("precedence: got %s want %s", got.ID, want)
+ }
+ }
+ check("template:playbook_bug:1")
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, 0, taskplan.Bug, kind.ID, equipo.Mutation{RequestID: "kind-default"}))
+ check(kind.ID)
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, "", wide.ID, equipo.Mutation{RequestID: "wide-default"}))
+ check(wide.ID)
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, taskplan.Bug, exact.ID, equipo.Mutation{RequestID: "exact-default"}))
+ check(exact.ID)
+ if err = f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, taskplan.Bug, wide.ID, equipo.Mutation{RequestID: "stale"}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("second default accepted without revision", err)
+ }
+ if n := f.count(t, "SELECT count(*) FROM playbook_defaults WHERE project_id=? AND kind='bug'", task.ProjectID); n != 1 {
+ t.Fatal("duplicate specificity", n)
+ }
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, taskplan.Bug, "", equipo.Mutation{RequestID: "clear", Revision: 1}))
+ check(wide.ID)
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, "", "", equipo.Mutation{RequestID: "clear-wide", Revision: 1}))
+ check(kind.ID)
+ f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address)
+ if err = f.Store.SetPlaybookDefault(ctx, peer, 0, taskplan.Bug, exact.ID, equipo.Mutation{RequestID: "member", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("member controlled default", err)
+ }
+ p, err := f.Store.ProposePlan(ctx, owner, taskplan.Plan{Kind: taskplan.Bug, ProjectID: task.ProjectID}, equipo.Mutation{RequestID: "default-proposal"})
+ must(t, err)
+ if p.PlaybookID != kind.ID {
+ t.Fatal("proposal ignored default")
+ }
+}
+func TestPlaybookSnapshot(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ row, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Snapshot"), equipo.Mutation{RequestID: "save"})
+ must(t, err)
+ plan, err := f.Store.InstantiatePlaybook(ctx, owner, row.ID, task.ID)
+ must(t, err)
+ in := library.PlaybookFields(row)
+ in.Steps[0].Instructions = "Later instructions"
+ edited, err := f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision})
+ must(t, err)
+ again, err := f.Store.InstantiatePlaybook(ctx, owner, row.ID, task.ID)
+ must(t, err)
+ if !reflect.DeepEqual(plan, again) || again.PlaybookRevision != 1 || edited.Revision != 2 {
+ t.Fatal("snapshot changed after library edit")
+ }
+ p, err := f.Store.TaskPlan(ctx, owner, task.ID)
+ must(t, err)
+ plan.Revision = p.Revision
+ p, err = f.Store.EditPlan(ctx, owner, plan, equipo.Mutation{RequestID: "use", Revision: p.Revision})
+ must(t, err)
+ in.Steps[0].Instructions = "Third version"
+ _, err = f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "edit-again", Revision: edited.Revision})
+ must(t, err)
+ saved, err := f.Store.TaskPlan(ctx, owner, task.ID)
+ must(t, err)
+ if !reflect.DeepEqual(p, saved) {
+ t.Fatal("task plan rewritten")
+ }
+}
+func TestPlaybookSuggestionNeedsPerson(t *testing.T) {
+ f, x, principal, claim := claimTools(t)
+ result := toolCall(t, x, principal, claim, "suggest", "suggest_playbook", map[string]any{"source_message_ids": []string{claim.Turn.MessageID}, "draft": map[string]any{"name": "Suggested", "instructions": "Investigate first"}})
+ if f.count(t, "SELECT count(*) FROM playbooks") != 0 {
+ t.Fatal("suggestion saved without person")
+ }
+ in := playbookInput("Reviewed suggestion")
+ if _, err := f.Store.SavePlaybookSuggestion(ctx, peer, result.ResourceID, in, equipo.Mutation{RequestID: "steal", Revision: 1}); err == nil {
+ t.Fatal("another person saved private suggestion")
+ }
+ if _, err := f.Store.SavePlaybookSuggestion(ctx, equipo.Actor{Address: "coordinator:" + claim.Binding.ID}, result.ResourceID, in, equipo.Mutation{RequestID: "model", Revision: 1}); err == nil {
+ t.Fatal("coordinator saved playbook")
+ }
+ row, err := f.Store.SavePlaybookSuggestion(ctx, owner, result.ResourceID, in, equipo.Mutation{RequestID: "accept", Revision: 1})
+ must(t, err)
+ if row.Creator != owner.Address || f.count(t, "SELECT count(*) FROM playbooks") != 1 {
+ t.Fatal("person save missing")
+ }
+ retry, err := f.Store.SavePlaybookSuggestion(ctx, owner, result.ResourceID, in, equipo.Mutation{RequestID: "accept", Revision: 1})
+ must(t, err)
+ if retry.ID != row.ID {
+ t.Fatal("suggestion retry duplicated playbook")
+ }
+ f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address)
+ if _, err = f.Store.SavePlaybookSuggestion(ctx, owner, result.ResourceID, in, equipo.Mutation{RequestID: "accept", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("removed person replayed save", err)
+ }
+}
+func TestPlaybookTemplates(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ for _, id := range []string{"playbook_bug", "playbook_website", "playbook_infra", "playbook_investigation", "playbook_blank"} {
+ row, err := f.Store.InstallPlaybookTemplate(ctx, owner, equipo.TemplateRef{ID: id, Version: 1}, equipo.Mutation{RequestID: id})
+ must(t, err)
+ in := library.PlaybookFields(row)
+ in.Name = "Our version"
+ row, err = f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: id + "edit", Revision: 1})
+ must(t, err)
+ diff, err := f.Store.PlaybookTemplateDiff(ctx, owner, row.ID, row.Template)
+ must(t, err)
+ current, err := f.Store.Playbook(ctx, owner, row.ID)
+ must(t, err)
+ if current.Name != "Our version" {
+ t.Fatal("preview changed installed copy")
+ }
+ original := diff.Suggested["name"]
+ diff.Suggested["name"] = json.RawMessage(`"forged"`)
+ if _, err = f.Store.ApplyPlaybookTemplate(ctx, owner, row.ID, diff, []string{"name"}, equipo.Mutation{RequestID: id + "forged", Revision: row.Revision}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("forged template diff accepted", err)
+ }
+ diff.Suggested["name"] = original
+ applied, err := f.Store.ApplyPlaybookTemplate(ctx, owner, row.ID, diff, []string{"name"}, equipo.Mutation{RequestID: id + "apply", Revision: row.Revision})
+ must(t, err)
+ if applied.Name == "Our version" || applied.Revision != 3 {
+ t.Fatal("explicit template update not applied")
+ }
+ if _, err = f.Store.ApplyPlaybookTemplate(ctx, owner, row.ID, diff, []string{"name"}, equipo.Mutation{RequestID: id + "stale", Revision: row.Revision}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("stale diff accepted", err)
+ }
+ if id == "playbook_investigation" {
+ p, err := f.Store.InstantiatePlaybook(ctx, owner, row.ID, task.ID)
+ must(t, err)
+ if taskplan.Validate(p) != nil || len(p.Steps) != 2 || p.Steps[0].Action != "investigate" || p.Steps[1].Action != "person" {
+ t.Fatal("investigation skipped research/person checkpoint", p)
+ }
+ }
+ }
+ in := playbookInput("Missing specialist")
+ in.Steps[0].Specialist = "absent"
+ if _, err := f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "missing"}); err == nil {
+ t.Fatal("missing specialist accepted")
+ }
+ sp, err := f.Store.CreateSpecialist(ctx, owner, specialistInput("Archived"), equipo.Mutation{RequestID: "specialist"})
+ must(t, err)
+ must(t, f.Store.DeleteSpecialist(ctx, owner, sp.Key, equipo.Mutation{RequestID: "archive", Revision: 1}))
+ in.Steps[0].Specialist = sp.Key
+ if _, err := f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "archived"}); err == nil {
+ t.Fatal("archived specialist accepted")
+ }
+}
+
+func TestPlaybookAuthorityAndRollback(t *testing.T) {
+ f := newFixture(t)
+ f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address)
+ in := playbookInput("Member playbook")
+ row, err := f.Store.SavePlaybook(ctx, peer, in, equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ outsider := equipo.Actor{Address: "other@example.com"}
+ must(t, f.Store.SetMember(ctx, owner, outsider.Address, equipo.RoleMember, true, 0))
+ edit := library.PlaybookFields(row)
+ edit.Name = "Changed"
+ if _, err = f.Store.SavePlaybook(ctx, outsider, edit, equipo.Mutation{RequestID: "steal", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("noncreator edited", err)
+ }
+ f.exec(t, `CREATE TRIGGER reject_playbook_audit BEFORE INSERT ON audit_events WHEN NEW.kind='playbook.save' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END`)
+ if _, err = f.Store.SavePlaybook(ctx, peer, edit, equipo.Mutation{RequestID: "rollback", Revision: 1}); err == nil {
+ t.Fatal("audit failure ignored")
+ }
+ unchanged, err := f.Store.Playbook(ctx, owner, row.ID)
+ must(t, err)
+ if unchanged.Revision != 1 || unchanged.Name != row.Name || f.count(t, "SELECT count(*) FROM playbook_revisions WHERE id=?", row.ID) != 1 {
+ t.Fatal("failed audit partially committed")
+ }
+ f.exec(t, "DROP TRIGGER reject_playbook_audit")
+ edited, err := f.Store.SavePlaybook(ctx, peer, edit, equipo.Mutation{RequestID: "edit", Revision: 1})
+ must(t, err)
+ retry, err := f.Store.SavePlaybook(ctx, peer, edit, equipo.Mutation{RequestID: "edit", Revision: 1})
+ must(t, err)
+ if retry.Revision != edited.Revision {
+ t.Fatal("edit retry advanced revision")
+ }
+ if _, err = f.Store.SavePlaybook(ctx, peer, edit, equipo.Mutation{RequestID: "stale", Revision: 1}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("stale edit accepted", err)
+ }
+ edit.Name = "Changed request"
+ if _, err = f.Store.SavePlaybook(ctx, peer, edit, equipo.Mutation{RequestID: "edit", Revision: 1}); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("changed retry accepted", err)
+ }
+ f.exec(t, "UPDATE members SET active=0 WHERE address=?", peer.Address)
+ if _, err = f.Store.SavePlaybook(ctx, peer, in, equipo.Mutation{RequestID: "create"}); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("revoked replay accepted", err)
+ }
+ must(t, f.Store.DeletePlaybook(ctx, owner, row.ID, equipo.Mutation{RequestID: "archive", Revision: 2}))
+ archived, err := f.Store.Playbook(ctx, owner, row.ID)
+ must(t, err)
+ if !archived.Archived {
+ t.Fatal("archive missing")
+ }
+}
+func TestPlaybookHTTP(t *testing.T) {
+ f := newFixture(t)
+ for _, path := range []string{"/playbooks", "/playbooks/new"} {
+ w := f.get(t, owner, path)
+ if w.Code != 200 {
+ t.Fatal("page unavailable", path, w.Code)
+ }
+ }
+ row, err := f.Store.SavePlaybook(ctx, owner, playbookInput("<script>bad</script>"), equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ w := f.get(t, owner, "/playbooks/"+row.ID+"/edit")
+ if w.Code != 200 || strings.Contains(w.Body.String(), "<script>bad</script>") || !strings.Contains(w.Body.String(), "step_0_instructions") {
+ t.Fatal("form missing or unescaped", w.Code, w.Body.String())
+ }
+ form := url.Values{"request_id": {"bad"}, "revision": {"1"}, "creator": {"someone"}}
+ req := httptest.NewRequest("POST", "/playbooks/"+row.ID+"/edit", strings.NewReader(form.Encode()))
+ req.Header.Set("Origin", origin)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.AddCookie(f.Cookies[owner.Address])
+ rec := httptest.NewRecorder()
+ f.Handler.ServeHTTP(rec, req)
+ if rec.Code < 400 {
+ t.Fatal("submitted authority accepted", rec.Code)
+ }
+}
+
+func TestPlaybookPlanProvenance(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ row, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Pinned playbook"), equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ p, err := f.Store.ProposePlan(ctx, owner, taskplan.Plan{Kind: taskplan.Bug, ProjectID: task.ProjectID, PlaybookID: row.ID}, equipo.Mutation{RequestID: "propose"})
+ must(t, err)
+ in := library.PlaybookFields(row)
+ in.Name = "Later library name"
+ in.Steps[0].Instructions = "Later instructions"
+ _, err = f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "update", Revision: 1})
+ must(t, err)
+ snap, err := f.Store.InstantiatePlaybook(ctx, owner, row.ID, p.TaskID)
+ must(t, err)
+ if snap.PlaybookRevision != 1 || snap.Steps[0].Instructions != "" {
+ t.Fatal("proposal snapshot replaced by later revision")
+ }
+ p.Steps[0].Instructions = "Task-specific change"
+ p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "edit-plan", Revision: 1})
+ must(t, err)
+ w := f.get(t, owner, "/tasks/"+p.TaskID+"/plan")
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "Pinned playbook") || !strings.Contains(w.Body.String(), "data-playbook-change=\"reproduce\"") {
+ t.Fatal("chosen playbook or task changes missing", w.Code)
+ }
+ p.PlaybookRevision = 999
+ if _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "forged", Revision: p.Revision}); err == nil {
+ t.Fatal("forged provenance accepted")
+ }
+}
+func TestPlaybookCoordinatorDefault(t *testing.T) {
+ f, x, principal, claim := claimTools(t)
+ var project int64
+ must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project))
+ row, err := f.Store.SavePlaybook(ctx, owner, playbookInput("Coordinator default"), equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, project, taskplan.Bug, row.ID, equipo.Mutation{RequestID: "default"}))
+ result := toolCall(t, x, principal, claim, "default", "propose_plan", map[string]any{"message_id": claim.Turn.MessageID, "plan": map[string]any{"kind": "bug", "project_id": project, "steps": []any{}}})
+ p, err := f.Store.TaskPlan(ctx, owner, result.ResourceID)
+ must(t, err)
+ if p.PlaybookID != row.ID || p.PlaybookRevision != 1 {
+ t.Fatal("coordinator ignored default")
+ }
+}
+
+func TestPlaybookLegacyBugDefault(t *testing.T) {
+ f := newFixture(t)
+ base := f.createTask(t)
+ in := playbookInput("Bug default")
+ in.Steps[0].Instructions = "Use this reproduction process"
+ row, err := f.Store.SavePlaybook(ctx, owner, in, equipo.Mutation{RequestID: "create"})
+ must(t, err)
+ must(t, f.Store.SetPlaybookDefault(ctx, owner, base.ProjectID, taskplan.Bug, row.ID, equipo.Mutation{RequestID: "default"}))
+ task, err := f.Store.CreateBug(ctx, owner, base.ProjectID, "Another bug", "another")
+ must(t, err)
+ p, err := f.Store.TaskPlan(ctx, owner, task.ID)
+ must(t, err)
+ if p.PlaybookID != row.ID || p.Steps[0].Instructions != in.Steps[0].Instructions {
+ t.Fatal("bug creation ignored default")
+ }
+}
diff --git a/internal/taskplan/playbooks.go b/internal/taskplan/playbooks.go
new file mode 100644
index 00000000..cee3383d
--- /dev/null
+++ b/internal/taskplan/playbooks.go
@@ -0,0 +1,55 @@
+package taskplan
+
+// ValidatePlaybook retains publication safeguards even for a saved investigation.
+// Investigation execution is projected separately, ending at its person checkpoint.
+func ValidatePlaybook(kind Kind, steps []Step) error {
+ if kind == Recommendation {
+ return ErrInvalid
+ }
+ p := Plan{Kind: kind, ProjectID: 1, Steps: steps}
+ if kind == Investigation {
+ p.Kind = Feature
+ research := 0
+ for _, s := range steps {
+ switch s.Action {
+ case "scope", "investigate", "recommend":
+ research++
+ case "review", "checks", "person":
+ default:
+ return ErrInvalid
+ }
+ }
+ if research == 0 {
+ return ErrInvalid
+ }
+ }
+ if err := Validate(p); err != nil {
+ return err
+ }
+ n := len(steps)
+ if n < 3 {
+ return ErrInvalid
+ }
+ end := n - 1
+ if end > 0 && steps[end-1].Action == "publish" {
+ end--
+ }
+ if end < 2 || steps[end-2].Action != "review" || steps[end-1].Action != "checks" {
+ return ErrInvalid
+ }
+ if kind == Investigation && Validate(Plan{Kind: kind, ProjectID: 1, Steps: PlaybookSteps(kind, steps)}) != nil {
+ return ErrInvalid
+ }
+ return nil
+}
+func PlaybookSteps(kind Kind, steps []Step) []Step {
+ out := []Step{}
+ for _, s := range steps {
+ if kind == Investigation && (s.Action == "review" || s.Action == "checks") {
+ continue
+ }
+ s.DependsOn = append([]string(nil), s.DependsOn...)
+ out = append(out, s)
+ }
+ return Normalize(Plan{Kind: kind, Steps: out}).Steps
+}
diff --git a/internal/taskplan/playbooks_test.go b/internal/taskplan/playbooks_test.go
new file mode 100644
index 00000000..985b58ea
--- /dev/null
+++ b/internal/taskplan/playbooks_test.go
@@ -0,0 +1,36 @@
+package taskplan
+
+import "testing"
+
+func TestPlaybookValidation(t *testing.T) {
+ steps := BugPlan("", 1).Steps
+ for _, key := range []string{"review", "verify", "merge"} {
+ t.Run(key, func(t *testing.T) {
+ changed := []Step{}
+ for _, st := range steps {
+ if st.Key != key {
+ changed = append(changed, st)
+ }
+ }
+ if ValidatePlaybook(Bug, changed) == nil {
+ t.Fatal("mandatory tail removed")
+ }
+ })
+ }
+ bad := append([]Step(nil), steps...)
+ bad[2], bad[3] = bad[3], bad[2]
+ if ValidatePlaybook(Bug, bad) == nil {
+ t.Fatal("tail order changed")
+ }
+ research := []Step{{Key: "research", Specialist: "engineering", Action: "investigate"}, steps[2], steps[3], steps[5]}
+ if ValidatePlaybook(Investigation, research) != nil {
+ t.Fatal("valid investigation rejected")
+ }
+ research[3].DependsOn = []string{"review"}
+ if ValidatePlaybook(Investigation, research) == nil {
+ t.Fatal("checkpoint depends on deferred review")
+ }
+ if ValidatePlaybook(Investigation, steps) == nil {
+ t.Fatal("investigation retained publication before checkpoint")
+ }
+}