oficina / equipo Public

Merge branch 'ask-for-access' into main

Let Equipo ask Amadan for repository access with one tap

The coordinator proposes a narrow access request; only the person's
confirmation files it, through the primary runner's forge credential,
against Amadan's real contract. The card links to Amadan's approval
page and resumes the original request once approved. Write gates use
write grants only. Protocol 26, migration 0091. Fable, 2 rounds.
claude agent, operated by paul@keymail.dev 98defecc90f292d6267048281b5837899599b62a parent 0d91a4eparent 9f08cd7
62 files changed, +2,964 −84
  • .rastrillo/budgets.txt +7 −7
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +30 −0
  • internal/equipo/access_review_test.go +34 −0
  • internal/equipo/chat/access_authority.go +67 −0
  • internal/equipo/chat/access_request.go +234 −0
  • internal/equipo/chat/access_request_test.go +194 −0
  • internal/equipo/chat/access_review_test.go +164 −0
  • internal/equipo/chat/placement_edges_test.go +1 −1
  • internal/equipo/chat/projects.go +11 −1
  • internal/equipo/chat/runner.go +2 −0
  • internal/equipo/chat/stream.go +3 −1
  • internal/equipo/chat/tools.go +29 −2
  • internal/equipo/chat_page.go +17 −0
  • internal/equipo/chat_wiring.go +3 −0
  • internal/equipo/copy.go +28 −0
  • internal/equipo/migrations/0091_access_requests.sql +1 −0
  • internal/equipo/migrations/schema.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/plan3test/plan3_release_test.go +2 −1
  • internal/runner/policy_inputs.go +4 −1
  • internal/runner/provider/actions.go +14 −2
  • internal/runner/provider/claude/converse_policy_test.go +13 −0
  • internal/runner/provider/claude/launcher.go +2 −2
  • internal/runner/provider/codex/launcher.go +1 −2
  • internal/runner/thin/access.go +266 −0
  • internal/runner/thin/access_catalog.go +99 −0
  • internal/runner/thin/access_contract.go +26 −0
  • internal/runner/thin/access_contract_test.go +69 −0
  • internal/runner/thin/access_forge.go +134 −0
  • internal/runner/thin/access_protocol.go +74 −0
  • internal/runner/thin/access_review_test.go +334 −0
  • internal/runner/thin/access_round3_test.go +250 −0
  • internal/runner/thin/access_test.go +395 −0
  • internal/runner/thin/bridge.go +5 −3
  • internal/runner/thin/claude.go +20 −9
  • internal/runner/thin/codex.go +9 −5
  • internal/runner/thin/forge.go +22 −10
  • internal/runner/thin/link.go +21 −1
  • internal/runner/thin/mcp.go +12 −5
  • internal/runner/thin/merge.go +1 −1
  • internal/runner/thin/run.go +10 −0
  • internal/runner/thin/state.go +5 −1
  • internal/thintest/access_browser_test.go +73 −0
  • internal/thintest/access_review_browser_test.go +50 −0
  • internal/thintest/access_round3_browser_test.go +48 −0
  • internal/wire/access.go +75 −0
  • internal/wire/access_test.go +40 −0
  • internal/wire/api.go +11 −10
  • internal/wire/assistant_test.go +1 −1
  • internal/wire/frames.go +10 −4
  • 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 +15 −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 passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index ee502561..2331581f 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,19 +14,19 @@ 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 21076 - Shared web views and Roster access status copy. Measured 21076 source lines after final access-request fixes.
+size internal/wire 6543 - Shared protocol types; protocol 26 adds durable confirmed access commands and state reports. Limits match measured lines. Access review guards and contract tests; limit matches 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).
perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
-size internal/runner 9930 9200 Runner configuration and provider seams, including optional Engineering module mounts. Measured 9930 source lines.
+size internal/runner 9933 9200 Runner configuration and provider seams, including optional Engineering module mounts. Measured 9930 source lines. Access review guards and contract tests; limit matches measured lines.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
time internal/runner/provider/codex 35s Plan 3 CI repair measured 24.464s for the full package (controller CI 27.908s).
time internal/runner/provider/pi 60s The real pinned Pi in bubblewrap against a fake TensorX: probes P1 to P5 (a hundred RPC turns), the hostile repository, and the pinned tree checked whole (about 160 MB); measured 22s locally.
time internal/runner/provider/opencode 90s The real pinned OpenCode in bubblewrap against a fake Go: probes, the hostile repository per source, termination, resume; the 260 MB binary hashed per launch. Measured 40s.
-size internal/runner/provider 5505 - Pi adds a pinned isolated shell, immutable configuration files and offline Go; the glance action pins its small models. Measured 5505 source lines.
+size internal/runner/provider 5517 - Provider policies, isolated Pi shell and fixed glance models; exact legacy/current coordinator tool sets. Measured 5517 source lines.
time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
@@ -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 27080 19975 Shared runner state and forge integration. Measured 27080 source and 19975 test lines including disconnect, POST outcome and expiry guards.
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 30667 - Transactional authority and access confirmation; resume after provisional expiry. Measured 30667 source 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 - 30981 Shared instance/browser fixtures, including final access outcomes at two widths and themes. Measured 30981 test 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..add25cb8 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4704,6 +4704,36 @@ 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.not_owned` | Amadan can’t ask the owner of %s for access. | Access request final fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.already` | Equipo already has access. | Access request final fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.unconfirmed` | I couldn’t confirm this access request with Amadan. Ask again to make a new request. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.missing` | Amadan no longer has this access request. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.uncheckable` | I can’t check this access request on Amadan. Ask again to make a new request. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.authority` | This runner can no longer ask for access. Confirm a new request after your runner is ready. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.confirm_namespace` | Ask Amadan for access to everything in %s? | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.namespace` | Everything in %s | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.granted_note` | Access granted to %s. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `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/access_review_test.go b/internal/equipo/access_review_test.go
new file mode 100644
index 00000000..864d06c2
--- /dev/null
+++ b/internal/equipo/access_review_test.go
@@ -0,0 +1,34 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "strings"
+ "testing"
+)
+
+func TestAccessGrantedNoteAndBroadLabel(t *testing.T) {
+ c := wire.Card{Kind: wire.CardAccess, State: wire.CardResolved, Access: &wire.AccessRequest{Target: "carlos", State: "approved"}}
+ v := cardView(c, nil, nil)
+ if !strings.Contains(v.Note, "Access granted") || !strings.Contains(v.Note, "carlos") {
+ t.Fatal("missing grant note", v.Note)
+ }
+ if !strings.Contains(v.AccessTarget, "Everything in carlos") {
+ t.Fatal("namespace label not broad", v.AccessTarget)
+ }
+}
+
+func TestAccessPostFinalCopy(t *testing.T) {
+ for _, state := range []string{"not_owned", "already"} {
+ c := wire.Card{Kind: wire.CardAccess, State: wire.CardResolved, Access: &wire.AccessRequest{Target: "carlos/platform", State: state}}
+ v := cardView(c, nil, nil)
+ if strings.Contains(v.Line, "Ask again") || strings.HasPrefix(v.Line, "access.") {
+ t.Fatal("outcome lacks final copy", v.Line)
+ }
+ if state == "not_owned" && !strings.Contains(v.Line, "owner of carlos") {
+ t.Fatal("owner refusal lacks namespace", v.Line)
+ }
+ if state == "already" && v.Line != "Equipo already has access." {
+ t.Fatal("existing access unclear", v.Line)
+ }
+ }
+}
diff --git a/internal/equipo/chat/access_authority.go b/internal/equipo/chat/access_authority.go
new file mode 100644
index 00000000..81c3795d
--- /dev/null
+++ b/internal/equipo/chat/access_authority.go
@@ -0,0 +1,67 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func (s *Store) AuthorizeAccess(ctx context.Context, l Lease, id string) (refused string, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if _, err := t.current(l); err != nil {
+ return err
+ }
+ var err error
+ refused, err = t.authorizeAccess(l, id)
+ return err
+ })
+ return
+}
+
+func (t *txn) authorizeAccess(l Lease, id string) (string, error) {
+ if l.Protocol < wire.ProtocolAccess {
+ return "withdrawn", nil
+ }
+ var c cardRecord
+ if err := t.db.Where("id = ? AND person = ? AND kind = ?", id, l.Runner.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 c.State != wire.CardOpen || a.State != "filing" {
+ return "withdrawn", nil
+ }
+ // Only the runner that received this confirmed command can settle its refusal.
+ var n int64
+ if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND person = ? AND kind = ? AND json_extract(body, '$.card_id') = ?", l.Runner.RunnerID, l.Runner.Person, wire.FrameRequestAccess, id).Count(&n).Error; err != nil {
+ return "", err
+ }
+ if n == 0 {
+ return "", ErrForbidden
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person)
+ if err != nil {
+ return "", err
+ }
+ role := wire.RolePrimary
+ if t.s.authority.RunnerRole != nil {
+ role, err = t.s.authority.RunnerRole(t.db, l.Runner.RunnerID)
+ if err != nil {
+ return "", err
+ }
+ }
+ if primary == l.Runner.RunnerID && role == wire.RolePrimary {
+ return "", nil
+ }
+ a.State = "authority"
+ raw, _ := json.Marshal(a)
+ c.Access = string(raw)
+ c.State = wire.CardResolved
+ if err := t.saveCard(&c); err != nil {
+ return "", err
+ }
+ return "withdrawn", t.s.authority.Audit(t.db, c.Person, "access.authority", c.ID)
+}
diff --git a/internal/equipo/chat/access_request.go b/internal/equipo/chat/access_request.go
new file mode 100644
index 00000000..9a8ed76a
--- /dev/null
+++ b/internal/equipo/chat/access_request.go
@@ -0,0 +1,234 @@
+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}
+ }
+ key := "access.confirm"
+ if !strings.Contains(in.Target, "/") {
+ key = "access.confirm_namespace"
+ }
+ c.Access, c.Name, c.Question = string(raw), in.Target, fmt.Sprintf(t.s.authority.Copy(key), 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) && !(a.State == "expired" && (v.State == "approved" || v.State == "pending")) {
+ return nil
+ }
+ if v.State != "pending" && !wire.AccessFinal(v.State) || len(v.RequestID) > 200 || v.ApproveURL != "" && !wire.AccessURL(v.ApproveURL, v.RequestID) {
+ return ErrInvalid
+ }
+ if (v.State == "pending" || v.State == "approved") && (v.RequestID == "" || !wire.AccessURL(v.ApproveURL, v.RequestID)) {
+ return ErrInvalid
+ }
+ if a.RequestID != "" && a.RequestID != v.RequestID {
+ return ErrInvalid
+ }
+ if a.State == "expired" && (v.State == "approved" || v.State == "pending") {
+ c.State = wire.CardOpen
+ }
+ 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..773e8d9e
--- /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", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"}
+ 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/access_review_test.go b/internal/equipo/chat/access_review_test.go
new file mode 100644
index 00000000..ee4e96bc
--- /dev/null
+++ b/internal/equipo/chat/access_review_test.go
@@ -0,0 +1,164 @@
+package chat
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "context"
+ "encoding/json"
+ "errors"
+ "gorm.io/gorm"
+ "strings"
+ "testing"
+)
+
+func TestAccessReportURLAndSecondaryGuards(t *testing.T) {
+ for _, bad := range []string{"https://amadan.net/other/ar_one", "https://amadan.net/settings/agents/requests/other", "https://amadan.net/settings/agents/requests/ar_one?x=1", "https://user@amadan.net/settings/agents/requests/ar_one", "https://amadan.net/settings/agents/requests/ar_one\\bad"} {
+ t.Run(bad, func(t *testing.T) {
+ r, turn := accessRig(t, "Fix carlos/platform")
+ c := proposeAccess(t, r, turn, "carlos/platform")
+ r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision})
+ err := r.s.tx(context.Background(), func(tx *txn) error {
+ return tx.accessReport(Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolAccess}, &wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: "pending", ApproveURL: bad})
+ })
+ if !errors.Is(err, ErrInvalid) {
+ t.Fatal("hostile link accepted", err)
+ }
+ })
+ }
+ r, turn := accessRig(t, "Fix carlos/platform")
+ c := proposeAccess(t, r, turn, "carlos/platform")
+ r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision})
+ err := r.s.tx(context.Background(), func(tx *txn) error {
+ return tx.accessReport(Lease{Runner: RunnerPrincipal{RunnerID: "SECONDARY", Person: hkOwner}, Protocol: wire.ProtocolAccess}, &wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: "approved", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"})
+ })
+ if !errors.Is(err, ErrForbidden) {
+ t.Fatal("secondary report accepted", err)
+ }
+}
+func TestAccessNamespaceUsesBroadCopy(t *testing.T) {
+ r, turn := accessRig(t, "Give access to the whole carlos namespace")
+ c := proposeAccess(t, r, turn, "carlos")
+ if c.Question == "access.confirm%!(EXTRA string=carlos)" || c.Question == "access.confirm" {
+ t.Fatal("namespace uses repository confirmation", c.Question)
+ }
+ var a wire.AccessRequest
+ json.Unmarshal([]byte(c.Access), &a)
+ if a.Target != "carlos" {
+ t.Fatal(a)
+ }
+ if c.Question != "access.confirm_namespace%!(EXTRA string=carlos)" {
+ t.Fatal("missing broad copy key", c.Question)
+ }
+}
+func TestAccessSaveDoesNotRewriteOtherCards(t *testing.T) {
+ r := newMeteredRig(t)
+ c := cardRecord{ID: "other", Person: hkOwner, Kind: wire.CardQuestion, Name: "original", Question: "original", Options: "[]"}
+ r.s.db.G.Create(&c)
+ c.Name = "changed"
+ c.Question = "changed"
+ if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.saveCard(&c) }); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ if c.Name != "original" || c.Question != "original" {
+ t.Fatal("unrelated card text rewritten")
+ }
+}
+
+func TestAccessDemotedPrimarySettlesCardBeforePost(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)
+ }
+ r.s.authority.PrimaryRunner = func(*gorm.DB, string) (string, error) { return "NEWPRIMARY", nil }
+ lease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolAccess}
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ no, err := tx.authorizeAccess(lease, c.ID)
+ if err == nil && no == "" {
+ t.Fatal("demoted primary authorized")
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ var a wire.AccessRequest
+ json.Unmarshal([]byte(c.Access), &a)
+ if c.State != wire.CardResolved || a.State != "authority" {
+ t.Fatal("demoted request still waits", c.State, a.State)
+ }
+}
+
+func TestAccessWorkerLeaseSettlesCard(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)
+ }
+ r.s.authority.RunnerRole = func(*gorm.DB, string) (string, error) { return wire.RoleWorker, nil }
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ no, err := tx.authorizeAccess(Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolAccess}, c.ID)
+ if err == nil && no == "" {
+ t.Fatal("worker lease authorized")
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ if c.State != wire.CardResolved {
+ t.Fatal("worker card not settled")
+ }
+}
+
+func TestAccessFindHintHonorsNegotiatedProtocol(t *testing.T) {
+ for _, proto := range []int{25, 26} {
+ r := placementRig(t)
+ r.s.db.G.Model(&runnerSessionRecord{}).Where("runner_id = ?", "RUNNER1").Update("protocol", proto)
+ if err := r.s.tx(context.Background(), func(tx *txn) error {
+ got, err := tx.find(turnRecord{ID: "find", Person: hkOwner}, "carlos/platform")
+ if strings.Contains(got.Text, "request_access") != (proto >= 26) {
+ t.Fatal("unsupported tool prompted", proto, got.Text)
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func TestAccessLateApprovalResumesAfterExpiry(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)
+ }
+ r.s.db.G.Model(&turnRecord{}).Where("id = ?", turn.ID).Update("state", wire.TurnReplied)
+ lease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolAccess}
+ for _, state := range []string{"expired", "pending", "approved", "approved"} {
+ report := wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: state, ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"}
+ if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.accessReport(lease, &report) }); err != nil {
+ t.Fatal(err)
+ }
+ if state == "pending" {
+ var saved cardRecord
+ r.s.db.G.First(&saved, "id = ?", c.ID)
+ var access wire.AccessRequest
+ json.Unmarshal([]byte(saved.Access), &access)
+ if access.State != "pending" || saved.State != wire.CardOpen {
+ t.Fatal("server pending did not correct local expiry")
+ }
+ }
+ }
+ h := wire.Hello{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 n int64
+ r.s.db.G.Model(&messageRecord{}).Where("idempotency_key = ?", "access-approved:"+c.ID).Count(&n)
+ if n != 1 {
+ t.Fatal("late approval did not resume exactly once", n)
+ }
+}
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..7c6baeae 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,11 @@ 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 {
+ fields := []string{"state", "choice", "answer_message", "undo", "revision", "updated_at"}
+ if c.Kind == wire.CardAccess {
+ fields = append(fields, "access", "name", "question")
+ }
+ if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select(fields).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..a94c7b9f 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
@@ -185,6 +185,8 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
// authorization (or a publication's, before the push).
refused := ""
switch {
+ case v.AccessCard != "":
+ refused, err = store.AuthorizeAccess(ctx, rc.lease, v.AccessCard)
case v.StepID != "" && v.Publication != "":
refused, err = store.AuthorizePublication(ctx, rc.lease, v.StepID, v.Attempt, v.Publication)
case v.StepID != "":
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 0b28a1f9..f687ab5d 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,9 +1042,20 @@ 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)
+ }
+ primary, 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 = ?", primary).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ if runner.Protocol >= wire.ProtocolAccess {
+ 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 +1182,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 +1202,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..ab38165b 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -96,6 +96,7 @@ type chatCard struct {
ReplyKey string
wire.Card
Line, Change, Agent, Namespace, Note string
+ AccessTarget string
Presentation chat.CardPresentation
Author, AuthorIcon, Verb string
// GrantHow introduces an access card's grant command.
@@ -150,6 +151,22 @@ 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)
+ if c.Access.State == "not_owned" {
+ ns, _, _ := strings.Cut(c.Access.Target, "/")
+ v.Line = fmt.Sprintf(v.Line, ns)
+ }
+ v.AccessTarget = c.Access.Target
+ if !strings.Contains(c.Access.Target, "/") {
+ v.AccessTarget = fmt.Sprintf(copyText("access.namespace"), c.Access.Target)
+ }
+ if c.Access.State == "approved" && c.State == wire.CardResolved {
+ v.Note = fmt.Sprintf(copyText("access.granted_note"), v.AccessTarget)
+ }
+ 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..e05b60e5 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -66,6 +66,34 @@ const BootLog = "Equipo could not start."
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
var pageCopy = map[string]string{
+ "access.not_owned": "Amadan can’t ask the owner of %s for access.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.already": "Equipo already has access.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.unconfirmed": "I couldn’t confirm this access request with Amadan. Ask again to make a new request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.missing": "Amadan no longer has this access request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.uncheckable": "I can’t check this access request on Amadan. Ask again to make a new request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.authority": "This runner can no longer ask for access. Confirm a new request after your runner is ready.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.confirm_namespace": "Ask Amadan for access to everything in %s?", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.namespace": "Everything in %s", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.granted_note": "Access granted to %s.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+
+ "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/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 3954b0ed..9201cbf0 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -712,3 +712,4 @@ CREATE INDEX chat_task_move ON chat_tasks(creator, move_project) WHERE move_proj
UPDATE chat_notebooks SET entries = (SELECT json_group_array(json(value)) FROM json_each(chat_notebooks.entries) WHERE NOT (coalesce(json_extract(value, '$.source'), '') = 'own' AND substr(json_extract(value, '$.id'), 1, 2) = 'mv')) WHERE entries IS NOT NULL AND entries <> '';
CREATE TABLE oficina_connections (person text PRIMARY KEY, refresh text, revision integer, created_at datetime, updated_at datetime);
ALTER TABLE chat_tasks ADD COLUMN move_abandoned numeric;
+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..223e244c
--- /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"}}: {{.AccessTarget}}{{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/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go
index 422bc8c5..5f1e26c3 100644
--- a/internal/plan3test/plan3_release_test.go
+++ b/internal/plan3test/plan3_release_test.go
@@ -181,10 +181,11 @@ func plan3CopyInventory(t *testing.T) {
approvedOficina := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged)")
acceptedRoster := strings.HasPrefix(key, "roster.") && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-14)")
acceptedPlacement := strings.HasPrefix(key, "placement.") && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)")
+ acceptedAccess := slices.Contains([]string{"access.not_owned", "access.already", "access.unconfirmed", "access.missing", "access.uncheckable", "access.authority", "access.confirm_namespace", "access.namespace", "access.granted_note", "access.title", "access.confirm", "access.ask", "access.approve", "access.aside", "access.reason", "access.role", "access.confirmation", "access.filing", "access.pending", "access.approved", "access.declined", "access.expired", "access.limited", "access.failed", "access.operator", "access.continue"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)")
acceptedPlacementEdges := slices.Contains([]string{"placement.late_push", "placement.late_report"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)")
acceptedReportActions := slices.Contains([]string{"roster.talk", "roster.round_busy", "roster.round_done", "roster.merge_busy", "roster.merge_done"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)")
acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key])
- if !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina {
+ if !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina {
t.Fatal("entry has no copy review status or applicable acceptance", key)
}
}
diff --git a/internal/runner/policy_inputs.go b/internal/runner/policy_inputs.go
index 579fcc1a..0b41654b 100644
--- a/internal/runner/policy_inputs.go
+++ b/internal/runner/policy_inputs.go
@@ -13,7 +13,7 @@ import (
// PolicyInputs builds a provider policy's inputs from the runner's own
// configuration; the policy hash is computed from them on every launch. It
// grants no authority: the caller still needs a verified account lease.
-func PolicyInputs(ctx context.Context, c Config, s provider.Selection, binding provider.Binding, work, step, policyScratch string) (provider.PolicyInputs, error) {
+func PolicyInputs(ctx context.Context, c Config, s provider.Selection, binding provider.Binding, work, step, policyScratch string, withoutAccess ...bool) (provider.PolicyInputs, error) {
r := Runtime{cfg: c}
configured, _, err := r.binding(s)
if err != nil {
@@ -54,6 +54,9 @@ func PolicyInputs(ctx context.Context, c Config, s provider.Selection, binding p
return provider.PolicyInputs{}, err
}
in := provider.PolicyInputs{Action: step, Workspace: work, Scratch: policyScratch, RuntimeFiles: runtimeFiles, DeniedPaths: denies.DeniedPaths, EgressHosts: network.Hosts, LauncherVersion: provider.LauncherVersion, BwrapVersion: "0.11.0", Tools: profile.MCPTools()}
+ if step == "converse" && len(withoutAccess) > 0 && withoutAccess[0] {
+ in.Tools = provider.WithoutAccess(in.Tools)
+ }
if s.Provider == "claude" {
in, err = claude.PolicyInputs(binding, in, profile.Specialist, s.Model)
} else {
diff --git a/internal/runner/provider/actions.go b/internal/runner/provider/actions.go
index 2c809821..1d4ec4f0 100644
--- a/internal/runner/provider/actions.go
+++ b/internal/runner/provider/actions.go
@@ -1,6 +1,9 @@
package provider
-import "amadan.net/oficina/equipo/internal/specialist"
+import (
+ "amadan.net/oficina/equipo/internal/specialist"
+ "slices"
+)
// ActionProfile is an executable capability, independent of a specialist's name.
type ActionProfile struct {
@@ -174,7 +177,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).
@@ -198,3 +201,12 @@ func CoordinatorNativeTools(family string) []string {
}
return nil
}
+
+// WithoutAccess removes only the protocol-26 proposal tool for an older peer.
+func WithoutAccess(tools []string) []string {
+ return slices.DeleteFunc(slices.Clone(tools), func(s string) bool { return s == "mcp__equipo__request_access" })
+}
+func (p ActionProfile) AcceptsTools(tools []string) bool {
+ want := p.MCPTools()
+ return slices.Equal(tools, want) || p.Action == "converse" && slices.Equal(tools, WithoutAccess(want))
+}
diff --git a/internal/runner/provider/claude/converse_policy_test.go b/internal/runner/provider/claude/converse_policy_test.go
index a08ff504..1d5b6cb0 100644
--- a/internal/runner/provider/claude/converse_policy_test.go
+++ b/internal/runner/provider/claude/converse_policy_test.go
@@ -25,3 +25,16 @@ func TestConversePolicyCoversEveryTool(t *testing.T) {
t.Fatal("a tool the conversation does not offer was accepted")
}
}
+
+func TestAccessLegacyPolicy(t *testing.T) {
+ p, _ := provider.Profile("converse")
+ tools := p.MCPTools()[1:]
+ b := provider.Binding{Provider: "claude", CredentialHome: "/private/account", Home: "/private/run", RuntimeRoot: "/private/runtime"}
+ if _, err := PolicyInputs(b, provider.PolicyInputs{Action: "converse", Tools: tools}, p.Specialist, "model"); err != nil {
+ t.Fatal("legacy tool set refused", err)
+ }
+ tools = append(tools, "mcp__equipo__merge_now")
+ if _, err := PolicyInputs(b, provider.PolicyInputs{Action: "converse", Tools: tools}, p.Specialist, "model"); err == nil {
+ t.Fatal("unexpected extra tool allowed")
+ }
+}
diff --git a/internal/runner/provider/claude/launcher.go b/internal/runner/provider/claude/launcher.go
index cbf084ab..cdeb4ef0 100644
--- a/internal/runner/provider/claude/launcher.go
+++ b/internal/runner/provider/claude/launcher.go
@@ -130,7 +130,7 @@ func nativeTools(role string) ([]string, error) {
func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, model string) (provider.PolicyInputs, error) {
if in.Action != "" {
profile, err := provider.Profile(in.Action)
- if err != nil || !reflect.DeepEqual(in.Tools, profile.MCPTools()) || (specialist != profile.Specialist && !(in.Action == "reproduce" && specialist == "Product")) {
+ if err != nil || !profile.AcceptsTools(in.Tools) || (specialist != profile.Specialist && !(in.Action == "reproduce" && specialist == "Product")) {
return in, provider.ErrPolicy
}
}
@@ -140,7 +140,7 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, mode
}
tools := append(append([]string{}, native...), "mcp__equipo__permission")
for _, tool := range in.Tools {
- converse := in.Action == "converse" && slices.Contains([]string{"mcp__equipo__status", "mcp__equipo__find", "mcp__equipo__search_code", "mcp__equipo__read_file", "mcp__equipo__add_project", "mcp__equipo__create_project", "mcp__equipo__set_project_home", "mcp__equipo__star_project", "mcp__equipo__write_note", "mcp__equipo__read_notes", "mcp__equipo__record_task", "mcp__equipo__add_finding", "mcp__equipo__start_task", "mcp__equipo__read_task", "mcp__equipo__cancel_task", "mcp__equipo__add_report", "mcp__equipo__hold_merge", "mcp__equipo__set_merge_policy", "mcp__equipo__propose_specialist", "mcp__equipo__research"}, tool)
+ converse := in.Action == "converse" && slices.Contains([]string{"mcp__equipo__request_access", "mcp__equipo__status", "mcp__equipo__find", "mcp__equipo__search_code", "mcp__equipo__read_file", "mcp__equipo__add_project", "mcp__equipo__create_project", "mcp__equipo__set_project_home", "mcp__equipo__star_project", "mcp__equipo__write_note", "mcp__equipo__read_notes", "mcp__equipo__record_task", "mcp__equipo__add_finding", "mcp__equipo__start_task", "mcp__equipo__read_task", "mcp__equipo__cancel_task", "mcp__equipo__add_report", "mcp__equipo__hold_merge", "mcp__equipo__set_merge_policy", "mcp__equipo__propose_specialist", "mcp__equipo__research"}, tool)
assist := in.Action == "assist" && slices.Contains([]string{"mcp__equipo__look", "mcp__equipo__describe", "mcp__equipo__use", "mcp__equipo__write_note", "mcp__equipo__read_notes"}, tool)
answer := in.Action == "answer" && slices.Contains([]string{"mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show"}, tool)
research := provider.ResearchAction(in.Action) && slices.Contains([]string{"mcp__equipo__submit_findings", "mcp__equipo__keep_image"}, tool)
diff --git a/internal/runner/provider/codex/launcher.go b/internal/runner/provider/codex/launcher.go
index 6aff4eb8..889ca318 100644
--- a/internal/runner/provider/codex/launcher.go
+++ b/internal/runner/provider/codex/launcher.go
@@ -11,7 +11,6 @@ import (
"io"
"path/filepath"
"reflect"
- "slices"
"sort"
"strconv"
"strings"
@@ -120,7 +119,7 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (p
profile, err := provider.Profile(in.Action)
// slices.Equal: a policy read back from its manifest lists no
// tools as null (a glance).
- if err != nil || !slices.Equal(in.Tools, profile.MCPTools()) {
+ if err != nil || !profile.AcceptsTools(in.Tools) {
return in, provider.ErrPolicy
}
}
diff --git a/internal/runner/thin/access.go b/internal/runner/thin/access.go
new file mode 100644
index 00000000..bc384e92
--- /dev/null
+++ b/internal/runner/thin/access.go
@@ -0,0 +1,266 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "strings"
+ "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, confirmed_at INTEGER NOT NULL DEFAULT 0, poll_failures INTEGER NOT NULL DEFAULT 0);`
+
+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,confirmed_at) VALUES(?,?,'queued',?)", c.CardID, string(raw), time.Now().UnixNano())
+ return err
+ })
+}
+
+type AccessEngine struct {
+ Authorize func(context.Context, string) error
+ 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
+ settled := false
+ localExpiry := false
+ 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.Authorize != nil {
+ err = e.Authorize(ctx, cmd.CardID)
+ settled = errors.Is(err, ErrWithdrawn)
+ }
+ if errors.Is(err, ErrNoAuthority) || ctx.Err() != nil {
+ _, _ = e.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE access_requests SET state='queued' WHERE card_id=?", id)
+ return err
+ }
+ if err != nil {
+ out.State = "authority"
+ } else {
+ if e.Forge == nil {
+ err = errAccess
+ } else {
+ out, err = e.Forge.RequestAccess(ctx, cmd)
+ }
+ if err != nil {
+ out.State = "failed"
+ if errors.Is(err, errAccessNotOwned) {
+ out.State = "not_owned"
+ }
+ if errors.Is(err, errAccessAlready) {
+ out.State = "already"
+ }
+ if errors.Is(err, errAccessLimit) {
+ out.State = "limited"
+ }
+ if errors.Is(err, errAccessContract) || errors.Is(err, errAccessState) {
+ out.State = "unconfirmed"
+ }
+ }
+ }
+ case "filing":
+ out.State = "unconfirmed"
+ case "pending", "checking_expiry":
+ out, err = e.Forge.PollAccess(ctx, old.RequestID, cmd)
+ if err == nil && out.RequestID != old.RequestID {
+ err = errAccessContract
+ }
+ // A server answer wins over the runner clock. An offline estimate is
+ // provisional and keeps reconciling the saved id, never another POST.
+ if err != nil && ctx.Err() == nil && (errors.Is(err, errAccess) || errors.Is(err, context.DeadlineExceeded)) && old.Expires > 0 && time.Now().After(time.Unix(old.Expires, 0).Add(10*time.Minute)) {
+ out, err, localExpiry = old, nil, true
+ out.State = "expired"
+ }
+ if err != nil {
+ final := ""
+ switch {
+ case errors.Is(err, errAccessMissing):
+ final = "missing"
+ case errors.Is(err, errAccessDenied), errors.Is(err, errAccessState):
+ final = "uncheckable"
+ case errors.Is(err, errAccessContract):
+ final = "unconfirmed"
+ }
+ if final == "" {
+ return err
+ }
+ var failures int
+ if xerr := e.State.db.QueryRowContext(ctx, "UPDATE access_requests SET poll_failures=poll_failures+1 WHERE card_id=? RETURNING poll_failures", id).Scan(&failures); xerr != nil {
+ return xerr
+ }
+ if failures < 3 {
+ return err
+ }
+ out = old
+ out.State = final
+ } else if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET poll_failures=0 WHERE card_id=?", id); err != nil {
+ return err
+ }
+
+ 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)
+ savedState := out.State
+ if localExpiry {
+ savedState = "checking_expiry"
+ }
+ if err := e.State.tx(ctx, func(tx *sql.Tx) error {
+ if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", savedState, string(raw), id); err != nil {
+ return err
+ }
+ if string(raw) == report || settled {
+ return nil
+ }
+ return e.State.enqueue(tx, wire.FrameAccess, "", out)
+ }); err != nil {
+ return err
+ }
+ if out.State == "approved" || out.State == "already" {
+ e.Forge.Recheck()
+ e.Forge.Reachable(ctx)
+ if e.Refresh != nil {
+ e.Refresh()
+ }
+ }
+ if e.Notify != nil {
+ e.Notify()
+ }
+ return nil
+}
+
+// Run reserves a filing worker independently of the five long polls.
+// SQLite insertion order breaks confirmation-time ties, including legacy rows.
+func (e *AccessEngine) Run(ctx context.Context) {
+ var wg sync.WaitGroup
+ defer wg.Wait()
+ type finished struct {
+ id string
+ filing bool
+ err error
+ }
+ active := map[string]bool{}
+ next := map[string]time.Time{}
+ delays := map[string]time.Duration{}
+ done := make(chan finished, 6)
+ filing, polls := false, 0
+ tick := time.NewTicker(time.Second)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case result := <-done:
+ delete(active, result.id)
+ if result.filing {
+ filing = false
+ } else {
+ polls--
+ }
+ delay := time.Second
+ var state string
+ if e.State.db.QueryRowContext(ctx, "SELECT state FROM access_requests WHERE card_id=?", result.id).Scan(&state) == nil && state == "checking_expiry" {
+ delay = time.Minute
+ }
+ if result.err != nil {
+ delay = min(max(delays[result.id]*2, 2*time.Second), time.Minute)
+ }
+ delays[result.id] = delay
+ next[result.id] = time.Now().Add(delay)
+ case <-tick.C:
+ rows, err := e.State.db.QueryContext(ctx, "SELECT card_id,state FROM access_requests WHERE state IN ('queued','filing','pending','checking_expiry') ORDER BY CASE WHEN state IN ('pending','checking_expiry') THEN 1 ELSE 0 END, confirmed_at, rowid LIMIT 128")
+ if err != nil {
+ continue
+ }
+ var jobs []struct{ id, state string }
+ for rows.Next() {
+ var j struct{ id, state string }
+ if rows.Scan(&j.id, &j.state) == nil {
+ jobs = append(jobs, j)
+ }
+ }
+ rows.Close()
+ for _, j := range jobs {
+ fresh := j.state == "queued" || j.state == "filing"
+ if active[j.id] || time.Now().Before(next[j.id]) || fresh && filing || !fresh && polls >= 5 {
+ continue
+ }
+ active[j.id] = true
+ if fresh {
+ filing = true
+ } else {
+ polls++
+ }
+ wg.Add(1)
+ go func(id string, fresh bool) { defer wg.Done(); err := e.Step(ctx, id); done <- finished{id, fresh, err} }(j.id, fresh)
+ }
+ }
+ }
+}
+
+func migrateAccess(ctx context.Context, db *sql.DB) error {
+ for _, column := range []string{"confirmed_at INTEGER NOT NULL DEFAULT 0", "poll_failures INTEGER NOT NULL DEFAULT 0"} {
+ if _, err := db.ExecContext(ctx, "ALTER TABLE access_requests ADD COLUMN "+column); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/runner/thin/access_catalog.go b/internal/runner/thin/access_catalog.go
new file mode 100644
index 00000000..1ce50236
--- /dev/null
+++ b/internal/runner/thin/access_catalog.go
@@ -0,0 +1,99 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "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 IN ('approved','already') 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()
+}
+
+func readRemote(ctx context.Context, f Forge, repo string) (workspace.Remote, error) {
+ if ff, ok := f.(*fileForge); ok {
+ if !slices.Contains(ff.Reachable(ctx), repo) {
+ return workspace.Remote{}, workspace.ErrGitPassword
+ }
+ return ff.remoteCredential(ctx, repo)
+ }
+ return f.Remote(ctx, repo)
+}
diff --git a/internal/runner/thin/access_contract.go b/internal/runner/thin/access_contract.go
new file mode 100644
index 00000000..84e44a4c
--- /dev/null
+++ b/internal/runner/thin/access_contract.go
@@ -0,0 +1,26 @@
+package thin
+
+// Copied from amadan/amadan 1dadddf6163bb40485b9e039f8ce9085efc81274,
+// internal/cli/agentaccess.go:26-48; emitted by internal/hub/agent_access.go:526-576.
+type amadanAccessInfo struct {
+ ID string `json:"id"`
+ State string `json:"state"`
+ Agent string `json:"agent"`
+ Operator string `json:"operator"`
+ Target string `json:"target"`
+ NS string `json:"ns"`
+ Repo string `json:"repo"`
+ Role string `json:"role"`
+ Reason string `json:"reason"`
+ Created int64 `json:"created"`
+ Expires int64 `json:"expires"`
+ Decided int64 `json:"decided"`
+ DecidedBy string `json:"decided_by,omitempty"`
+ ApproveURL string `json:"approve_url"`
+ Existing bool `json:"existing,omitempty"`
+ Events []struct {
+ Kind string `json:"kind"`
+ Actor string `json:"actor,omitempty"`
+ At int64 `json:"at"`
+ } `json:"events,omitempty"`
+}
diff --git a/internal/runner/thin/access_contract_test.go b/internal/runner/thin/access_contract_test.go
new file mode 100644
index 00000000..c5db2670
--- /dev/null
+++ b/internal/runner/thin/access_contract_test.go
@@ -0,0 +1,69 @@
+package thin
+
+import (
+ "encoding/json"
+ "net/http"
+ "time"
+)
+
+// Copied from amadan/amadan 1dadddf6163bb40485b9e039f8ce9085efc81274,
+// internal/cli/agentaccess.go:26-48. The handlers emit this shape in
+// internal/hub/agent_access.go:526-576 (POST and GET both call it).
+type testAccessInfo struct {
+ ID string `json:"id"`
+ State string `json:"state"`
+ Agent string `json:"agent"`
+ Operator string `json:"operator"`
+ Target string `json:"target"`
+ NS string `json:"ns"`
+ Repo string `json:"repo"`
+ Role string `json:"role"`
+ Reason string `json:"reason"`
+ Created int64 `json:"created"`
+ Expires int64 `json:"expires"`
+ Decided int64 `json:"decided"`
+ DecidedBy string `json:"decided_by,omitempty"`
+ ApproveURL string `json:"approve_url"`
+ Existing bool `json:"existing,omitempty"`
+ Events []struct {
+ Kind string `json:"kind"`
+ Actor string `json:"actor,omitempty"`
+ At int64 `json:"at"`
+ } `json:"events,omitempty"`
+}
+
+func accessResponse(id, state string) testAccessInfo {
+ c := accessCommand()
+ now := time.Now().Unix()
+ return testAccessInfo{ID: id, State: state, Agent: "equipo~owner@example.com", Operator: "owner@example.com", Target: c.Target, NS: "carlos", Repo: "platform", Role: c.Role, Reason: c.Reason, Created: now, Expires: now + 72*3600, ApproveURL: "https://amadan.net/settings/agents/requests/" + id}
+}
+func writeAccessInfo(w http.ResponseWriter, v testAccessInfo) {
+ raw, _ := json.Marshal(v)
+ var body map[string]any
+ json.Unmarshal(raw, &body)
+ if _, ok := body["events"]; !ok {
+ body["events"] = []any{}
+ }
+ json.NewEncoder(w).Encode(body)
+}
+func writeAccess(w http.ResponseWriter, id, state string) {
+ writeAccessInfo(w, accessResponse(id, state))
+}
+
+// Copied from the same Amadan commit, internal/hub/agent_meta.go:35-43.
+type testAccessAgentMeta struct {
+ Session string `json:"session,omitempty"`
+ Harness string `json:"harness,omitempty"`
+ Host string `json:"host,omitempty"`
+ Driven *bool `json:"driven,omitempty"`
+
+ Driver string `json:"-"`
+}
+
+// POST body copied from internal/hub/agent_access.go:161-166.
+type testAccessCreate struct {
+ Target string `json:"target"`
+ Role string `json:"role"`
+ Reason string `json:"reason"`
+ Agent *testAccessAgentMeta `json:"agent"`
+}
diff --git a/internal/runner/thin/access_forge.go b/internal/runner/thin/access_forge.go
new file mode 100644
index 00000000..561bdba1
--- /dev/null
+++ b/internal/runner/thin/access_forge.go
@@ -0,0 +1,134 @@
+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 errAccessContract = errors.New("access response not confirmed")
+var errAccessMissing = errors.New("access request missing")
+var errAccessDenied = errors.New("access check denied")
+var errAccessState = errors.New("access state unknown")
+var errAccessNotOwned = errors.New("access target not owned")
+var errAccessAlready = errors.New("access already granted")
+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.AccessCommand) (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, expected wire.AccessCommand) (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, &expected)
+}
+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 method == http.MethodPost {
+ if res.StatusCode == http.StatusNotFound {
+ return wire.AccessReport{}, errAccessNotOwned
+ }
+ if res.StatusCode == http.StatusConflict {
+ return wire.AccessReport{}, errAccessAlready
+ }
+ }
+ if method == http.MethodGet {
+ if res.StatusCode == 404 {
+ return wire.AccessReport{}, errAccessMissing
+ }
+ if res.StatusCode == 401 || res.StatusCode == 403 {
+ return wire.AccessReport{}, errAccessDenied
+ }
+ }
+ if res.StatusCode >= 300 && res.StatusCode < 400 {
+ return wire.AccessReport{}, errAccessContract
+ }
+ if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
+ return wire.AccessReport{}, errAccess
+ }
+ var out amadanAccessInfo
+ raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ if err != nil || json.Unmarshal(raw, &out) != nil {
+ return wire.AccessReport{}, errAccessContract
+ }
+ var fields map[string]json.RawMessage
+ if json.Unmarshal(raw, &fields) != nil {
+ return wire.AccessReport{}, errAccessContract
+ }
+ for _, key := range []string{"id", "state", "agent", "operator", "target", "ns", "repo", "role", "reason", "created", "expires", "decided", "approve_url", "events"} {
+ if len(fields[key]) == 0 || string(fields[key]) == "null" {
+ return wire.AccessReport{}, errAccessContract
+ }
+ }
+ if !accessID.MatchString(out.ID) || !wire.AccessURL(out.ApproveURL, out.ID) || out.Created <= 0 || out.Expires <= out.Created || out.Agent == "" || out.Operator == "" || !wire.ValidAccessTarget(out.Target) || !wire.AccessRole(out.Role) || !wire.ValidAccessReason(out.Reason) {
+ return wire.AccessReport{}, errAccessContract
+ }
+ ns, repo, _ := strings.Cut(out.Target, "/")
+ if out.NS != ns || out.Repo != repo || expected == nil || out.Target != expected.Target || out.Role != expected.Role || out.Reason != expected.Reason {
+ return wire.AccessReport{}, errAccessContract
+ }
+ if out.State != "pending" && out.State != "approved" && out.State != "declined" && out.State != "expired" {
+ return wire.AccessReport{}, errAccessState
+ }
+ if method == http.MethodPost && (out.State != "pending" || (res.StatusCode == 200) != out.Existing) {
+ return wire.AccessReport{}, errAccessContract
+ }
+ if method == http.MethodGet && res.StatusCode != 200 {
+ return wire.AccessReport{}, errAccessContract
+ }
+ // 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_protocol.go b/internal/runner/thin/access_protocol.go
new file mode 100644
index 00000000..4870fdd0
--- /dev/null
+++ b/internal/runner/thin/access_protocol.go
@@ -0,0 +1,74 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+const accessPrompt = "For a not-shared repository, request_access(target, role, reason) raises a confirmation card; default agent, single repo, or a namespace only when explicitly requested. Never retry unprompted. "
+const accessOld = "Equipo needs an update before it can request access."
+
+func accessRefused(call wire.ToolCall, protocol int) (wire.ToolResult, bool) {
+ if call.Name != wire.ToolRequestAccess || protocol == 0 || protocol >= wire.ProtocolAccess {
+ return wire.ToolResult{}, false
+ }
+ return wire.ToolResult{CallID: call.CallID, IsError: true, Code: "access_unsupported", Text: accessOld}, true
+}
+func (c *coordBase) accessProtocol() int {
+ if c.o.Protocol != nil {
+ if p := c.o.Protocol(); p != 0 {
+ return p
+ }
+ }
+ return wire.ProtocolCurrent
+}
+func accessToolSetAt(set toolSet, protocol int) toolSet {
+ if protocol == 0 || protocol >= wire.ProtocolAccess {
+ return set
+ }
+ set.names = slices.DeleteFunc(slices.Clone(set.names), func(n string) bool { return n == wire.ToolRequestAccess })
+ set.list = slices.DeleteFunc(slices.Clone(set.list), func(v any) bool { m, ok := v.(map[string]any); return ok && m["name"] == wire.ToolRequestAccess })
+ if set.permission != nil {
+ names := set.names
+ set.permission = func(raw json.RawMessage) string { return permissionText(raw, names) }
+ }
+ return set
+}
+func (c *coordBase) accessToolSet(tools bool) toolSet {
+ base := c.profile.set(tools)
+ out := accessToolSetAt(base, c.accessProtocol())
+ out.current = func() toolSet { return accessToolSetAt(base, c.accessProtocol()) }
+ return out
+}
+func (c *coordBase) accessOpening(catalog []wire.RepoInfo) string {
+ text := c.profile.opening(c.person, catalog)
+ if c.accessProtocol() < wire.ProtocolAccess {
+ text = strings.ReplaceAll(text, accessPrompt, "")
+ }
+ return text
+}
+func (l *Link) acceptAccess(ctx context.Context, id string, c wire.AccessCommand) error {
+ if l.knownWorker(ctx) || l.Access == nil {
+ return errAccess
+ }
+ return l.State.AcceptAccess(ctx, id, c)
+}
+
+func (l *Link) ConfirmAccess(ctx context.Context, id string) error {
+ p, _ := l.Spoken()
+ if p < wire.ProtocolAccess {
+ return ErrNoAuthority
+ }
+ return l.lease(ctx, wire.LeaseCheck{AccessCard: id})
+}
+
+// LastProtocol retains the last welcome across disconnects; zero means unknown.
+func (l *Link) LastProtocol() int {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.proto
+}
diff --git a/internal/runner/thin/access_review_test.go b/internal/runner/thin/access_review_test.go
new file mode 100644
index 00000000..479c6b6d
--- /dev/null
+++ b/internal/runner/thin/access_review_test.go
@@ -0,0 +1,334 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func TestAccessContractRequiresConfirmedFields(t *testing.T) {
+ for _, field := range []string{"target", "role", "reason", "approve_url", "expires", "state"} {
+ t.Run(field, func(t *testing.T) {
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ v := accessResponse("ar_one", "pending")
+ v.Existing = true
+ raw, _ := json.Marshal(v)
+ var body map[string]any
+ json.Unmarshal(raw, &body)
+ body["events"] = []any{}
+ delete(body, field)
+ json.NewEncoder(w).Encode(body)
+ })
+ if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil {
+ t.Fatal("incomplete existing response reused", field)
+ }
+ })
+ }
+}
+func TestAccessHostileApprovalURL(t *testing.T) {
+ for _, url := range []string{"https://amadan.net/other/ar_one", "https://amadan.net/settings/agents/requests/other", "https://amadan.net/settings/agents/requests/ar_one?x=1", "https://user@amadan.net/settings/agents/requests/ar_one", "https://amadan.net/settings/agents/requests/ar_one\\other", "https://amadan.net/settings/agents/requests/%61r_one", "https://amadan.net/settings/agents/requests/ar_one#x"} {
+ t.Run(url, func(t *testing.T) {
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ v := accessResponse("ar_one", "pending")
+ v.ApproveURL = url
+ w.WriteHeader(201)
+ writeAccessInfo(w, v)
+ })
+ if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil {
+ t.Fatal("hostile approval URL accepted")
+ }
+ })
+ }
+ var redirected atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/other" {
+ redirected.Add(1)
+ writeAccess(w, "ar_one", "pending")
+ return
+ }
+ http.Redirect(w, r, "/other", http.StatusFound)
+ })
+ if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil || redirected.Load() != 0 {
+ t.Fatal("redirect followed", err)
+ }
+}
+func TestAccessMalformedResponseFinishesWithoutRepost(t *testing.T) {
+ var posts atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ posts.Add(1)
+ w.WriteHeader(201)
+ fmt.Fprint(w, `{"id":"ar_one","state":"mystery"}`)
+ })
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ c := accessCommand()
+ s.AcceptAccess(ctx, "frame", c)
+ e := &AccessEngine{State: s, Forge: f}
+ for i := 0; i < 3; i++ {
+ if err := e.Step(ctx, c.CardID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var state string
+ s.db.QueryRow("SELECT state FROM access_requests").Scan(&state)
+ if state != "unconfirmed" || posts.Load() != 1 {
+ t.Fatal("malformed response not final and distinct", state, posts.Load())
+ }
+}
+func TestAccessPermanentPollErrorsAndLocalExpiry(t *testing.T) {
+ for _, mode := range []string{"404", "401", "unknown", "expiry"} {
+ t.Run(mode, func(t *testing.T) {
+ var calls atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ switch mode {
+ case "404":
+ w.WriteHeader(404)
+ case "401":
+ w.WriteHeader(401)
+ case "expiry":
+ w.WriteHeader(503)
+ default:
+ v := accessResponse("ar_one", "mystery")
+ writeAccessInfo(w, v)
+ }
+ })
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ c := accessCommand()
+ s.AcceptAccess(ctx, "frame", c)
+ old := wire.AccessReport{CardID: c.CardID, Person: c.Person, RequestID: "ar_one", State: "pending", Expires: time.Now().Add(time.Hour).Unix()}
+ if mode == "expiry" {
+ old.Expires = time.Now().Add(-11 * time.Minute).Unix()
+ }
+ raw, _ := json.Marshal(old)
+ s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw))
+ e := &AccessEngine{State: s, Forge: f}
+ for i := 0; i < 6; i++ {
+ _ = e.Step(ctx, c.CardID)
+ }
+ var state string
+ s.db.QueryRow("SELECT state FROM access_requests").Scan(&state)
+ want := "uncheckable"
+ if mode == "404" {
+ want = "missing"
+ }
+ if mode == "expiry" {
+ want = "checking_expiry"
+ }
+ if state != want || mode != "expiry" && calls.Load() > 3 || mode == "expiry" && calls.Load() != 6 {
+ t.Fatal("poll did not finish", state, calls.Load())
+ }
+ })
+ }
+}
+func TestAccessReadGrantCannotWrite(t *testing.T) {
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/v1/repos" {
+ fmt.Fprint(w, `{"repos":[]}`)
+ return
+ }
+ fmt.Fprint(w, `{"ns":"carlos","name":"platform","tier":"private"}`)
+ })
+ f.accessTargets = func(context.Context) ([]string, error) { return []string{"carlos/platform"}, nil }
+ ctx := context.Background()
+ repo := "amadan.net/carlos/platform"
+ if !slices.Contains(f.Reachable(ctx), repo) {
+ t.Fatal("read grant missing")
+ }
+ if remote, err := readRemote(ctx, f, repo); err != nil || remote.GitPassword == "" {
+ t.Fatal("read grant cannot fetch", err)
+ }
+ if _, err := f.Remote(ctx, repo); err == nil {
+ t.Fatal("read grant got write credential")
+ }
+ if _, err := f.Merge(ctx, repo, "branch", forge.HubMergeRequest{}); !errors.Is(err, forge.ErrMergeRefused) {
+ t.Fatal("read grant reached merge", err)
+ }
+ if _, err := f.ciCredential(ctx, repo); !errors.Is(err, forge.ErrCIRead) {
+ t.Fatal("read grant got CI credential", err)
+ }
+}
+func TestAccessDowngradeRefusesBeforeQueue(t *testing.T) {
+ b := &bridge{speaks: wire.Protocol25, trip: func(context.Context, wire.ToolCall) wire.ToolResult {
+ t.Fatal("unsupported tool sent")
+ return wire.ToolResult{}
+ }}
+ got := b.roundTrip(context.Background(), wire.ToolCall{Name: wire.ToolRequestAccess})
+ if !got.IsError || !strings.Contains(got.Code, "unsupported") {
+ t.Fatal(got)
+ }
+}
+
+type accessQueueForge struct{ filed chan string }
+
+func (f *accessQueueForge) RequestAccess(_ context.Context, c wire.AccessCommand) (wire.AccessReport, error) {
+ f.filed <- c.CardID
+ return wire.AccessReport{RequestID: c.CardID, State: "limited"}, nil
+}
+func (*accessQueueForge) PollAccess(ctx context.Context, _ string, _ wire.AccessCommand) (wire.AccessReport, error) {
+ <-ctx.Done()
+ return wire.AccessReport{}, ctx.Err()
+}
+func (*accessQueueForge) Recheck() {}
+func (*accessQueueForge) Reachable(context.Context) []string { return nil }
+func TestAccessSixthConfirmationDoesNotStarve(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ f := &accessQueueForge{filed: make(chan string, 2)}
+ for i := 0; i < 5; i++ {
+ c := accessCommand()
+ c.CardID = fmt.Sprint("pending", i)
+ s.AcceptAccess(ctx, c.CardID, c)
+ raw, _ := json.Marshal(wire.AccessReport{RequestID: c.CardID, State: "pending", Expires: time.Now().Add(time.Hour).Unix()})
+ s.db.Exec("UPDATE access_requests SET state='pending',report=? WHERE card_id=?", string(raw), c.CardID)
+ }
+ done := make(chan struct{})
+ e := &AccessEngine{State: s, Forge: f}
+ go func() { e.Run(ctx); close(done) }()
+ defer func() { cancel(); <-done }()
+ time.Sleep(1200 * time.Millisecond)
+ for _, id := range []string{"z-first-confirmed", "a-second-confirmed"} {
+ c := accessCommand()
+ c.CardID = id
+ s.AcceptAccess(ctx, id, c)
+ }
+ for _, want := range []string{"z-first-confirmed", "a-second-confirmed"} {
+ select {
+ case got := <-f.filed:
+ if got != want {
+ t.Fatal("confirmation order", got, want)
+ }
+ case <-time.After(2500 * time.Millisecond):
+ t.Fatal("new confirmation starved behind polls")
+ }
+ }
+}
+
+func TestAccessToolsAndPromptFollowProtocol(t *testing.T) {
+ for _, proto := range []int{25, 26} {
+ c := coordBase{o: ClaudeOptions{Protocol: func() int { return proto }}, profile: profileFor(wire.LaneCoordinator)}
+ offered := slices.Contains(c.accessToolSet(true).names, wire.ToolRequestAccess)
+ prompted := strings.Contains(c.accessOpening(nil), "request_access")
+ if offered != (proto >= 26) || prompted != (proto >= 26) {
+ t.Fatal("wrong tool or prompt at protocol", proto, offered, prompted)
+ }
+ }
+}
+func TestAccessUnencodableCallIsRetired(t *testing.T) {
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ call := wire.ToolCall{CallID: "call", TurnID: "finished-turn", Name: wire.ToolRequestAccess, Args: json.RawMessage(`{}`)}
+ if err := s.SendToolCall(ctx, call); err != nil {
+ t.Fatal(err)
+ }
+ frames, _, err := s.Unacked(ctx, 0)
+ if err != nil || len(frames) != 1 {
+ t.Fatal(err, frames)
+ }
+ l := &Link{State: s, proto: 25}
+ wait := l.waitTool(call.CallID)
+ if err := l.send(ctx, nil, frames[0]); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case res := <-wait:
+ if res.Code != "access_unsupported" {
+ t.Fatal(res)
+ }
+ default:
+ t.Fatal("no immediate unsupported result")
+ }
+ frames, _, err = s.Unacked(ctx, 0)
+ if err != nil || len(frames) != 0 {
+ t.Fatal("old call can replay after upgrade", frames, err)
+ }
+}
+func TestAccessWorkerCommandRefused(t *testing.T) {
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ l := &Link{State: s, Role: wire.RoleWorker, Access: &AccessEngine{State: s}}
+ if err := l.acceptAccess(ctx, "frame", accessCommand()); err == nil {
+ t.Fatal("worker accepted access command")
+ }
+ var n int
+ s.db.QueryRow("SELECT count(*) FROM access_requests").Scan(&n)
+ if n != 0 {
+ t.Fatal("worker persisted command")
+ }
+}
+
+func TestAccessExistingScopeAndReasonMustMatch(t *testing.T) {
+ for _, field := range []string{"target", "reason"} {
+ t.Run(field, func(t *testing.T) {
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ v := accessResponse("ar_one", "pending")
+ v.Existing = true
+ if field == "target" {
+ v.Target = "carlos"
+ v.Repo = ""
+ } else {
+ v.Reason = "A different request."
+ }
+ writeAccessInfo(w, v)
+ })
+ if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil {
+ t.Fatal("different confirmed request reused", field)
+ }
+ })
+ }
+}
+
+func TestAccessWithdrawnLeaseDoesNotPoisonStream(t *testing.T) {
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ c := accessCommand()
+ s.AcceptAccess(ctx, "frame", c)
+ e := &AccessEngine{State: s, Authorize: func(context.Context, string) error { return ErrWithdrawn }}
+ if err := e.Step(ctx, c.CardID); err != nil {
+ t.Fatal(err)
+ }
+ frames, _, err := s.Unacked(ctx, 0)
+ if err != nil || len(frames) != 0 {
+ t.Fatal("demoted runner repeats a report it cannot submit", frames, err)
+ }
+ var state string
+ s.db.QueryRow("SELECT state FROM access_requests").Scan(&state)
+ if state != "authority" {
+ t.Fatal(state)
+ }
+}
diff --git a/internal/runner/thin/access_round3_test.go b/internal/runner/thin/access_round3_test.go
new file mode 100644
index 00000000..dc94b70a
--- /dev/null
+++ b/internal/runner/thin/access_round3_test.go
@@ -0,0 +1,250 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/coder/websocket"
+)
+
+func TestAccessUnknownProtocolQueuesDurably(t *testing.T) {
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ l := &Link{State: s}
+ b := &bridge{Link: l, State: s}
+ call := wire.ToolCall{CallID: "offline", TurnID: "turn", Name: wire.ToolRequestAccess, Args: json.RawMessage(`{}`)}
+ cancelctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ result := make(chan wire.ToolResult, 1)
+ go func() { result <- b.roundTrip(cancelctx, call) }()
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ frames, _, err := s.Unacked(ctx, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(frames) == 1 {
+ break
+ }
+ select {
+ case got := <-result:
+ t.Fatal("offline tool was not queued", got)
+ default:
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("offline tool not durably queued")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ cancel()
+ if got := <-result; got.Code == "access_unsupported" {
+ t.Fatal("disconnected request refused as old protocol")
+ }
+ c := coordBase{o: ClaudeOptions{Protocol: func() int { p, _ := l.Spoken(); return p }}, profile: profileFor(wire.LaneCoordinator)}
+ if !slices.Contains(c.accessToolSet(true).names, wire.ToolRequestAccess) || !strings.Contains(c.accessOpening(nil), "request_access") || strings.Contains(c.sessionAccount(), "legacy") {
+ t.Fatal("unknown protocol removes tools or changes session key")
+ }
+}
+
+func TestAccessDisconnectKeepsNegotiatedSession(t *testing.T) {
+ for _, proto := range []int{25, 26} {
+ t.Run(fmt.Sprint(proto), func(t *testing.T) {
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ l := &Link{proto: proto, conn: &websocket.Conn{}}
+ c := coordBase{o: ClaudeOptions{Protocol: l.LastProtocol}, profile: profileFor(wire.LaneCoordinator)}
+ key := c.sessionAccount()
+ tools := slices.Clone(c.accessToolSet(true).names)
+ capability := c.accessProtocol() >= wire.ProtocolAccess
+ for _, provider := range []string{"claude", "codex"} {
+ if err := s.saveSession(ctx, "person", wire.LaneCoordinator, provider, key, "resume-id", "turn"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ l.conn = nil
+ if c.accessProtocol() >= wire.ProtocolAccess != capability {
+ t.Fatal("disconnect rotates coordinator capability")
+ }
+ if c.sessionAccount() != key || !slices.Equal(tools, c.accessToolSet(true).names) {
+ t.Fatal("disconnect changes session key or tools")
+ }
+ _, refused := accessRefused(wire.ToolCall{Name: wire.ToolRequestAccess}, (&bridge{Link: l}).spoken())
+ if refused != (proto < 26) {
+ t.Fatal("disconnected link forgot negotiation")
+ }
+ for _, provider := range []string{"claude", "codex"} {
+ if err := s.saveSession(ctx, "person", wire.LaneCoordinator, provider, c.sessionAccount(), "resume-id", "turn"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ l.conn = &websocket.Conn{}
+ for _, provider := range []string{"claude", "codex"} {
+ row, ok, err := s.session(ctx, "person", wire.LaneCoordinator, provider)
+ if err != nil || !ok || row.Account != c.sessionAccount() || row.SessionID != "resume-id" {
+ t.Fatal("reconnect loses provider resume", provider, row, err)
+ }
+ }
+ if proto == 26 && strings.Contains(key, "legacy") {
+ t.Fatal("protocol 26 legacy key")
+ }
+ })
+ }
+}
+
+func TestAccessPostFinalOutcomes(t *testing.T) {
+ for _, status := range []int{404, 409} {
+ t.Run(fmt.Sprint(status), func(t *testing.T) {
+ var posts, lists, refresh atomic.Int32
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/v1/repos" {
+ lists.Add(1)
+ fmt.Fprint(w, `{"repos":[]}`)
+ return
+ }
+ posts.Add(1)
+ w.WriteHeader(status)
+ })
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ c := accessCommand()
+ if err := s.AcceptAccess(ctx, "frame", c); err != nil {
+ t.Fatal(err)
+ }
+ e := &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }}
+ for i := 0; i < 3; i++ {
+ if err := e.Step(ctx, c.CardID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var state string
+ s.db.QueryRow("SELECT state FROM access_requests").Scan(&state)
+ want := "not_owned"
+ if status == 409 {
+ want = "already"
+ }
+ if state != want || !wire.AccessFinal(state) || posts.Load() != 1 {
+ t.Fatal("POST outcome is not distinct and final", state, posts.Load())
+ }
+ if status == 409 && (refresh.Load() != 1 || lists.Load() != 1) {
+ t.Fatal("already-access did not refresh catalog", refresh.Load(), lists.Load())
+ }
+ if status == 404 && refresh.Load() != 0 {
+ t.Fatal("not-owned refreshed catalog")
+ }
+ })
+ }
+}
+
+func TestAccessExpiryClockMarginAndReconciliation(t *testing.T) {
+ for _, mode := range []string{"margin", "server_pending", "server_approved", "offline_then_approved", "server_expired"} {
+ t.Run(mode, func(t *testing.T) {
+ var gets, refresh atomic.Int32
+ var online atomic.Bool
+ online.Store(mode != "margin" && mode != "offline_then_approved")
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/v1/repos" {
+ fmt.Fprint(w, `{"repos":[]}`)
+ return
+ }
+ gets.Add(1)
+ if !online.Load() {
+ w.WriteHeader(503)
+ return
+ }
+ state := "approved"
+ if mode == "server_pending" {
+ state = "pending"
+ }
+ if mode == "server_expired" {
+ state = "expired"
+ }
+ v := accessResponse("ar_one", state)
+ v.Created = time.Now().Add(-72 * time.Hour).Unix()
+ v.Expires = time.Now().Add(-20 * time.Minute).Unix()
+ writeAccessInfo(w, v)
+ })
+ ctx := context.Background()
+ dir := t.TempDir()
+ s, err := OpenState(ctx, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { s.Close() }()
+ c := accessCommand()
+ s.AcceptAccess(ctx, "frame", c)
+ expires := time.Now().Add(-20 * time.Minute).Unix()
+ if mode == "margin" {
+ expires = time.Now().Add(-5 * time.Minute).Unix()
+ }
+ old := wire.AccessReport{CardID: c.CardID, Person: c.Person, RequestID: "ar_one", State: "pending", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one", Expires: expires}
+ raw, _ := json.Marshal(old)
+ s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw))
+ e := &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }}
+ _ = e.Step(ctx, c.CardID)
+ var report string
+ s.db.QueryRow("SELECT report FROM access_requests").Scan(&report)
+ var got wire.AccessReport
+ json.Unmarshal([]byte(report), &got)
+ want := "approved"
+ switch mode {
+ case "margin", "server_pending":
+ want = "pending"
+ case "offline_then_approved", "server_expired":
+ want = "expired"
+ }
+ if got.State != want || gets.Load() != 1 {
+ t.Fatal("clock overrode server or safety margin", got.State, want, gets.Load())
+ }
+ if mode == "offline_then_approved" {
+ s.Close()
+ s, err = OpenState(ctx, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.State = s
+ online.Store(true)
+ runctx, stop := context.WithCancel(ctx)
+ done := make(chan struct{})
+ go func() { e.Run(runctx); close(done) }()
+ deadline := time.Now().Add(3 * time.Second)
+ for refresh.Load() == 0 && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ stop()
+ <-done
+
+ s.db.QueryRow("SELECT report FROM access_requests").Scan(&report)
+ json.Unmarshal([]byte(report), &got)
+ if got.State != "approved" || refresh.Load() != 1 {
+ t.Fatal("local expiry lost later approval after restart", got, refresh.Load())
+ }
+ }
+ if mode == "server_expired" {
+ _ = e.Step(ctx, c.CardID)
+ if gets.Load() != 1 {
+ t.Fatal("server expiry is not final")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/runner/thin/access_test.go b/internal/runner/thin/access_test.go
new file mode 100644
index 00000000..dd5b192b
--- /dev/null
+++ b/internal/runner/thin/access_test.go
@@ -0,0 +1,395 @@
+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 testAccessCreate
+ json.NewDecoder(r.Body).Decode(&body)
+ if body.Target != "carlos/platform" || body.Role != "agent" || (body.Agent == nil || body.Agent.Session == "") {
+ t.Errorf("body: %+v", body)
+ }
+ w.WriteHeader(201)
+ writeAccess(w, "ar_one", "pending")
+ 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)
+ }
+ writeAccess(w, "ar_one", "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
+ }
+ if r.Method == "POST" {
+ w.WriteHeader(201)
+ writeAccess(w, "ar_one", "pending")
+ } else {
+ writeAccess(w, "ar_one", 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)
+ wantCalls := int32(1)
+ wantFrames := 1
+ if state == "declined" || state == "expired" {
+ wantCalls = 2
+ wantFrames = 2
+ }
+ if calls.Load() != wantCalls || len(frames) != wantFrames || !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 != "unconfirmed" {
+ 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" {
+ w.WriteHeader(201)
+ writeAccess(w, "ar_one", "pending")
+ return
+ }
+ mu.Lock()
+ times = append(times, time.Now())
+ mu.Unlock()
+ n := gets.Add(1)
+ if n == 1 {
+ w.WriteHeader(503)
+ return
+ }
+ writeAccess(w, "ar_one", "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) {
+ v := accessResponse("existing_one", "pending")
+ v.Existing = true
+ v.Role = role
+ writeAccessInfo(w, v)
+ })
+ 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")
+ }
+ })
+ }
+}
+
+func TestAccessRunnerChecksCurrentAuthorityBeforeFiling(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()
+ 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)
+ }
+ e := &AccessEngine{State: s, Forge: f, Authorize: func(context.Context, string) error {
+ var phase string
+ s.db.QueryRow("SELECT state FROM access_requests").Scan(&phase)
+ if phase != "filing" {
+ t.Fatal("authority was not checked immediately before POST", phase)
+ }
+ return errAccess
+ }}
+ if err := e.Step(ctx, cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ if calls.Load() != 0 {
+ t.Fatal("revoked runner contacted forge")
+ }
+ var state string
+ if err := s.db.QueryRow("SELECT state FROM access_requests").Scan(&state); err != nil || state != "authority" {
+ t.Fatal(state, err)
+ }
+ e.Authorize = func(context.Context, string) error { return nil }
+ if err := e.Step(ctx, cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ if calls.Load() != 0 {
+ t.Fatal("revoked confirmation was reused")
+ }
+}
diff --git a/internal/runner/thin/bridge.go b/internal/runner/thin/bridge.go
index 0b0d7fc1..f089febd 100644
--- a/internal/runner/thin/bridge.go
+++ b/internal/runner/thin/bridge.go
@@ -464,13 +464,12 @@ func (b *bridge) clone(ctx context.Context, repo string) string {
return ""
}
-// spoken is the link's protocol now, 0 when unknown.
+// spoken keeps the last negotiated protocol while disconnected, or 0 if unknown.
func (b *bridge) spoken() int {
if b.Link == nil {
return b.speaks
}
- p, _ := b.Link.Spoken()
- return p
+ return b.Link.LastProtocol()
}
// exploreRefused answers record_task for an exploration on a connection
@@ -509,6 +508,9 @@ func researchRefused(call wire.ToolCall, spoken int, res *wire.ToolResult) (wire
const toolResearchOld = "Equipo needs an update before it can research."
func (b *bridge) roundTrip(ctx context.Context, call wire.ToolCall) wire.ToolResult {
+ if res, no := accessRefused(call, b.spoken()); no {
+ return res
+ }
if res, refused := exploreRefused(call, b.spoken(), nil); refused {
// An instance below protocol 10 refuses it anyway (the kind is
// never dropped from an exploration); say why, here.
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index 0be555d6..cb80a226 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -67,7 +67,8 @@ type ClaudeOptions struct {
Logger *slog.Logger
// Tools runs the coordinator's Equipo tools for a turn. Nil serves no
// tools (the permission callback still denies everything else).
- Tools ToolCaller
+ Tools ToolCaller
+ Protocol func() int
// Catalog is the context index, summarised in a fresh session.
Catalog func() []wire.RepoInfo
// MoveInNote is appended to move-in and explore prompts (tests steer
@@ -250,6 +251,7 @@ func (c *coordBase) setTurn(ctx context.Context, turn string, attempt int64, kin
}
type claudeProcess struct {
+ access bool
lease *provider.AccountLease
process provider.Process
cancel context.CancelFunc
@@ -361,6 +363,9 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st
if err != nil {
return c.missing(ctx, in)
}
+ if c.proc != nil && c.profile.action == "converse" && c.proc.access != (c.accessProtocol() >= wire.ProtocolAccess) {
+ c.stop(true)
+ }
p := c.proc
if p != nil {
select {
@@ -477,7 +482,7 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st
mark(&timing.FirstTextMs)
timing.LastTextMs = max(time.Since(stdin).Milliseconds(), 1)
emit(text)
- } else if kind, tool, ok := streamActivity(ev.Payload, c.profile.set(true).names); ok {
+ } else if kind, tool, ok := streamActivity(ev.Payload, c.accessToolSet(true).names); ok {
if kind == wire.ActivityThink {
mark(&timing.FirstThinkingMs)
} else {
@@ -627,11 +632,17 @@ func (c *claudeCoordinator) idleExit() {
// houseRule versions the opening's rule. Changing the rule's text changes
// it, so sessions started under an older rule are not resumed.
-const houseRule = "2026-11-11.1"
+const houseRule = "2026-11-17.2"
// sessionAccount records the account and the lane's rule a session runs
// on.
-func (c *coordBase) sessionAccount() string { return c.account.ID + "#rule-" + c.profile.rule }
+func (c *coordBase) sessionAccount() string {
+ suffix := ""
+ if c.profile.action == "converse" && c.accessProtocol() < wire.ProtocolAccess {
+ suffix = "/access-legacy"
+ }
+ return c.account.ID + "#rule-" + c.profile.rule + suffix
+}
// missing is a turn that cannot have its files: refused for room on this
// runner (runner_storage_full), or not here whole.
@@ -713,7 +724,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(accessPrompt + "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")
@@ -757,7 +768,7 @@ func conversation(tail []wire.TailMessage) string {
func (c *coordBase) prompt(fresh bool, in TurnInput, catalog []wire.RepoInfo) (string, []string) {
var b strings.Builder
if fresh {
- b.WriteString(c.profile.opening(c.person, catalog))
+ b.WriteString(c.accessOpening(catalog))
if _, job := wire.JobOf(c.lane); job {
if ref := mainNotebook(c.o.SessionRoot, c.person, notebookContext); ref != "" {
b.WriteString("\n" + jobNotebookNote + ref)
@@ -978,7 +989,7 @@ func (c *claudeCoordinator) start(ctx context.Context) (err error) {
if err != nil {
return err
}
- p := &claudeProcess{lease: lease, frames: make(chan []byte, 64), exited: make(chan struct{})}
+ p := &claudeProcess{access: c.accessProtocol() >= wire.ProtocolAccess, lease: lease, frames: make(chan []byte, 64), exited: make(chan struct{})}
defer func() {
if err != nil {
c.cleanup(p)
@@ -1018,11 +1029,11 @@ func (c *claudeCoordinator) start(ctx context.Context) (err error) {
if o.Tools != nil {
call = c.toolCall
}
- if p.tool, err = openToolSet(context.Background(), o.Runner.StateDir, c.profile.set(call != nil), call); err != nil {
+ if p.tool, err = openToolSet(context.Background(), o.Runner.StateDir, c.accessToolSet(call != nil), call); err != nil {
return err
}
sel := provider.Selection{ConnectionID: c.account.LocalID, Provider: c.account.Provider, Family: c.account.Family, Model: c.account.Model, AccountID: c.account.AccountID}
- in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, p.workspace, c.profile.action, p.scratch)
+ in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, p.workspace, c.profile.action, p.scratch, c.accessProtocol() < wire.ProtocolAccess)
if err != nil {
return err
}
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go
index 609c7608..241b33a5 100644
--- a/internal/runner/thin/codex.go
+++ b/internal/runner/thin/codex.go
@@ -69,6 +69,7 @@ type codexCoordinator struct {
}
type codexProcess struct {
+ access bool
lease *provider.AccountLease
process provider.Process
cancel context.CancelFunc
@@ -150,6 +151,9 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str
if c.idle != nil {
c.idle.Stop()
}
+ if c.proc != nil && c.profile.action == "converse" && c.proc.access != (c.accessProtocol() >= wire.ProtocolAccess) {
+ c.stop(true)
+ }
if p := c.proc; p != nil {
select {
case <-p.exited:
@@ -291,7 +295,7 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str
mark(&timing.FirstThinkingMs)
case "mcpToolCall":
items[n.Item.ID] = n.Item
- kind, tool = wire.ActivityTool, activityName(n.Item.Tool, c.profile.set(true).names)
+ kind, tool = wire.ActivityTool, activityName(n.Item.Tool, c.accessToolSet(true).names)
if n.Item.Server != "equipo" {
tool = "other"
}
@@ -369,7 +373,7 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str
// answer replies to a request the app-server makes: only the lane's own
// Equipo tools are approved.
func (c *codexCoordinator) answer(p *codexProcess, m connect.Message, items map[string]codexItem) {
- answerApproval(p.rpc, m, items, c.profile.set(true).names)
+ answerApproval(p.rpc, m, items, c.accessToolSet(true).names)
}
// answerApproval replies to a request the app-server makes. Only an
@@ -409,7 +413,7 @@ func (c *codexCoordinator) start(ctx context.Context) (err error) {
if err != nil {
return err
}
- p := &codexProcess{lease: lease, exited: make(chan struct{})}
+ p := &codexProcess{access: c.accessProtocol() >= wire.ProtocolAccess, lease: lease, exited: make(chan struct{})}
defer func() {
if err != nil {
c.cleanup(p)
@@ -439,11 +443,11 @@ func (c *codexCoordinator) start(ctx context.Context) (err error) {
if o.Tools != nil {
call = c.toolCall
}
- if p.tool, err = openToolSet(context.Background(), o.Runner.StateDir, c.profile.set(call != nil), call); err != nil {
+ if p.tool, err = openToolSet(context.Background(), o.Runner.StateDir, c.accessToolSet(call != nil), call); err != nil {
return err
}
sel := provider.Selection{ConnectionID: c.account.LocalID, Provider: "codex", Family: c.account.Family, Model: c.account.Model, AccountID: c.account.AccountID}
- in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, c.workspace(), c.profile.action, p.scratch)
+ in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, c.workspace(), c.profile.action, p.scratch, c.accessProtocol() < wire.ProtocolAccess)
if err != nil {
return err
}
diff --git a/internal/runner/thin/forge.go b/internal/runner/thin/forge.go
index e950d934..58d48d16 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,13 +143,20 @@ 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()
}
func (f *fileForge) Remote(ctx context.Context, repo string) (workspace.Remote, error) {
- if !slices.Contains(f.Reachable(ctx), repo) {
+ f.list(ctx)
+ if !slices.Contains(f.Repos(), repo) {
return workspace.Remote{}, workspace.ErrGitPassword
}
+ return f.remoteCredential(ctx, repo)
+}
+
+func (f *fileForge) remoteCredential(ctx context.Context, repo string) (workspace.Remote, error) {
names, _ := f.creds.RepositoryNames()
if !slices.Contains(names, repo) {
// Created or reachable through the agent's namespace grant: the
@@ -221,7 +231,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)
}
@@ -287,7 +297,8 @@ func (f *fileForge) Create(ctx context.Context, repo string) error {
// Merge sends the hub the merge request with the agent's credential for
// repo (its own entry, or the agent-wide one).
func (f *fileForge) Merge(ctx context.Context, repo, branch string, req forge.HubMergeRequest) (forge.HubMergeResult, error) {
- if !slices.Contains(f.Reachable(ctx), repo) {
+ f.list(ctx)
+ if !slices.Contains(f.Repos(), repo) {
return forge.HubMergeResult{}, forge.ErrMergeRefused
}
c, err := f.creds.Credential(ctx, repo)
@@ -317,7 +328,8 @@ func (f *fileForge) CIStatus(ctx context.Context, repo, branch, logs string) (fo
}
func (f *fileForge) ciCredential(ctx context.Context, repo string) (forge.Credential, error) {
- if !slices.Contains(f.Reachable(ctx), repo) {
+ f.list(ctx)
+ if !slices.Contains(f.Repos(), repo) {
return forge.Credential{}, forge.ErrCIRead
}
c, err := f.creds.Credential(ctx, repo)
@@ -381,7 +393,7 @@ func (c *Clones) fetch(ctx context.Context, repo string, shallow bool, branch st
if !repoKey.MatchString(repo) {
return ErrNoCreate
}
- remote, err := c.Forge.Remote(ctx, repo)
+ remote, err := readRemote(ctx, c.Forge, repo)
if err != nil {
return err
}
@@ -465,7 +477,7 @@ func groupCommand(ctx context.Context, name string, args ...string) *exec.Cmd {
// DefaultBranch asks the remote which branch HEAD names.
func (c *Clones) DefaultBranch(ctx context.Context, repo string) (string, error) {
- remote, err := c.Forge.Remote(ctx, repo)
+ remote, err := readRemote(ctx, c.Forge, repo)
if err != nil {
return "", err
}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 62ea6b6b..399ef837 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).
@@ -120,7 +121,7 @@ type Link struct {
tools map[string]chan wire.ToolResult
leaseSeq int64
helloSoon bool
- // proto is what the current connection speaks; role what the instance
+ // proto keeps the last negotiated version; role is what the instance
// said this runner is (primary at protocol 1).
proto int
role string
@@ -465,6 +466,21 @@ func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error
l.mu.Lock()
proto := l.proto
l.mu.Unlock()
+ if f.Type == wire.FrameToolCall {
+ body, err := f.Decode()
+ if err != nil {
+ return err
+ }
+ if call, ok := body.(*wire.ToolCall); ok {
+ if result, refused := accessRefused(*call, proto); refused {
+ if err := l.State.Acked(ctx, f.ID); err != nil {
+ return err
+ }
+ l.deliverTool(result)
+ return nil
+ }
+ }
+ }
f, err := wire.Encode(f, max(proto, wire.Protocol1))
if errors.Is(err, wire.ErrProtocol) {
if l.Logger != nil {
@@ -820,6 +836,10 @@ 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 err = l.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..7ad7640c 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"
)
@@ -47,6 +48,7 @@ func openToolSocket(ctx context.Context, root string, call ToolFunc) (*toolSocke
// callback's answer (nil: no permission tool, as for Codex, which asks
// through the app-server instead).
type toolSet struct {
+ current func() toolSet
list []any
names []string
permission func(json.RawMessage) string
@@ -151,6 +153,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")},
@@ -203,6 +206,10 @@ func serveMCP(ctx context.Context, c net.Conn, set toolSet, call ToolFunc) {
if len(q.ID) == 0 {
continue
}
+ active := set
+ if set.current != nil {
+ active = set.current()
+ }
reply := map[string]any{"jsonrpc": "2.0", "id": q.ID}
switch q.Method {
case "initialize":
@@ -222,8 +229,8 @@ func serveMCP(ctx context.Context, c net.Conn, set toolSet, call ToolFunc) {
reply["error"] = map[string]any{"code": -32600, "message": "not initialized"}
break
}
- tools := slices.Clone(set.list)
- if set.permission != nil {
+ tools := slices.Clone(active.list)
+ if active.permission != nil {
permission := map[string]any{"name": "permission", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"tool_name": map[string]string{"type": "string"}, "tool_use_id": map[string]string{"type": "string"}, "input": map[string]string{"type": "object"}}, "required": []string{"tool_name", "input"}, "additionalProperties": false}}
tools = append([]any{permission}, tools...)
}
@@ -238,11 +245,11 @@ func serveMCP(ctx context.Context, c net.Conn, set toolSet, call ToolFunc) {
reply["error"] = map[string]any{"code": -32602, "message": "unavailable"}
break
}
- if p.Name == "permission" && set.permission != nil {
- reply["result"] = map[string]any{"content": []any{map[string]string{"type": "text", "text": set.permission(p.Arguments)}}}
+ if p.Name == "permission" && active.permission != nil {
+ reply["result"] = map[string]any{"content": []any{map[string]string{"type": "text", "text": active.permission(p.Arguments)}}}
break
}
- if call == nil || !slices.Contains(set.names, p.Name) {
+ if call == nil || !slices.Contains(active.names, p.Name) {
reply["error"] = map[string]any{"code": -32602, "message": "unavailable"}
break
}
diff --git a/internal/runner/thin/merge.go b/internal/runner/thin/merge.go
index fcf0d093..ac839f2c 100644
--- a/internal/runner/thin/merge.go
+++ b/internal/runner/thin/merge.go
@@ -282,7 +282,7 @@ const unbornDefault = "main"
// Heads asks the remote, in one ls-remote, for its default branch, that
// branch's tip and the heads of the named branches (absent: gone).
func (c *Clones) Heads(ctx context.Context, repo string, branches []string) (string, string, map[string]string, error) {
- remote, err := c.Forge.Remote(ctx, repo)
+ remote, err := readRemote(ctx, c.Forge, repo)
if err != nil {
return "", "", nil, err
}
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 1c2e654c..56431c3b 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -196,10 +196,14 @@ 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}
o.Claude.Tools, o.Claude.Catalog = tools.Call, index.Catalog
+ o.Claude.Protocol = link.LastProtocol
conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait}
conns.ClaudeUsage = o.Claude.Profile
conns.ClaudeStatus = func(ctx context.Context, b provider.Binding) (provider.Identity, string, error) {
@@ -305,6 +309,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, Authorize: link.ConfirmAccess, 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..304b6de2 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -58,7 +58,11 @@ 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
+ }
+ if err = migrateAccess(ctx, d); 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/thintest/access_review_browser_test.go b/internal/thintest/access_review_browser_test.go
new file mode 100644
index 00000000..5efd3d77
--- /dev/null
+++ b/internal/thintest/access_review_browser_test.go
@@ -0,0 +1,50 @@
+//go:build browser
+
+package thintest
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "fmt"
+ "testing"
+)
+
+func TestBrowserAccessReview(t *testing.T) {
+ for _, width := range []int64{1280, 390} {
+ for _, scheme := range []string{"light", "dark"} {
+ t.Run(fmt.Sprintf("%d-%s", width, scheme), func(t *testing.T) {
+ r := newToolRigSaying(t, wire.ProtocolCurrent, "Give access to the whole carlos namespace")
+ reason := `I need access. <img src=x onerror="window.accessInjection=true">`
+ got := r.call("broad-access", wire.ToolRequestAccess, map[string]any{"target": "carlos", "reason": reason})
+ if got.Code != "asked" {
+ t.Fatal(got)
+ }
+ r.runner.Send(r.ctx, "broad-reply", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Please confirm."})
+ r.wait("reply", 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-confirm]')`, "confirmation")
+ p.check(`document.querySelector('[data-access-state]').textContent.includes('Ask Amadan for access to everything in carlos?')`, "broad scope")
+ p.check(`!document.querySelector('[data-access-state] img') && !window.accessInjection && document.querySelector('[data-access-state]').textContent.includes('<img')`, "reason is escaped text")
+ p.fits("broad confirmation")
+ p.shot(fmt.Sprintf("access-review-broad-%d-%s", width, scheme))
+ p.click(`[data-access-confirm]`)
+ _, body, err := r.runner.Expect(r.ctx, wire.FrameRequestAccess)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := body.(*wire.AccessCommand)
+ r.runner.Send(r.ctx, "broad-pending", wire.FrameAccess, wire.AccessReport{CardID: cmd.CardID, Person: cmd.Person, RequestID: "ar_broad", State: "pending", ApproveURL: "https://amadan.net/settings/agents/requests/ar_broad"})
+ p.wait(`document.querySelector('[data-access-state="pending"]')`, "pending")
+ p.check(`document.querySelector('[data-access-state]').textContent.includes('Everything in carlos')`, "pending stays broad")
+ p.click(`[data-access-aside]`)
+ p.wait(`document.querySelector('[equipo-aside-stub]')`, "aside")
+ r.runner.Send(r.ctx, "broad-approved", wire.FrameAccess, wire.AccessReport{CardID: cmd.CardID, Person: cmd.Person, RequestID: "ar_broad", State: "approved", ApproveURL: "https://amadan.net/settings/agents/requests/ar_broad"})
+ p.wait(`document.querySelector('[equipo-card-done]')?.textContent.includes('Access granted')`, "visible grant note")
+ p.check(`!document.querySelector('[equipo-aside-stub]')`, "grant replaces aside stub")
+ p.fits("grant note")
+ p.shot(fmt.Sprintf("access-review-granted-%d-%s", width, scheme))
+ })
+ }
+ }
+}
diff --git a/internal/thintest/access_round3_browser_test.go b/internal/thintest/access_round3_browser_test.go
new file mode 100644
index 00000000..21ac3c7b
--- /dev/null
+++ b/internal/thintest/access_round3_browser_test.go
@@ -0,0 +1,48 @@
+//go:build browser
+
+package thintest
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "fmt"
+ "testing"
+)
+
+func TestBrowserAccessFinalOutcomes(t *testing.T) {
+ for _, width := range []int64{1280, 390} {
+ for _, scheme := range []string{"light", "dark"} {
+ for _, outcome := range []string{"not_owned", "already"} {
+ t.Run(fmt.Sprintf("%d-%s-%s", width, scheme, outcome), func(t *testing.T) {
+ r := newToolRigSaying(t, wire.ProtocolCurrent, "Fix carlos/platform")
+ if got := r.call("access-proposal", wire.ToolRequestAccess, map[string]any{"target": "carlos/platform", "reason": "I need access to fix the build."}); got.Code != "asked" {
+ t.Fatal(got)
+ }
+ r.runner.Send(r.ctx, "reply", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Please confirm."})
+ r.wait("reply", 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-confirm]')`, "confirmation")
+ 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 err := r.runner.Send(r.ctx, "final", wire.FrameAccess, wire.AccessReport{CardID: cmd.CardID, Person: cmd.Person, State: outcome}); err != nil {
+ t.Fatal(err)
+ }
+ p.wait(`document.querySelector('[data-access-state="`+outcome+`"]')`, outcome)
+ want := "Equipo already has access."
+ if outcome == "not_owned" {
+ want = "Amadan can’t ask the owner of carlos for access."
+ }
+ p.check(`document.querySelector('[data-access-state] [role="status"]').textContent === `+fmt.Sprintf("%q", want), "clear final copy")
+ p.check(`!document.querySelector('[data-access-confirm], [data-access-approve], [data-access-aside]')`, "no retry or approval action")
+ p.fits(outcome)
+ p.shot(fmt.Sprintf("access-final-%s-%d-%s", outcome, width, scheme))
+ })
+ }
+ }
+ }
+}
diff --git a/internal/wire/access.go b/internal/wire/access.go
new file mode 100644
index 00000000..2cf61bcc
--- /dev/null
+++ b/internal/wire/access.go
@@ -0,0 +1,75 @@
+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", "unconfirmed", "missing", "uncheckable", "authority", "not_owned", "already":
+ return true
+ }
+ return false
+}
+func AccessRole(s string) bool { return s == "agent" || s == "reader" || s == "runner" }
+
+// Amadan 1dadddf internal/hub/server.go:993 and agent_access.go:547.
+func AccessURL(s, id string) bool {
+ if !accessTarget.MatchString(id) || strings.Contains(id, "/") {
+ return false
+ }
+ u, err := url.Parse(s)
+ return err == nil && u.Scheme == "https" && u.Host == "amadan.net" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.RawFragment == "" && u.RawPath == "" && !strings.ContainsAny(s, "\\#") && u.Path == "/settings/agents/requests/"+id
+}
+
+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..55a2346b
--- /dev/null
+++ b/internal/wire/access_test.go
@@ -0,0 +1,40 @@
+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)
+ }
+ }
+}
+
+func TestAccessLeaseDowngrade(t *testing.T) {
+ f, err := wire.NewFrame("lease", wire.FrameLease, wire.LeaseCheck{AccessCard: "card"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := wire.Encode(f, wire.Protocol25); err == nil {
+ t.Fatal("access lease sent to old instance")
+ }
+ 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..527b9f1a 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:
@@ -399,7 +403,8 @@ type Run struct {
// LeaseCheck asks the instance to confirm, before execution, that this
// connection still holds Generation. The instance acks it only then.
type LeaseCheck struct {
- Generation int64 `json:"generation"`
+ AccessCard string `json:"access_card,omitempty"`
+ Generation int64 `json:"generation"`
// Protocol 2: the start authorization of one step attempt. The
// instance acks it only while the attempt is assigned to this runner
// and not withdrawn, and records that it started.
@@ -578,7 +583,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 +670,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 +681,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..3fd117de 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,12 @@ 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
+ }
+ if v, ok := body.(*LeaseCheck); ok && v.AccessCard != "" && protocol < ProtocolAccess {
+ 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"})