oficina / equipo Public

equipo: grants for every specialist, step bindings, revoke by specialist

Task 16 of dynamic specialists slice 1 (half 1b).

What changed (internal/equipo/chat unless noted):
- grants.go (new). grantFor(profile, project) generalises researchGrant:
  the project's active row, else the team's (scopeRow); granted only when
  the profile is on the menu, the unrevoked grants are exactly its
  capabilities (each once), each at the row's revision and given by its
  approver, and that approver is an owner now (roster read in the
  transaction; a lookup error denies). A project row that fails a check
  is no grant: the team's row does not stand in. grantFor moved here from
  specialist_added.go (its body only; startMaker is unchanged).
- researchGrant(project) is grantFor for research-v1 against the task's
  project (tool, dispatch and start). research-v1 stays team-only: a
  project-scoped Add queues the specialist_added continuation, which
  starts a task with the specialist as maker, and Research is no maker.
- Dispatch writes the full binding (specialist_id, revision, project
  scope, capabilities JSON) on the step: Research at its grant, and the
  maker step of a task with maker_specialist_id at makerGrant (the task's
  maker, found by grantFor, equal to any earlier binding). A maker step
  with no usable grant ends cancelled (specialist_no_grant) at dispatch
  and never runs as plain Engineering. The maker dispatch carries
  specialist_id/revision/project/profile/capabilities (protocol 36; Encode
  refuses it below). Each sent dispatch appends a specialist.used row
  (chat_specialist_audit and the instance audit), no credentials.
  writeStep now saves the four binding columns.
- Authorize: a purpose unknown for the step is refused, never a start
  check (merge_request only on merge steps, page_render only on
  Engineering steps). authorizeSpecialist: a maker step is granted (start,
  pre-push, page_render) only at protocol 36+, bound to the task's maker,
  while its binding equals grantFor for the task's project; page_render
  also needs page.render in the binding. An unbound non-maker step is
  unaffected but never renders. Research checks its binding too; a
  pre-0115 Research step with an empty binding is checked by its grant id
  alone, as before.
- authorizePublication refuses a maker step whose binding no longer
  holds or is not the task's maker.
- RevokeSpecialist -> cancelSpecialist: Research runs under it (bound to
  it, legacy under its grants, or undispatched in a project resolving to
  it) cancelled as today; maker steps (bound to it, or unbound on a task
  it makes) get the ordinary cancel: never placed or dispatch retired
  undelivered ends cancelled at once, else cancel_step and the runner
  reports its end; transfers closed. Pending publications of steps bound
  to it are withdrawn (publish command retired, transfers closed,
  publication failed, reason cancelled). Nothing of another specialist or
  Engineering's own is touched.
- copy.go: work.reason.specialist_no_grant (pending).
- .rastrillo/budgets.txt: chat 39001/14022, internal/equipo 23933.

Tests: specialist_grants_test.go (new); TestGrantFor rows get grants;
specialists_test.go researchGrant("").
  CGO_ENABLED=0 go test ./internal/equipo/chat/ -run 'TestGrantFor|TestDesign|TestRenderLease|TestResearch|TestPublicationNeeds|TestSpecialistAdded'

RED (tests against the old code, with only the reason constant added):
13 failures, e.g. "approver demoted: granted", "binding \"\" 0 \"\" \"\"",
"Engineering's step granted \"page_render\"", "a mismatched binding: \"\"",
"publication with the approver demoted", "cancels 0 0 0", "held step
after revoke {... State:queued}".

GREEN: the targeted tests; the whole chat package; ./internal/equipo/;
thintest -run 'Specialist|Research|Propose|Design|Lease|Authorize|
Publication|Worker|Merge|Preview|Publish|Relay|Transfer|Start|Cancel|
Explore'; plan3test -run 'Contract|Protocol|Specialist|Lease'; headless
-run 'Research|Specialist'; vet, gofmt, darwin/arm64 runner build,
runner-dead-references.py.

Mutations (57, each broken, its test run, restored; all failed):
menu check (off-menu row with no grants); blank approver; grant revision;
granter; capability set; approver demoted; roster error; team row over
project row; two rows per scope; bindingHolds always true; makerGrant any
row; makerGrant ignoring an old binding; no grant runs as Engineering;
no bind; dispatch without binding; no used audit (maker, Research);
binding columns not saved; unbound renders; bound non-maker; maker id;
protocol 36; binding not held; render without page.render; unknown
purpose; merge purpose anywhere; render purpose anywhere; Authorize gate
and binding call removed; Research binding unchecked; legacy Research
refused; Research start/dispatch/tool resolving the team; Research not
bound; Research old binding ignored; cancel any bound/legacy/waiting
Research; resolvesTo (own row, project row anywhere); revoke without
cancelSpecialist; cancelMakers skipped; held unbound not cancelled;
delivered ended at once; started-unacked ended at once; undelivered
asked not ended; maker transfers open; publications skipped, of every
specialist, command not retired, transfers open, left pending, reason
unset; publication binding, maker id, unbound maker. Survivors fixed:
the menu guard was layered under a profile equality (removed, then
killed); researchGrant's capability check is covered by usableGrant
(removed); a Suite step was added for resolvesTo; three mutations first
did not compile and were redone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f60c0a6f9b0c9cb0800fd4265332384a067c849d parent e372e63
12 files changed, +1,451 −103
  • .rastrillo/budgets.txt +2 −2
  • internal/equipo/chat/grants.go +372 −0
  • internal/equipo/chat/research.go +27 −15
  • internal/equipo/chat/runners.go +19 −1
  • internal/equipo/chat/specialist_added.go +0 −31
  • internal/equipo/chat/specialist_added_test.go +4 −1
  • internal/equipo/chat/specialist_grants_test.go +933 −0
  • internal/equipo/chat/specialists.go +52 −50
  • internal/equipo/chat/specialists_test.go +1 −1
  • internal/equipo/chat/tasks.go +27 −1
  • internal/equipo/chat/transfers.go +13 −1
  • internal/equipo/copy.go +1 −0

CI cancelled — superseded by a newer push — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 828ed282..d1da8d62 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 23925 - Preview grants, retry/timeline, no-access merges, kept work, check-db copy, notification actions, places page and its superseded card, GitHub owner routes; measured 23925 source lines.
+size internal/equipo 23933 - Preview grants, retry/timeline, no-access merges, kept work, check-db copy, notification actions, places page and its superseded card, GitHub owner routes, specialist copy; measured 23933 source lines.
size internal/wire 8481 - Protocol 31 facts, 32 unfinished work, task evidence, CI units, notification inputs, 33 Assistant files, 34 places, 35 diffs, 36 Design (binding, options, render_file); measured 8481 source lines.
size internal/equipotest - 12684 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures, Rastrillo asset contract, renderer pin link; measured 0/12684 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 37987 11950 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places and where their cards land, waiting cards, 36 proposal project and Build's note; measured 37987/11950.
+size internal/equipo/chat 39001 14022 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places and where their cards land, waiting cards, 36 proposal project and Build's note, scoped specialists and their continuation, grants and step bindings; measured 39001/14022.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
diff --git a/internal/equipo/chat/grants.go b/internal/equipo/chat/grants.go
new file mode 100644
index 00000000..60bdd351
--- /dev/null
+++ b/internal/equipo/chat/grants.go
@@ -0,0 +1,372 @@
+package chat
+
+import (
+ "encoding/json"
+ "errors"
+ "slices"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/specialist"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Every attempt is bound to its grant (dynamic specialists §1). A data
+// specialist's step records, when dispatched, the specialist it runs as:
+// its id, revision, scope and capabilities (bind). Every privileged
+// effect of the attempt checks that binding again in its own
+// transaction against grantFor for the task's project: the start and
+// pre-push authorization and each page_render check (Authorize), and a
+// worker commit's push (authorizePublication). Revoking a specialist
+// cancels the steps bound to it and withdraws their pending
+// publications (cancelSpecialist).
+
+// reasonSpecialistNoGrant ends a data specialist's maker step that has
+// no usable grant (revoked, or its binding no longer holds): nothing of
+// that attempt runs.
+const reasonSpecialistNoGrant = "specialist_no_grant"
+
+// auditUsed is the specialist audit action of one dispatch under a
+// grant (instance audit kind specialist.used).
+const auditUsed = "used"
+
+// scopeRow is the active row of profile a project's work runs as: the
+// project's own, else the team's (""); nil when there is none, or when
+// a scope holds more than one (the unique indexes forbid it; it
+// denies). It checks nothing else (usableGrant does).
+func (t *txn) scopeRow(profile, project string) (*specialistRecord, error) {
+ var rows []specialistRecord
+ if err := t.db.Where("profile = ? AND state = ? AND project_id IN ?", profile, wire.SpecialistActive, []string{project, ""}).Order("id").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ pick := func(scope string) (*specialistRecord, bool) {
+ var out *specialistRecord
+ for i := range rows {
+ if rows[i].ProjectID != scope {
+ continue
+ }
+ if out != nil {
+ return nil, true
+ }
+ out = &rows[i]
+ }
+ return out, out != nil
+ }
+ if sp, ok := pick(project); ok || project == "" {
+ return sp, nil
+ }
+ sp, _ := pick("")
+ return sp, nil
+}
+
+// usableGrant is the specialist a profile's work in project runs as and
+// the grants it runs under, only when every one of these holds now, read
+// in this transaction: the profile is on the menu; scopeRow finds the
+// row (a project's own row wins, and when it fails a check below the
+// team's row does not stand in for it); its unrevoked grants are
+// exactly the profile's capabilities, each once, each at the row's
+// revision and given by its approver; and that approver is an owner now.
+// Otherwise nil. A lookup error is returned, and denies too.
+func (t *txn) usableGrant(profile, project string) (*specialistRecord, []grantRecord, error) {
+ p, ok := specialist.Lookup(profile)
+ if !ok {
+ return nil, nil, nil
+ }
+ sp, err := t.scopeRow(profile, project)
+ if err != nil || sp == nil {
+ return nil, nil, err
+ }
+ if sp.Approver == "" {
+ return nil, nil, nil
+ }
+ var grants []grantRecord
+ if err := t.db.Where("specialist_id = ? AND revoked_at IS NULL", sp.ID).Find(&grants).Error; err != nil {
+ return nil, nil, err
+ }
+ held := make([]string, 0, len(grants))
+ for _, g := range grants {
+ if g.Revision != sp.Revision || g.GrantedBy != sp.Approver {
+ return nil, nil, nil
+ }
+ held = append(held, g.Capability)
+ }
+ want := slices.Clone(p.Capabilities)
+ slices.Sort(held)
+ slices.Sort(want)
+ if !slices.Equal(held, want) {
+ return nil, nil, nil
+ }
+ if err := t.isOwner(sp.Approver); errors.Is(err, ErrForbidden) {
+ return nil, nil, nil
+ } else if err != nil {
+ return nil, nil, err
+ }
+ return sp, grants, nil
+}
+
+// grantFor is the specialist a profile's work in project runs as now, if
+// its grant is usable (usableGrant); nil otherwise.
+func (t *txn) grantFor(profile, project string) (*specialistRecord, error) {
+ sp, _, err := t.usableGrant(profile, project)
+ return sp, err
+}
+
+// binding is what a step records of the specialist it runs as: the row,
+// its revision and scope, and its profile's capabilities (a JSON list,
+// in the menu's order). The zero binding is none.
+type binding struct {
+ ID string
+ Revision int64
+ Project string
+ Caps string
+}
+
+// bindingOf is the binding a step dispatched under sp records.
+func bindingOf(sp specialistRecord) binding {
+ b := binding{ID: sp.ID, Revision: sp.Revision, Project: sp.ProjectID}
+ if p, ok := specialist.Lookup(sp.Profile); ok {
+ raw, _ := json.Marshal(p.Capabilities)
+ b.Caps = string(raw)
+ }
+ return b
+}
+
+func stepBinding(s stepRecord) binding {
+ return binding{ID: s.SpecialistID, Revision: s.SpecialistRevision, Project: s.SpecialistProject, Caps: s.SpecialistCaps}
+}
+
+// bind records sp's binding on the step (the caller saves s).
+func bind(s *stepRecord, sp specialistRecord) {
+ b := bindingOf(sp)
+ s.SpecialistID, s.SpecialistRevision, s.SpecialistProject, s.SpecialistCaps = b.ID, b.Revision, b.Project, b.Caps
+}
+
+// boundDispatch puts sp's binding and profile in a maker step's
+// dispatch (protocol 36).
+func boundDispatch(cmd *wire.DispatchCommand, sp specialistRecord) {
+ b := bindingOf(sp)
+ cmd.SpecialistID, cmd.SpecialistRevision, cmd.SpecialistProject, cmd.Profile = b.ID, b.Revision, b.Project, sp.Profile
+ if p, ok := specialist.Lookup(sp.Profile); ok {
+ cmd.Capabilities = slices.Clone(p.Capabilities)
+ }
+}
+
+// boundCaps are the capabilities the step's binding records.
+func boundCaps(s stepRecord) []string {
+ var caps []string
+ if json.Unmarshal([]byte(s.SpecialistCaps), &caps) != nil {
+ return nil
+ }
+ return caps
+}
+
+// bindingHolds reports whether the step's binding is exactly what
+// grantFor finds now for its task's project, for the bound row's
+// profile. A step with no binding never holds.
+func (t *txn) bindingHolds(s stepRecord, k taskRecord) (bool, error) {
+ var row specialistRecord
+ if err := t.db.Where("id = ?", s.SpecialistID).Limit(1).Find(&row).Error; err != nil || row.ID == "" {
+ return false, err
+ }
+ sp, err := t.grantFor(row.Profile, k.ProjectID)
+ if err != nil || sp == nil {
+ return false, err
+ }
+ return bindingOf(*sp) == stepBinding(s), nil
+}
+
+// makerGrant is the specialist the task's maker step runs as at its
+// dispatch: the task's maker, found by grantFor for the task's project,
+// and the one the step is already bound to when it is (an earlier
+// attempt's). nil: no usable grant, and the step must not run (as plain
+// Engineering least of all).
+func (t *txn) makerGrant(k taskRecord, s stepRecord) (*specialistRecord, error) {
+ var row specialistRecord
+ if err := t.db.Where("id = ?", k.MakerSpecialistID).Limit(1).Find(&row).Error; err != nil || row.ID == "" {
+ return nil, err
+ }
+ sp, err := t.grantFor(row.Profile, k.ProjectID)
+ if err != nil || sp == nil || sp.ID != k.MakerSpecialistID {
+ return nil, err
+ }
+ if s.SpecialistID != "" && stepBinding(s) != bindingOf(*sp) {
+ return nil, nil
+ }
+ return sp, nil
+}
+
+// specialistUsed appends the specialist.used audit row of one dispatch
+// under sp, in the dispatch's transaction: the task, the step attempt,
+// the runner, the task's project and the binding. Never a credential.
+func (t *txn) specialistUsed(sp specialistRecord, k taskRecord, s stepRecord) error {
+ b := bindingOf(sp)
+ var caps []string
+ _ = json.Unmarshal([]byte(b.Caps), &caps)
+ detail := "profile=" + sp.Profile + " scope=" + sp.ProjectID + " project=" + k.ProjectID + " task=" + k.ID + " step=" + s.ID + " attempt=" + strconv.FormatInt(s.Attempt, 10) + " runner=" + s.RunnerID + " capabilities=" + strings.Join(caps, ",")
+ a := specialistAuditRecord{ID: newID("sa_"), SpecialistID: sp.ID, Action: auditUsed, Actor: "system", Revision: sp.Revision, Detail: detail, At: t.now()}
+ if err := t.db.Create(&a).Error; err != nil {
+ return err
+ }
+ if t.s.authority.Audit == nil {
+ return nil
+ }
+ return t.s.authority.Audit(t.db, "system", "specialist."+auditUsed, sp.ID+"@"+sp.Profile+":"+k.ID+"/"+s.ID+"/"+strconv.FormatInt(s.Attempt, 10))
+}
+
+// authorizeSpecialist is a lease's binding check for a step that is not
+// Research (authorizeResearch checks those): a step with no binding on a
+// task with no maker is Engineering's own (or a judge's) and unaffected,
+// except that it never renders. A maker step is granted only on a
+// connection at ProtocolDesign or above, bound to the task's maker,
+// while its binding holds (bindingHolds); a render only while that
+// binding holds page.render. A step bound to anything else is refused.
+func (t *txn) authorizeSpecialist(l Lease, s stepRecord, purpose string) (string, error) {
+ k, err := t.loadTask(s.TaskID)
+ if err != nil {
+ return "", err
+ }
+ maker := s.Specialist == wire.SpecialistEngineering && k.MakerSpecialistID != ""
+ if !maker && s.SpecialistID == "" {
+ if purpose == wire.LeasePurposeRender {
+ return "withdrawn", nil
+ }
+ return "", nil
+ }
+ if !maker || s.SpecialistID != k.MakerSpecialistID || l.Protocol < wire.ProtocolDesign {
+ return reasonSpecialistNoGrant, nil
+ }
+ holds, err := t.bindingHolds(s, k)
+ if err != nil {
+ return "", err
+ }
+ if !holds {
+ return reasonSpecialistNoGrant, nil
+ }
+ if purpose == wire.LeasePurposeRender && !slices.Contains(boundCaps(s), specialist.CapabilityPageRender) {
+ return "withdrawn", nil
+ }
+ return "", nil
+}
+
+// leasePurposeKnown reports whether a lease purpose is one this instance
+// checks for this step kind. Any other is refused, never taken for a
+// start check.
+func leasePurposeKnown(stepSpecialist, purpose string) bool {
+ switch purpose {
+ case "", wire.LeasePurposePreview, wire.LeasePurposePublish, wire.LeasePurposeMint:
+ // Preview and publish purposes on other steps are refused below.
+ return true
+ case wire.LeasePurposeMerge:
+ return stepSpecialist == wire.SpecialistMerge
+ case wire.LeasePurposeRender:
+ return stepSpecialist == wire.SpecialistEngineering
+ }
+ return false
+}
+
+// cancelSpecialist settles everything that runs under sp, in its
+// revoke's transaction: its Research steps (cancelResearch), its maker
+// steps (cancelMakers) and the pending publications of the steps bound
+// to it (withdrawPublications). Nothing bound to any other specialist,
+// and no step of Engineering's own, is touched.
+func (t *txn) cancelSpecialist(sp specialistRecord) error {
+ if err := t.withdrawPublications(sp); err != nil {
+ return err
+ }
+ if err := t.cancelResearch(sp); err != nil {
+ return err
+ }
+ return t.cancelMakers(sp)
+}
+
+// cancelMakers gives every unfinished maker step of sp (bound to it, or
+// not yet dispatched on a task whose maker it is) the ordinary cancel.
+// One that cannot have run ends cancelled at once: never placed, or its
+// dispatch retired before its runner took it. One its runner may hold
+// is asked to stop and reports its end (its termination proof); its
+// leases are refused from now on (authorizeSpecialist). The task waits.
+func (t *txn) cancelMakers(sp specialistRecord) error {
+ var rows []stepRecord
+ if err := t.db.Where("specialist = ? AND state IN ? AND (specialist_id = ? OR task_id IN (SELECT id FROM chat_tasks WHERE maker_specialist_id = ?))", wire.SpecialistEngineering, []string{wire.StepQueued, wire.StepRunning}, sp.ID, sp.ID).Order("created_at, id").Find(&rows).Error; err != nil {
+ return err
+ }
+ for i := range rows {
+ s := &rows[i]
+ k, err := t.loadTask(s.TaskID)
+ if err != nil {
+ return err
+ }
+ if err := t.closeTransfers(s.ID, s.Attempt); err != nil {
+ return err
+ }
+ if s.RunnerID != "" {
+ res := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.RunnerID, wire.FrameDispatch, `%"step_id":"`+s.ID+`","attempt":`+itoa64(s.Attempt)+`,%`).Update("acked_at", t.now())
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 || s.StartedAt != nil {
+ if err := t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: s.TaskID, StepID: s.ID, Attempt: s.Attempt}); err != nil {
+ return err
+ }
+ continue
+ }
+ }
+ now := t.now()
+ s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, reasonSpecialistNoGrant, true, &now, "", nil
+ if err := t.saveStep(s, &k); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// withdrawPublications withdraws the pending publication of every step
+// bound to sp: a worker's commit the primary was to push is not pushed.
+// Its publish command, if not yet delivered, is retired; its transfers
+// are closed; and the publication fails as cancelled, so a primary that
+// holds the command is refused its push (authorizePublication).
+func (t *txn) withdrawPublications(sp specialistRecord) error {
+ var rows []stepRecord
+ if err := t.db.Where("specialist_id = ? AND publication = ?", sp.ID, wire.PublicationPending).Find(&rows).Error; err != nil {
+ return err
+ }
+ for i := range rows {
+ s := &rows[i]
+ k, err := t.loadTask(s.TaskID)
+ if err != nil {
+ return err
+ }
+ if err := t.db.Model(&commandRecord{}).Where("kind = ? AND acked_at IS NULL AND body LIKE ?", wire.FramePublish, `%"publication":"`+s.PublicationID+`"%`).Update("acked_at", t.now()).Error; err != nil {
+ return err
+ }
+ if err := t.closeTransfers(s.ID, s.Attempt); err != nil {
+ return err
+ }
+ s.Publication = wire.PublicationFailed
+ if wire.StepTerminal(s.State) {
+ s.Reason = "cancelled"
+ }
+ if err := t.saveStep(s, &k); err != nil {
+ return err
+ }
+ if err := t.advance(&k); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// researchResolvesTo reports whether a Research step of a task in
+// project, not yet bound to any grant, would run under sp: sp is that
+// project's own row, or the team's and the project has no active row of
+// its own.
+func (t *txn) researchResolvesTo(sp specialistRecord, project string) (bool, error) {
+ if sp.ProjectID != "" {
+ return sp.ProjectID == project, nil
+ }
+ var own int64
+ if err := t.db.Model(&specialistRecord{}).Where("profile = ? AND state = ? AND project_id = ? AND project_id <> ''", sp.Profile, wire.SpecialistActive, project).Count(&own).Error; err != nil {
+ return false, err
+ }
+ return own == 0, nil
+}
diff --git a/internal/equipo/chat/research.go b/internal/equipo/chat/research.go
index 77556872..778229b2 100644
--- a/internal/equipo/chat/research.go
+++ b/internal/equipo/chat/research.go
@@ -112,7 +112,7 @@ func (t *txn) toolResearch(l Lease, r turnRecord, v *wire.ToolCall) (wire.ToolRe
}
proposed = append(proposed, u)
}
- if _, _, err := t.researchGrant(); errors.Is(err, ErrNoGrant) {
+ if _, _, err := t.researchGrant(k.ProjectID); errors.Is(err, ErrNoGrant) {
return refused("no_grant", toolResearchNoGrant), nil
} else if err != nil {
return wire.ToolResult{}, err
@@ -553,16 +553,23 @@ func (t *txn) dispatchResearch(k *taskRecord, s *stepRecord) error {
s.Summary = "Nothing to read: no page was approved."
return nil
}
- sp, g, err := t.researchGrant()
+ sp, g, err := t.researchGrant(k.ProjectID)
if errors.Is(err, ErrNoGrant) {
end(wire.StepCancelled, wire.ReasonResearchNoGrant)
return nil
} else if err != nil {
return err
}
- // The attempt is bound to this grant at this revision: its start is
- // authorized only while it is still the usable one (authorizeResearch).
+ if s.SpecialistID != "" && stepBinding(*s) != bindingOf(sp) {
+ // Bound at an earlier dispatch to a grant that no longer holds.
+ end(wire.StepCancelled, wire.ReasonResearchNoGrant)
+ return nil
+ }
+ // The attempt is bound to this grant at this revision, and to the
+ // specialist's full binding: its start is authorized only while it
+ // is still the usable one (authorizeResearch).
s.ResearchGrant, s.ResearchGrantRevision = g.ID, sp.Revision
+ bind(s, sp)
if _, err := t.place(k, s); err != nil {
return err
}
@@ -629,6 +636,9 @@ func (t *txn) dispatchResearch(k *taskRecord, s *stepRecord) error {
if err := t.schedulerFields(*k, *s, &cmd); err != nil {
return err
}
+ if err := t.specialistUsed(sp, *k, *s); err != nil {
+ return err
+ }
return t.commandTo(s.RunnerID, s.Person, wire.FrameDispatch, cmd)
}
@@ -718,23 +728,25 @@ func (t *txn) researchReport(l Lease, k *taskRecord, s *stepRecord, v *wire.Step
// authorizeResearch is a Research attempt's start authorization, checked
// in Authorize's transaction right before its fetch phase (every lease,
-// a deferred resume's too): the usable grant now (researchGrant: active,
-// unrevoked, its approver an owner now) is the one the attempt was
-// dispatched under, at that revision. Otherwise the start is refused and
-// the step ends cancelled (research_no_grant), which releases the
-// Engineering it held.
+// a deferred resume's too): the usable grant now for the task's project
+// (researchGrant: active, unrevoked, its approver an owner now) is the
+// one the attempt was dispatched under, at that revision, and its full
+// binding is that grant's. A step dispatched before bindings (task 16)
+// has none: its grant alone is checked, as before. Otherwise the start
+// is refused and the step ends cancelled (research_no_grant), which
+// releases the Engineering it held.
func (t *txn) authorizeResearch(s *stepRecord) (string, error) {
- sp, g, err := t.researchGrant()
+ k, err := t.loadTask(s.TaskID)
+ if err != nil {
+ return "", err
+ }
+ sp, g, err := t.researchGrant(k.ProjectID)
if err != nil && !errors.Is(err, ErrNoGrant) {
return "", err
}
- if err == nil && s.ResearchGrant != "" && g.ID == s.ResearchGrant && sp.Revision == s.ResearchGrantRevision {
+ if err == nil && s.ResearchGrant != "" && g.ID == s.ResearchGrant && sp.Revision == s.ResearchGrantRevision && (s.SpecialistID == "" || stepBinding(*s) == bindingOf(sp)) {
return "", nil
}
- k, err := t.loadTask(s.TaskID)
- if err != nil {
- return "", err
- }
now := t.now()
s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, wire.ReasonResearchNoGrant, true, &now, "", nil
if err := t.saveStep(s, &k); err != nil {
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index ac2c8289..d6322adc 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -590,7 +590,12 @@ func (t *txn) withdraw(k *taskRecord, s *stepRecord) error {
// it started. Refused is the reason a lease is refused, "" when granted.
//
// A Research step's lease rechecks the grant it was dispatched under
-// (authorizeResearch), on every call.
+// (authorizeResearch), on every call. Any other step bound to a data
+// specialist, and every maker step of a task with one, is granted only
+// while its binding equals grantFor for its task's project, its start
+// and each page_render check alike (authorizeSpecialist); page_render
+// needs page.render in that binding. A purpose unknown for the step is
+// refused.
//
// A merge step's lease is also merge authority's (authorizeMergeLease):
// an automatic merge on a connection below wire.ProtocolMergeFacts is
@@ -612,6 +617,19 @@ func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt i
refused = "withdrawn"
return nil
}
+ // A purpose this instance does not check for this step is refused,
+ // never taken for a start check.
+ if !leasePurposeKnown(st.Specialist, purpose) {
+ refused = "withdrawn"
+ return nil
+ }
+ if st.Specialist != wire.SpecialistResearch {
+ r, err := t.authorizeSpecialist(l, st, purpose)
+ if err != nil || r != "" {
+ refused = r
+ return err
+ }
+ }
if st.Specialist == wire.SpecialistMerge {
r, err := t.authorizeMergeLease(l, &st, purpose)
if err != nil || r != "" {
diff --git a/internal/equipo/chat/specialist_added.go b/internal/equipo/chat/specialist_added.go
index 2b856b11..58c7f89b 100644
--- a/internal/equipo/chat/specialist_added.go
+++ b/internal/equipo/chat/specialist_added.go
@@ -397,34 +397,3 @@ func (t *txn) startMaker(r turnRecord, task, specialistID string) (string, *wire
}
return b.SpecialistID, nil, nil
}
-
-// grantFor is the specialist a profile's work in project runs as: the
-// active row for that profile and project, else the team's ("") row; nil
-// when there is none, or when a scope holds more than one (the unique
-// indexes forbid it; it denies). Minimal here (plan task 15): task 16
-// generalises it to check the grants themselves, the revision, the
-// approver and the menu, as researchGrant does.
-func (t *txn) grantFor(profile, project string) (*specialistRecord, error) {
- var rows []specialistRecord
- if err := t.db.Where("profile = ? AND state = ? AND project_id IN ?", profile, wire.SpecialistActive, []string{project, ""}).Order("id").Find(&rows).Error; err != nil {
- return nil, err
- }
- pick := func(scope string) (*specialistRecord, bool) {
- var out *specialistRecord
- for i := range rows {
- if rows[i].ProjectID != scope {
- continue
- }
- if out != nil {
- return nil, true
- }
- out = &rows[i]
- }
- return out, out != nil
- }
- if sp, ok := pick(project); ok || project == "" {
- return sp, nil
- }
- sp, _ := pick("")
- return sp, nil
-}
diff --git a/internal/equipo/chat/specialist_added_test.go b/internal/equipo/chat/specialist_added_test.go
index 3e09077d..cd0a8e26 100644
--- a/internal/equipo/chat/specialist_added_test.go
+++ b/internal/equipo/chat/specialist_added_test.go
@@ -306,7 +306,10 @@ func TestGrantFor(t *testing.T) {
return sp.ID
}
row := func(id, project, state string) {
- r.exec("INSERT INTO chat_specialists(id, profile, project_id, name, state, revision) VALUES (?, ?, ?, 'Design', ?, 2)", id, specialist.ProfileDesign, project, state)
+ r.exec("INSERT INTO chat_specialists(id, profile, project_id, name, state, revision, approver) VALUES (?, ?, ?, 'Design', ?, 2, ?)", id, specialist.ProfileDesign, project, state, hkOwner)
+ for _, c := range []string{specialist.CapabilityBranchEdit, specialist.CapabilityPageRender} {
+ r.exec("INSERT INTO chat_capability_grants(id, specialist_id, capability, revision, granted_by, granted_at) VALUES (?, ?, ?, 2, ?, ?)", newID("g_"), id, c, hkOwner, r.now)
+ }
}
if got := get(specialist.ProfileDesign, "p1"); got != "" {
t.Fatalf("none: %q", got)
diff --git a/internal/equipo/chat/specialist_grants_test.go b/internal/equipo/chat/specialist_grants_test.go
new file mode 100644
index 00000000..aeb6ff58
--- /dev/null
+++ b/internal/equipo/chat/specialist_grants_test.go
@@ -0,0 +1,933 @@
+package chat
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/equipo/internal/specialist"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Task 16 (dynamic specialists slice 1): grants for every specialist
+// (grantFor), the step's full binding at dispatch, the binding checked
+// again by every privileged effect, and revocation by specialist.
+
+// grantRig is designRig whose runner leases are current and whose
+// instance audit log is kept.
+func grantRig(t *testing.T) (*hkRig, Lease, *[]string) {
+ r, l := designRig(t)
+ r.s.authority.CurrentRunner = func(*gorm.DB, RunnerPrincipal) error { return nil }
+ r.s.authority.RunnerRole = func(*gorm.DB, string) (string, error) { return wire.RolePrimary, nil }
+ audit := &[]string{}
+ r.s.authority.Audit = func(_ *gorm.DB, actor, kind, record string) error {
+ *audit = append(*audit, actor+" "+kind+" "+record)
+ return nil
+ }
+ return r, l, audit
+}
+
+// designStarted adds Design for project (Patrix or Suite) through its
+// card, and its continuation records an exploration there and starts it
+// with Design: the specialist as it is now, the task and its step.
+func (r *hkRig) designStarted(l Lease, project string) (specialistRecord, string, stepRecord) {
+ r.t.Helper()
+ var sp specialistRecord
+ var next turnRecord
+ if project == "Patrix" {
+ sp, next = r.added(l, askWords)
+ } else {
+ sp, next = r.added2(l)
+ }
+ res := r.call(l, next.ID, wire.ToolRecordTask, map[string]any{"repo": project, "title": "Calmer " + project + " design", "brief": "Options.", "kind": wire.KindExplore})
+ task := madeTask2(r.t, res)
+ if res := r.call(l, next.ID, wire.ToolStartTask, map[string]any{"task": task, "specialist": sp.ID}); res.IsError || res.Code != "started" {
+ r.t.Fatalf("start %s with Design: %+v", project, res)
+ }
+ r.must(r.s.db.G.Where("id = ?", sp.ID).First(&sp).Error)
+ return sp, task, r.makerStep(task)
+}
+
+// makerStep is the task's newest Engineering step.
+func (r *hkRig) makerStep(task string) stepRecord {
+ r.t.Helper()
+ var s stepRecord
+ r.must(r.s.db.G.Where("task_id = ? AND specialist = ?", task, wire.SpecialistEngineering).Order("idx DESC").First(&s).Error)
+ return s
+}
+
+func (r *hkRig) authorize(l Lease, s stepRecord, purpose string) string {
+ r.t.Helper()
+ refused, err := r.s.Authorize(r.ctx, l, s.ID, s.Attempt, purpose, "", "")
+ r.must(err)
+ return refused
+}
+
+func (r *hkRig) revoke(id string) {
+ r.t.Helper()
+ var sp specialistRecord
+ r.must(r.s.db.G.Where("id = ?", id).First(&sp).Error)
+ if _, err := r.s.RevokeSpecialist(r.ctx, paul, id, wire.RevokeSpecialist{Revision: sp.Revision}); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+// dispatched is the newest dispatch command for the step.
+func (r *hkRig) dispatched(stepID string) (commandRecord, wire.DispatchCommand) {
+ r.t.Helper()
+ var c commandRecord
+ r.must(r.s.db.G.Where("kind = ? AND body LIKE ?", wire.FrameDispatch, `%"step_id":"`+stepID+`"%`).Order("seq DESC").First(&c).Error)
+ var d wire.DispatchCommand
+ r.must(json.Unmarshal([]byte(c.Body), &d))
+ return c, d
+}
+
+// cancels counts the cancel_step commands for the step.
+func (r *hkRig) cancels(stepID string) int64 {
+ return r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameCancelStep, `%"step_id":"`+stepID+`"%`)
+}
+
+// ackDispatches marks the step's dispatches delivered to its runner.
+func (r *hkRig) ackDispatches(stepID string) {
+ r.exec("UPDATE runner_commands SET acked_at = ? WHERE kind = ? AND body LIKE ?", r.now, wire.FrameDispatch, `%"step_id":"`+stepID+`"%`)
+}
+
+func (r *hkRig) stepNow(id string) stepRecord {
+ r.t.Helper()
+ var s stepRecord
+ r.must(r.s.db.G.Where("id = ?", id).First(&s).Error)
+ return s
+}
+
+var designCaps = `["branch.edit","page.render"]`
+
+// TestGrantForChecksTheGrant: grantFor finds the project's row, else the
+// team's, and grants it only while it holds exactly its profile's
+// capabilities, unrevoked, at its revision, given by its approver, who
+// is an owner now; and only for a profile on the menu. A project row
+// that fails any of these is no grant: the team's row does not stand in.
+func TestGrantForChecksTheGrant(t *testing.T) {
+ r, l, _ := grantRig(t)
+ sp := r.propose(l, "Patrix", "p_patrix")
+ r.must(r.answer(paul, sp, wire.ChoiceAdd, 1))
+ team := r.propose(l, "", "")
+ r.must(r.answer(paul, team, wire.ChoiceAdd, 1))
+ r.must(r.s.db.G.Where("id = ?", sp.ID).First(&sp).Error)
+ get := func(project string) string {
+ t.Helper()
+ var found *specialistRecord
+ r.must(r.tx(func(tx *txn) error {
+ var err error
+ found, err = tx.grantFor(specialist.ProfileDesign, project)
+ return err
+ }))
+ if found == nil {
+ return ""
+ }
+ return found.ID
+ }
+ if got := get("p_patrix"); got != sp.ID {
+ t.Fatalf("project row over the team's: %q", got)
+ }
+ if got := get("p_suite"); got != team.ID {
+ t.Fatalf("another project, the team's row: %q", got)
+ }
+ denied := func(what string) {
+ t.Helper()
+ if got := get("p_patrix"); got != "" {
+ t.Fatalf("%s: granted %q", what, got)
+ }
+ if got := get("p_suite"); got != team.ID {
+ t.Fatalf("%s: the team's row for Suite %q", what, got)
+ }
+ }
+ usable := func(what string) {
+ t.Helper()
+ if got := get("p_patrix"); got != sp.ID {
+ t.Fatalf("%s: %q", what, got)
+ }
+ }
+ // The approver (Paul approved both) demoted: neither holds.
+ r.exec("UPDATE members SET role = 'member' WHERE address = ?", paul)
+ if a, b := get("p_patrix"), get("p_suite"); a != "" || b != "" {
+ t.Fatalf("approver demoted: %q %q", a, b)
+ }
+ r.exec("UPDATE members SET role = 'owner' WHERE address = ?", paul)
+ usable("approver an owner again")
+ r.exec("UPDATE chat_specialists SET approver = ? WHERE id = ?", hkOwner, sp.ID)
+ denied("approver not the granter")
+ r.exec("UPDATE chat_specialists SET approver = ? WHERE id = ?", paul, sp.ID)
+ // The grants: one revoked, one missing, one extra, one at another
+ // revision, one by someone else, one twice.
+ var grants []grantRecord
+ r.must(r.s.db.G.Where("specialist_id = ?", sp.ID).Order("capability").Find(&grants).Error)
+ if len(grants) != 2 {
+ t.Fatalf("grants %+v", grants)
+ }
+ g := grants[1].ID
+ r.exec("UPDATE chat_capability_grants SET revoked_at = ?, revoked_by = ? WHERE id = ?", r.now, paul, g)
+ denied("a grant revoked")
+ r.exec("UPDATE chat_capability_grants SET revoked_at = NULL, revoked_by = '' WHERE id = ?", g)
+ usable("unrevoked")
+ r.exec("UPDATE chat_capability_grants SET capability = ? WHERE id = ?", specialist.CapabilityWebResearch, g)
+ denied("another capability in its place")
+ r.exec("UPDATE chat_capability_grants SET capability = ? WHERE id = ?", grants[0].Capability, g)
+ denied("one capability twice")
+ r.exec("UPDATE chat_capability_grants SET capability = ? WHERE id = ?", grants[1].Capability, g)
+ r.exec("INSERT INTO chat_capability_grants(id, specialist_id, capability, revision, granted_by, granted_at) VALUES ('g_extra', ?, ?, ?, ?, ?)", sp.ID, specialist.CapabilityWebResearch, sp.Revision, paul, r.now)
+ denied("a capability beside the profile's")
+ r.exec("DELETE FROM chat_capability_grants WHERE id = 'g_extra'")
+ r.exec("UPDATE chat_capability_grants SET revoked_at = ? WHERE id = ?", r.now, g)
+ r.exec("INSERT INTO chat_capability_grants(id, specialist_id, capability, revision, granted_by, granted_at) VALUES ('g_extra', ?, ?, ?, ?, ?)", sp.ID, grants[0].Capability, sp.Revision, paul, r.now)
+ denied("one missing, the other twice")
+ r.exec("DELETE FROM chat_capability_grants WHERE id = 'g_extra'")
+ denied("one missing")
+ r.exec("UPDATE chat_capability_grants SET revoked_at = NULL WHERE id = ?", g)
+ r.exec("UPDATE chat_capability_grants SET revision = revision - 1 WHERE id = ?", g)
+ denied("a grant at another revision")
+ r.exec("UPDATE chat_capability_grants SET revision = revision + 1 WHERE id = ?", g)
+ r.exec("UPDATE chat_capability_grants SET granted_by = ? WHERE id = ?", hkOwner, g)
+ denied("granted by someone else")
+ r.exec("UPDATE chat_capability_grants SET granted_by = ? WHERE id = ?", paul, g)
+ r.exec("UPDATE chat_specialists SET revision = revision + 1 WHERE id = ?", sp.ID)
+ denied("the specialist moved on from its grants")
+ r.exec("UPDATE chat_specialists SET revision = revision - 1 WHERE id = ?", sp.ID)
+ r.exec("UPDATE chat_specialists SET approver = '' WHERE id = ?", sp.ID)
+ r.exec("UPDATE chat_capability_grants SET granted_by = '' WHERE specialist_id = ?", sp.ID)
+ r.exec("INSERT INTO members(address, active, role) VALUES ('', 1, 'owner')")
+ denied("no approver")
+ r.exec("DELETE FROM members WHERE address = ''")
+ r.exec("UPDATE chat_specialists SET approver = ? WHERE id = ?", paul, sp.ID)
+ r.exec("UPDATE chat_capability_grants SET granted_by = ? WHERE specialist_id = ?", paul, sp.ID)
+ usable("restored")
+ // A profile missing from the menu: no grant, for any row of it.
+ r.exec("UPDATE chat_specialists SET profile = 'design-v0' WHERE profile = ?", specialist.ProfileDesign)
+ var found *specialistRecord
+ r.must(r.tx(func(tx *txn) error {
+ var err error
+ found, err = tx.grantFor("design-v0", "p_patrix")
+ return err
+ }))
+ if found != nil {
+ t.Fatalf("a profile off the menu: %+v", found)
+ }
+ // Even one with no grants to compare (an empty profile would match).
+ r.exec("UPDATE chat_capability_grants SET revoked_at = ? WHERE specialist_id = ?", r.now, sp.ID)
+ r.must(r.tx(func(tx *txn) error {
+ var err error
+ found, err = tx.grantFor("design-v0", "p_patrix")
+ return err
+ }))
+ if found != nil {
+ t.Fatalf("a profile off the menu with no grants: %+v", found)
+ }
+}
+
+// TestDesignDispatchBinds: the Design step's dispatch records its full
+// binding on the step and in the command (id, revision, project,
+// profile, capabilities) and appends a specialist.used audit row in the
+// dispatch's transaction, naming no credential. A step bound to the
+// team's row records the team's scope.
+func TestDesignDispatchBinds(t *testing.T) {
+ r, l, audit := grantRig(t)
+ sp, task, s := r.designStarted(l, "Patrix")
+ if s.SpecialistID != sp.ID || s.SpecialistRevision != sp.Revision || s.SpecialistProject != "p_patrix" || s.SpecialistCaps != designCaps {
+ t.Fatalf("binding %q %d %q %q", s.SpecialistID, s.SpecialistRevision, s.SpecialistProject, s.SpecialistCaps)
+ }
+ _, d := r.dispatched(s.ID)
+ if d.SpecialistID != sp.ID || d.SpecialistRevision != sp.Revision || d.SpecialistProject != "p_patrix" || d.Profile != specialist.ProfileDesign || strings.Join(d.Capabilities, ",") != "branch.edit,page.render" {
+ t.Fatalf("dispatch binding %+v", d)
+ }
+ if !wire.ValidSpecialistBinding(&d) {
+ t.Fatalf("the wire refuses the binding %+v", d)
+ }
+ var used []specialistAuditRecord
+ r.must(r.s.db.G.Where("specialist_id = ? AND action = ?", sp.ID, "used").Find(&used).Error)
+ if len(used) != 1 || used[0].Revision != sp.Revision || !strings.Contains(used[0].Detail, "task="+task) || !strings.Contains(used[0].Detail, "step="+s.ID) || !strings.Contains(used[0].Detail, "capabilities=branch.edit,page.render") {
+ t.Fatalf("used rows %+v", used)
+ }
+ n := 0
+ for _, a := range *audit {
+ if strings.Contains(a, " specialist.used "+sp.ID+"@") {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatalf("instance audit %q", *audit)
+ }
+ // Placed again (a new attempt): bound again, audited again.
+ r.must(r.tx(func(tx *txn) error {
+ k, err := tx.loadTask(task)
+ if err != nil {
+ return err
+ }
+ st := tx.mustStep(s.ID)
+ if err := tx.replace(&k, &st); err != nil {
+ return err
+ }
+ return tx.saveStep(&st, &k)
+ }))
+ if s2 := r.stepNow(s.ID); s2.Attempt != 2 || s2.SpecialistID != sp.ID || r.count("SELECT count(*) FROM chat_specialist_audit WHERE specialist_id = ? AND action = 'used'", sp.ID) != 2 {
+ t.Fatalf("second attempt %+v", s2)
+ }
+ // An attempt whose step is bound to something the grant no longer is
+ // (here, another revision) is not dispatched: it ends cancelled.
+ r.exec("UPDATE chat_steps SET specialist_revision = specialist_revision + 5 WHERE id = ?", s.ID)
+ r.must(r.tx(func(tx *txn) error {
+ k, err := tx.loadTask(task)
+ if err != nil {
+ return err
+ }
+ st := tx.mustStep(s.ID)
+ if err := tx.replace(&k, &st); err != nil {
+ return err
+ }
+ if st.State != wire.StepCancelled || st.Reason != reasonSpecialistNoGrant {
+ t.Fatalf("a mismatched binding dispatched %+v", st)
+ }
+ return tx.saveStep(&st, &k)
+ }))
+
+ // A team row: its scope is the team's.
+ team := r.propose(l, "", "")
+ r.must(r.answer(paul, team, wire.ChoiceAdd, 1))
+ r.must(r.s.db.G.Where("id = ?", team.ID).First(&team).Error)
+ k := r.teamTask(l, "k_suite_team", "p_suite", team.ID)
+ ts := r.makerStep(k)
+ if ts.SpecialistID != team.ID || ts.SpecialistProject != "" || ts.SpecialistRevision != team.Revision {
+ t.Fatalf("team binding %+v", ts)
+ }
+}
+
+// mustStep reads a step in the transaction (test helper).
+func (t *txn) mustStep(id string) stepRecord {
+ var s stepRecord
+ _ = t.db.Where("id = ?", id).First(&s).Error
+ return s
+}
+
+// teamTask records a task in project for Paul with maker as its maker
+// and starts it (as task 17's routing will): its step dispatched.
+func (r *hkRig) teamTask(l Lease, id, project, maker string) string {
+ r.t.Helper()
+ r.must(r.s.db.G.Create(&taskRecord{ID: id, ProjectID: project, Title: "Team design", Stage: wire.StageNoted, Creator: paul, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Branch: "equipo/" + id}).Error)
+ r.must(r.tx(func(tx *txn) error {
+ res, err := tx.startTask(turnRecord{ID: "t_team_" + id, Person: paul, Kind: wire.TurnPerson}, id, "", maker)
+ if err == nil && res.IsError {
+ r.t.Fatalf("start %s: %+v", id, res)
+ }
+ return err
+ }))
+ return id
+}
+
+// TestDesignRevokeBeforeStart: revoked between dispatch and start. A
+// dispatch the runner never took is retired and the step ends cancelled
+// at once (nothing ran); one it took gets the ordinary cancel (asked to
+// stop, its end reported), and its start is refused from then on.
+// Either way the task waits, not ended.
+func TestDesignRevokeBeforeStart(t *testing.T) {
+ r, l, _ := grantRig(t)
+ sp, task, s := r.designStarted(l, "Patrix")
+ r.revoke(sp.ID)
+ got := r.stepNow(s.ID)
+ if got.State != wire.StepCancelled || got.Reason != reasonSpecialistNoGrant || !got.Terminated {
+ t.Fatalf("undelivered step after revoke %+v", got)
+ }
+ if c, _ := r.dispatched(s.ID); c.AckedAt == nil {
+ t.Fatal("its dispatch was not retired")
+ }
+ if n := r.cancels(s.ID); n != 0 {
+ t.Fatalf("%d cancels for a dispatch never delivered", n)
+ }
+ if refused := r.authorize(l, got, ""); refused == "" {
+ t.Fatal("started after revoke")
+ }
+ if k := r.load(task); wire.FinalStage(k.Stage) || k.MakerSpecialistID != sp.ID {
+ t.Fatalf("task after revoke %+v", k)
+ }
+
+ // Delivered, not started: asked to stop; its start refused.
+ sp2, task2, s2 := r.designStarted(l, "Suite")
+ r.ackDispatches(s2.ID)
+ r.revoke(sp2.ID)
+ got = r.stepNow(s2.ID)
+ if got.State != wire.StepQueued || got.Terminated || r.cancels(s2.ID) != 1 {
+ t.Fatalf("delivered step after revoke %+v, %d cancels", got, r.cancels(s2.ID))
+ }
+ if refused := r.authorize(l, got, ""); refused != reasonSpecialistNoGrant {
+ t.Fatalf("start of a revoked step: %q", refused)
+ }
+ if r.stepNow(s2.ID).StartedAt != nil {
+ t.Fatal("a refused start recorded a start")
+ }
+ r.must(r.tx(func(tx *txn) error {
+ return tx.stepReport(l, &wire.StepReport{TaskID: task2, StepID: s2.ID, Attempt: s2.Attempt, State: wire.StepCancelled, Reason: "cancelled", Termination: true})
+ }))
+ if got := r.stepNow(s2.ID); got.State != wire.StepCancelled || !got.Terminated {
+ t.Fatalf("after its end %+v", got)
+ }
+ if k := r.load(task2); wire.FinalStage(k.Stage) {
+ t.Fatalf("task ended %+v", k)
+ }
+}
+
+// TestDesignRevokeBetweenRenders: a render is granted while the binding
+// holds; after a revoke the next is refused, and so is the pre-push
+// check; the running step gets one cancel.
+func TestDesignRevokeBetweenRenders(t *testing.T) {
+ r, l, _ := grantRig(t)
+ sp, _, s := r.designStarted(l, "Patrix")
+ // Started before its dispatch's ack was applied (both in flight).
+ if refused := r.authorize(l, s, ""); refused != "" {
+ t.Fatalf("start %q", refused)
+ }
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused != "" {
+ t.Fatalf("first render %q", refused)
+ }
+ r.revoke(sp.ID)
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("a render after revoke")
+ }
+ if refused := r.authorize(l, s, ""); refused == "" {
+ t.Fatal("a push check after revoke")
+ }
+ if got := r.stepNow(s.ID); got.StartedAt == nil || wire.StepTerminal(got.State) || r.cancels(s.ID) != 1 {
+ t.Fatalf("running step after revoke %+v, %d cancels", got, r.cancels(s.ID))
+ }
+}
+
+// TestRenderLeaseNeedsPageRender: a page_render check is granted only
+// to a step bound to a specialist whose binding holds page.render: never
+// to Engineering's own step, nor to a Research step, nor below
+// ProtocolDesign; an unknown purpose is refused for every step and
+// records no start; merge_request only on a merge step.
+func TestRenderLeaseNeedsPageRender(t *testing.T) {
+ r, l, _ := grantRig(t)
+ _, _, s := r.designStarted(l, "Patrix")
+ eng := r.plainTask(l, "k_plain")
+ for _, purpose := range []string{wire.LeasePurposeRender, "page_render2", "something", wire.LeasePurposeMerge} {
+ if refused := r.authorize(l, eng, purpose); refused == "" {
+ t.Fatalf("Engineering's step granted %q", purpose)
+ }
+ }
+ if got := r.stepNow(eng.ID); got.StartedAt != nil {
+ t.Fatal("a refused purpose recorded a start")
+ }
+ if refused := r.authorize(l, eng, ""); refused != "" {
+ t.Fatalf("Engineering's start %q", refused)
+ }
+ for _, purpose := range []string{"page_render2", "something", wire.LeasePurposeMerge} {
+ if refused := r.authorize(l, s, purpose); refused == "" {
+ t.Fatalf("Design's step granted %q", purpose)
+ }
+ }
+ // Bound, but its capabilities as recorded lack page.render: the
+ // binding no longer matches, refused.
+ r.exec("UPDATE chat_steps SET specialist_caps = ? WHERE id = ?", `["branch.edit"]`, s.ID)
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("render without page.render in the binding")
+ }
+ r.exec("UPDATE chat_steps SET specialist_caps = ? WHERE id = ?", designCaps, s.ID)
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused != "" {
+ t.Fatalf("render restored %q", refused)
+ }
+ // The task's maker is not the specialist the step is bound to.
+ k := r.load(s.TaskID)
+ r.exec("UPDATE chat_tasks SET maker_specialist_id = '' WHERE id = ?", k.ID)
+ if refused := r.authorize(l, s, ""); refused == "" {
+ t.Fatal("a bound step on a task with no maker")
+ }
+ other, _, _ := r.designStarted(l, "Suite")
+ r.exec("UPDATE chat_tasks SET maker_specialist_id = ? WHERE id = ?", other.ID, k.ID)
+ if refused := r.authorize(l, s, ""); refused == "" {
+ t.Fatal("a step bound to one specialist on a task made by another")
+ }
+ r.exec("UPDATE chat_tasks SET maker_specialist_id = ? WHERE id = ?", k.MakerSpecialistID, k.ID)
+ // Below ProtocolDesign a Design step is never granted.
+ old := l
+ old.Protocol = wire.ProtocolDesign - 1
+ if refused := r.authorize(old, s, ""); refused == "" {
+ t.Fatal("a Design step's lease below 36")
+ }
+ // A Research step (bound to web.research) never renders.
+ rs := r.researchStep(l, "k_research")
+ if refused := r.authorize(l, rs, ""); refused != "" {
+ t.Fatalf("Research start %q", refused)
+ }
+ if refused := r.authorize(l, rs, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("a Research step rendered")
+ }
+ // A maker whose binding holds but has no page.render (research-v1 as
+ // a maker, which routing will refuse): it starts, never renders.
+ var research specialistRecord
+ r.must(r.s.db.G.Where("profile = ? AND state = ?", specialist.ProfileResearch, wire.SpecialistActive).First(&research).Error)
+ rm := r.makerStep(r.teamTask(l, "k_rmaker", "p_patrix", research.ID))
+ if rm.SpecialistID != research.ID || rm.SpecialistCaps != `["web.research"]` {
+ t.Fatalf("research maker binding %+v", rm)
+ }
+ if refused := r.authorize(l, rm, ""); refused != "" {
+ t.Fatalf("research maker start %q", refused)
+ }
+ if refused := r.authorize(l, rm, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("a maker without page.render rendered")
+ }
+}
+
+// plainTask records and starts an Engineering task for Paul in Patrix.
+func (r *hkRig) plainTask(l Lease, id string) stepRecord {
+ r.t.Helper()
+ r.teamTask(l, id, "p_patrix", "")
+ s := r.makerStep(id)
+ if s.SpecialistID != "" || s.SpecialistCaps != "" {
+ r.t.Fatalf("Engineering bound %+v", s)
+ }
+ return s
+}
+
+// researchStep is a Research step of a new task in Patrix placed on
+// RUNNER1 under the team's research-v1 grant, bound as dispatch binds
+// it.
+func (r *hkRig) researchStep(l Lease, task string) stepRecord {
+ r.t.Helper()
+ var sp specialistRecord
+ r.s.db.G.Where("profile = ? AND state = ? AND project_id = ''", specialist.ProfileResearch, wire.SpecialistActive).Limit(1).Find(&sp)
+ if sp.ID == "" {
+ sp = approvedResearch(r, paul)
+ }
+ var g grantRecord
+ r.must(r.s.db.G.Where("specialist_id = ? AND revoked_at IS NULL", sp.ID).First(&g).Error)
+ r.must(r.s.db.G.Create(&taskRecord{ID: task, ProjectID: "p_patrix", Title: "Look it up", Stage: wire.StageInProgress, Creator: paul, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Branch: "equipo/" + task}).Error)
+ s := stepRecord{ID: "s_" + task, TaskID: task, Idx: 1, Specialist: wire.SpecialistResearch, Person: paul, State: wire.StepQueued, Attempt: 1, RunnerID: "RUNNER1", ResearchGrant: g.ID, ResearchGrantRevision: sp.Revision, SpecialistID: sp.ID, SpecialistRevision: sp.Revision, SpecialistCaps: `["web.research"]`, CreatedAt: r.now, UpdatedAt: r.now}
+ r.must(r.s.db.G.Create(&s).Error)
+ return s
+}
+
+// TestResearchLegacyEmptyBinding: a Research step queued or running at
+// the upgrade has no binding (only its grant id): its start is checked
+// as before, against the grant the task's project resolves to now; a
+// new one's binding is checked too; revoking cancels both.
+func TestResearchLegacyEmptyBinding(t *testing.T) {
+ r, l, _ := grantRig(t)
+ bound := r.researchStep(l, "k_bound")
+ legacy := r.researchStep(l, "k_legacy")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '' WHERE id = ?", legacy.ID)
+ running := r.researchStep(l, "k_running")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', state = ?, started_at = ? WHERE id = ?", wire.StepRunning, r.now, running.ID)
+ for _, s := range []stepRecord{bound, legacy, r.stepNow(running.ID)} {
+ if refused := r.authorize(l, s, ""); refused != "" {
+ t.Fatalf("%s start %q", s.ID, refused)
+ }
+ }
+ // A bound step whose binding no longer matches is refused.
+ r.exec("UPDATE chat_steps SET specialist_revision = specialist_revision + 1 WHERE id = ?", bound.ID)
+ if refused := r.authorize(l, r.stepNow(bound.ID), ""); refused != wire.ReasonResearchNoGrant {
+ t.Fatalf("a mismatched binding: %q", refused)
+ }
+ var sp specialistRecord
+ r.must(r.s.db.G.Where("profile = ? AND state = ?", specialist.ProfileResearch, wire.SpecialistActive).First(&sp).Error)
+ r.revoke(sp.ID)
+ if got := r.stepNow(legacy.ID); got.State != wire.StepCancelled || got.Reason != wire.ReasonResearchNoGrant {
+ t.Fatalf("legacy queued after revoke %+v", got)
+ }
+ if got := r.stepNow(running.ID); got.State != wire.StepRunning || r.cancels(running.ID) != 1 {
+ t.Fatalf("legacy running after revoke %+v", got)
+ }
+ if refused := r.authorize(l, r.stepNow(running.ID), ""); refused != wire.ReasonResearchNoGrant {
+ t.Fatalf("legacy running start after revoke %q", refused)
+ }
+}
+
+// TestResearchDispatchBinds: dispatching Research records the full
+// binding of the grant the task's project resolves to.
+func TestResearchDispatchBinds(t *testing.T) {
+ r, l, _ := grantRig(t)
+ s := r.researchStep(l, "k_r")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', research_grant = '', runner_id = '' WHERE id = ?", s.ID)
+ r.must(r.s.db.G.Create(&researchSourceRecord{StepID: s.ID, Idx: 0, SourceID: "src1", URL: "https://example.com/", Origin: wire.ResearchOriginPerson, Approved: true}).Error)
+ r.exec("CREATE TABLE runners (id text, person text, role text, label text, revoked_at datetime, removing_at datetime, tainted_at datetime)")
+ r.exec("INSERT INTO runners(id, person, role) VALUES ('RUNNER1', ?, 'primary')", paul)
+ var sp specialistRecord
+ r.must(r.s.db.G.Where("profile = ? AND state = ?", specialist.ProfileResearch, wire.SpecialistActive).First(&sp).Error)
+ dispatch := func() stepRecord {
+ t.Helper()
+ var st stepRecord
+ r.must(r.tx(func(tx *txn) error {
+ k, err := tx.loadTask(s.TaskID)
+ if err != nil {
+ return err
+ }
+ st = tx.mustStep(s.ID)
+ if err := tx.dispatchResearch(&k, &st); err != nil {
+ return err
+ }
+ return tx.saveStep(&st, &k)
+ }))
+ return st
+ }
+ if st := dispatch(); st.SpecialistID != sp.ID || st.SpecialistRevision != sp.Revision || st.SpecialistProject != "" || st.SpecialistCaps != `["web.research"]` {
+ t.Fatalf("Research binding %+v", st)
+ }
+ // Patrix gets its own research-v1 row: a Patrix task's Research binds
+ // to it (the project's row over the team's), and is sent, audited.
+ own := researchRow(r, "sp_rpatrix", "p_patrix")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', research_grant = '', placement = '' WHERE id = ?", s.ID)
+ r.must(r.s.db.G.Create(&researchAddressRecord{RunnerID: "RUNNER1", Source: "hello", Address: "93.184.216.34", SeenAt: r.now}).Error)
+ r.must(r.s.db.G.Create(&researchPrefixRecord{RunnerID: "RUNNER1", Prefix: "93.184.216.0/24", ConfirmedBy: paul, ConfirmedAt: r.now}).Error)
+ st := dispatch()
+ if st.SpecialistID != own.ID || st.SpecialistProject != "p_patrix" || st.RunnerID != "RUNNER1" {
+ t.Fatalf("Patrix Research binding %+v", st)
+ }
+ if n := r.count("SELECT count(*) FROM chat_specialist_audit WHERE specialist_id = ? AND action = 'used' AND detail LIKE ?", own.ID, "%step="+s.ID+"%"); n != 1 {
+ t.Fatalf("%d used rows for the Research dispatch", n)
+ }
+ if refused := r.authorize(l, r.stepNow(s.ID), ""); refused != "" {
+ t.Fatalf("Patrix Research start %q", refused)
+ }
+ // Bound earlier to what no longer holds: ends cancelled at dispatch.
+ r.exec("UPDATE chat_steps SET specialist_revision = specialist_revision + 1 WHERE id = ?", s.ID)
+ if st := dispatch(); st.State != wire.StepCancelled || st.Reason != wire.ReasonResearchNoGrant {
+ t.Fatalf("a mismatched Research binding dispatched %+v", st)
+ }
+ // research asks for the task's project's grant: Patrix's own, with
+ // the team's revoked.
+ r.revoke(sp.ID)
+ turn := r.asked("t_research", wire.LaneCoordinator, "Look up https://example.com/ for the Patrix task.")
+ r.must(r.s.db.G.Create(&taskRecord{ID: "k_r2", ProjectID: "p_patrix", Title: "Look again", Stage: wire.StageNoted, Creator: paul, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Branch: "equipo/k_r2"}).Error)
+ if res := r.call(l, turn.ID, wire.ToolResearch, map[string]any{"task": "k_r2", "question": "What does the page say?", "urls": []string{"https://example.com/"}}); res.IsError {
+ t.Fatalf("research in Patrix with Patrix's own grant: %+v", res)
+ }
+}
+
+// researchRow writes an active research-v1 row for project, granted by
+// Paul as an Add does (the menu does not propose one per project yet).
+func researchRow(r *hkRig, id, project string) specialistRecord {
+ r.t.Helper()
+ sp := specialistRecord{ID: id, Profile: specialist.ProfileResearch, ProjectID: project, Name: "Research", Brief: "Look things up.", State: wire.SpecialistActive, Revision: 2, Approver: paul, ApprovedAt: &r.now, CreatedAt: r.now, UpdatedAt: r.now}
+ r.must(r.s.db.G.Create(&sp).Error)
+ r.must(r.s.db.G.Create(&grantRecord{ID: "g_" + id, SpecialistID: id, Capability: specialist.CapabilityWebResearch, Revision: 2, GrantedBy: paul, GrantedAt: r.now}).Error)
+ return sp
+}
+
+// TestResearchRevokeByScope: revoking one research-v1 row cancels only
+// the Research that runs under it: steps bound to it, steps from before
+// bindings dispatched under its grant, and steps not yet dispatched in a
+// project that resolves to it. Research under Patrix's own row is left
+// when the team's is revoked, and the other way round.
+func TestResearchRevokeByScope(t *testing.T) {
+ r, l, _ := grantRig(t)
+ team := approvedResearch(r, paul)
+ r.must(r.s.db.G.Where("id = ?", team.ID).First(&team).Error)
+ own := researchRow(r, "sp_rpatrix", "p_patrix")
+ ownBound := r.researchStep(l, "k_own_bound")
+ r.exec("UPDATE chat_steps SET specialist_id = ?, specialist_project = 'p_patrix', research_grant = 'g_sp_rpatrix' WHERE id = ?", own.ID, ownBound.ID)
+ ownLegacy := r.researchStep(l, "k_own_legacy")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', research_grant = 'g_sp_rpatrix' WHERE id = ?", ownLegacy.ID)
+ patrixWaiting := r.researchStep(l, "k_patrix_waiting")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', research_grant = '', runner_id = '', placement = ? WHERE id = ?", wire.PlacementBoundary, patrixWaiting.ID)
+ suiteWaiting := r.researchStep(l, "k_suite_waiting")
+ r.exec("UPDATE chat_tasks SET project_id = 'p_suite' WHERE id = 'k_suite_waiting'")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', research_grant = '', runner_id = '', placement = ? WHERE id = ?", wire.PlacementBoundary, suiteWaiting.ID)
+ teamBound := r.researchStep(l, "k_team_bound")
+ ended := func(s stepRecord) bool { return r.stepNow(s.ID).State == wire.StepCancelled }
+ r.revoke(team.ID)
+ if !ended(teamBound) || !ended(suiteWaiting) {
+ t.Fatalf("the team's Research after its revoke: %+v %+v", r.stepNow(teamBound.ID), r.stepNow(suiteWaiting.ID))
+ }
+ for _, s := range []stepRecord{ownBound, ownLegacy, patrixWaiting} {
+ if ended(s) {
+ t.Fatalf("Patrix's own Research %s cancelled by the team's revoke", s.ID)
+ }
+ }
+ // A Suite step waiting with no grant at all: not Patrix's to cancel.
+ suiteLater := r.researchStep(l, "k_suite_later")
+ r.exec("UPDATE chat_tasks SET project_id = 'p_suite' WHERE id = 'k_suite_later'")
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_caps = '', research_grant = '', runner_id = '', placement = ? WHERE id = ?", wire.PlacementBoundary, suiteLater.ID)
+ r.revoke(own.ID)
+ for _, s := range []stepRecord{ownBound, ownLegacy, patrixWaiting} {
+ if !ended(s) {
+ t.Fatalf("Patrix's Research %s after Patrix's revoke %+v", s.ID, r.stepNow(s.ID))
+ }
+ }
+ if ended(suiteLater) {
+ t.Fatal("Patrix's revoke cancelled Suite's Research")
+ }
+}
+
+// TestDesignRevokeBeforePush: revoked between commit and push. On the
+// primary the pre-push check is refused; a worker's commit waiting for
+// the primary to push it is withdrawn at the revoke (its publish
+// command retired, its transfers closed) and its publication check is
+// refused; a binding that stops holding without a revoke (the approver
+// demoted) refuses the publication too.
+func TestDesignRevokeBeforePush(t *testing.T) {
+ r, l, _ := grantRig(t)
+ sp, task, s := r.designStarted(l, "Patrix")
+ r.ackDispatches(s.ID)
+ if refused := r.authorize(l, s, ""); refused != "" {
+ t.Fatalf("start %q", refused)
+ }
+ // A worker's commit, as if it ran there: the primary is to push it.
+ r.exec("UPDATE chat_steps SET runner_id = 'WORKER1', state = ?, candidate_sha = ?, publication = ?, publication_id = 'pb_1' WHERE id = ?", wire.StepDone, strings.Repeat("a", 40), wire.PublicationPending, s.ID)
+ r.must(r.s.db.G.Create(&transferRecord{ID: "tr_out", Person: paul, FromRunner: "WORKER1", ToRunner: "RUNNER1", TaskID: task, StepID: s.ID, Attempt: s.Attempt, Direction: wire.TransferOutbound, State: transferComplete, ExpiresAt: r.now.Add(wire.TransferTTL), CreatedAt: r.now}).Error)
+ r.must(r.s.db.G.Create(&commandRecord{Person: paul, RunnerID: "RUNNER1", Kind: wire.FramePublish, Body: `{"publication":"pb_1","task_id":"` + task + `","step_id":"` + s.ID + `","attempt":1}`, CreatedAt: r.now}).Error)
+ publication := func() string {
+ t.Helper()
+ refused, err := r.s.AuthorizePublication(r.ctx, l, s.ID, s.Attempt, "pb_1")
+ r.must(err)
+ return refused
+ }
+ if refused := publication(); refused != "" {
+ t.Fatalf("publication while bound %q", refused)
+ }
+ r.exec("UPDATE members SET role = 'member' WHERE address = ?", paul)
+ if refused := publication(); refused == "" {
+ t.Fatal("publication with the approver demoted")
+ }
+ r.exec("UPDATE members SET role = 'owner' WHERE address = ?", paul)
+ if refused := publication(); refused != "" {
+ t.Fatalf("publication restored %q", refused)
+ }
+ r.revoke(sp.ID)
+ got := r.stepNow(s.ID)
+ if got.Publication != wire.PublicationFailed || got.Reason != "cancelled" {
+ t.Fatalf("publication after revoke %+v", got)
+ }
+ if n := r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND acked_at IS NULL", wire.FramePublish); n != 0 {
+ t.Fatalf("%d publish commands still to send", n)
+ }
+ if n := r.count("SELECT count(*) FROM runner_transfers WHERE id = 'tr_out' AND state = ?", transferClosed); n != 1 {
+ t.Fatal("its transfer is open")
+ }
+ if refused := publication(); refused == "" {
+ t.Fatal("publication after revoke")
+ }
+
+ // On the primary: its own pre-push check after the revoke. A commit
+ // still being uploaded is never pushed: its transfer is closed.
+ sp2, task2, s2 := r.designStarted(l, "Suite")
+ r.ackDispatches(s2.ID)
+ if refused := r.authorize(l, s2, ""); refused != "" {
+ t.Fatalf("Suite start %q", refused)
+ }
+ r.must(r.s.db.G.Create(&transferRecord{ID: "tr_up", Person: paul, FromRunner: "WORKER1", ToRunner: "RUNNER1", TaskID: task2, StepID: s2.ID, Attempt: s2.Attempt, Direction: wire.TransferOutbound, State: transferOpen, ExpiresAt: r.now.Add(wire.TransferTTL), CreatedAt: r.now}).Error)
+ r.revoke(sp2.ID)
+ if refused := r.authorize(l, s2, ""); refused != reasonSpecialistNoGrant {
+ t.Fatalf("Suite pre-push after revoke %q", refused)
+ }
+ if n := r.count("SELECT count(*) FROM runner_transfers WHERE id = 'tr_up' AND state = ?", transferClosed); n != 1 {
+ t.Fatal("an upload of a revoked step's commit is open")
+ }
+}
+
+// TestPublicationNeedsTheMaker: a maker step's publication is refused
+// when the step is bound to another specialist than the task's maker, or
+// to none at all.
+func TestPublicationNeedsTheMaker(t *testing.T) {
+ r, l, _ := grantRig(t)
+ _, task, s := r.designStarted(l, "Patrix")
+ other, _, _ := r.designStarted(l, "Suite")
+ r.exec("UPDATE chat_steps SET runner_id = 'WORKER1', state = ?, candidate_sha = ?, publication = ?, publication_id = 'pb_1' WHERE id = ?", wire.StepDone, strings.Repeat("a", 40), wire.PublicationPending, s.ID)
+ publication := func() string {
+ t.Helper()
+ refused, err := r.s.AuthorizePublication(r.ctx, l, s.ID, s.Attempt, "pb_1")
+ r.must(err)
+ return refused
+ }
+ if refused := publication(); refused != "" {
+ t.Fatalf("bound %q", refused)
+ }
+ k := r.load(task)
+ r.exec("UPDATE chat_tasks SET maker_specialist_id = ? WHERE id = ?", other.ID, task)
+ if refused := publication(); refused == "" {
+ t.Fatal("published for a task made by another specialist")
+ }
+ r.exec("UPDATE chat_tasks SET maker_specialist_id = ? WHERE id = ?", k.MakerSpecialistID, task)
+ r.exec("UPDATE chat_steps SET specialist_id = '', specialist_revision = 0, specialist_project = '', specialist_caps = '' WHERE id = ?", s.ID)
+ if refused := publication(); refused == "" {
+ t.Fatal("published an unbound maker step")
+ }
+}
+
+// TestDesignApproverDemoted: the approver stops being an owner: no
+// start, no render; an owner again, both are granted (the binding is
+// unchanged); a lookup error denies.
+func TestDesignApproverDemoted(t *testing.T) {
+ r, l, _ := grantRig(t)
+ _, _, s := r.designStarted(l, "Patrix")
+ r.exec("UPDATE members SET role = 'member' WHERE address = ?", paul)
+ if refused := r.authorize(l, s, ""); refused != reasonSpecialistNoGrant {
+ t.Fatalf("start with the approver demoted %q", refused)
+ }
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("render with the approver demoted")
+ }
+ r.exec("UPDATE members SET active = 0, role = 'owner' WHERE address = ?", paul)
+ if refused := r.authorize(l, s, ""); refused == "" {
+ t.Fatal("start with the approver removed")
+ }
+ r.exec("UPDATE members SET active = 1 WHERE address = ?", paul)
+ if refused := r.authorize(l, s, ""); refused != "" {
+ t.Fatalf("an owner again %q", refused)
+ }
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused != "" {
+ t.Fatalf("render, an owner again %q", refused)
+ }
+}
+
+// TestDesignProfileOffTheMenu: a binding to a profile no longer on the
+// menu never holds, at start, render or dispatch.
+func TestDesignProfileOffTheMenu(t *testing.T) {
+ r, l, _ := grantRig(t)
+ sp, task, s := r.designStarted(l, "Patrix")
+ r.exec("UPDATE chat_specialists SET profile = 'design-v0' WHERE id = ?", sp.ID)
+ if refused := r.authorize(l, s, ""); refused == "" {
+ t.Fatal("start under a profile off the menu")
+ }
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("render under a profile off the menu")
+ }
+ r.must(r.tx(func(tx *txn) error {
+ k, err := tx.loadTask(task)
+ if err != nil {
+ return err
+ }
+ st := tx.mustStep(s.ID)
+ if err := tx.replace(&k, &st); err != nil {
+ return err
+ }
+ if st.State != wire.StepCancelled || st.Reason != reasonSpecialistNoGrant {
+ t.Fatalf("dispatched under a profile off the menu %+v", st)
+ }
+ return tx.saveStep(&st, &k)
+ }))
+}
+
+// TestDesignProjectRowOverTeamRow: a step bound to the team's Design in
+// Patrix stops holding once Patrix has its own Design (grantFor now
+// finds that row), while the team's binding in Suite holds.
+func TestDesignProjectRowOverTeamRow(t *testing.T) {
+ r, l, _ := grantRig(t)
+ team := r.propose(l, "", "")
+ r.must(r.answer(paul, team, wire.ChoiceAdd, 1))
+ r.must(r.s.db.G.Where("id = ?", team.ID).First(&team).Error)
+ patrix := r.makerStep(r.teamTask(l, "k_tp", "p_patrix", team.ID))
+ suite := r.makerStep(r.teamTask(l, "k_ts", "p_suite", team.ID))
+ for _, s := range []stepRecord{patrix, suite} {
+ if refused := r.authorize(l, s, wire.LeasePurposeRender); refused != "" {
+ t.Fatalf("%s render under the team's %q", s.ID, refused)
+ }
+ }
+ own := r.propose(l, "Patrix", "p_patrix")
+ r.must(r.answer(paul, own, wire.ChoiceAdd, 1))
+ if refused := r.authorize(l, patrix, wire.LeasePurposeRender); refused == "" {
+ t.Fatal("the team's binding held in Patrix over Patrix's own row")
+ }
+ if refused := r.authorize(l, suite, wire.LeasePurposeRender); refused != "" {
+ t.Fatalf("Suite under the team's %q", refused)
+ }
+ // A new step of the team-made Patrix task is not dispatched under
+ // Patrix's own row (it is not the task's maker): it ends cancelled.
+ r.must(r.tx(func(tx *txn) error {
+ k, err := tx.loadTask("k_tp")
+ if err != nil {
+ return err
+ }
+ n := stepRecord{ID: "s_tp2", TaskID: k.ID, Idx: patrix.Idx + 1, Specialist: wire.SpecialistEngineering, Person: paul, State: wire.StepQueued, Attempt: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ if err := tx.db.Create(&n).Error; err != nil {
+ return err
+ }
+ if err := tx.dispatchStep(&k, &n); err != nil {
+ return err
+ }
+ if n.State != wire.StepCancelled || n.SpecialistID != "" {
+ t.Fatalf("dispatched under Patrix's row %+v", n)
+ }
+ return tx.saveStep(&n, &k)
+ }))
+}
+
+// TestDesignRevokeOneProject: revoking Patrix's Design cancels Patrix's
+// Design step only; Suite's Design and Engineering's own step go on,
+// with no cancel and their starts granted.
+func TestDesignRevokeOneProject(t *testing.T) {
+ r, l, audit := grantRig(t)
+ patrix, _, ps := r.designStarted(l, "Patrix")
+ _, _, ss := r.designStarted(l, "Suite")
+ eng := r.plainTask(l, "k_plain")
+ for _, s := range []stepRecord{ps, ss, eng} {
+ r.ackDispatches(s.ID)
+ if refused := r.authorize(l, s, ""); refused != "" {
+ t.Fatalf("%s start %q", s.ID, refused)
+ }
+ }
+ r.exec("UPDATE chat_steps SET publication = ?, publication_id = 'pb_suite' WHERE id = ?", wire.PublicationPending, ss.ID)
+ before := len(*audit)
+ r.revoke(patrix.ID)
+ if got := r.stepNow(ss.ID); got.Publication != wire.PublicationPending {
+ t.Fatalf("Suite's publication after Patrix's revoke %+v", got)
+ }
+ if r.cancels(ps.ID) != 1 || r.cancels(ss.ID) != 0 || r.cancels(eng.ID) != 0 {
+ t.Fatalf("cancels %d %d %d", r.cancels(ps.ID), r.cancels(ss.ID), r.cancels(eng.ID))
+ }
+ if refused := r.authorize(l, ps, ""); refused == "" {
+ t.Fatal("Patrix's Design after its revoke")
+ }
+ for _, s := range []stepRecord{ss, eng} {
+ if refused := r.authorize(l, s, ""); refused != "" {
+ t.Fatalf("%s after Patrix's revoke %q", s.ID, refused)
+ }
+ if got := r.stepNow(s.ID); wire.StepTerminal(got.State) {
+ t.Fatalf("%s ended %+v", s.ID, got)
+ }
+ }
+ if refused := r.authorize(l, ss, wire.LeasePurposeRender); refused != "" {
+ t.Fatalf("Suite's render after Patrix's revoke %q", refused)
+ }
+ for _, a := range (*audit)[before:] {
+ if strings.Contains(a, "specialist.used") {
+ t.Fatalf("a revoke audited a use: %q", a)
+ }
+ }
+ // Engineering's step is not bound and audits no use.
+ if r.count("SELECT count(*) FROM chat_specialist_audit WHERE action = 'used' AND detail LIKE ?", "%step="+eng.ID+"%") != 0 {
+ t.Fatal("Engineering's dispatch audited a specialist use")
+ }
+}
+
+// TestDesignHeldStepAfterRevoke: a Design step not yet dispatched (held
+// for Research) ends cancelled at the revoke, and a dispatch later finds
+// no grant: it never runs as plain Engineering.
+func TestDesignHeldStepAfterRevoke(t *testing.T) {
+ r, l, _ := grantRig(t)
+ sp, task, s := r.designStarted(l, "Patrix")
+ held := stepRecord{ID: "s_held", TaskID: task, Idx: s.Idx + 1, Specialist: wire.SpecialistEngineering, Person: paul, State: wire.StepQueued, Attempt: 1, Placement: wire.PlacementResearch, CreatedAt: r.now, UpdatedAt: r.now}
+ r.must(r.s.db.G.Create(&held).Error)
+ r.revoke(sp.ID)
+ if got := r.stepNow(held.ID); got.State != wire.StepCancelled || got.Reason != reasonSpecialistNoGrant || !got.Terminated {
+ t.Fatalf("held step after revoke %+v", got)
+ }
+ // A new step of the task (a fix round, say) finds no grant at dispatch.
+ r.must(r.tx(func(tx *txn) error {
+ k, err := tx.loadTask(task)
+ if err != nil {
+ return err
+ }
+ n := stepRecord{ID: "s_next", TaskID: task, Idx: s.Idx + 2, Specialist: wire.SpecialistEngineering, Person: paul, State: wire.StepQueued, Attempt: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ if err := tx.db.Create(&n).Error; err != nil {
+ return err
+ }
+ if err := tx.dispatchStep(&k, &n); err != nil {
+ return err
+ }
+ if n.State != wire.StepCancelled || n.Reason != reasonSpecialistNoGrant || n.SpecialistID != "" {
+ t.Fatalf("dispatched after revoke %+v", n)
+ }
+ return tx.saveStep(&n, &k)
+ }))
+ if n := r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameDispatch, `%"step_id":"s_next"%`); n != 0 {
+ t.Fatalf("%d dispatches after revoke", n)
+ }
+}
diff --git a/internal/equipo/chat/specialists.go b/internal/equipo/chat/specialists.go
index 6e78c225..38c7801c 100644
--- a/internal/equipo/chat/specialists.go
+++ b/internal/equipo/chat/specialists.go
@@ -17,7 +17,7 @@ import (
// proposes a specialist from the closed menu (internal/specialist); one
// card asks the proposing owner; only an owner's Add, in one transaction,
// makes it active and writes its grants and audit row. Every later use
-// checks the grant again (researchGrant). The table is the team's: a
+// checks the grant again (grantFor, grants.go). The table is the team's: a
// specialist is not any one person's.
// specialistRecord is one data-defined specialist. Only Name, Brief and
@@ -122,9 +122,11 @@ const (
)
// scopedProfiles may be proposed for one project as well as the whole
-// team. Any other profile is the team's only: research-v1, whose grant
-// (researchGrant) knows one team-wide row until plan task 16 resolves it
-// per project, so a project's Research row would be used for every task.
+// team. Any other profile is the team's only: research-v1. Its grant
+// resolves per project now (researchGrant through grantFor), but a
+// project-scoped Add queues the specialist_added continuation, which
+// starts a task with that specialist as its maker, and Research is no
+// maker; it stays team-wide until that continuation checks the profile.
var scopedProfiles = []string{specialist.ProfileDesign}
// declineWindow is how long an owner's Not now holds a profile and scope
@@ -379,59 +381,45 @@ func (t *txn) specialistAudit(sp specialistRecord, action, actor string) error {
return t.s.authority.Audit(t.db, actor, "specialist."+action, sp.ID+"@"+sp.Profile)
}
-// researchGrant is the grant a Research step runs under (later slices
-// call it at dispatch and before each use). It is usable only when: one
-// research-v1 specialist is active; its profile is still on the menu;
-// exactly one grant is unrevoked, for web.research and nothing beside
-// it, at the specialist's current revision, given by its approver; and
-// that approver is an owner now, read in this transaction. Anything else
-// is ErrNoGrant; a lookup error is returned, and denies too.
-func (t *txn) researchGrant() (specialistRecord, grantRecord, error) {
- var rows []specialistRecord
- if err := t.db.Where("profile = ? AND state = ?", specialist.ProfileResearch, wire.SpecialistActive).Find(&rows).Error; err != nil {
- return specialistRecord{}, grantRecord{}, err
- }
- if len(rows) != 1 {
- return specialistRecord{}, grantRecord{}, ErrNoGrant
- }
- sp := rows[0]
- p, ok := specialist.Lookup(sp.Profile)
- if !ok || !slices.Equal(p.Capabilities, []string{specialist.CapabilityWebResearch}) {
- return specialistRecord{}, grantRecord{}, ErrNoGrant
- }
- var grants []grantRecord
- if err := t.db.Where("specialist_id = ? AND revoked_at IS NULL", sp.ID).Find(&grants).Error; err != nil {
+// researchGrant is the grant a Research step of a task in project runs
+// under (checked at dispatch and before each start): the research-v1
+// specialist grantFor finds for that project (its own row, else the
+// team's), whose one grant is web.research and nothing beside it, at its
+// revision, given by its approver, an owner now (usableGrant). Anything
+// else is ErrNoGrant; a lookup error is returned, and denies too.
+func (t *txn) researchGrant(project string) (specialistRecord, grantRecord, error) {
+ sp, grants, err := t.usableGrant(specialist.ProfileResearch, project)
+ if err != nil {
return specialistRecord{}, grantRecord{}, err
}
- if len(grants) != 1 {
- return specialistRecord{}, grantRecord{}, ErrNoGrant
- }
- g := grants[0]
- if g.Capability != specialist.CapabilityWebResearch || g.Revision != sp.Revision || sp.Approver == "" || g.GrantedBy != sp.Approver {
+ // usableGrant has checked the grants are exactly the profile's,
+ // web.research alone; the length check only guards the index.
+ if sp == nil || len(grants) != 1 {
return specialistRecord{}, grantRecord{}, ErrNoGrant
}
- if err := t.isOwner(sp.Approver); errors.Is(err, ErrForbidden) {
- return specialistRecord{}, grantRecord{}, ErrNoGrant
- } else if err != nil {
- return specialistRecord{}, grantRecord{}, err
- }
- return sp, g, nil
+ return *sp, grants[0], nil
}
-// cancelResearch cancels every unfinished Research step, in the revoke's
-// transaction. One that is queued (waiting for its fixed point, its card,
-// the inventory or a runner; dispatched; or authorized and deferred on
-// its runner) ends cancelled at once: its card is withdrawn, its dispatch
-// retired, a runner that may hold it is asked to cancel it, and the
-// Engineering it held is released. A running one gets the ordinary
-// cancel: its runner is asked to stop it and reports its end, and its
-// start authorization is refused from now on (authorizeResearch). There
-// is one Research specialist (research-v1), so every Research step is
-// its.
+// cancelResearch cancels every unfinished Research step that runs under
+// sp, in the revoke's transaction: one bound to it at dispatch; one from
+// before bindings (task 16) dispatched under one of its grants; and one
+// not yet dispatched whose task's project resolves to it
+// (researchResolvesTo). One that is queued (waiting for its fixed point,
+// its card, the inventory or a runner; dispatched; or authorized and
+// deferred on its runner) ends cancelled at once: its card is withdrawn,
+// its dispatch retired, a runner that may hold it is asked to cancel it,
+// and the Engineering it held is released. A running one gets the
+// ordinary cancel: its runner is asked to stop it and reports its end,
+// and its start authorization is refused from now on
+// (authorizeResearch).
func (t *txn) cancelResearch(sp specialistRecord) error {
if sp.Profile != specialist.ProfileResearch {
return nil
}
+ var grants []string
+ if err := t.db.Model(&grantRecord{}).Where("specialist_id = ?", sp.ID).Pluck("id", &grants).Error; err != nil {
+ return err
+ }
var rows []stepRecord
if err := t.db.Where("specialist = ? AND state IN ?", wire.SpecialistResearch, []string{wire.StepQueued, wire.StepRunning}).Order("created_at, id").Find(&rows).Error; err != nil {
return err
@@ -442,6 +430,19 @@ func (t *txn) cancelResearch(sp specialistRecord) error {
if err != nil {
return err
}
+ mine := s.SpecialistID == sp.ID
+ switch {
+ case s.SpecialistID != "":
+ case s.ResearchGrant != "":
+ mine = slices.Contains(grants, s.ResearchGrant)
+ default:
+ if mine, err = t.researchResolvesTo(sp, k.ProjectID); err != nil {
+ return err
+ }
+ }
+ if !mine {
+ continue
+ }
if err := t.retireResearch(*s); err != nil {
return err
}
@@ -462,8 +463,9 @@ func (t *txn) cancelResearch(sp specialistRecord) error {
// RevokeSpecialist is POST /api/v1/specialists/{id}/revoke: an owner,
// read in this transaction, revokes an active specialist at its current
-// revision. Its grants are revoked with an audit row, and its unfinished
-// Research steps cancelled (cancelResearch), in one transaction.
+// revision. Its grants are revoked with an audit row, and the steps
+// bound to it cancelled and their pending publications withdrawn
+// (cancelSpecialist), in one transaction.
func (s *Store) RevokeSpecialist(ctx context.Context, person, id string, in wire.RevokeSpecialist) (out wire.Specialist, err error) {
err = s.tx(ctx, func(t *txn) error {
if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
@@ -495,7 +497,7 @@ func (s *Store) RevokeSpecialist(ctx context.Context, person, id string, in wire
if err := t.specialistAudit(sp, auditRevoked, person); err != nil {
return err
}
- if err := t.cancelResearch(sp); err != nil {
+ if err := t.cancelSpecialist(sp); err != nil {
return err
}
out = specialistView(sp)
diff --git a/internal/equipo/chat/specialists_test.go b/internal/equipo/chat/specialists_test.go
index 1f8045ca..cbd7dda2 100644
--- a/internal/equipo/chat/specialists_test.go
+++ b/internal/equipo/chat/specialists_test.go
@@ -66,7 +66,7 @@ func (r *hkRig) grant() (specialistRecord, grantRecord, error) {
var g grantRecord
err := r.tx(func(t *txn) error {
var err error
- sp, g, err = t.researchGrant()
+ sp, g, err = t.researchGrant("")
return err
})
return sp, g, err
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 70d16522..27ea93e0 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -810,7 +810,7 @@ func (t *txn) writeStep(s *stepRecord) error {
}
s.Revision++
s.UpdatedAt = t.now()
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model").Updates(s).Error; err != nil {
+ if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "specialist_id", "specialist_revision", "specialist_project", "specialist_caps", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model").Updates(s).Error; err != nil {
return err
}
if s.Retired {
@@ -1108,6 +1108,23 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
if s.Specialist == wire.SpecialistResearch {
return t.dispatchResearch(k, s)
}
+ // A maker step of a task with a data specialist as its maker runs as
+ // that specialist, bound to its grant now (makerGrant); with no
+ // usable grant it ends cancelled here, and never runs as plain
+ // Engineering.
+ var maker *specialistRecord
+ if s.Specialist == wire.SpecialistEngineering && k.MakerSpecialistID != "" {
+ var err error
+ if maker, err = t.makerGrant(*k, *s); err != nil {
+ return err
+ }
+ if maker == nil {
+ now := t.now()
+ s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince, s.RunnerID = wire.StepCancelled, reasonSpecialistNoGrant, true, &now, "", nil, ""
+ return nil
+ }
+ bind(s, *maker)
+ }
var copyCommand *wire.CopyDispatch
if s.Specialist == wire.SpecialistCopy {
var err error
@@ -1266,6 +1283,15 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
return err
}
}
+ if maker != nil {
+ // The step's full binding (protocol 36; Encode refuses the
+ // dispatch below it, so it never runs there as plain
+ // Engineering), and the grant's use audited.
+ boundDispatch(&cmd, *maker)
+ if err := t.specialistUsed(*maker, *k, *s); err != nil {
+ return err
+ }
+ }
return t.commandTo(s.RunnerID, s.Person, wire.FrameDispatch, cmd)
}
diff --git a/internal/equipo/chat/transfers.go b/internal/equipo/chat/transfers.go
index 40570913..b0b03590 100644
--- a/internal/equipo/chat/transfers.go
+++ b/internal/equipo/chat/transfers.go
@@ -280,7 +280,8 @@ func (t *txn) published(l Lease, v *wire.PublishedReport) error {
// AuthorizePublication is the primary's confirmation immediately before
// it pushes a worker's commit: the publication is still the step's
-// pending one and the task is neither cancelled nor ended.
+// pending one, the task is neither cancelled nor ended, and a maker
+// step's binding still holds.
func (s *Store) AuthorizePublication(ctx context.Context, l Lease, stepID string, attempt int64, publication string) (refused string, err error) {
err = s.tx(ctx, func(t *txn) error {
if _, err := t.current(l); err != nil {
@@ -310,6 +311,17 @@ func (t *txn) authorizePublication(l Lease, stepID string, attempt int64, public
if primary != l.Runner.RunnerID || s.Attempt != attempt || s.PublicationID != publication || s.Publication != wire.PublicationPending || k.CancelRequested || wire.FinalStage(k.Stage) {
return "cancelled", nil
}
+ // A maker step's commit is pushed only while its binding holds
+ // (grantFor for the task's project, as at its start).
+ if s.SpecialistID != "" || k.MakerSpecialistID != "" && s.Specialist == wire.SpecialistEngineering {
+ holds, err := t.bindingHolds(s, k)
+ if err != nil {
+ return "", err
+ }
+ if !holds || s.SpecialistID != k.MakerSpecialistID {
+ return "cancelled", nil
+ }
+ }
return "", nil
}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index a20fdca3..4adcf31b 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2019,6 +2019,7 @@ var pageCopy = map[string]string{
"work.reason.research_no_grant": "it’s no longer on your team", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"work.reason.research_unsupported": "the runner needs an update to run Research", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"work.reason.research_no_inventory": "the primary machine reported no public internet address", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
+ "work.reason.specialist_no_grant": "it’s no longer on your team", // COPY REVIEW PENDING
"chat.card.research_sources": "Let Research read these pages?", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"chat.card.research_inventory": "Equipo detected these public internet addresses for your primary machine. Confirm they’re yours so Research can block pages served from them.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"chat.activity.research": "Asking Research to read some pages…", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)