oficina / equipo Public

Add confirmed repository access requests through Amadan

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev a6f12ff72ec9d53b4fc843bf992eadbf12ec88bc parent 0d91a4e
43 files changed, +1,484 −46
  • .rastrillo/budgets.txt +5 −5
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +21 −0
  • internal/equipo/chat/access_request.go +227 −0
  • internal/equipo/chat/access_request_test.go +194 −0
  • internal/equipo/chat/placement_edges_test.go +1 −1
  • internal/equipo/chat/projects.go +7 −1
  • internal/equipo/chat/runner.go +2 −0
  • internal/equipo/chat/stream.go +1 −1
  • internal/equipo/chat/tools.go +19 −2
  • internal/equipo/chat_page.go +5 −0
  • internal/equipo/chat_wiring.go +3 −0
  • internal/equipo/copy.go +18 −0
  • internal/equipo/migrations/0091_access_requests.sql +1 −0
  • internal/equipo/render.go +1 −1
  • internal/equipo/static/equipo.css +6 −3
  • internal/equipo/templates/access_card.html +11 −0
  • internal/equipo/templates/chat.html +1 −0
  • internal/runner/provider/actions.go +1 −1
  • internal/runner/thin/access.go +194 −0
  • internal/runner/thin/access_catalog.go +88 −0
  • internal/runner/thin/access_forge.go +94 −0
  • internal/runner/thin/access_test.go +343 −0
  • internal/runner/thin/claude.go +1 −1
  • internal/runner/thin/forge.go +10 −5
  • internal/runner/thin/link.go +8 −0
  • internal/runner/thin/mcp.go +2 −0
  • internal/runner/thin/run.go +9 −0
  • internal/runner/thin/state.go +1 −1
  • internal/thintest/access_browser_test.go +73 −0
  • internal/wire/access.go +70 −0
  • internal/wire/access_test.go +27 −0
  • internal/wire/api.go +11 −10
  • internal/wire/assistant_test.go +1 −1
  • internal/wire/frames.go +8 −3
  • internal/wire/mixed_protocol_test.go +1 −1
  • internal/wire/models_test.go +1 −1
  • internal/wire/opencode_test.go +1 −1
  • internal/wire/publish_test.go +1 −1
  • internal/wire/runners.go +12 −2
  • internal/wire/runners_test.go +1 −1
  • internal/wire/schedule_test.go +1 −1
  • internal/wire/usage_test.go +1 −1
  • internal/wire/warm_test.go +1 −1

CI cancelled — superseded by a newer push — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index ee502561..9dbf048b 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ 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 21028 - Shared web views, Oficina connection routes and consent, and the stopping display for abandoned moves. Measured 21028 source lines.
-size internal/wire 6448 - Shared protocol types, placement metadata and optional task stopping flag. No runner frame change. Measured 6448 source lines.
+size internal/equipo 21054 - Shared web views and Roster access confirmation and state presentation. Limits match measured lines.
+size internal/wire 6534 - Shared protocol types; protocol 26 adds durable confirmed access commands and state reports. Limits match measured lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 26411 18927 Shared runner state and execution helpers; placement prompt and durable notebook corrections. Measured 26379 source and 18927 test lines.
+size internal/runner/thin 26812 19270 Shared runner state and forge integration; durable access polling, grants and restart guards. Limits match measured lines.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -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 30325 - Transactional authority, dispatch, placement and job stops; abandonment proof and historical reports share the transaction. Measured 30325 source lines.
+size internal/equipo/chat 30577 - Transactional authority and dispatch; access proposals, person confirmation and approval continuation. Limits match measured lines.
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.
@@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 11062 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11062 test lines.
-size internal/thintest - 30810 Shared instance and browser harness for placement, job states and Oficina connections; abandon proof and late push history. Measured 30810 test lines.
+size internal/thintest - 30883 Shared instance/browser fixtures; access confirmation and four outcomes at two sizes and two themes. Limits match measured lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index ad073a3f..b75529e3 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4704,6 +4704,27 @@ All eight entries have individual `COPY REVIEW REQUIRED` markers. The API guide
## Plan 3 copy inventory (for Paul's review)
+| Key | Text | Use | Status |
+| --- | --- | --- | --- |
+| `access.title` | Ask for access | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.confirm` | Ask Amadan for access to %s? | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.ask` | Ask for access | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.approve` | Approve on Amadan | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.aside` | Not now | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.reason` | Equipo’s own words | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.role` | Role | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.confirmation` | Waiting for your confirmation | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.filing` | Asking Amadan for access | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.pending` | Waiting for approval on Amadan | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.approved` | Access approved | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.declined` | Access declined | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.expired` | This access request expired | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.limited` | Amadan cannot accept more access requests right now. Ask again later. | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.failed` | The access request could not be completed. Ask again to make a new request. | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.operator` | Only the agent’s operator can approve this on Amadan. | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.continue` | Access to %s was approved. Continue the original request: %s. | Access request | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+
+
Oficina ID consumer: COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13).
| Key | Copy | Surface | Review |
diff --git a/internal/equipo/chat/access_request.go b/internal/equipo/chat/access_request.go
new file mode 100644
index 00000000..3b917a09
--- /dev/null
+++ b/internal/equipo/chat/access_request.go
@@ -0,0 +1,227 @@
+package chat
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func (t *txn) requestAccess(r turnRecord, in wire.AccessRequest) (wire.ToolResult, error) {
+ in.Target = strings.TrimPrefix(strings.TrimSpace(in.Target), "amadan.net/")
+ if in.Role == "" {
+ in.Role = "agent"
+ }
+ reason, ok := cleanText(in.Reason, 1000)
+ if !ok || !wire.ValidAccessReason(reason) || !wire.ValidAccessTarget(in.Target) || !wire.AccessRole(in.Role) || in.State != "" || in.RequestID != "" || in.ApproveURL != "" || in.Expires != 0 || r.Kind != wire.TurnPerson {
+ return refused("invalid", toolBadInput), nil
+ }
+ id, err := t.s.authority.PrimaryRunner(t.db, r.Person)
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
+ var runner runnerSessionRecord
+ if err := t.db.First(&runner, "runner_id = ?", id).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ if runner.Protocol < wire.ProtocolAccess {
+ return refused("runner_too_old", toolJobsTooOld), nil
+ }
+ var messages []messageRecord
+ if err := t.db.Where("person = ? AND turn_id = ? AND role = ?", r.Person, r.ID, wire.RolePerson).Order("seq").Find(&messages).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ if len(messages) == 0 {
+ return refused("not_asked", toolBadInput), nil
+ }
+ if !strings.Contains(in.Target, "/") {
+ targets := []string{}
+ explicit := false
+ for _, m := range messages {
+ for _, word := range strings.Fields(m.Text) {
+ word = strings.TrimPrefix(strings.Trim(word, ".,?!\"'`()[]"), "amadan.net/")
+ if strings.HasPrefix(word, in.Target+"/") && wire.ValidAccessTarget(word) && !slices.Contains(targets, word) {
+ targets = append(targets, word)
+ }
+ }
+ lower := strings.ToLower(m.Text)
+ if m.Origin == originComposer && !uncertainPlacement(lower) && (strings.Contains(lower, "whole "+strings.ToLower(in.Target)+" namespace") || strings.Contains(lower, "whole namespace "+strings.ToLower(in.Target)) || strings.Contains(lower, "entire "+strings.ToLower(in.Target)+" namespace") || strings.Contains(lower, "entire namespace "+strings.ToLower(in.Target))) {
+ explicit = true
+ }
+ }
+ if len(targets) == 1 && !explicit {
+ in.Target = targets[0]
+ } else if !explicit {
+ return refused("narrow_target", "Name the single repository. A namespace needs the person's explicit request for that namespace."), nil
+ }
+ }
+ var old []cardRecord
+ if err := t.db.Where("person = ? AND kind = ? AND coalesce(access, '') <> '' AND (turn_id = ? OR state = ?)", r.Person, wire.CardAccess, r.ID, wire.CardOpen).Find(&old).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ for _, c := range old {
+ var a wire.AccessRequest
+ if json.Unmarshal([]byte(c.Access), &a) != nil {
+ return wire.ToolResult{}, ErrInvalid
+ }
+ if c.TurnID == r.ID || a.Target == in.Target && c.State == wire.CardOpen {
+ return refused("already_asked", "An access card already exists. Wait for the person; never retry on your own."), nil
+ }
+ }
+ in.Reason, in.State = reason, "confirmation"
+ raw, _ := json.Marshal(in)
+ now := t.now()
+ // Replace only the explanatory find card in this same turn.
+ var c cardRecord
+ if err := t.db.Where("person = ? AND turn_id = ? AND kind = ? AND coalesce(access, '') = ''", r.Person, r.ID, wire.CardAccess).Find(&c).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ fresh := c.ID == ""
+ if fresh {
+ c = cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardAccess, State: wire.CardOpen, TurnID: r.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
+ }
+ c.Access, c.Name, c.Question = string(raw), in.Target, fmt.Sprintf(t.s.authority.Copy("access.confirm"), in.Target)
+ if fresh {
+ if err := t.db.Create(&c).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ } else if err := t.saveCard(&c); err != nil {
+ return wire.ToolResult{}, err
+ }
+ if err := t.s.authority.Audit(t.db, r.Person, "access.proposed", c.ID); err != nil {
+ return wire.ToolResult{}, err
+ }
+ return wire.ToolResult{Code: "asked", Text: toolAsked}, t.cardEvent(c)
+}
+
+func (t *txn) confirmAccess(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
+ current, err := t.cardView(c)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ var a wire.AccessRequest
+ if err := json.Unmarshal([]byte(c.Access), &a); err != nil {
+ return wire.Card{}, current, err
+ }
+ if c.State != wire.CardOpen || c.Revision != in.Revision || a.State != "confirmation" {
+ return wire.Card{}, current, ErrCardConflict
+ }
+ if in.Choice != "confirm" {
+ return wire.Card{}, current, ErrInvalid
+ }
+ id, err := t.s.authority.PrimaryRunner(t.db, person)
+ if err != nil {
+ return wire.Card{}, current, err
+ }
+ var runner runnerSessionRecord
+ if err := t.db.First(&runner, "runner_id = ?", id).Error; err != nil {
+ return wire.Card{}, current, err
+ }
+ if runner.Protocol < wire.ProtocolAccess {
+ return wire.Card{}, current, ErrConflict
+ }
+ a.State = "filing"
+ raw, _ := json.Marshal(a)
+ c.Access = string(raw)
+ if err := t.saveCard(&c); err != nil {
+ return wire.Card{}, current, err
+ }
+ if err := t.s.authority.Audit(t.db, person, "access.confirmed", c.ID); err != nil {
+ return wire.Card{}, current, err
+ }
+ if err := t.command(person, wire.FrameRequestAccess, wire.AccessCommand{CardID: c.ID, Person: person, Target: a.Target, Role: a.Role, Reason: a.Reason, Confirmed: true}); err != nil {
+ return wire.Card{}, current, err
+ }
+ out, err := t.cardView(c)
+ return out, wire.Card{}, err
+}
+
+func (t *txn) accessReport(l Lease, v *wire.AccessReport) error {
+ if v.Person != l.Runner.Person || l.Protocol < wire.ProtocolAccess {
+ return ErrForbidden
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, v.Person)
+ if err != nil {
+ return err
+ }
+ if primary != l.Runner.RunnerID {
+ return ErrForbidden
+ }
+ var c cardRecord
+ if err := t.db.Where("id = ? AND person = ? AND kind = ?", v.CardID, v.Person, wire.CardAccess).First(&c).Error; err != nil {
+ return err
+ }
+ var a wire.AccessRequest
+ if json.Unmarshal([]byte(c.Access), &a) != nil {
+ return ErrInvalid
+ }
+ if a.State == "confirmation" {
+ return ErrForbidden
+ }
+ if wire.AccessFinal(a.State) {
+ return nil
+ }
+ if v.State != "pending" && !wire.AccessFinal(v.State) || len(v.RequestID) > 200 || v.ApproveURL != "" && !wire.AccessURL(v.ApproveURL) {
+ return ErrInvalid
+ }
+ if (v.State == "pending" || v.State == "approved") && v.RequestID == "" {
+ return ErrInvalid
+ }
+ if a.RequestID != "" && a.RequestID != v.RequestID {
+ return ErrInvalid
+ }
+ a.State, a.RequestID = v.State, v.RequestID
+ if v.ApproveURL != "" {
+ a.ApproveURL = v.ApproveURL
+ }
+ if v.Expires != 0 {
+ a.Expires = v.Expires
+ }
+ raw, _ := json.Marshal(a)
+ c.Access = string(raw)
+ if wire.AccessFinal(a.State) && a.State != "approved" {
+ c.State = wire.CardResolved
+ }
+ if err := t.saveCard(&c); err != nil {
+ return err
+ }
+ if err := t.s.authority.Audit(t.db, v.Person, "access."+a.State, c.ID); err != nil {
+ return err
+ }
+ if a.State == "approved" {
+ h, err := t.hello(v.Person)
+ if err != nil {
+ return err
+ }
+ return t.resolveAccess(v.Person, h)
+ }
+ return nil
+}
+
+func (t *txn) continueAccess(c cardRecord, h wire.Hello) error {
+ var a wire.AccessRequest
+ if json.Unmarshal([]byte(c.Access), &a) != nil {
+ return ErrInvalid
+ }
+ if a.State != "approved" || strings.Contains(a.Target, "/") && !slices.ContainsFunc(h.Catalog, func(e wire.RepoInfo) bool { return intended(e.Repo, a.Target) }) {
+ return nil
+ }
+ c.State = wire.CardResolved
+ if err := t.saveCard(&c); err != nil {
+ return err
+ }
+ var messages []messageRecord
+ if err := t.db.Where("person = ? AND turn_id = ? AND role = ?", c.Person, c.TurnID, wire.RolePerson).Order("seq").Find(&messages).Error; err != nil {
+ return err
+ }
+ words := []string{}
+ for _, m := range messages {
+ words = append(words, m.Text)
+ }
+ _, _, err := t.send(c.Lane, c.Person, "access-approved:"+c.ID, fmt.Sprintf(t.s.authority.Copy("access.continue"), a.Target, strings.Join(words, "\n")), nil, func(m messageRecord) error {
+ return t.db.Create(&cardThreadRecord{ID: newID("ct_"), Person: c.Person, CardID: c.ID, TurnID: m.TurnID, MessageID: m.ID, CreatedAt: t.now()}).Error
+ })
+ return err
+}
diff --git a/internal/equipo/chat/access_request_test.go b/internal/equipo/chat/access_request_test.go
new file mode 100644
index 00000000..76ec3016
--- /dev/null
+++ b/internal/equipo/chat/access_request_test.go
@@ -0,0 +1,194 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func accessRig(t *testing.T, words string) (*meteredRig, turnRecord) {
+ t.Helper()
+ r := placementRig(t)
+ turn := turnRecord{ID: "tr_access", Person: hkOwner, Kind: wire.TurnPerson, State: wire.TurnRunning}
+ for _, row := range []any{&turn, &messageRecord{ID: "m_access", Person: hkOwner, TurnID: turn.ID, Role: wire.RolePerson, Text: words, Origin: originComposer}} {
+ if err := r.s.db.G.Create(row).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ return r, turn
+}
+func proposeAccess(t *testing.T, r *meteredRig, turn turnRecord, target string) cardRecord {
+ t.Helper()
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ got, err := tx.requestAccess(turn, wire.AccessRequest{Target: target, Reason: "I need to fix the build."})
+ if err == nil && got.Code != "asked" {
+ t.Fatalf("proposal: %+v", got)
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ var c cardRecord
+ if err := r.s.db.G.Where("turn_id = ? AND kind = ?", turn.ID, wire.CardAccess).First(&c).Error; err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+func TestAccessConfirmationAndNarrowTarget(t *testing.T) {
+ r, turn := accessRig(t, "Fix the build in carlos/platform")
+ c := proposeAccess(t, r, turn, "carlos")
+ var a wire.AccessRequest
+ if err := json.Unmarshal([]byte(c.Access), &a); err != nil {
+ t.Fatal(err)
+ }
+ if a.Target != "carlos/platform" || a.Role != "agent" || a.State != "confirmation" {
+ t.Fatalf("unsafe proposal: %+v", a)
+ }
+ var n int64
+ r.s.db.G.Model(&commandRecord{}).Where("kind = ?", wire.FrameRequestAccess).Count(&n)
+ if n != 0 {
+ t.Fatal("model filed without confirmation")
+ }
+ r.removed = true
+ if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); !errors.Is(err, ErrForbidden) {
+ t.Fatal("removed member", err)
+ }
+ r.removed = false
+ if _, _, err := r.s.Answer(context.Background(), hkMember, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); !errors.Is(err, ErrNotFound) {
+ t.Fatal("another person", err)
+ }
+ if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ var commands []commandRecord
+ r.s.db.G.Where("kind = ?", wire.FrameRequestAccess).Find(&commands)
+ if len(commands) != 1 {
+ t.Fatalf("commands: %+v", commands)
+ }
+ var cmd wire.AccessCommand
+ if err := json.Unmarshal([]byte(commands[0].Body), &cmd); err != nil {
+ t.Fatal(err)
+ }
+ if cmd.Target != "carlos/platform" || cmd.CardID != c.ID || !cmd.Confirmed {
+ t.Fatalf("command: %+v", cmd)
+ }
+ if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); !errors.Is(err, ErrCardConflict) {
+ t.Fatal("double confirm", err)
+ }
+}
+func TestAccessNamespaceRequiresExplicitRequest(t *testing.T) {
+ for _, tc := range []struct {
+ words string
+ allowed bool
+ }{{"Fix the build", false}, {"Do not give access to the whole carlos namespace", false}, {"Fix a build in namespace carlos", false}, {"Give access to the whole carlos namespace", true}} {
+ t.Run(tc.words, func(t *testing.T) {
+ r, turn := accessRig(t, tc.words)
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ got, err := tx.requestAccess(turn, wire.AccessRequest{Target: "carlos", Reason: "I need access."})
+ if (got.Code == "asked") != tc.allowed {
+ t.Fatalf("namespace: %+v", got)
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+func TestAccessFinalRequiresNewConfirmation(t *testing.T) {
+ for _, state := range []string{"declined", "expired", "limited", "failed"} {
+ t.Run(state, func(t *testing.T) {
+ r, turn := accessRig(t, "Fix carlos/platform")
+ c := proposeAccess(t, r, turn, "carlos/platform")
+ if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ return tx.accessReport(Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolCurrent}, &wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_1", State: state})
+ }); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ if c.State != wire.CardResolved {
+ t.Fatalf("not final: %+v", c)
+ }
+ if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); !errors.Is(err, ErrCardConflict) {
+ t.Fatal("final reused", err)
+ }
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ got, err := tx.requestAccess(turn, wire.AccessRequest{Target: "carlos/platform", Reason: "Try again."})
+ if got.Code == "asked" {
+ t.Fatal("model retried")
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ turn.ID = "tr_again"
+ if err := r.s.db.G.Create(&turn).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.db.G.Create(&messageRecord{ID: "m_again", Person: hkOwner, TurnID: turn.ID, Role: wire.RolePerson, Text: "Try carlos/platform again", Origin: originComposer, IdempotencyKey: "again"}).Error; err != nil {
+ t.Fatal(err)
+ }
+ next := proposeAccess(t, r, turn, "carlos/platform")
+ var a wire.AccessRequest
+ json.Unmarshal([]byte(next.Access), &a)
+ if next.ID == c.ID || a.State != "confirmation" {
+ t.Fatal("retry lacks new confirmation")
+ }
+ })
+ }
+}
+
+func TestAccessApprovalWaitsForCatalogAndContinuesOnce(t *testing.T) {
+ r, turn := accessRig(t, "Fix the build in carlos/platform")
+ r.s.authority.Copy = func(key string) string {
+ if key == "access.confirm" {
+ return "Ask Amadan for access to %s?"
+ }
+ if key == "access.continue" {
+ return "Access to %s was approved. Continue the original request: %s."
+ }
+ return key
+ }
+ c := proposeAccess(t, r, turn, "carlos/platform")
+ lease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolCurrent}
+ report := wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: "approved"}
+ if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.accessReport(lease, &report) }); !errors.Is(err, ErrForbidden) {
+ t.Fatal("unconfirmed report accepted", err)
+ }
+ if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.db.G.Model(&turnRecord{}).Where("id = ?", turn.ID).Update("state", wire.TurnReplied).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.accessReport(lease, &report) }); err != nil {
+ t.Fatal(err)
+ }
+ var n int64
+ r.s.db.G.Model(&messageRecord{}).Where("idempotency_key = ?", "access-approved:"+c.ID).Count(&n)
+ if n != 0 {
+ t.Fatal("continued before catalog refresh")
+ }
+ h := wire.Hello{Repos: []string{"amadan.net/carlos/platform"}, Catalog: []wire.RepoInfo{{Repo: "amadan.net/carlos/platform"}}}
+ for i := 0; i < 2; i++ {
+ if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.resolveAccess(hkOwner, h) }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var messages []messageRecord
+ r.s.db.G.Where("idempotency_key = ?", "access-approved:"+c.ID).Find(&messages)
+ if len(messages) != 1 || !strings.Contains(messages[0].Text, "Fix the build in carlos/platform") || messages[0].Origin != originGenerated {
+ t.Fatalf("continuation: %+v", messages)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ if c.State != wire.CardResolved {
+ t.Fatal("approval unresolved")
+ }
+}
diff --git a/internal/equipo/chat/placement_edges_test.go b/internal/equipo/chat/placement_edges_test.go
index 132c2b4b..5940472b 100644
--- a/internal/equipo/chat/placement_edges_test.go
+++ b/internal/equipo/chat/placement_edges_test.go
@@ -206,7 +206,7 @@ func TestPlacementMissingRepositorySharingHint(t *testing.T) {
}
if err := r.s.tx(context.Background(), func(tx *txn) error {
got, err := tx.find(turnRecord{ID: "tr_missing", Person: hkOwner}, query)
- for _, want := range []string{"equipo-paul", "not shared with Equipo", "namespace on Amadan", "merging", "per-project"} {
+ for _, want := range []string{"equipo-paul", "not shared with Equipo", "request_access", "single repository", "merging", "per-project"} {
if !strings.Contains(got.Text, want) {
t.Errorf("not-found result lacks %q: %+v", want, got)
}
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index f90bced4..3d70a924 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -44,6 +44,7 @@ func (projectRecord) TableName() string { return "chat_projects" }
// cardRecord is a card in one person's conversation.
type cardRecord struct {
+ Access string
Placement string
ID string `gorm:"primaryKey"`
Person string `gorm:"index:chat_card_person"`
@@ -264,6 +265,11 @@ func (t *txn) projectView(p projectRecord) (wire.Project, error) {
func (t *txn) cardView(c cardRecord) (wire.Card, error) {
v := wire.Card{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, TurnID: c.TurnID, ProjectID: c.ProjectID, Question: c.Question, Options: []string{}, Choice: c.Choice, TaskID: c.TaskID, CreatedAt: c.CreatedAt, UpdatedAt: c.UpdatedAt, ActionID: c.ActionID, VisibleAt: c.VisibleAt}
+ if c.Access != "" {
+ if err := json.Unmarshal([]byte(c.Access), &v.Access); err != nil {
+ return v, err
+ }
+ }
if c.Options != "" {
if err := json.Unmarshal([]byte(c.Options), &v.Options); err != nil {
return v, err
@@ -367,7 +373,7 @@ func (t *txn) saveCard(c *cardRecord) error {
}
c.Revision++
c.UpdatedAt = t.now()
- if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("state", "choice", "answer_message", "undo", "revision", "updated_at").Updates(c).Error; err != nil {
+ if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("state", "choice", "answer_message", "undo", "revision", "updated_at", "access", "name", "question").Updates(c).Error; err != nil {
return err
}
return t.cardEvent(*c)
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 60d73138..e5f26560 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -318,6 +318,8 @@ func (s *Store) Apply(ctx context.Context, l Lease, f wire.Frame, body any) erro
}
}
switch v := body.(type) {
+ case *wire.AccessReport:
+ return t.accessReport(l, v)
case *wire.Ack:
return t.ack(l, v.ID)
case *wire.DeltaReport:
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index db60c360..79aea08f 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -177,7 +177,7 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
switch v := body.(type) {
case *wire.Hello:
err = store.Heartbeat(ctx, rc.lease, *v)
- case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport, *wire.StepActivityReport, *wire.Blob, *wire.PublishedReport, *wire.ResearchFile, *wire.GlanceReport:
+ case *wire.AccessReport, *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport, *wire.StepActivityReport, *wire.Blob, *wire.PublishedReport, *wire.ResearchFile, *wire.GlanceReport:
err = store.Apply(ctx, rc.lease, f, body)
case *wire.LeaseCheck:
// Answered only while this connection holds the lease; at
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 0b28a1f9..16b3ac78 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -431,6 +431,7 @@ func madeTask(r toolCallRecord) string {
// madeCodes are the results that show a mutation happened, for the kinds
// whose result can also be "nothing done".
var madeCodes = map[string][]string{
+ wire.ToolRequestAccess: {"asked"},
wire.ToolRecordTask: {"recorded"},
wire.ToolStartTask: {"started"},
wire.ToolAskPerson: {"asked"},
@@ -550,6 +551,12 @@ func (t *txn) runTool(l Lease, v *wire.ToolCall) (wire.ToolResult, error) {
return t.authorizeCreate(r, in.Repo)
}
return t.projectCreated(r, v.CallID, in.Repo)
+ case wire.ToolRequestAccess:
+ var in wire.AccessRequest
+ if wire.Strict(v.Args, &in) != nil {
+ return refused("invalid", toolBadInput), nil
+ }
+ return t.requestAccess(r, in)
case wire.ToolFind:
var in struct {
Query string `json:"query"`
@@ -1035,10 +1042,11 @@ func (t *txn) find(r turnRecord, query string) (wire.ToolResult, error) {
if len(namespaces) > 0 {
reach = strings.Join(namespaces, ", ")
}
- hint := fmt.Sprintf("Nothing Equipo's agent can reach matches %q. It reaches: %s. Tell the person the repository or namespace is not shared with Equipo. To share it, add the Equipo agent %s to that namespace on Amadan. Mention that merging is a separate per-project setting.", query, reach, h.Agent)
+ hint := fmt.Sprintf("Nothing Equipo's agent can reach matches %q. It reaches: %s. Tell the person the repository or namespace is not shared with Equipo. The agent is %s. Mention that merging is a separate per-project setting.", query, reach, h.Agent)
if h.Agent == "" {
- hint = fmt.Sprintf("Nothing Equipo's agent can reach matches %q. Tell the person it is not shared with Equipo. Sharing requires adding the Equipo agent to that namespace on Amadan; its name is unavailable until the runner reconnects. Do not invent a name. Mention that merging is a separate per-project setting.", query)
+ hint = fmt.Sprintf("Nothing Equipo's agent can reach matches %q. Tell the person it is not shared with Equipo. The agent name is unavailable until the runner reconnects. Do not invent a name. Mention that merging is a separate per-project setting.", query)
}
+ hint += " Use request_access with the single repository, role agent unless asked otherwise, and your reason. It only raises a confirmation card. Never retry unprompted."
return wire.ToolResult{Code: "none", Text: hint}, nil
}
@@ -1164,6 +1172,12 @@ func (t *txn) resolveAccess(person string, h wire.Hello) error {
}
for i := range rows {
c := rows[i]
+ if c.Access != "" {
+ if err := t.continueAccess(c, h); err != nil {
+ return err
+ }
+ continue
+ }
if c.Name == "" || !slices.ContainsFunc(h.Catalog, func(e wire.RepoInfo) bool { return intended(e.Repo, c.Name) }) {
continue
}
@@ -1178,6 +1192,9 @@ func (t *txn) resolveAccess(person string, h wire.Hello) error {
// answerAccess is the person acting on a grant card: their runner checks
// what its agent reaches now, and the card resolves itself if it does.
func (t *txn) answerAccess(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
+ if c.Access != "" {
+ return t.confirmAccess(person, c, in)
+ }
v, err := t.cardView(c)
if err != nil {
return wire.Card{}, wire.Card{}, err
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index 63eaa54e..e9075b68 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -150,6 +150,11 @@ func cardView(c wire.Card, choices []string, tasks map[string]wire.Task) chatCar
}
v.Open = c.State == wire.CardHomeSet || c.State == wire.CardHomeAsk
case wire.CardAccess:
+ if c.Access != nil {
+ v.Open = c.State == wire.CardOpen
+ v.Line = copyText("access." + c.Access.State)
+ break
+ }
reach := strings.Join(c.Options, ", ")
// The command names a namespace only when the person gave one
// with a repository; otherwise it keeps the placeholder and says
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index e7577293..b3bbe889 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -189,6 +189,9 @@ func (s *Store) RunnerStreamHandler(logger *slog.Logger) http.Handler {
// shortens long quoted subjects on the visible line.
func activityLabel(a wire.Activity, turnKind, subject string) string {
tool := a.Tool
+ if tool == wire.ToolRequestAccess {
+ return copyText("access.title")
+ }
if a.Kind == wire.ActivityThink {
tool = "thinking"
}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 9e930101..cbfdf224 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -66,6 +66,24 @@ const BootLog = "Equipo could not start."
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
var pageCopy = map[string]string{
+ "access.title": "Ask for access", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.confirm": "Ask Amadan for access to %s?", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.ask": "Ask for access", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.approve": "Approve on Amadan", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.aside": "Not now", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.reason": "Equipo’s own words", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.role": "Role", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.confirmation": "Waiting for your confirmation", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.filing": "Asking Amadan for access", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.pending": "Waiting for approval on Amadan", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.approved": "Access approved", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.declined": "Access declined", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.expired": "This access request expired", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.limited": "Amadan cannot accept more access requests right now. Ask again later.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.failed": "The access request could not be completed. Ask again to make a new request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.operator": "Only the agent’s operator can approve this on Amadan.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.continue": "Access to %s was approved. Continue the original request: %s.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+
"placement.new_named": "New project: %s", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)
"placement.abandon": "Abandon move", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)
"placement.late_report": "Report received after the move was abandoned: %s", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
diff --git a/internal/equipo/migrations/0091_access_requests.sql b/internal/equipo/migrations/0091_access_requests.sql
new file mode 100644
index 00000000..ee0b215e
--- /dev/null
+++ b/internal/equipo/migrations/0091_access_requests.sql
@@ -0,0 +1 @@
+ALTER TABLE chat_cards ADD COLUMN access text;
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index 517dd4a1..d48eb0e5 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -60,7 +60,7 @@ func init() {
page = template.Must(page.ParseFS(appFS, "templates/layout.html"))
}
if name != "signin_page" && name != "id_public" && name != "errors" {
- page = template.Must(page.ParseFS(appFS, "templates/chrome.html", "templates/forms.html", "templates/task_card.html", "templates/conversation_card.html", "templates/work_parts.html", "templates/housekeeping_settings.html", "templates/settings_nav.html", "templates/merge_policy.html", "templates/placement_chip.html"))
+ page = template.Must(page.ParseFS(appFS, "templates/chrome.html", "templates/forms.html", "templates/task_card.html", "templates/conversation_card.html", "templates/work_parts.html", "templates/housekeeping_settings.html", "templates/settings_nav.html", "templates/merge_policy.html", "templates/placement_chip.html", "templates/access_card.html"))
}
if name == "oficina_id" || name == "id_public" {
page = template.Must(page.ParseFS(appFS, "templates/id_body.html"))
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index c7520ab2..ea0467d6 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -1821,7 +1821,7 @@ label[equipo-sp-label] { cursor: pointer; }
}
[equipo-set-aside] { position: absolute; inset-block-start: .375rem; inset-inline-end: .375rem; z-index: 1; }
[equipo-set-aside] button { display: grid; place-items: center; border: 0; border-radius: var(--rst-radius); background: transparent; color: var(--rst-text-muted); inline-size: 2.25rem; block-size: 2.25rem; cursor: pointer; }
-[equipo-roster-card][data-ask] > [equipo-card-line] { padding-inline-end: 2rem; font-size: 1rem; font-weight: 450; line-height: 1.5; }
+[equipo-roster-card][data-ask] > [equipo-card-line], [equipo-roster-card][data-ask] [data-access-state] > [equipo-card-line] { padding-inline-end: 2rem; font-size: 1rem; font-weight: 450; line-height: 1.5; }
[equipo-roster-card] button:hover { filter: none; background-color: var(--rst-control-face-hover); }
[equipo-set-aside] button:active { background: var(--rst-control-face-press); transform: translateY(1px); }
[equipo-roster-card] button:focus-visible, [equipo-aside-stub] button:focus-visible { outline: 2px solid var(--rst-accent); outline-offset: 2px; }
@@ -2027,7 +2027,7 @@ label[equipo-sp-label] { cursor: pointer; }
/* The set-aside control centres on the card's first line. */
[equipo-set-aside] { inset-block-start: .625rem; inset-inline-end: .5rem; }
[equipo-roster-card]:has(> [equipo-roster-task], > [equipo-copy-hold]) > [equipo-set-aside] { inset-block-start: .375rem; }
-[equipo-roster-card][data-ask] > [equipo-card-line], [data-question-thread] [data-first] [equipo-thread-bubble] { padding-inline-end: 2.25rem; }
+[equipo-roster-card][data-ask] > [equipo-card-line], [equipo-roster-card][data-ask] [data-access-state] > [equipo-card-line], [data-question-thread] [data-first] [equipo-thread-bubble] { padding-inline-end: 2.25rem; }
/* A card's composer is the main composer, in the card. */
[equipo-subchat] { margin: 0 -1rem -1rem; padding: .75rem 1rem 1rem; }
[equipo-subchat][data-question-thread] { margin: 0; padding: 0; }
@@ -2045,7 +2045,7 @@ label[equipo-sp-label] { cursor: pointer; }
[equipo-roster-card] [equipo-actions] button:first-of-type:nth-last-of-type(2), [equipo-roster-card] [equipo-actions] button:first-of-type:nth-last-of-type(2) ~ button { grid-column: 1 / -1; }
[equipo-set-aside] { inset-block-start: .25rem; inset-inline-end: .25rem; }
[equipo-roster-card]:has(> [equipo-roster-task], > [equipo-copy-hold]) > [equipo-set-aside] { inset-block-start: 0; }
- [equipo-roster-card][data-ask] > [equipo-card-line], [data-question-thread] [data-first] [equipo-thread-bubble] { padding-inline-end: 2.5rem; }
+ [equipo-roster-card][data-ask] > [equipo-card-line], [equipo-roster-card][data-ask] [data-access-state] > [equipo-card-line], [data-question-thread] [data-first] [equipo-thread-bubble] { padding-inline-end: 2.5rem; }
[equipo-subchat] { margin: 0 -.875rem -.875rem; padding: .75rem .875rem .875rem; }
[equipo-subchat][data-question-thread] { margin: 0; padding: 0; }
}
@@ -2103,3 +2103,6 @@ label[equipo-sp-label] { cursor: pointer; }
[equipo-placement-page] { padding: 1rem; }
[equipo-placement-page] [rst-btn] { inline-size: 100%; min-block-size: 2.75rem; }
}
+
+[data-access-state] { display: contents; }
+[data-access-aside] { min-block-size: 2.75rem; }
diff --git a/internal/equipo/templates/access_card.html b/internal/equipo/templates/access_card.html
new file mode 100644
index 00000000..d68dde26
--- /dev/null
+++ b/internal/equipo/templates/access_card.html
@@ -0,0 +1,11 @@
+{{define "access-card"}}
+<div data-access-state="{{.Access.State}}">
+<h3 equipo-card-line>{{if eq .Access.State "confirmation"}}{{.Question}}{{else}}{{copy "access.title"}}: {{.Access.Target}}{{end}}</h3>
+<p equipo-card-note>{{copy "access.role"}}: {{.Access.Role}}</p>
+<p equipo-card-note>{{copy "access.reason"}}</p><p>{{.Access.Reason}}</p>
+<p equipo-card-note role="status">{{.Line}}</p>
+{{if eq .Access.State "confirmation"}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}<button rst-btn="primary" type="submit" name="choice" value="confirm" data-access-confirm>{{copy "access.ask"}}</button></form>{{end}}
+{{if and (eq .Access.State "pending") .Access.ApproveURL}}<p equipo-card-note>{{copy "access.operator"}}</p><div equipo-actions><a rst-btn="primary" href="{{.Access.ApproveURL}}" target="_blank" rel="noopener noreferrer" data-access-approve>{{copy "access.approve"}}</a></div>{{end}}
+{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/visibility" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="aside" value="true">{{template "card-job" .}}<button equipo-link type="submit" data-access-aside>{{copy "access.aside"}}</button></form>{{end}}
+</div>
+{{end}}
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index f0eba660..215b4bcf 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -19,6 +19,7 @@
{{else if eq .Kind "publish"}}<p equipo-card-line>{{.Line}}</p>{{with .Site}}{{if .URL}}<p equipo-card-note><a href="{{.URL}}" rel="noopener" target="_blank" data-site-link>{{copy "chat.card.site_link"}}</a></p>{{end}}{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{range .Options}}<button rst-btn="{{if eq . "publish"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-publish-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if eq .Kind "merge"}}<p equipo-card-line>{{.Line}}</p>{{with .PreviewURL}}<p equipo-card-note><a href="{{.}}" rel="noopener" target="_blank" data-preview-link>{{copy "chat.card.preview_link"}}</a></p>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{range .Options}}<button rst-btn="{{if eq . "merge"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-merge-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if or (eq .Kind "merge_ships") (eq .Kind "merge_policy") (eq .Kind "merge_receipt")}}{{if eq .Kind "merge_receipt"}}<div equipo-card-line equipo-markdown data-merge-receipt>{{chatMarkdown .Line}}</div>{{else}}<p equipo-card-line>{{.Line}}</p>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{range .Options}}<button rst-btn="{{if or (eq . "save") (eq . "not_ships")}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-merge-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
+{{else if .Access}}{{template "access-card" .}}
{{else if eq .Kind "access"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<details equipo-grant><summary rst-btn>{{copy "chat.card.grant"}}</summary><p>{{.GrantHow}}</p><code>amadan agent grant {{.Agent}} {{.Namespace}}</code><form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}<button rst-btn name="choice" value="check" type="submit" data-grant-check>{{copy "chat.card.grant_check"}}</button></form></details>{{end}}
{{end}}<p equipo-card-error role="alert" hidden></p></section>{{end}}{{if .Presentation.Coverage.Skipped}}<section equipo-roster-card data-flat>{{template "work-task-receipt" .}}</section>{{end}}{{if not .SetAside}}{{range .ResearchReports}}<div equipo-roster-byline><span equipo-roster-avatar>{{icon "search"}}</span><b>{{copy "work.specialist.research"}}</b><span>{{copy "roster.reports"}}</span>{{template "roster-project" $}}{{with .At}}<time datetime="{{.Format "2006-01-02T15:04:05Z07:00"}}">{{.Format "15:04"}}</time>{{end}}</div><section equipo-roster-card data-research-report><header equipo-roster-research-head><h3>{{copy "roster.research"}}</h3>{{with $.Presentation.Context.TaskTitle}}<span equipo-roster-task>{{.}}</span>{{end}}</header><p>{{.Summary}}</p><ol equipo-roster-findings>{{range .Facts}}<li><div><strong>{{.Label}}</strong> {{.Value}}</div>{{range .Sources}}{{if .URL}}<a href="{{.URL}}" title="{{.URL}}" target="_blank" rel="noopener"><span>{{.Domain}}</span></a>{{else}}<span>{{.ID}}</span>{{end}}{{end}}</li>{{end}}{{range .Gaps}}<li data-gap>{{.}}</li>{{end}}</ol><div equipo-roster-links><button type="button" rst-btn data-report-talk aria-controls="report-thread-{{$.ID}}" aria-expanded="{{if $.Presentation.Thread}}true{{else}}false{{end}}">{{copy "roster.talk"}}</button><a href="/tasks/{{$.TaskID}}#research-{{.StepID}}">{{copy "roster.research_log"}} ({{len .Fetches}})</a></div></section>{{end}}{{end}}
</li>{{end}}
diff --git a/internal/runner/provider/actions.go b/internal/runner/provider/actions.go
index 2c809821..3d313b89 100644
--- a/internal/runner/provider/actions.go
+++ b/internal/runner/provider/actions.go
@@ -174,7 +174,7 @@ func ResearchReaderAction(action string) bool { return action == "implement" ||
// ConverseTools is the thin coordinator's tool set (wire.ConverseTools
// plus create_project, which the runner carries out itself).
func ConverseTools() []string {
- return []string{"status", "find", "search_code", "read_file", "add_project", "create_project", "set_project_home", "star_project", "ask_person", "write_note", "read_notes", "record_task", "add_finding", "start_task", "read_task", "cancel_task", "add_report", "hold_merge", "set_merge_policy", "propose_specialist", "research"}
+ return []string{"request_access", "status", "find", "search_code", "read_file", "add_project", "create_project", "set_project_home", "star_project", "ask_person", "write_note", "read_notes", "record_task", "add_finding", "start_task", "read_task", "cancel_task", "add_report", "hold_merge", "set_merge_policy", "propose_specialist", "research"}
}
// AssistTools is the Assistant's tool set (wire.AssistTools).
diff --git a/internal/runner/thin/access.go b/internal/runner/thin/access.go
new file mode 100644
index 00000000..7fbd4290
--- /dev/null
+++ b/internal/runner/thin/access.go
@@ -0,0 +1,194 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+const accessSchema = `CREATE TABLE IF NOT EXISTS access_requests (card_id TEXT PRIMARY KEY, command TEXT NOT NULL, report TEXT NOT NULL DEFAULT '', state TEXT NOT NULL);`
+
+func (s *State) AcceptAccess(ctx context.Context, frame string, c wire.AccessCommand) error {
+ if !validAccessCommand(c) {
+ return errAccess
+ }
+ raw, _ := json.Marshal(c)
+ return s.tx(ctx, func(tx *sql.Tx) error {
+ fresh, err := seen(tx, frame)
+ if err != nil || !fresh {
+ return err
+ }
+ var old string
+ err = tx.QueryRow("SELECT command FROM access_requests WHERE card_id=?", c.CardID).Scan(&old)
+ if err == nil {
+ if old != string(raw) {
+ return errAccess
+ }
+ return nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ _, err = tx.Exec("INSERT INTO access_requests(card_id,command,state) VALUES(?,?,'queued')", c.CardID, string(raw))
+ return err
+ })
+}
+
+type AccessEngine struct {
+ State *State
+ Forge AccessForge
+ Refresh func()
+ Notify func()
+ Logger *slog.Logger
+}
+
+// Step files at most once. An interrupted POST has an uncertain outcome and
+// needs a fresh person confirmation; a saved id always resumes by GET.
+func (e *AccessEngine) Step(ctx context.Context, id string) error {
+ var command, report, state string
+ if err := e.State.db.QueryRowContext(ctx, "SELECT command,report,state FROM access_requests WHERE card_id=?", id).Scan(&command, &report, &state); err != nil {
+ return err
+ }
+ if wire.AccessFinal(state) {
+ return nil
+ }
+ var cmd wire.AccessCommand
+ var old wire.AccessReport
+ if json.Unmarshal([]byte(command), &cmd) != nil {
+ return errAccess
+ }
+ if report != "" && json.Unmarshal([]byte(report), &old) != nil {
+ return errAccess
+ }
+ var out wire.AccessReport
+ var err error
+ switch state {
+ case "queued":
+ if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET state='filing' WHERE card_id=?", id); err != nil {
+ return err
+ }
+ if e.Forge == nil {
+ err = errAccess
+ } else {
+ out, err = e.Forge.RequestAccess(ctx, cmd)
+ }
+ if err != nil {
+ out.State = "failed"
+ if errors.Is(err, errAccessLimit) {
+ out.State = "limited"
+ }
+ }
+ case "filing":
+ out.State = "failed"
+ case "pending":
+ out, err = e.Forge.PollAccess(ctx, old.RequestID)
+ if err != nil {
+ return err
+ }
+ if out.RequestID != old.RequestID {
+ return errAccess
+ }
+ default:
+ return errAccess
+ }
+ out.CardID, out.Person = cmd.CardID, cmd.Person
+ if out.ApproveURL == "" {
+ out.ApproveURL = old.ApproveURL
+ }
+ if out.Expires == 0 {
+ out.Expires = old.Expires
+ }
+ raw, _ := json.Marshal(out)
+ if err := e.State.tx(ctx, func(tx *sql.Tx) error {
+ if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", out.State, string(raw), id); err != nil {
+ return err
+ }
+ if string(raw) == report {
+ return nil
+ }
+ return e.State.enqueue(tx, wire.FrameAccess, "", out)
+ }); err != nil {
+ return err
+ }
+ if out.State == "approved" {
+ e.Forge.Recheck()
+ e.Forge.Reachable(ctx)
+ if e.Refresh != nil {
+ e.Refresh()
+ }
+ }
+ if e.Notify != nil {
+ e.Notify()
+ }
+ return nil
+}
+
+// Run bounds simultaneous long polls to five, matching the hub's waiting
+// limit. Even an immediate pending response waits before another GET.
+func (e *AccessEngine) Run(ctx context.Context) {
+ var wg sync.WaitGroup
+ defer wg.Wait()
+ active := map[string]bool{}
+ done := make(chan string, 5)
+ ticker := time.NewTicker(time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case id := <-done:
+ delete(active, id)
+ case <-ticker.C:
+ rows, err := e.State.db.QueryContext(ctx, "SELECT card_id FROM access_requests WHERE state IN ('queued','filing','pending') ORDER BY card_id LIMIT 5")
+ if err != nil {
+ continue
+ }
+ var ids []string
+ for rows.Next() {
+ var id string
+ if rows.Scan(&id) == nil {
+ ids = append(ids, id)
+ }
+ }
+ rows.Close()
+ for _, id := range ids {
+ if len(active) >= 5 {
+ break
+ }
+ if active[id] {
+ continue
+ }
+ active[id] = true
+ wg.Add(1)
+ go func(id string) {
+ defer wg.Done()
+ defer func() { done <- id }()
+ delay := time.Second
+ for ctx.Err() == nil {
+ err := e.Step(ctx, id)
+ var state string
+ if e.State.db.QueryRowContext(ctx, "SELECT state FROM access_requests WHERE card_id=?", id).Scan(&state) == nil && wire.AccessFinal(state) {
+ return
+ }
+ if err != nil {
+ delay = min(delay*2, time.Minute)
+ } else {
+ delay = time.Second
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(delay):
+ }
+ }
+ }(id)
+ }
+ }
+ }
+}
diff --git a/internal/runner/thin/access_catalog.go b/internal/runner/thin/access_catalog.go
new file mode 100644
index 00000000..a7814579
--- /dev/null
+++ b/internal/runner/thin/access_catalog.go
@@ -0,0 +1,88 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Named read grants supplement the writable /repos list. Verify them with
+// the hub on each refresh; an old approval alone is never current access.
+func (f *fileForge) readGrants(ctx context.Context) []string {
+ if f.accessTargets == nil {
+ return nil
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if time.Since(f.accessAt) < reachEvery {
+ return slices.Clone(f.accessRepos)
+ }
+ targets, err := f.accessTargets(ctx)
+ if err != nil {
+ return nil
+ }
+ credential, err := f.agent(ctx)
+ if err != nil {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ out := []string{}
+ client := *f.client
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ for _, target := range targets {
+ if ctx.Err() != nil {
+ break
+ }
+ if !wire.ValidAccessTarget(target) || !strings.Contains(target, "/") {
+ continue
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, f.hub+"/api/v1/repos/"+target, nil)
+ if err != nil {
+ continue
+ }
+ req.Header.Set("Authorization", "Bearer "+credential.Bearer)
+ res, err := client.Do(req)
+ if err != nil {
+ continue
+ }
+ var info struct {
+ NS string `json:"ns"`
+ Name string `json:"name"`
+ Tier string `json:"tier"`
+ }
+ valid := res.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(res.Body, 16<<10)).Decode(&info) == nil && info.NS+"/"+info.Name == target && info.Tier != "private_e2ee"
+ res.Body.Close()
+ if valid {
+ out = append(out, nsPrefix+target)
+ }
+ }
+ f.accessRepos, f.accessAt = out, time.Now()
+ return slices.Clone(out)
+}
+
+func (s *State) accessReadTargets(ctx context.Context) ([]string, error) {
+ rows, err := s.db.QueryContext(ctx, "SELECT command FROM access_requests WHERE state='approved' AND json_extract(command, '$.role') <> 'agent' ORDER BY rowid DESC LIMIT ?", wire.MaxCatalog)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []string{}
+ for rows.Next() {
+ var raw string
+ if err := rows.Scan(&raw); err != nil {
+ return nil, err
+ }
+ var c wire.AccessCommand
+ if json.Unmarshal([]byte(raw), &c) == nil && c.Role != "agent" && strings.Contains(c.Target, "/") && !slices.Contains(out, c.Target) {
+ out = append(out, c.Target)
+ }
+ }
+ return out, rows.Err()
+}
diff --git a/internal/runner/thin/access_forge.go b/internal/runner/thin/access_forge.go
new file mode 100644
index 00000000..195da801
--- /dev/null
+++ b/internal/runner/thin/access_forge.go
@@ -0,0 +1,94 @@
+package thin
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "os"
+ "regexp"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+var errAccess = errors.New("access request unavailable")
+var errAccessLimit = errors.New("access request limit reached")
+var accessID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,200}$`)
+
+type AccessForge interface {
+ RequestAccess(context.Context, wire.AccessCommand) (wire.AccessReport, error)
+ PollAccess(context.Context, string) (wire.AccessReport, error)
+ Recheck()
+ Reachable(context.Context) []string
+}
+
+func validAccessCommand(c wire.AccessCommand) bool {
+ return c.Confirmed && c.CardID != "" && c.Person != "" && wire.ValidAccessTarget(c.Target) && wire.AccessRole(c.Role) && wire.ValidAccessReason(c.Reason)
+}
+func (f *fileForge) RequestAccess(ctx context.Context, c wire.AccessCommand) (wire.AccessReport, error) {
+ if !validAccessCommand(c) {
+ return wire.AccessReport{}, errAccess
+ }
+ host, _ := os.Hostname()
+ raw, _ := json.Marshal(map[string]any{"target": c.Target, "role": c.Role, "reason": c.Reason, "agent": map[string]string{"session": "equipo-access-" + c.CardID, "harness": "equipo", "host": host}})
+ return f.accessHTTP(ctx, http.MethodPost, "/api/v1/agents/access-requests", raw, &c)
+}
+func (f *fileForge) PollAccess(ctx context.Context, id string) (wire.AccessReport, error) {
+ if !accessID.MatchString(id) {
+ return wire.AccessReport{}, errAccess
+ }
+ return f.accessHTTP(ctx, http.MethodGet, "/api/v1/agents/access-requests/"+id+"?wait=30", nil, nil)
+}
+func (f *fileForge) accessHTTP(ctx context.Context, method, path string, body []byte, expected *wire.AccessCommand) (wire.AccessReport, error) {
+ credential, err := f.agent(ctx)
+ if err != nil {
+ return wire.AccessReport{}, errAccess
+ }
+ req, err := http.NewRequestWithContext(ctx, method, f.hub+path, bytes.NewReader(body))
+ if err != nil {
+ return wire.AccessReport{}, errAccess
+ }
+ req.Header.Set("Authorization", "Bearer "+credential.Bearer)
+ req.Header.Set("Content-Type", "application/json")
+ // A poll can wait 30 seconds at the hub. Do not inherit the shorter list timeout.
+ client := *f.client
+ client.Timeout = 40 * time.Second
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ res, err := client.Do(req)
+ if err != nil {
+ return wire.AccessReport{}, errAccess
+ }
+ defer res.Body.Close()
+ if res.StatusCode == http.StatusTooManyRequests {
+ return wire.AccessReport{}, errAccessLimit
+ }
+ if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
+ return wire.AccessReport{}, errAccess
+ }
+ var out struct {
+ Target string `json:"target"`
+ Role string `json:"role"`
+ Reason string `json:"reason"`
+ ID string `json:"id"`
+ State string `json:"state"`
+ ApproveURL string `json:"approve_url"`
+ Expires int64 `json:"expires"`
+ }
+ if json.NewDecoder(io.LimitReader(res.Body, 16<<10)).Decode(&out) != nil || !accessID.MatchString(out.ID) || out.State != "pending" && out.State != "approved" && out.State != "declined" && out.State != "expired" || out.ApproveURL != "" && !wire.AccessURL(out.ApproveURL) || out.Expires < 0 {
+ return wire.AccessReport{}, errAccess
+ }
+ if expected != nil && (out.Target != "" && out.Target != expected.Target || out.Role != "" && out.Role != expected.Role || out.Reason != "" && out.Reason != expected.Reason) {
+ return wire.AccessReport{}, errAccess
+ }
+ // Never forward response text, including a hub error that echoes credentials.
+ for _, value := range []string{out.ID, out.ApproveURL} {
+ if credential.Bearer != "" && strings.Contains(value, credential.Bearer) || credential.GitPassword != "" && strings.Contains(value, credential.GitPassword) {
+ return wire.AccessReport{}, errAccess
+ }
+ }
+ return wire.AccessReport{RequestID: out.ID, State: out.State, ApproveURL: out.ApproveURL, Expires: out.Expires}, nil
+}
diff --git a/internal/runner/thin/access_test.go b/internal/runner/thin/access_test.go
new file mode 100644
index 00000000..1234df4f
--- /dev/null
+++ b/internal/runner/thin/access_test.go
@@ -0,0 +1,343 @@
+package thin
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func accessForge(t *testing.T, handler http.HandlerFunc) *fileForge {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ dir := t.TempDir()
+ p := filepath.Join(dir, "forge.json")
+ if err := os.WriteFile(p, []byte(`{"agent":"equipo~owner@example.com","api":"SECRET-ACCESS-TOKEN","git":"SECRET-GIT-TOKEN"}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ f := NewFileForge(p, dir, true).(*fileForge)
+ f.hub = srv.URL
+ f.client = srv.Client()
+ return f
+}
+func accessCommand() wire.AccessCommand {
+ return wire.AccessCommand{CardID: "c_access", Person: "p", Target: "carlos/platform", Role: "agent", Reason: "I need to fix the build.", Confirmed: true}
+}
+func TestAccessRunnerConfirmation(t *testing.T) {
+ var calls atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(500) })
+ s, err := OpenState(context.Background(), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ cmd := accessCommand()
+ cmd.Confirmed = false
+ if err := s.AcceptAccess(context.Background(), "frame", cmd); err == nil {
+ t.Fatal("unconfirmed accepted")
+ }
+ if _, err := f.RequestAccess(context.Background(), cmd); err == nil {
+ t.Fatal("unconfirmed filed")
+ }
+ if calls.Load() != 0 {
+ t.Fatal("unconfirmed network request")
+ }
+}
+func TestAccessRunnerRestartAndApprovalRefresh(t *testing.T) {
+ ctx := context.Background()
+ var posts, gets, lists atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer SECRET-ACCESS-TOKEN" {
+ t.Error("credential missing")
+ }
+ switch {
+ case r.URL.Path == "/api/v1/repos":
+ n := lists.Add(1)
+ if n == 1 {
+ fmt.Fprint(w, `{"repos":[]}`)
+ return
+ }
+ if r.Header.Get("If-None-Match") != "" {
+ t.Error("grant refresh reused list validator")
+ }
+ fmt.Fprint(w, `{"repos":[{"ns":"carlos","name":"platform"}]}`)
+ case r.Method == "POST":
+ posts.Add(1)
+ var body struct {
+ Target, Role, Reason string
+ Agent map[string]string
+ }
+ json.NewDecoder(r.Body).Decode(&body)
+ if body.Target != "carlos/platform" || body.Role != "agent" || body.Agent["session"] == "" {
+ t.Errorf("body: %+v", body)
+ }
+ w.WriteHeader(201)
+ fmt.Fprint(w, `{"id":"ar_one","state":"pending","approve_url":"https://amadan.net/agents/access-requests/ar_one","expires":1795176000}`)
+ default:
+ gets.Add(1)
+ if r.URL.Path != "/api/v1/agents/access-requests/ar_one" || r.URL.Query().Get("wait") != "30" {
+ t.Error("not long polling saved id", r.URL)
+ }
+ fmt.Fprint(w, `{"id":"ar_one","state":"approved"}`)
+ }
+ })
+ f.Reachable(ctx)
+ f.mu.Lock()
+ f.etag = "stale"
+ f.mu.Unlock()
+ dir := t.TempDir()
+ s, err := OpenState(ctx, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := accessCommand()
+ if err := s.AcceptAccess(ctx, "frame", cmd); err != nil {
+ t.Fatal(err)
+ }
+ e := &AccessEngine{State: s, Forge: f}
+ if err := e.Step(ctx, cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ s.Close()
+ s, err = OpenState(ctx, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ var refresh atomic.Int32
+ e = &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }}
+ if err := s.AcceptAccess(ctx, "frame-again", cmd); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 3; i++ {
+ if err := e.Step(ctx, cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if posts.Load() != 1 || gets.Load() != 1 || refresh.Load() != 1 || lists.Load() != 2 {
+ t.Fatalf("posts %d gets %d refresh %d lists %d", posts.Load(), gets.Load(), refresh.Load(), lists.Load())
+ }
+ frames, _, err := s.Unacked(ctx, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(frames) != 2 {
+ t.Fatalf("reports: %d", len(frames))
+ }
+}
+func TestAccessRunnerFinalAndLimits(t *testing.T) {
+ for _, state := range []string{"declined", "expired", "limited", "failed"} {
+ t.Run(state, func(t *testing.T) {
+ var calls atomic.Int32
+ var logs bytes.Buffer
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if state == "limited" {
+ w.WriteHeader(429)
+ fmt.Fprint(w, "SECRET-ACCESS-TOKEN")
+ return
+ }
+ if state == "failed" {
+ w.WriteHeader(500)
+ fmt.Fprint(w, "SECRET-ACCESS-TOKEN")
+ return
+ }
+ fmt.Fprintf(w, `{"id":"ar_one","state":%q}`, state)
+ })
+ s, err := OpenState(context.Background(), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ cmd := accessCommand()
+ s.AcceptAccess(context.Background(), "frame", cmd)
+ e := &AccessEngine{State: s, Forge: f, Logger: slog.New(slog.NewTextHandler(&logs, nil))}
+ for i := 0; i < 3; i++ {
+ if err := e.Step(context.Background(), cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ frames, _, err := s.Unacked(context.Background(), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := json.Marshal(frames)
+ if calls.Load() != 1 || len(frames) != 1 || !strings.Contains(string(raw), `\"state\":\"`+state+`\"`) && !strings.Contains(string(raw), `"state":"`+state+`"`) {
+ t.Fatalf("calls %d reports %s", calls.Load(), raw)
+ }
+ if strings.Contains(logs.String()+string(raw), "SECRET-") {
+ t.Fatal("credential escaped")
+ }
+ })
+ }
+}
+
+func TestAccessRunnerUncertainPostDoesNotRefile(t *testing.T) {
+ var calls atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(500) })
+ ctx := context.Background()
+ dir := t.TempDir()
+ s, err := OpenState(ctx, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := accessCommand()
+ if err := s.AcceptAccess(ctx, "frame", cmd); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec("UPDATE access_requests SET state='filing'"); err != nil {
+ t.Fatal(err)
+ }
+ s.Close()
+ s, err = OpenState(ctx, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ e := &AccessEngine{State: s, Forge: f}
+ if err := e.Step(ctx, cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ if calls.Load() != 0 {
+ t.Fatal("repeated uncertain POST")
+ }
+ var state string
+ if err := s.db.QueryRow("SELECT state FROM access_requests").Scan(&state); err != nil || state != "failed" {
+ t.Fatal(state, err)
+ }
+}
+
+func TestAccessRunnerRunBackoffAndCancellation(t *testing.T) {
+ var gets atomic.Int32
+ var times []time.Time
+ var mu sync.Mutex
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" {
+ fmt.Fprint(w, `{"id":"ar_one","state":"pending"}`)
+ return
+ }
+ mu.Lock()
+ times = append(times, time.Now())
+ mu.Unlock()
+ n := gets.Add(1)
+ if n == 1 {
+ w.WriteHeader(503)
+ return
+ }
+ fmt.Fprint(w, `{"id":"ar_one","state":"expired"}`)
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ cmd := accessCommand()
+ if err := s.AcceptAccess(ctx, "frame", cmd); err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan struct{})
+ e := &AccessEngine{State: s, Forge: f}
+ go func() { e.Run(ctx); close(done) }()
+ deadline := time.After(10 * time.Second)
+ for gets.Load() < 2 {
+ select {
+ case <-deadline:
+ t.Fatal("poll did not recover")
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("poll leaked after cancellation")
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(times) != 2 || times[1].Sub(times[0]) < 1900*time.Millisecond {
+ t.Fatalf("no error backoff: %v", times)
+ }
+}
+
+func TestAccessReadGrantEntersCatalogWithoutWriteAuthority(t *testing.T) {
+ var readable atomic.Bool
+ readable.Store(true)
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/v1/repos" {
+ fmt.Fprint(w, `{"repos":[]}`)
+ return
+ }
+ if r.URL.Path != "/api/v1/repos/carlos/platform" {
+ t.Error("broadened grant", r.URL.Path)
+ }
+ if !readable.Load() {
+ w.WriteHeader(404)
+ return
+ }
+ fmt.Fprint(w, `{"ns":"carlos","name":"platform","tier":"private"}`)
+ })
+ f.accessTargets = func(context.Context) ([]string, error) { return []string{"carlos/platform"}, nil }
+ if got := f.Reachable(context.Background()); len(got) != 1 || got[0] != "amadan.net/carlos/platform" {
+ t.Fatal("reader missing from catalog", got)
+ }
+ if got := f.Repos(); len(got) != 0 {
+ t.Fatal("reader gained write authority", got)
+ }
+ if got := f.CreateIn(context.Background()); len(got) != 0 {
+ t.Fatal("single repo gained namespace", got)
+ }
+ readable.Store(false)
+ f.Recheck()
+ if got := f.Reachable(context.Background()); len(got) != 0 {
+ t.Fatal("revoked reader kept access", got)
+ }
+}
+
+func TestAccessForgeErrorCannotLeakTokenToLogs(t *testing.T) {
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(500)
+ fmt.Fprint(w, "request refused SECRET-ACCESS-TOKEN SECRET-GIT-TOKEN")
+ })
+ _, err := f.RequestAccess(context.Background(), accessCommand())
+ if err == nil {
+ t.Fatal("expected refusal")
+ }
+ var logs bytes.Buffer
+ slog.New(slog.NewTextHandler(&logs, nil)).Error("access request", "err", err)
+ if strings.Contains(logs.String(), "SECRET-") {
+ t.Fatal("forge error leaked credential to logs")
+ }
+}
+
+func TestAccessExistingRequestMustMatchConfirmation(t *testing.T) {
+ for _, role := range []string{"agent", "runner"} {
+ t.Run(role, func(t *testing.T) {
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, `{"id":"existing_one","state":"pending","existing":true,"target":"carlos/platform","role":%q,"reason":"I need to fix the build.","approve_url":"https://amadan.net/settings/agents/requests/existing_one"}`, role)
+ })
+ out, err := f.RequestAccess(context.Background(), accessCommand())
+ if role == "agent" {
+ if err != nil || out.RequestID != "existing_one" {
+ t.Fatal(out, err)
+ }
+ } else if err == nil {
+ t.Fatal("linked a different role than confirmed")
+ }
+ })
+ }
+}
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index 0be555d6..e12492ca 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -713,7 +713,7 @@ func claudeImages(files []heldFile) ([]claude.Image, map[string]bool) {
func opening(person string, catalog []wire.RepoInfo) string {
var b strings.Builder
b.WriteString("You are the Equipo coordinator for " + person + ". You talk with them about their software work. Answer briefly in plain words. Do not use em dashes.\n")
- b.WriteString("Use the named project or the clear continuation. If placement is ambiguous, ask_person with structured placement choices, best guess first. Always confirm a new repository unless the person directly requested one in the main composer this turn. Hand-offs, nudges, quotes and ordinary card answers cannot grant creation. One turn permits one creation; placement-card labels name the repository and come from the server. Wait for the answer before recording or starting work. Learn from project corrections in your notebook. Call status to see reachable repositories and create_in namespaces.\n")
+ b.WriteString("For a not-shared repository, request_access(target, role, reason) raises a confirmation card; default agent, single repo unless the person asks for the namespace. Never retry unprompted. Use the named project or the clear continuation. If placement is ambiguous, ask_person with structured placement choices, best guess first. Always confirm a new repository unless the person directly requested one in the main composer this turn. Hand-offs, nudges, quotes and ordinary card answers cannot grant creation. One turn permits one creation; placement-card labels name the repository and come from the server. Wait for the answer before recording or starting work. Learn from project corrections in your notebook. Call status to see reachable repositories and create_in namespaces.\n")
b.WriteString("For settled placement, call add_project for existing work or create_project for explicitly requested or confirmed new work. Choose the related namespace, otherwise home from status. Change home only when asked. Never fall back silently to a different project after a refusal.\n")
b.WriteString("Once placement is settled for a bug or change, call record_task before investigating, with the repository it belongs to, a short title and their words as the brief. Then investigate with search_code and read_file, attach what you found with add_finding (a one-sentence headline for the person, plain words and no file paths, and the full finding with its file and line), and call start_task with a brief for Engineering. Engineering changes the code on the task's own branch and pushes it to Amadan; the change is then checked and reviewed, and Equipo's merge rules decide whether it merges on its own or asks the person with a card that gives Equipo's call. You cannot make it merge: when you have a concrete reason a change needs the person's look, call hold_merge with that reason. When the person says how a project should merge (\"always ask me about Suite\", \"main is not a release for Woodstar\"), call set_merge_policy with their words; a stricter rule applies at once and a looser one waits for their tap. Never offer to merge or open a pull request, and never ask the person to merge. Use ask_person only for a question only the person can answer. Mockups, prototypes, design options and spikes are explorations: record them with kind explore; they end at a preview and the person's choice of direction, never a merge. A website meant to go live is a change, not an exploration: ask Engineering for plain HTML and CSS files with no build step, kept in one folder that release/preview.json names. Once it is merged its person is asked whether to publish it; never say it is live before then.\n")
b.WriteString("Never file the same problem twice. If record_task returns similar open tasks and one of them is what the person is reporting, call add_report on it with their words and tell them in one line it is already logged and where it stands, naming it as a markdown link; record a separate task only when it is clearly a different problem.\n")
diff --git a/internal/runner/thin/forge.go b/internal/runner/thin/forge.go
index e950d934..8d267998 100644
--- a/internal/runner/thin/forge.go
+++ b/internal/runner/thin/forge.go
@@ -75,10 +75,13 @@ func ValidNewRepo(repo string) bool {
// runner created are kept in its own state directory, never written into
// the credential file, and use the same agent credential.
type fileForge struct {
- creds forge.FileCredentials
- created string
- hub string
- client *http.Client
+ accessTargets func(context.Context) ([]string, error)
+ accessAt time.Time
+ accessRepos []string
+ creds forge.FileCredentials
+ created string
+ hub string
+ client *http.Client
// Enabled turns repository creation on. Off, CreateIn is empty.
enabled bool
@@ -140,6 +143,8 @@ func (f *fileForge) agent(ctx context.Context) (forge.Credential, error) {
func (f *fileForge) Recheck() {
f.mu.Lock()
f.nsAt = time.Time{}
+ f.etag = ""
+ f.accessAt = time.Time{}
f.mu.Unlock()
}
@@ -221,7 +226,7 @@ func (f *fileForge) CreateIn(ctx context.Context) []string {
func (f *fileForge) Reachable(ctx context.Context) []string {
_, listed := f.list(ctx)
- out := append(f.Repos(), listed...)
+ out := append(append(f.Repos(), listed...), f.readGrants(ctx)...)
slices.Sort(out)
return slices.Compact(out)
}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 62ea6b6b..1c4e4362 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -75,6 +75,7 @@ type Link struct {
Engine *Engine
// Steps runs dispatched step attempts; Recheck looks at what the
// agent reaches now (a person acted on a grant card).
+ Access *AccessEngine
Steps *StepEngine
Recheck func()
// Files writes attachment chunks; nil acks them unwritten (tests).
@@ -820,6 +821,13 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro
if err = l.State.AcceptWatch(ctx, f.ID, *v); err != nil {
return 0, err
}
+ case *wire.AccessCommand:
+ if l.knownWorker(ctx) || l.Access == nil {
+ return 0, errAccess
+ }
+ if err = l.State.AcceptAccess(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
case *wire.RecheckCommand:
fresh, err := l.State.SeenResult(ctx, f.ID)
if err != nil {
diff --git a/internal/runner/thin/mcp.go b/internal/runner/thin/mcp.go
index 23fcc455..d8875061 100644
--- a/internal/runner/thin/mcp.go
+++ b/internal/runner/thin/mcp.go
@@ -13,6 +13,7 @@ import (
"sync"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/wire"
"amadan.net/oficina/equipo/internal/runner"
)
@@ -151,6 +152,7 @@ var str = map[string]string{"type": "string"}
// converseTools are the coordinator's tools as the model sees them. The
// descriptions are for the model; people never read them.
var converseTools = []any{
+ map[string]any{"name": wire.ToolRequestAccess, "description": "Propose an access request for an unreachable repository. The person confirms before filing; never retry unprompted. Prefer one repository; namespace only if explicitly requested. Role defaults to agent.", "inputSchema": toolSchema(map[string]any{"target": str, "role": str, "reason": str}, "target", "reason")},
map[string]any{"name": "status", "description": "Read-only: this person's runner, model connections, current projects, the repositories you can add (can_add) and the namespaces you can create repositories in (create_in, with home for unrelated new work). Call it before choosing where work goes.", "inputSchema": toolSchema(map[string]any{})},
map[string]any{"name": "find", "description": "Read-only: find which repository an app, product or feature lives in, by name, alias or keyword (for example Woodstar). Returns candidates with reasons, or says nothing Equipo's agent can reach matches.", "inputSchema": toolSchema(map[string]any{"query": str}, "query")},
map[string]any{"name": "search_code", "description": "Read-only: search a repository's default branch for a fixed string, case insensitive. Returns path:line: text, bounded.", "inputSchema": toolSchema(map[string]any{"repo": str, "query": str}, "repo", "query")},
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 1c2e654c..3c537152 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -196,6 +196,9 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
if fg == nil {
fg = NewFileForge(c.AmadanCredentialPath, c.StateDir, !o.NoCreate)
}
+ if ff, ok := fg.(*fileForge); ok {
+ ff.accessTargets = state.accessReadTargets
+ }
clones := &Clones{Root: c.WorkspaceRoot, Git: c.GitPath, Forge: fg}
index := &Index{Forge: fg, Clones: clones, Path: filepath.Join(c.StateDir, "catalog.json"), Logger: o.Logger, Changed: link.HelloSoon, Pace: o.IndexPace}
tools := &bridge{State: state, Link: link, Forge: fg, Clones: clones, Index: index, Logger: o.Logger, SessionRoot: o.Claude.SessionRoot, Activity: link.Activity}
@@ -305,6 +308,12 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
link.Notify()
return nil
}
+ if af, ok := fg.(AccessForge); ok {
+ link.Access = &AccessEngine{State: state, Forge: af, Refresh: func() { index.Kick(); link.HelloSoon() }, Notify: link.Notify, Logger: o.Logger}
+ accessDone := make(chan struct{})
+ go func() { defer close(accessDone); link.Access.Run(ctx) }()
+ defer func() { cancel(); <-accessDone }()
+ }
go index.Loop(ctx)
link.Hello = func() wire.Hello {
repos := fg.Repos()
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index c27e1903..fff790e3 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -58,7 +58,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
d.SetMaxOpenConns(1)
- if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+usageSchema+profileSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema+researchSchema+scheduleSchema); err != nil {
+ if _, err = d.ExecContext(ctx, schema+accessSchema+stepSchema+watchSchema+askSchema+connSchema+usageSchema+profileSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema+researchSchema+scheduleSchema); err != nil {
d.Close()
return nil, err
}
diff --git a/internal/thintest/access_browser_test.go b/internal/thintest/access_browser_test.go
new file mode 100644
index 00000000..1b4ff0c6
--- /dev/null
+++ b/internal/thintest/access_browser_test.go
@@ -0,0 +1,73 @@
+//go:build browser
+
+package thintest
+
+import (
+ "fmt"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func TestBrowserAccessRequest(t *testing.T) {
+ for _, outcome := range []string{"approved", "declined", "expired", "limited"} {
+ for _, width := range []int64{1280, 390} {
+ for _, scheme := range []string{"light", "dark"} {
+ t.Run(fmt.Sprintf("%d-%s-%s", width, scheme, outcome), func(t *testing.T) {
+ r := newToolRigSaying(t, wire.ProtocolCurrent, "Fix the build in carlos/platform")
+ got := r.call("access-proposal", wire.ToolRequestAccess, map[string]any{"target": "carlos/platform", "reason": "I need access to fix the build."})
+ if got.Code != "asked" {
+ t.Fatal(got)
+ }
+ var card wire.Card
+ r.wait("proposal", func(c *Conversation) bool {
+ for _, v := range c.Cards {
+ if v.Access != nil {
+ card = v
+ return true
+ }
+ }
+ return false
+ })
+ if err := r.runner.Send(r.ctx, "proposal-reply", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Please confirm the access request."}); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
+ p := openInner(t, r.inst.URL, r.inst.Cookie(), width, 844, width == 390, scheme, "reduce")
+ defer p.stop()
+ p.open("/conversation")
+ p.wait(`document.querySelector('[data-access-state="confirmation"]')`, "confirmation")
+ p.check(`document.querySelector('[data-access-state]').textContent.includes('Ask Amadan for access to carlos/platform?')`, "target confirmation")
+ p.check(`document.querySelector('[data-access-state]').textContent.includes('Equipo’s own words')`, "reason attribution")
+ p.check(`!document.querySelector('[data-access-approve]')`, "no approval before filing")
+ p.fits("access confirmation")
+ p.shot(fmt.Sprintf("access-confirm-%d-%s", width, scheme))
+ p.click(`[data-access-aside]`)
+ p.wait(`document.querySelector('[equipo-aside-stub]')`, "aside")
+ p.click(`[equipo-aside-stub] [data-aside-undo]`)
+ p.wait(`document.querySelector('[data-access-confirm]')`, "restore")
+ p.click(`[data-access-confirm]`)
+ _, body, err := r.runner.Expect(r.ctx, wire.FrameRequestAccess)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := body.(*wire.AccessCommand)
+ if !cmd.Confirmed || cmd.CardID != card.ID || cmd.Target != "carlos/platform" || cmd.Role != "agent" {
+ t.Fatalf("command: %+v", cmd)
+ }
+ for _, state := range []string{"pending", outcome} {
+ if err := r.runner.Send(r.ctx, "access-"+state, wire.FrameAccess, wire.AccessReport{CardID: card.ID, Person: cmd.Person, RequestID: "ar_test", State: state, ApproveURL: "https://amadan.net/settings/agents/requests/ar_test"}); err != nil {
+ t.Fatal(err)
+ }
+ p.wait(`document.querySelector('[data-access-state="`+state+`"]')`, state)
+ if state == "pending" {
+ p.check(`(()=>{const a=document.querySelector('[data-access-approve]');return a.target==='_blank'&&a.rel.includes('noopener')&&a.href==='https://amadan.net/settings/agents/requests/ar_test'})()`, "approval link")
+ }
+ p.fits("access " + state)
+ p.shot(fmt.Sprintf("access-%s-%d-%s", state, width, scheme))
+ }
+ })
+ }
+ }
+ }
+}
diff --git a/internal/wire/access.go b/internal/wire/access.go
new file mode 100644
index 00000000..e0cce688
--- /dev/null
+++ b/internal/wire/access.go
@@ -0,0 +1,70 @@
+package wire
+
+import (
+ "net/url"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+const (
+ ToolRequestAccess = "request_access"
+ FrameRequestAccess = "request_access"
+ FrameAccess = "access"
+)
+
+// AccessRequest is a proposal until the person confirms its exact fields.
+type AccessRequest struct {
+ Target string `json:"target"`
+ Role string `json:"role,omitempty"`
+ Reason string `json:"reason"`
+ State string `json:"state,omitempty"`
+ RequestID string `json:"request_id,omitempty"`
+ ApproveURL string `json:"approve_url,omitempty"`
+ Expires int64 `json:"expires,omitempty"`
+}
+type AccessCommand struct {
+ CardID string `json:"card_id"`
+ Person string `json:"person"`
+ Target string `json:"target"`
+ Role string `json:"role"`
+ Reason string `json:"reason"`
+ Confirmed bool `json:"confirmed"`
+}
+type AccessReport struct {
+ CardID string `json:"card_id"`
+ Person string `json:"person"`
+ RequestID string `json:"request_id"`
+ State string `json:"state"`
+ ApproveURL string `json:"approve_url,omitempty"`
+ Expires int64 `json:"expires,omitempty"`
+}
+
+var accessTarget = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}(/[A-Za-z0-9][A-Za-z0-9_.-]{0,99})?$`)
+
+func ValidAccessTarget(s string) bool { return accessTarget.MatchString(s) }
+func AccessFinal(state string) bool {
+ switch state {
+ case "approved", "declined", "expired", "limited", "failed":
+ return true
+ }
+ return false
+}
+func AccessRole(s string) bool { return s == "agent" || s == "reader" || s == "runner" }
+func AccessURL(s string) bool {
+ u, err := url.Parse(s)
+ return err == nil && u.Scheme == "https" && u.Host == "amadan.net" && u.User == nil && strings.HasPrefix(u.Path, "/")
+}
+
+func ValidAccessReason(s string) bool {
+ if strings.TrimSpace(s) == "" || !utf8.ValidString(s) || utf8.RuneCountInString(s) > 280 {
+ return false
+ }
+ for _, r := range s {
+ if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/wire/access_test.go b/internal/wire/access_test.go
new file mode 100644
index 00000000..53f78a2c
--- /dev/null
+++ b/internal/wire/access_test.go
@@ -0,0 +1,27 @@
+package wire_test
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "testing"
+)
+
+func TestAccessProtocol(t *testing.T) {
+ if wire.ProtocolAccess != 26 {
+ t.Fatal("access must follow main protocol 25")
+ }
+ for kind, body := range map[string]any{wire.FrameRequestAccess: wire.AccessCommand{CardID: "c", Person: "p", Target: "ns/repo", Role: "agent", Reason: "Fix it", Confirmed: true}, wire.FrameAccess: wire.AccessReport{CardID: "c", Person: "p", RequestID: "ar", State: "pending"}} {
+ f, err := wire.NewFrame("id", kind, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !f.Durable() {
+ t.Fatal("access frame not durable")
+ }
+ if _, err := wire.Encode(f, wire.Protocol25); err == nil {
+ t.Fatal("access sent to old peer")
+ }
+ if _, err := wire.Encode(f, wire.ProtocolAccess); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
diff --git a/internal/wire/api.go b/internal/wire/api.go
index 02fc1aaa..8b655dd5 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -343,16 +343,17 @@ type AddProject struct {
// Card is something in the conversation the person can act on: a project
// the coordinator added (Remove) or a question (answer).
type Card struct {
- ID string `json:"id"`
- Revision int64 `json:"revision"`
- Kind string `json:"kind"`
- State string `json:"state"`
- TurnID string `json:"turn_id"`
- ProjectID string `json:"project_id"`
- Name string `json:"name"`
- Question string `json:"question"`
- Options []string `json:"options"`
- Choice string `json:"choice"`
+ Access *AccessRequest `json:"access,omitempty"`
+ ID string `json:"id"`
+ Revision int64 `json:"revision"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+ TurnID string `json:"turn_id"`
+ ProjectID string `json:"project_id"`
+ Name string `json:"name"`
+ Question string `json:"question"`
+ Options []string `json:"options"`
+ Choice string `json:"choice"`
// TaskID names the task a task card reports.
TaskID string `json:"task_id"`
CreatedAt time.Time `json:"created_at"`
diff --git a/internal/wire/assistant_test.go b/internal/wire/assistant_test.go
index 90ca307e..07e42dd9 100644
--- a/internal/wire/assistant_test.go
+++ b/internal/wire/assistant_test.go
@@ -81,7 +81,7 @@ func TestAssistantCardJSON(t *testing.T) {
// A runner that speaks 24 or more is spoken to at 24, the warm
// protocol; glances came at 23 and jobs at 22.
func TestSpokenIs24(t *testing.T) {
- if wire.Spoken(99) != 25 || wire.ProtocolCurrent != wire.ProtocolPlacement || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
+ if wire.Spoken(99) != 26 || wire.ProtocolCurrent != wire.ProtocolAccess || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
t.Fatalf("spoken %d, current %d", wire.Spoken(99), wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/frames.go b/internal/wire/frames.go
index eb678aad..1ce49e62 100644
--- a/internal/wire/frames.go
+++ b/internal/wire/frames.go
@@ -67,7 +67,7 @@ type Frame struct {
// Durable reports whether a frame must be acked and resent until acked.
func (f Frame) Durable() bool {
switch f.Type {
- case FrameMessage, FrameAttachment, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameBlob, FrameSendPack, FramePublish, FramePublished, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage, FrameDisconnect, FramePreference, FrameSecret, FrameCheck, FrameModel, FrameModels, FrameBudget, FrameResumeSpend, FrameResearchFile, FrameRelease, FramePriority, FrameWarm:
+ case FrameRequestAccess, FrameAccess, FrameMessage, FrameAttachment, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameBlob, FrameSendPack, FramePublish, FramePublished, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage, FrameDisconnect, FramePreference, FrameSecret, FrameCheck, FrameModel, FrameModels, FrameBudget, FrameResumeSpend, FrameResearchFile, FrameRelease, FramePriority, FrameWarm:
return true
}
return false
@@ -162,6 +162,10 @@ func (f Frame) Decode() (any, error) {
v = &CheckCommand{}
case FrameModel:
v = &ModelCommand{}
+ case FrameRequestAccess:
+ v = &AccessCommand{}
+ case FrameAccess:
+ v = &AccessReport{}
case FrameModels:
v = &ModelsCommand{}
case FrameBudget:
@@ -578,7 +582,7 @@ const (
)
// ConverseTools is the coordinator's tool set in a conversation.
-var ConverseTools = []string{ToolStatus, ToolFind, ToolSearchCode, ToolReadFile, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolReadNotes, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolReadTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProposeSpecialist, ToolResearch}
+var ConverseTools = []string{ToolRequestAccess, ToolStatus, ToolFind, ToolSearchCode, ToolReadFile, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolReadNotes, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolReadTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProposeSpecialist, ToolResearch}
// MoveInTools are the tools a move_in or explore turn may use: it looks
// around and takes notes, and never acts for the person.
@@ -665,6 +669,7 @@ var MutationKinds = map[string]string{
ToolStartTask: "task_start",
ToolCancelTask: "task_cancel",
ToolAddFinding: "finding",
+ ToolRequestAccess: "ask",
ToolAskPerson: "ask",
// One proposal per profile in a turn, in any attempt and wording.
ToolProposeSpecialist: "specialist",
@@ -675,7 +680,7 @@ var MutationKinds = map[string]string{
// WriteTools change something outside the coordinator's session: the
// runner replays an exact repeat of one in a later attempt from its own
// record.
-var WriteTools = []string{ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProjectCreated, ToolProposeSpecialist, ToolResearch}
+var WriteTools = []string{ToolRequestAccess, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProjectCreated, ToolProposeSpecialist, ToolResearch}
// ActivityReport is what the coordinator started doing: thinking, or a
// tool by name. Sent once, never acked, like a delta.
diff --git a/internal/wire/mixed_protocol_test.go b/internal/wire/mixed_protocol_test.go
index 0a844244..5e43bc37 100644
--- a/internal/wire/mixed_protocol_test.go
+++ b/internal/wire/mixed_protocol_test.go
@@ -15,7 +15,7 @@ import (
// both go out whole; at 11 both are downgraded. The numbers are written
// out so that pointing ProtocolResearch back at 12 fails here.
func TestEncodeMixedMeteredAndResearch(t *testing.T) {
- if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol25 {
+ if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol26 {
t.Fatalf("metered %d, research %d, current %d", wire.ProtocolMetered, wire.ProtocolResearch, wire.ProtocolCurrent)
}
metered := wire.HeldConnection{LocalID: "tensorx-1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}}
diff --git a/internal/wire/models_test.go b/internal/wire/models_test.go
index cc00ef24..690486f7 100644
--- a/internal/wire/models_test.go
+++ b/internal/wire/models_test.go
@@ -94,7 +94,7 @@ func modelsFrames(t *testing.T) map[string]wire.Frame {
// protocol is checked because an older step in Encode's chain could
// undo a newer one (S5's bug).
func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) {
- if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol25 {
+ if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol26 {
t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent)
}
fs := modelsFrames(t)
diff --git a/internal/wire/opencode_test.go b/internal/wire/opencode_test.go
index 9092d2a7..13c459cd 100644
--- a/internal/wire/opencode_test.go
+++ b/internal/wire/opencode_test.go
@@ -57,7 +57,7 @@ func providersIn(t *testing.T, raw []byte) (providers, harnesses []string) {
// leave hello and sync, its usage rows leave every report, and a connect
// or a report about one is refused. At 17 nothing changes.
func TestEncodeBelowProtocol17DropsOpenCode(t *testing.T) {
- if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol25 {
+ if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol26 {
t.Fatalf("opencode %d, current %d", wire.ProtocolOpenCode, wire.ProtocolCurrent)
}
budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1}
diff --git a/internal/wire/publish_test.go b/internal/wire/publish_test.go
index 13246578..95588ac6 100644
--- a/internal/wire/publish_test.go
+++ b/internal/wire/publish_test.go
@@ -17,7 +17,7 @@ import (
// and a hello's sites capability are dropped, so nothing a protocol 15
// peer decodes strictly carries them.
func TestEncodeBelowProtocol16DropsPublish(t *testing.T) {
- if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol25 {
+ if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol26 {
t.Fatalf("publish %d, current %d", wire.ProtocolPublish, wire.ProtocolCurrent)
}
publish := wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 75c33eec..7ec619d9 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -51,6 +51,7 @@ const (
Protocol23 = 23
Protocol24 = 24
Protocol25 = 25
+ Protocol26 = 26
// ProtocolSpend is the first protocol with a fix round's Feedback and
// a usage row's Turns; Encode drops both below it.
ProtocolSpend = Protocol3
@@ -173,7 +174,8 @@ const (
ProtocolWarm = Protocol24
// ProtocolPlacement adds durable notebook corrections for project moves.
ProtocolPlacement = Protocol25
- ProtocolCurrent = ProtocolPlacement
+ ProtocolAccess = Protocol26
+ ProtocolCurrent = ProtocolAccess
)
// Runner roles. A person's first runner is the primary: the coordinator,
@@ -540,7 +542,12 @@ type RunnerProtocol struct {
}
// Speaks reports whether a frame type exists at protocol.
-func Speaks(protocol int, kind string) bool { return protocol >= Protocol2 || !protocol2Only[kind] }
+func Speaks(protocol int, kind string) bool {
+ if kind == FrameRequestAccess || kind == FrameAccess {
+ return protocol >= ProtocolAccess
+ }
+ return protocol >= Protocol2 || !protocol2Only[kind]
+}
// ErrProtocol means a frame cannot be spoken at the connection's protocol.
var ErrProtocol = errors.New("wire: frame not in this protocol")
@@ -590,6 +597,9 @@ func Encode(f Frame, protocol int) (Frame, error) {
if protocol < ProtocolGlance && f.Type == FrameGlance || protocol < ProtocolWarm && f.Type == FrameWarm {
return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol)
}
+ if v, ok := body.(*ToolCall); ok && protocol < ProtocolAccess && v.Name == ToolRequestAccess {
+ return Frame{}, ErrProtocol
+ }
changed := false
if protocol < ProtocolPlacement {
if v, ok := body.(*MessageCommand); ok && len(v.PlacementNotes) > 0 {
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go
index 1d9d91bc..261fdebd 100644
--- a/internal/wire/runners_test.go
+++ b/internal/wire/runners_test.go
@@ -413,7 +413,7 @@ func TestEncodeBelowProtocol9DropsPreviews(t *testing.T) {
if _, err := wire.Encode(d, wire.ProtocolPreview); err != nil {
t.Fatal(err)
}
- if wire.ProtocolCurrent != wire.ProtocolPlacement || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
+ if wire.ProtocolCurrent != wire.ProtocolAccess || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
t.Fatalf("current %d", wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go
index 3df34bf7..5e7b095b 100644
--- a/internal/wire/schedule_test.go
+++ b/internal/wire/schedule_test.go
@@ -17,7 +17,7 @@ import (
// refused anything that spends, never handed it), and a dispatch loses
// its priority, deadline and release; what 13 already had is unchanged.
func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) {
- if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol25 {
+ if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol26 {
t.Fatalf("scheduler %d, current %d", wire.ProtocolScheduler, wire.ProtocolCurrent)
}
by := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC)
diff --git a/internal/wire/usage_test.go b/internal/wire/usage_test.go
index bd8af724..0c1354a0 100644
--- a/internal/wire/usage_test.go
+++ b/internal/wire/usage_test.go
@@ -44,7 +44,7 @@ func headrooms(t *testing.T, raw []byte) []map[string]json.RawMessage {
// decodes strictly against the frozen protocol 14 headroom, and the
// caller's own values are untouched; at 15 nothing changes.
func TestEncodeBelowProtocol15DropsReadingTimes(t *testing.T) {
- if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol25 {
+ if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol26 {
t.Fatalf("readings %d, current %d", wire.ProtocolReadings, wire.ProtocolCurrent)
}
at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC)
diff --git a/internal/wire/warm_test.go b/internal/wire/warm_test.go
index 81c740ba..14413fc0 100644
--- a/internal/wire/warm_test.go
+++ b/internal/wire/warm_test.go
@@ -13,7 +13,7 @@ import (
// other (durable, acked), and Encode refuses it below 24: an older
// runner's strict decoder would close the stream on it.
func TestEncodeWarmBelow24(t *testing.T) {
- if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolPlacement || wire.Spoken(99) != 25 {
+ if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolAccess || wire.Spoken(99) != 26 {
t.Fatalf("protocols %d %d", wire.ProtocolWarm, wire.ProtocolCurrent)
}
f, err := wire.NewFrame("c1", wire.FrameWarm, wire.WarmCommand{Person: "ana@example.com"})