Harden access contracts, polling and runner authority
41 files changed,
+1,166
−151
.rastrillo/budgets.txt+7 −7docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+7 −0internal/equipo/access_review_test.go+18 −0internal/equipo/chat/access_authority.go+67 −0internal/equipo/chat/access_request.go+7 −3internal/equipo/chat/access_request_test.go+1 −1internal/equipo/chat/access_review_test.go+128 −0internal/equipo/chat/projects.go+5 −1internal/equipo/chat/stream.go+2 −0internal/equipo/chat/tools.go+11 −1internal/equipo/chat_page.go+8 −0internal/equipo/copy.go+8 −0internal/equipo/templates/access_card.html+1 −1internal/plan3test/plan3_release_test.go+1 −1internal/runner/policy_inputs.go+4 −1internal/runner/provider/actions.go+13 −1internal/runner/provider/claude/converse_policy_test.go+13 −0internal/runner/provider/claude/launcher.go+1 −1internal/runner/provider/codex/launcher.go+1 −2internal/runner/thin/access.go+123 −62internal/runner/thin/access_catalog.go+11 −0internal/runner/thin/access_contract.go+26 −0internal/runner/thin/access_contract_test.go+69 −0internal/runner/thin/access_forge.go+45 −15internal/runner/thin/access_protocol.go+65 −0internal/runner/thin/access_review_test.go+332 −0internal/runner/thin/access_test.go+39 −20internal/runner/thin/bridge.go+3 −0internal/runner/thin/claude.go+20 −9internal/runner/thin/codex.go+9 −5internal/runner/thin/forge.go+12 −5internal/runner/thin/link.go+16 −4internal/runner/thin/mcp.go+10 −5internal/runner/thin/merge.go+1 −1internal/runner/thin/run.go+2 −1internal/runner/thin/state.go+4 −0internal/thintest/access_review_browser_test.go+50 −0internal/wire/access.go+8 −3internal/wire/access_test.go+13 −0internal/wire/frames.go+2 −1internal/wire/runners.go+3 −0
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 7edf7198..ea0d4e12 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 21054 - Shared web views and Roster access confirmation and state presentation. Limits match measured lines. |
| -size internal/wire 6534 - Shared protocol types; protocol 26 adds durable confirmed access commands and state reports. Limits match measured lines. |
| +size internal/equipo 21070 - Shared web views and Roster access confirmation and state presentation. Limits match measured lines. Access review guards and contract tests; limit matches measured lines. |
| +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 - Pi adds a pinned isolated shell, immutable configuration files and offline Go; the glance action pins its small models. Measured 5505 source lines. Access review guards and contract tests; limit matches measured 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 26817 19303 Shared runner state and forge integration; durable access polling, grants and restart guards. Limits match measured lines. |
| +size internal/runner/thin 27057 19723 Shared runner state and forge integration; durable access polling, grants and restart guards. Limits match measured lines. Access review guards and contract tests; limit matches measured lines. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 30577 - Transactional authority and dispatch; access proposals, person confirmation and approval continuation. Limits match measured lines. |
| +size internal/equipo/chat 30664 - Transactional authority and dispatch; access proposals, person confirmation and approval continuation. Limits match measured lines. Access review guards and contract tests; limit matches measured lines. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally). |
| size internal/headless - 11062 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11062 test lines. |
| -size internal/thintest - 30883 Shared instance/browser fixtures; access confirmation and four outcomes at two sizes and two themes. Limits match measured lines. |
| +size internal/thintest - 30933 Shared instance/browser fixtures; access confirmation and four outcomes at two sizes and two themes. Limits match measured lines. Access review guards and contract tests; limit matches measured lines. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
| perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage. |
| perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index b75529e3..d7b606d3 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -4706,6 +4706,13 @@ All eight entries have individual `COPY REVIEW REQUIRED` markers. The API guide |
| | Key | Text | Use | Status | |
| | --- | --- | --- | --- | |
| +| `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) | |
diff --git a/internal/equipo/access_review_test.go b/internal/equipo/access_review_test.go| new file mode 100644 |
| index 00000000..582c0f2a |
| --- /dev/null |
| +++ b/internal/equipo/access_review_test.go |
| @@ -0,0 +1,18 @@ |
| +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) |
| + } |
| +} |
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| index 3b917a09..bebc6ab5 100644 |
| --- a/internal/equipo/chat/access_request.go |
| +++ b/internal/equipo/chat/access_request.go |
| @@ -82,7 +82,11 @@ func (t *txn) requestAccess(r turnRecord, in wire.AccessRequest) (wire.ToolResul |
| if fresh { |
| c = cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardAccess, State: wire.CardOpen, TurnID: r.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane} |
| } |
| - c.Access, c.Name, c.Question = string(raw), in.Target, fmt.Sprintf(t.s.authority.Copy("access.confirm"), in.Target) |
| + 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 |
| @@ -163,10 +167,10 @@ func (t *txn) accessReport(l Lease, v *wire.AccessReport) error { |
| if wire.AccessFinal(a.State) { |
| return nil |
| } |
| - if v.State != "pending" && !wire.AccessFinal(v.State) || len(v.RequestID) > 200 || v.ApproveURL != "" && !wire.AccessURL(v.ApproveURL) { |
| + 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 == "" { |
| + if (v.State == "pending" || v.State == "approved") && (v.RequestID == "" || !wire.AccessURL(v.ApproveURL, v.RequestID)) { |
| return ErrInvalid |
| } |
| if a.RequestID != "" && a.RequestID != v.RequestID { |
diff --git a/internal/equipo/chat/access_request_test.go b/internal/equipo/chat/access_request_test.go| index 76ec3016..773e8d9e 100644 |
| --- a/internal/equipo/chat/access_request_test.go |
| +++ b/internal/equipo/chat/access_request_test.go |
| @@ -158,7 +158,7 @@ func TestAccessApprovalWaitsForCatalogAndContinuesOnce(t *testing.T) { |
| } |
| 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"} |
| + 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) |
| } |
diff --git a/internal/equipo/chat/access_review_test.go b/internal/equipo/chat/access_review_test.go| new file mode 100644 |
| index 00000000..206d2b64 |
| --- /dev/null |
| +++ b/internal/equipo/chat/access_review_test.go |
| @@ -0,0 +1,128 @@ |
| +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) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go| index 3d70a924..7c6baeae 100644 |
| --- a/internal/equipo/chat/projects.go |
| +++ b/internal/equipo/chat/projects.go |
| @@ -373,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", "access", "name", "question").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/stream.go b/internal/equipo/chat/stream.go| index 79aea08f..a94c7b9f 100644 |
| --- a/internal/equipo/chat/stream.go |
| +++ b/internal/equipo/chat/stream.go |
| @@ -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 16b3ac78..f687ab5d 100644 |
| --- a/internal/equipo/chat/tools.go |
| +++ b/internal/equipo/chat/tools.go |
| @@ -1046,7 +1046,17 @@ func (t *txn) find(r turnRecord, query string) (wire.ToolResult, error) { |
| if h.Agent == "" { |
| hint = fmt.Sprintf("Nothing Equipo's agent can reach matches %q. Tell the person it is not shared with Equipo. The agent name is unavailable until the runner reconnects. Do not invent a name. Mention that merging is a separate per-project setting.", query) |
| } |
| - hint += " Use request_access with the single repository, role agent unless asked otherwise, and your reason. It only raises a confirmation card. Never retry unprompted." |
| + 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 |
| } |
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go| index e9075b68..550f7982 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. |
| @@ -153,6 +154,13 @@ func cardView(c wire.Card, choices []string, tasks map[string]wire.Task) chatCar |
| if c.Access != nil { |
| v.Open = c.State == wire.CardOpen |
| v.Line = copyText("access." + c.Access.State) |
| + 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, ", ") |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index cbfdf224..83278d20 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -66,6 +66,14 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + "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) |
diff --git a/internal/equipo/templates/access_card.html b/internal/equipo/templates/access_card.html| index d68dde26..223e244c 100644 |
| --- a/internal/equipo/templates/access_card.html |
| +++ b/internal/equipo/templates/access_card.html |
| @@ -1,6 +1,6 @@ |
| {{define "access-card"}} |
| <div data-access-state="{{.Access.State}}"> |
| -<h3 equipo-card-line>{{if eq .Access.State "confirmation"}}{{.Question}}{{else}}{{copy "access.title"}}: {{.Access.Target}}{{end}}</h3> |
| +<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> |
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go| index 0a5627d4..0616ea99 100644 |
| --- a/internal/plan3test/plan3_release_test.go |
| +++ b/internal/plan3test/plan3_release_test.go |
| @@ -181,7 +181,7 @@ 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.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)") |
| + acceptedAccess := slices.Contains([]string{"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]) |
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 3d313b89..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 { |
| @@ -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 685d8475..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 |
| } |
| } |
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| index 828f0820..d761b05e 100644 |
| --- a/internal/runner/thin/access.go |
| +++ b/internal/runner/thin/access.go |
| @@ -6,13 +6,14 @@ import ( |
| "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);` |
| +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) { |
| @@ -35,13 +36,13 @@ func (s *State) AcceptAccess(ctx context.Context, frame string, c wire.AccessCom |
| if !errors.Is(err, sql.ErrNoRows) { |
| return err |
| } |
| - _, err = tx.Exec("INSERT INTO access_requests(card_id,command,state) VALUES(?,?,'queued')", c.CardID, string(raw)) |
| + _, 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) error |
| + Authorize func(context.Context, string) error |
| State *State |
| Forge AccessForge |
| Refresh func() |
| @@ -68,38 +69,88 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| return errAccess |
| } |
| var out wire.AccessReport |
| + settled := false |
| var err error |
| switch state { |
| case "queued": |
| - if e.Authorize != nil { |
| - if err := e.Authorize(ctx); err != nil { |
| - return err |
| - } |
| - } |
| if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET state='filing' WHERE card_id=?", id); err != nil { |
| return err |
| } |
| - if e.Forge == nil { |
| - err = errAccess |
| - } else { |
| - out, err = e.Forge.RequestAccess(ctx, cmd) |
| + if 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 = "failed" |
| - if errors.Is(err, errAccessLimit) { |
| - out.State = "limited" |
| + 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, errAccessLimit) { |
| + out.State = "limited" |
| + } |
| + if errors.Is(err, errAccessContract) || errors.Is(err, errAccessState) { |
| + out.State = "unconfirmed" |
| + } |
| } |
| } |
| case "filing": |
| - out.State = "failed" |
| + out.State = "unconfirmed" |
| case "pending": |
| - out, err = e.Forge.PollAccess(ctx, old.RequestID) |
| + out = old |
| + if old.Expires > 0 && time.Now().Unix() >= old.Expires { |
| + out.State = "expired" |
| + break |
| + } |
| + pollctx, cancel := context.WithCancel(ctx) |
| + if old.Expires > 0 { |
| + cancel() |
| + pollctx, cancel = context.WithDeadline(ctx, time.Unix(old.Expires, 0)) |
| + } |
| + out, err = e.Forge.PollAccess(pollctx, old.RequestID, cmd) |
| + cancel() |
| + if old.Expires > 0 && time.Now().Unix() >= old.Expires { |
| + out = old |
| + out.State = "expired" |
| + break |
| + } |
| + if err == nil && out.RequestID != old.RequestID { |
| + err = errAccessContract |
| + } |
| 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 |
| } |
| - if out.RequestID != old.RequestID { |
| - return errAccess |
| - } |
| + |
| default: |
| return errAccess |
| } |
| @@ -115,7 +166,7 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", out.State, string(raw), id); err != nil { |
| return err |
| } |
| - if string(raw) == report { |
| + if string(raw) == report || settled { |
| return nil |
| } |
| return e.State.enqueue(tx, wire.FrameAccess, "", out) |
| @@ -135,66 +186,76 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| return nil |
| } |
| -// Run bounds simultaneous long polls to five, matching the hub's waiting |
| -// limit. Even an immediate pending response waits before another GET. |
| +// 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{} |
| - done := make(chan string, 5) |
| - ticker := time.NewTicker(time.Second) |
| - defer ticker.Stop() |
| + 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 id := <-done: |
| - delete(active, id) |
| - case <-ticker.C: |
| - rows, err := e.State.db.QueryContext(ctx, "SELECT card_id FROM access_requests WHERE state IN ('queued','filing','pending') ORDER BY card_id LIMIT 5") |
| + case result := <-done: |
| + delete(active, result.id) |
| + if result.filing { |
| + filing = false |
| + } else { |
| + polls-- |
| + } |
| + delay := time.Second |
| + 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') ORDER BY CASE WHEN state='pending' THEN 1 ELSE 0 END, confirmed_at, rowid LIMIT 128") |
| if err != nil { |
| continue |
| } |
| - var ids []string |
| + var jobs []struct{ id, state string } |
| for rows.Next() { |
| - var id string |
| - if rows.Scan(&id) == nil { |
| - ids = append(ids, id) |
| + var j struct{ id, state string } |
| + if rows.Scan(&j.id, &j.state) == nil { |
| + jobs = append(jobs, j) |
| } |
| } |
| rows.Close() |
| - for _, id := range ids { |
| - if len(active) >= 5 { |
| - break |
| - } |
| - if active[id] { |
| + for _, j := range jobs { |
| + fresh := j.state != "pending" |
| + if active[j.id] || time.Now().Before(next[j.id]) || fresh && filing || !fresh && polls >= 5 { |
| continue |
| } |
| - active[id] = true |
| + active[j.id] = true |
| + if fresh { |
| + filing = true |
| + } else { |
| + polls++ |
| + } |
| wg.Add(1) |
| - go func(id string) { |
| - defer wg.Done() |
| - defer func() { done <- id }() |
| - delay := time.Second |
| - for ctx.Err() == nil { |
| - err := e.Step(ctx, id) |
| - var state string |
| - if e.State.db.QueryRowContext(ctx, "SELECT state FROM access_requests WHERE card_id=?", id).Scan(&state) == nil && wire.AccessFinal(state) { |
| - return |
| - } |
| - if err != nil { |
| - delay = min(delay*2, time.Minute) |
| - } else { |
| - delay = time.Second |
| - } |
| - select { |
| - case <-ctx.Done(): |
| - return |
| - case <-time.After(delay): |
| - } |
| - } |
| - }(id) |
| + 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| index a7814579..31b3fa57 100644 |
| --- a/internal/runner/thin/access_catalog.go |
| +++ b/internal/runner/thin/access_catalog.go |
| @@ -9,6 +9,7 @@ import ( |
| "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -86,3 +87,13 @@ func (s *State) accessReadTargets(ctx context.Context) ([]string, error) { |
| } |
| 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| index 195da801..9ccbff26 100644 |
| --- a/internal/runner/thin/access_forge.go |
| +++ b/internal/runner/thin/access_forge.go |
| @@ -16,12 +16,16 @@ import ( |
| ) |
| 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 errAccessLimit = errors.New("access request limit reached") |
| var accessID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,200}$`) |
| type AccessForge interface { |
| RequestAccess(context.Context, wire.AccessCommand) (wire.AccessReport, error) |
| - PollAccess(context.Context, string) (wire.AccessReport, error) |
| + PollAccess(context.Context, string, wire.AccessCommand) (wire.AccessReport, error) |
| Recheck() |
| Reachable(context.Context) []string |
| } |
| @@ -37,11 +41,11 @@ func (f *fileForge) RequestAccess(ctx context.Context, c wire.AccessCommand) (wi |
| raw, _ := json.Marshal(map[string]any{"target": c.Target, "role": c.Role, "reason": c.Reason, "agent": map[string]string{"session": "equipo-access-" + c.CardID, "harness": "equipo", "host": host}}) |
| return f.accessHTTP(ctx, http.MethodPost, "/api/v1/agents/access-requests", raw, &c) |
| } |
| -func (f *fileForge) PollAccess(ctx context.Context, id string) (wire.AccessReport, error) { |
| +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, nil) |
| + 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) |
| @@ -66,23 +70,49 @@ func (f *fileForge) accessHTTP(ctx context.Context, method, path string, body [] |
| if res.StatusCode == http.StatusTooManyRequests { |
| return wire.AccessReport{}, errAccessLimit |
| } |
| + 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 struct { |
| - Target string `json:"target"` |
| - Role string `json:"role"` |
| - Reason string `json:"reason"` |
| - ID string `json:"id"` |
| - State string `json:"state"` |
| - ApproveURL string `json:"approve_url"` |
| - Expires int64 `json:"expires"` |
| + 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 |
| } |
| - if json.NewDecoder(io.LimitReader(res.Body, 16<<10)).Decode(&out) != nil || !accessID.MatchString(out.ID) || out.State != "pending" && out.State != "approved" && out.State != "declined" && out.State != "expired" || out.ApproveURL != "" && !wire.AccessURL(out.ApproveURL) || out.Expires < 0 { |
| - return wire.AccessReport{}, errAccess |
| + var fields map[string]json.RawMessage |
| + if json.Unmarshal(raw, &fields) != nil { |
| + return wire.AccessReport{}, errAccessContract |
| } |
| - if expected != nil && (out.Target != "" && out.Target != expected.Target || out.Role != "" && out.Role != expected.Role || out.Reason != "" && out.Reason != expected.Reason) { |
| - return wire.AccessReport{}, errAccess |
| + 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} { |
diff --git a/internal/runner/thin/access_protocol.go b/internal/runner/thin/access_protocol.go| new file mode 100644 |
| index 00000000..48673f97 |
| --- /dev/null |
| +++ b/internal/runner/thin/access_protocol.go |
| @@ -0,0 +1,65 @@ |
| +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 >= 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 { |
| + return c.o.Protocol() |
| + } |
| + return wire.ProtocolCurrent |
| +} |
| +func accessToolSetAt(set toolSet, protocol int) toolSet { |
| + if 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}) |
| +} |
diff --git a/internal/runner/thin/access_review_test.go b/internal/runner/thin/access_review_test.go| new file mode 100644 |
| index 00000000..a32ce749 |
| --- /dev/null |
| +++ b/internal/runner/thin/access_review_test.go |
| @@ -0,0 +1,332 @@ |
| +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) |
| + 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(-time.Second).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 = "expired" |
| + } |
| + if state != want || calls.Load() > 3 || mode == "expiry" && calls.Load() != 0 { |
| + 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_test.go b/internal/runner/thin/access_test.go| index a7d55233..dd5b192b 100644 |
| --- a/internal/runner/thin/access_test.go |
| +++ b/internal/runner/thin/access_test.go |
| @@ -76,22 +76,19 @@ func TestAccessRunnerRestartAndApprovalRefresh(t *testing.T) { |
| fmt.Fprint(w, `{"repos":[{"ns":"carlos","name":"platform"}]}`) |
| case r.Method == "POST": |
| posts.Add(1) |
| - var body struct { |
| - Target, Role, Reason string |
| - Agent map[string]string |
| - } |
| + var body testAccessCreate |
| json.NewDecoder(r.Body).Decode(&body) |
| - if body.Target != "carlos/platform" || body.Role != "agent" || body.Agent["session"] == "" { |
| + if body.Target != "carlos/platform" || body.Role != "agent" || (body.Agent == nil || body.Agent.Session == "") { |
| t.Errorf("body: %+v", body) |
| } |
| w.WriteHeader(201) |
| - fmt.Fprint(w, `{"id":"ar_one","state":"pending","approve_url":"https://amadan.net/agents/access-requests/ar_one","expires":1795176000}`) |
| + 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) |
| } |
| - fmt.Fprint(w, `{"id":"ar_one","state":"approved"}`) |
| + writeAccess(w, "ar_one", "approved") |
| } |
| }) |
| f.Reachable(ctx) |
| @@ -155,7 +152,12 @@ func TestAccessRunnerFinalAndLimits(t *testing.T) { |
| fmt.Fprint(w, "SECRET-ACCESS-TOKEN") |
| return |
| } |
| - fmt.Fprintf(w, `{"id":"ar_one","state":%q}`, state) |
| + 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 { |
| @@ -175,7 +177,13 @@ func TestAccessRunnerFinalAndLimits(t *testing.T) { |
| t.Fatal(err) |
| } |
| raw, _ := json.Marshal(frames) |
| - if calls.Load() != 1 || len(frames) != 1 || !strings.Contains(string(raw), `\"state\":\"`+state+`\"`) && !strings.Contains(string(raw), `"state":"`+state+`"`) { |
| + 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-") { |
| @@ -215,7 +223,7 @@ func TestAccessRunnerUncertainPostDoesNotRefile(t *testing.T) { |
| t.Fatal("repeated uncertain POST") |
| } |
| var state string |
| - if err := s.db.QueryRow("SELECT state FROM access_requests").Scan(&state); err != nil || state != "failed" { |
| + if err := s.db.QueryRow("SELECT state FROM access_requests").Scan(&state); err != nil || state != "unconfirmed" { |
| t.Fatal(state, err) |
| } |
| } |
| @@ -226,7 +234,8 @@ func TestAccessRunnerRunBackoffAndCancellation(t *testing.T) { |
| var mu sync.Mutex |
| f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| if r.Method == "POST" { |
| - fmt.Fprint(w, `{"id":"ar_one","state":"pending"}`) |
| + w.WriteHeader(201) |
| + writeAccess(w, "ar_one", "pending") |
| return |
| } |
| mu.Lock() |
| @@ -237,7 +246,7 @@ func TestAccessRunnerRunBackoffAndCancellation(t *testing.T) { |
| w.WriteHeader(503) |
| return |
| } |
| - fmt.Fprint(w, `{"id":"ar_one","state":"expired"}`) |
| + writeAccess(w, "ar_one", "expired") |
| }) |
| ctx, cancel := context.WithCancel(context.Background()) |
| defer cancel() |
| @@ -328,7 +337,10 @@ func TestAccessExistingRequestMustMatchConfirmation(t *testing.T) { |
| for _, role := range []string{"agent", "runner"} { |
| t.Run(role, func(t *testing.T) { |
| f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| - fmt.Fprintf(w, `{"id":"existing_one","state":"pending","existing":true,"target":"carlos/platform","role":%q,"reason":"I need to fix the build.","approve_url":"https://amadan.net/settings/agents/requests/existing_one"}`, role) |
| + v := accessResponse("existing_one", "pending") |
| + v.Existing = true |
| + v.Role = role |
| + writeAccessInfo(w, v) |
| }) |
| out, err := f.RequestAccess(context.Background(), accessCommand()) |
| if role == "agent" { |
| @@ -355,22 +367,29 @@ func TestAccessRunnerChecksCurrentAuthorityBeforeFiling(t *testing.T) { |
| if err := s.AcceptAccess(ctx, "frame", cmd); err != nil { |
| t.Fatal(err) |
| } |
| - e := &AccessEngine{State: s, Forge: f, Authorize: func(context.Context) error { return errAccess }} |
| - if err := e.Step(ctx, cmd.CardID); err == nil { |
| - t.Fatal("stale authority permitted filing") |
| + 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 != "queued" { |
| + 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) error { return nil } |
| + e.Authorize = func(context.Context, string) error { return nil } |
| if err := e.Step(ctx, cmd.CardID); err != nil { |
| t.Fatal(err) |
| } |
| - if calls.Load() != 1 { |
| - t.Fatal("current authority did not permit request") |
| + 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..b7b2e360 100644 |
| --- a/internal/runner/thin/bridge.go |
| +++ b/internal/runner/thin/bridge.go |
| @@ -509,6 +509,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 bb71756b..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-17.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("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. 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 8d267998..58d48d16 100644 |
| --- a/internal/runner/thin/forge.go |
| +++ b/internal/runner/thin/forge.go |
| @@ -149,9 +149,14 @@ func (f *fileForge) Recheck() { |
| } |
| 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 |
| @@ -292,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) |
| @@ -322,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) |
| @@ -386,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 |
| } |
| @@ -470,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 1c4e4362..07d646e3 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -466,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 { |
| @@ -822,10 +837,7 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro |
| return 0, err |
| } |
| case *wire.AccessCommand: |
| - if l.knownWorker(ctx) || l.Access == nil { |
| - return 0, errAccess |
| - } |
| - if err = l.State.AcceptAccess(ctx, f.ID, *v); err != nil { |
| + if err = l.acceptAccess(ctx, f.ID, *v); err != nil { |
| return 0, err |
| } |
| case *wire.RecheckCommand: |
diff --git a/internal/runner/thin/mcp.go b/internal/runner/thin/mcp.go| index d8875061..7ad7640c 100644 |
| --- a/internal/runner/thin/mcp.go |
| +++ b/internal/runner/thin/mcp.go |
| @@ -48,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 |
| @@ -205,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": |
| @@ -224,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...) |
| } |
| @@ -240,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 0b80b21e..220aa65a 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -203,6 +203,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| 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 = func() int { p, _ := link.Spoken(); return p } |
| 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) { |
| @@ -309,7 +310,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| return nil |
| } |
| if af, ok := fg.(AccessForge); ok { |
| - link.Access = &AccessEngine{State: state, Forge: af, Authorize: link.Confirm, Refresh: func() { index.Kick(); link.HelloSoon() }, Notify: link.Notify, Logger: o.Logger} |
| + 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 }() |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index fff790e3..304b6de2 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -62,6 +62,10 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| d.Close() |
| return nil, err |
| } |
| + if err = migrateAccess(ctx, d); err != nil { |
| + d.Close() |
| + return nil, err |
| + } |
| // Added in slice 2b: a run's kind (person, move_in or explore) and |
| // the person's own words (JSON list), apart from the frame's text. |
| // Added with attachments: the files a run carries (JSON list). |
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/wire/access.go b/internal/wire/access.go| index e0cce688..29118fb4 100644 |
| --- a/internal/wire/access.go |
| +++ b/internal/wire/access.go |
| @@ -46,15 +46,20 @@ var accessTarget = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}(/[A-Za-z |
| func ValidAccessTarget(s string) bool { return accessTarget.MatchString(s) } |
| func AccessFinal(state string) bool { |
| switch state { |
| - case "approved", "declined", "expired", "limited", "failed": |
| + case "approved", "declined", "expired", "limited", "failed", "unconfirmed", "missing", "uncheckable", "authority": |
| return true |
| } |
| return false |
| } |
| func AccessRole(s string) bool { return s == "agent" || s == "reader" || s == "runner" } |
| -func AccessURL(s string) bool { |
| + |
| +// 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 && strings.HasPrefix(u.Path, "/") |
| + 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 { |
diff --git a/internal/wire/access_test.go b/internal/wire/access_test.go| index 53f78a2c..55a2346b 100644 |
| --- a/internal/wire/access_test.go |
| +++ b/internal/wire/access_test.go |
| @@ -25,3 +25,16 @@ func TestAccessProtocol(t *testing.T) { |
| } |
| } |
| } |
| + |
| +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/frames.go b/internal/wire/frames.go| index 1ce49e62..527b9f1a 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -403,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. |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index 7ec619d9..3fd117de 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -600,6 +600,9 @@ func Encode(f Frame, protocol int) (Frame, error) { |
| 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 { |