Preserve access sessions across disconnects and reconcile expiry
19 files changed,
+427
−41
.rastrillo/budgets.txt+4 −4docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+2 −0internal/equipo/access_review_test.go+16 −0internal/equipo/chat/access_request.go+4 −1internal/equipo/chat/access_review_test.go+36 −0internal/equipo/chat_page.go+4 −0internal/equipo/copy.go+2 −0internal/plan3test/plan3_release_test.go+1 −1internal/runner/thin/access.go+27 −22internal/runner/thin/access_catalog.go+1 −1internal/runner/thin/access_forge.go+10 −0internal/runner/thin/access_protocol.go+12 −3internal/runner/thin/access_review_test.go+5 −3internal/runner/thin/access_round3_test.go+250 −0internal/runner/thin/bridge.go+2 −3internal/runner/thin/link.go+1 −1internal/runner/thin/run.go+1 −1internal/thintest/access_round3_browser_test.go+48 −0internal/wire/access.go+1 −1
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 87e5fc2d..2331581f 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 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/equipo 21076 - Shared web views and Roster access status copy. Measured 21076 source lines after final access-request fixes. |
| size internal/wire 6543 - Shared protocol types; protocol 26 adds durable confirmed access commands and state reports. Limits match measured lines. Access review guards and contract tests; limit matches measured lines. |
| size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| @@ -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 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. |
| +size internal/runner/thin 27080 19975 Shared runner state and forge integration. Measured 27080 source and 19975 test lines including disconnect, POST outcome and expiry guards. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 30664 - Transactional authority, dispatch and access confirmation; fresh per-card runner leases and demotion outcomes. Measured 30664 source lines. |
| +size internal/equipo/chat 30667 - Transactional authority and access confirmation; resume after provisional expiry. Measured 30667 source lines. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally). |
| size internal/headless - 11062 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11062 test lines. |
| -size internal/thintest - 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. |
| +size internal/thintest - 30981 Shared instance/browser fixtures, including final access outcomes at two widths and themes. Measured 30981 test lines. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
| perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage. |
| perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index d7b606d3..add25cb8 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -4706,6 +4706,8 @@ All eight entries have individual `COPY REVIEW REQUIRED` markers. The API guide |
| | Key | Text | Use | Status | |
| | --- | --- | --- | --- | |
| +| `access.not_owned` | Amadan can’t ask the owner of %s for access. | Access request final fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
| +| `access.already` | Equipo already has access. | Access request final fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
| | `access.unconfirmed` | I couldn’t confirm this access request with Amadan. Ask again to make a new request. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
| | `access.missing` | Amadan no longer has this access request. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
| | `access.uncheckable` | I can’t check this access request on Amadan. Ask again to make a new request. | Access request review fixes | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
diff --git a/internal/equipo/access_review_test.go b/internal/equipo/access_review_test.go| index 582c0f2a..864d06c2 100644 |
| --- a/internal/equipo/access_review_test.go |
| +++ b/internal/equipo/access_review_test.go |
| @@ -16,3 +16,19 @@ func TestAccessGrantedNoteAndBroadLabel(t *testing.T) { |
| t.Fatal("namespace label not broad", v.AccessTarget) |
| } |
| } |
| + |
| +func TestAccessPostFinalCopy(t *testing.T) { |
| + for _, state := range []string{"not_owned", "already"} { |
| + c := wire.Card{Kind: wire.CardAccess, State: wire.CardResolved, Access: &wire.AccessRequest{Target: "carlos/platform", State: state}} |
| + v := cardView(c, nil, nil) |
| + if strings.Contains(v.Line, "Ask again") || strings.HasPrefix(v.Line, "access.") { |
| + t.Fatal("outcome lacks final copy", v.Line) |
| + } |
| + if state == "not_owned" && !strings.Contains(v.Line, "owner of carlos") { |
| + t.Fatal("owner refusal lacks namespace", v.Line) |
| + } |
| + if state == "already" && v.Line != "Equipo already has access." { |
| + t.Fatal("existing access unclear", v.Line) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/chat/access_request.go b/internal/equipo/chat/access_request.go| index bebc6ab5..9a8ed76a 100644 |
| --- a/internal/equipo/chat/access_request.go |
| +++ b/internal/equipo/chat/access_request.go |
| @@ -164,7 +164,7 @@ func (t *txn) accessReport(l Lease, v *wire.AccessReport) error { |
| if a.State == "confirmation" { |
| return ErrForbidden |
| } |
| - if wire.AccessFinal(a.State) { |
| + if wire.AccessFinal(a.State) && !(a.State == "expired" && (v.State == "approved" || v.State == "pending")) { |
| return nil |
| } |
| if v.State != "pending" && !wire.AccessFinal(v.State) || len(v.RequestID) > 200 || v.ApproveURL != "" && !wire.AccessURL(v.ApproveURL, v.RequestID) { |
| @@ -176,6 +176,9 @@ func (t *txn) accessReport(l Lease, v *wire.AccessReport) error { |
| if a.RequestID != "" && a.RequestID != v.RequestID { |
| return ErrInvalid |
| } |
| + if a.State == "expired" && (v.State == "approved" || v.State == "pending") { |
| + c.State = wire.CardOpen |
| + } |
| a.State, a.RequestID = v.State, v.RequestID |
| if v.ApproveURL != "" { |
| a.ApproveURL = v.ApproveURL |
diff --git a/internal/equipo/chat/access_review_test.go b/internal/equipo/chat/access_review_test.go| index 206d2b64..ee4e96bc 100644 |
| --- a/internal/equipo/chat/access_review_test.go |
| +++ b/internal/equipo/chat/access_review_test.go |
| @@ -126,3 +126,39 @@ func TestAccessFindHintHonorsNegotiatedProtocol(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestAccessLateApprovalResumesAfterExpiry(t *testing.T) { |
| + r, turn := accessRig(t, "Fix carlos/platform") |
| + c := proposeAccess(t, r, turn, "carlos/platform") |
| + if _, _, err := r.s.Answer(context.Background(), hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.s.db.G.Model(&turnRecord{}).Where("id = ?", turn.ID).Update("state", wire.TurnReplied) |
| + lease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolAccess} |
| + for _, state := range []string{"expired", "pending", "approved", "approved"} { |
| + report := wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: state, ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"} |
| + if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.accessReport(lease, &report) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if state == "pending" { |
| + var saved cardRecord |
| + r.s.db.G.First(&saved, "id = ?", c.ID) |
| + var access wire.AccessRequest |
| + json.Unmarshal([]byte(saved.Access), &access) |
| + if access.State != "pending" || saved.State != wire.CardOpen { |
| + t.Fatal("server pending did not correct local expiry") |
| + } |
| + } |
| + } |
| + h := wire.Hello{Catalog: []wire.RepoInfo{{Repo: "amadan.net/carlos/platform"}}} |
| + for i := 0; i < 2; i++ { |
| + if err := r.s.tx(context.Background(), func(tx *txn) error { return tx.resolveAccess(hkOwner, h) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var n int64 |
| + r.s.db.G.Model(&messageRecord{}).Where("idempotency_key = ?", "access-approved:"+c.ID).Count(&n) |
| + if n != 1 { |
| + t.Fatal("late approval did not resume exactly once", n) |
| + } |
| +} |
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go| index 550f7982..ab38165b 100644 |
| --- a/internal/equipo/chat_page.go |
| +++ b/internal/equipo/chat_page.go |
| @@ -154,6 +154,10 @@ 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) |
| + if c.Access.State == "not_owned" { |
| + ns, _, _ := strings.Cut(c.Access.Target, "/") |
| + v.Line = fmt.Sprintf(v.Line, ns) |
| + } |
| v.AccessTarget = c.Access.Target |
| if !strings.Contains(c.Access.Target, "/") { |
| v.AccessTarget = fmt.Sprintf(copyText("access.namespace"), c.Access.Target) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 83278d20..e05b60e5 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -66,6 +66,8 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + "access.not_owned": "Amadan can’t ask the owner of %s for access.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
| + "access.already": "Equipo already has access.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
| "access.unconfirmed": "I couldn’t confirm this access request with Amadan. Ask again to make a new request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
| "access.missing": "Amadan no longer has this access request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
| "access.uncheckable": "I can’t check this access request on Amadan. Ask again to make a new request.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go| index 0616ea99..5f1e26c3 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.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)") |
| + acceptedAccess := slices.Contains([]string{"access.not_owned", "access.already", "access.unconfirmed", "access.missing", "access.uncheckable", "access.authority", "access.confirm_namespace", "access.namespace", "access.granted_note", "access.title", "access.confirm", "access.ask", "access.approve", "access.aside", "access.reason", "access.role", "access.confirmation", "access.filing", "access.pending", "access.approved", "access.declined", "access.expired", "access.limited", "access.failed", "access.operator", "access.continue"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)") |
| acceptedPlacementEdges := slices.Contains([]string{"placement.late_push", "placement.late_report"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)") |
| acceptedReportActions := slices.Contains([]string{"roster.talk", "roster.round_busy", "roster.round_done", "roster.merge_busy", "roster.merge_done"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)") |
| acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key]) |
diff --git a/internal/runner/thin/access.go b/internal/runner/thin/access.go| index d761b05e..bc384e92 100644 |
| --- a/internal/runner/thin/access.go |
| +++ b/internal/runner/thin/access.go |
| @@ -70,6 +70,7 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| } |
| var out wire.AccessReport |
| settled := false |
| + localExpiry := false |
| var err error |
| switch state { |
| case "queued": |
| @@ -94,6 +95,12 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| } |
| if err != nil { |
| out.State = "failed" |
| + if errors.Is(err, errAccessNotOwned) { |
| + out.State = "not_owned" |
| + } |
| + if errors.Is(err, errAccessAlready) { |
| + out.State = "already" |
| + } |
| if errors.Is(err, errAccessLimit) { |
| out.State = "limited" |
| } |
| @@ -104,27 +111,17 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| } |
| case "filing": |
| out.State = "unconfirmed" |
| - case "pending": |
| - 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 |
| - } |
| + case "pending", "checking_expiry": |
| + out, err = e.Forge.PollAccess(ctx, old.RequestID, cmd) |
| if err == nil && out.RequestID != old.RequestID { |
| err = errAccessContract |
| } |
| + // A server answer wins over the runner clock. An offline estimate is |
| + // provisional and keeps reconciling the saved id, never another POST. |
| + if err != nil && ctx.Err() == nil && (errors.Is(err, errAccess) || errors.Is(err, context.DeadlineExceeded)) && old.Expires > 0 && time.Now().After(time.Unix(old.Expires, 0).Add(10*time.Minute)) { |
| + out, err, localExpiry = old, nil, true |
| + out.State = "expired" |
| + } |
| if err != nil { |
| final := "" |
| switch { |
| @@ -162,8 +159,12 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| out.Expires = old.Expires |
| } |
| raw, _ := json.Marshal(out) |
| + savedState := out.State |
| + if localExpiry { |
| + savedState = "checking_expiry" |
| + } |
| if err := e.State.tx(ctx, func(tx *sql.Tx) error { |
| - if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", out.State, string(raw), id); err != nil { |
| + if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", savedState, string(raw), id); err != nil { |
| return err |
| } |
| if string(raw) == report || settled { |
| @@ -173,7 +174,7 @@ func (e *AccessEngine) Step(ctx context.Context, id string) error { |
| }); err != nil { |
| return err |
| } |
| - if out.State == "approved" { |
| + if out.State == "approved" || out.State == "already" { |
| e.Forge.Recheck() |
| e.Forge.Reachable(ctx) |
| if e.Refresh != nil { |
| @@ -215,13 +216,17 @@ func (e *AccessEngine) Run(ctx context.Context) { |
| polls-- |
| } |
| delay := time.Second |
| + var state string |
| + if e.State.db.QueryRowContext(ctx, "SELECT state FROM access_requests WHERE card_id=?", result.id).Scan(&state) == nil && state == "checking_expiry" { |
| + delay = time.Minute |
| + } |
| if result.err != nil { |
| delay = min(max(delays[result.id]*2, 2*time.Second), time.Minute) |
| } |
| delays[result.id] = delay |
| next[result.id] = time.Now().Add(delay) |
| case <-tick.C: |
| - rows, err := e.State.db.QueryContext(ctx, "SELECT card_id,state FROM access_requests WHERE state IN ('queued','filing','pending') ORDER BY CASE WHEN state='pending' THEN 1 ELSE 0 END, confirmed_at, rowid LIMIT 128") |
| + rows, err := e.State.db.QueryContext(ctx, "SELECT card_id,state FROM access_requests WHERE state IN ('queued','filing','pending','checking_expiry') ORDER BY CASE WHEN state IN ('pending','checking_expiry') THEN 1 ELSE 0 END, confirmed_at, rowid LIMIT 128") |
| if err != nil { |
| continue |
| } |
| @@ -234,7 +239,7 @@ func (e *AccessEngine) Run(ctx context.Context) { |
| } |
| rows.Close() |
| for _, j := range jobs { |
| - fresh := j.state != "pending" |
| + fresh := j.state == "queued" || j.state == "filing" |
| if active[j.id] || time.Now().Before(next[j.id]) || fresh && filing || !fresh && polls >= 5 { |
| continue |
| } |
diff --git a/internal/runner/thin/access_catalog.go b/internal/runner/thin/access_catalog.go| index 31b3fa57..1ce50236 100644 |
| --- a/internal/runner/thin/access_catalog.go |
| +++ b/internal/runner/thin/access_catalog.go |
| @@ -69,7 +69,7 @@ func (f *fileForge) readGrants(ctx context.Context) []string { |
| } |
| func (s *State) accessReadTargets(ctx context.Context) ([]string, error) { |
| - rows, err := s.db.QueryContext(ctx, "SELECT command FROM access_requests WHERE state='approved' AND json_extract(command, '$.role') <> 'agent' ORDER BY rowid DESC LIMIT ?", wire.MaxCatalog) |
| + rows, err := s.db.QueryContext(ctx, "SELECT command FROM access_requests WHERE state IN ('approved','already') AND json_extract(command, '$.role') <> 'agent' ORDER BY rowid DESC LIMIT ?", wire.MaxCatalog) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/runner/thin/access_forge.go b/internal/runner/thin/access_forge.go| index 9ccbff26..561bdba1 100644 |
| --- a/internal/runner/thin/access_forge.go |
| +++ b/internal/runner/thin/access_forge.go |
| @@ -20,6 +20,8 @@ var errAccessContract = errors.New("access response not confirmed") |
| var errAccessMissing = errors.New("access request missing") |
| var errAccessDenied = errors.New("access check denied") |
| var errAccessState = errors.New("access state unknown") |
| +var errAccessNotOwned = errors.New("access target not owned") |
| +var errAccessAlready = errors.New("access already granted") |
| var errAccessLimit = errors.New("access request limit reached") |
| var accessID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,200}$`) |
| @@ -70,6 +72,14 @@ func (f *fileForge) accessHTTP(ctx context.Context, method, path string, body [] |
| if res.StatusCode == http.StatusTooManyRequests { |
| return wire.AccessReport{}, errAccessLimit |
| } |
| + if method == http.MethodPost { |
| + if res.StatusCode == http.StatusNotFound { |
| + return wire.AccessReport{}, errAccessNotOwned |
| + } |
| + if res.StatusCode == http.StatusConflict { |
| + return wire.AccessReport{}, errAccessAlready |
| + } |
| + } |
| if method == http.MethodGet { |
| if res.StatusCode == 404 { |
| return wire.AccessReport{}, errAccessMissing |
diff --git a/internal/runner/thin/access_protocol.go b/internal/runner/thin/access_protocol.go| index 48673f97..4870fdd0 100644 |
| --- a/internal/runner/thin/access_protocol.go |
| +++ b/internal/runner/thin/access_protocol.go |
| @@ -13,19 +13,21 @@ const accessPrompt = "For a not-shared repository, request_access(target, role, |
| 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 { |
| + if call.Name != wire.ToolRequestAccess || protocol == 0 || protocol >= wire.ProtocolAccess { |
| return wire.ToolResult{}, false |
| } |
| return wire.ToolResult{CallID: call.CallID, IsError: true, Code: "access_unsupported", Text: accessOld}, true |
| } |
| func (c *coordBase) accessProtocol() int { |
| if c.o.Protocol != nil { |
| - return c.o.Protocol() |
| + if p := c.o.Protocol(); p != 0 { |
| + return p |
| + } |
| } |
| return wire.ProtocolCurrent |
| } |
| func accessToolSetAt(set toolSet, protocol int) toolSet { |
| - if protocol >= wire.ProtocolAccess { |
| + if protocol == 0 || protocol >= wire.ProtocolAccess { |
| return set |
| } |
| set.names = slices.DeleteFunc(slices.Clone(set.names), func(n string) bool { return n == wire.ToolRequestAccess }) |
| @@ -63,3 +65,10 @@ func (l *Link) ConfirmAccess(ctx context.Context, id string) error { |
| } |
| return l.lease(ctx, wire.LeaseCheck{AccessCard: id}) |
| } |
| + |
| +// LastProtocol retains the last welcome across disconnects; zero means unknown. |
| +func (l *Link) LastProtocol() int { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.proto |
| +} |
diff --git a/internal/runner/thin/access_review_test.go b/internal/runner/thin/access_review_test.go| index a32ce749..479c6b6d 100644 |
| --- a/internal/runner/thin/access_review_test.go |
| +++ b/internal/runner/thin/access_review_test.go |
| @@ -100,6 +100,8 @@ func TestAccessPermanentPollErrorsAndLocalExpiry(t *testing.T) { |
| w.WriteHeader(404) |
| case "401": |
| w.WriteHeader(401) |
| + case "expiry": |
| + w.WriteHeader(503) |
| default: |
| v := accessResponse("ar_one", "mystery") |
| writeAccessInfo(w, v) |
| @@ -115,7 +117,7 @@ func TestAccessPermanentPollErrorsAndLocalExpiry(t *testing.T) { |
| 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() |
| + old.Expires = time.Now().Add(-11 * time.Minute).Unix() |
| } |
| raw, _ := json.Marshal(old) |
| s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw)) |
| @@ -130,9 +132,9 @@ func TestAccessPermanentPollErrorsAndLocalExpiry(t *testing.T) { |
| want = "missing" |
| } |
| if mode == "expiry" { |
| - want = "expired" |
| + want = "checking_expiry" |
| } |
| - if state != want || calls.Load() > 3 || mode == "expiry" && calls.Load() != 0 { |
| + if state != want || mode != "expiry" && calls.Load() > 3 || mode == "expiry" && calls.Load() != 6 { |
| t.Fatal("poll did not finish", state, calls.Load()) |
| } |
| }) |
diff --git a/internal/runner/thin/access_round3_test.go b/internal/runner/thin/access_round3_test.go| new file mode 100644 |
| index 00000000..dc94b70a |
| --- /dev/null |
| +++ b/internal/runner/thin/access_round3_test.go |
| @@ -0,0 +1,250 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +func TestAccessUnknownProtocolQueuesDurably(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + l := &Link{State: s} |
| + b := &bridge{Link: l, State: s} |
| + call := wire.ToolCall{CallID: "offline", TurnID: "turn", Name: wire.ToolRequestAccess, Args: json.RawMessage(`{}`)} |
| + cancelctx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + result := make(chan wire.ToolResult, 1) |
| + go func() { result <- b.roundTrip(cancelctx, call) }() |
| + deadline := time.Now().Add(2 * time.Second) |
| + for { |
| + frames, _, err := s.Unacked(ctx, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(frames) == 1 { |
| + break |
| + } |
| + select { |
| + case got := <-result: |
| + t.Fatal("offline tool was not queued", got) |
| + default: |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("offline tool not durably queued") |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + cancel() |
| + if got := <-result; got.Code == "access_unsupported" { |
| + t.Fatal("disconnected request refused as old protocol") |
| + } |
| + c := coordBase{o: ClaudeOptions{Protocol: func() int { p, _ := l.Spoken(); return p }}, profile: profileFor(wire.LaneCoordinator)} |
| + if !slices.Contains(c.accessToolSet(true).names, wire.ToolRequestAccess) || !strings.Contains(c.accessOpening(nil), "request_access") || strings.Contains(c.sessionAccount(), "legacy") { |
| + t.Fatal("unknown protocol removes tools or changes session key") |
| + } |
| +} |
| + |
| +func TestAccessDisconnectKeepsNegotiatedSession(t *testing.T) { |
| + for _, proto := range []int{25, 26} { |
| + t.Run(fmt.Sprint(proto), func(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + l := &Link{proto: proto, conn: &websocket.Conn{}} |
| + c := coordBase{o: ClaudeOptions{Protocol: l.LastProtocol}, profile: profileFor(wire.LaneCoordinator)} |
| + key := c.sessionAccount() |
| + tools := slices.Clone(c.accessToolSet(true).names) |
| + capability := c.accessProtocol() >= wire.ProtocolAccess |
| + for _, provider := range []string{"claude", "codex"} { |
| + if err := s.saveSession(ctx, "person", wire.LaneCoordinator, provider, key, "resume-id", "turn"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + l.conn = nil |
| + if c.accessProtocol() >= wire.ProtocolAccess != capability { |
| + t.Fatal("disconnect rotates coordinator capability") |
| + } |
| + if c.sessionAccount() != key || !slices.Equal(tools, c.accessToolSet(true).names) { |
| + t.Fatal("disconnect changes session key or tools") |
| + } |
| + _, refused := accessRefused(wire.ToolCall{Name: wire.ToolRequestAccess}, (&bridge{Link: l}).spoken()) |
| + if refused != (proto < 26) { |
| + t.Fatal("disconnected link forgot negotiation") |
| + } |
| + for _, provider := range []string{"claude", "codex"} { |
| + if err := s.saveSession(ctx, "person", wire.LaneCoordinator, provider, c.sessionAccount(), "resume-id", "turn"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + l.conn = &websocket.Conn{} |
| + for _, provider := range []string{"claude", "codex"} { |
| + row, ok, err := s.session(ctx, "person", wire.LaneCoordinator, provider) |
| + if err != nil || !ok || row.Account != c.sessionAccount() || row.SessionID != "resume-id" { |
| + t.Fatal("reconnect loses provider resume", provider, row, err) |
| + } |
| + } |
| + if proto == 26 && strings.Contains(key, "legacy") { |
| + t.Fatal("protocol 26 legacy key") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAccessPostFinalOutcomes(t *testing.T) { |
| + for _, status := range []int{404, 409} { |
| + t.Run(fmt.Sprint(status), func(t *testing.T) { |
| + var posts, lists, refresh atomic.Int32 |
| + f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/api/v1/repos" { |
| + lists.Add(1) |
| + fmt.Fprint(w, `{"repos":[]}`) |
| + return |
| + } |
| + posts.Add(1) |
| + w.WriteHeader(status) |
| + }) |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + c := accessCommand() |
| + if err := s.AcceptAccess(ctx, "frame", c); err != nil { |
| + t.Fatal(err) |
| + } |
| + e := &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }} |
| + for i := 0; i < 3; i++ { |
| + if err := e.Step(ctx, c.CardID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var state string |
| + s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) |
| + want := "not_owned" |
| + if status == 409 { |
| + want = "already" |
| + } |
| + if state != want || !wire.AccessFinal(state) || posts.Load() != 1 { |
| + t.Fatal("POST outcome is not distinct and final", state, posts.Load()) |
| + } |
| + if status == 409 && (refresh.Load() != 1 || lists.Load() != 1) { |
| + t.Fatal("already-access did not refresh catalog", refresh.Load(), lists.Load()) |
| + } |
| + if status == 404 && refresh.Load() != 0 { |
| + t.Fatal("not-owned refreshed catalog") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAccessExpiryClockMarginAndReconciliation(t *testing.T) { |
| + for _, mode := range []string{"margin", "server_pending", "server_approved", "offline_then_approved", "server_expired"} { |
| + t.Run(mode, func(t *testing.T) { |
| + var gets, refresh atomic.Int32 |
| + var online atomic.Bool |
| + online.Store(mode != "margin" && mode != "offline_then_approved") |
| + f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/api/v1/repos" { |
| + fmt.Fprint(w, `{"repos":[]}`) |
| + return |
| + } |
| + gets.Add(1) |
| + if !online.Load() { |
| + w.WriteHeader(503) |
| + return |
| + } |
| + state := "approved" |
| + if mode == "server_pending" { |
| + state = "pending" |
| + } |
| + if mode == "server_expired" { |
| + state = "expired" |
| + } |
| + v := accessResponse("ar_one", state) |
| + v.Created = time.Now().Add(-72 * time.Hour).Unix() |
| + v.Expires = time.Now().Add(-20 * time.Minute).Unix() |
| + writeAccessInfo(w, v) |
| + }) |
| + ctx := context.Background() |
| + dir := t.TempDir() |
| + s, err := OpenState(ctx, dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer func() { s.Close() }() |
| + c := accessCommand() |
| + s.AcceptAccess(ctx, "frame", c) |
| + expires := time.Now().Add(-20 * time.Minute).Unix() |
| + if mode == "margin" { |
| + expires = time.Now().Add(-5 * time.Minute).Unix() |
| + } |
| + old := wire.AccessReport{CardID: c.CardID, Person: c.Person, RequestID: "ar_one", State: "pending", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one", Expires: expires} |
| + raw, _ := json.Marshal(old) |
| + s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw)) |
| + e := &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }} |
| + _ = e.Step(ctx, c.CardID) |
| + var report string |
| + s.db.QueryRow("SELECT report FROM access_requests").Scan(&report) |
| + var got wire.AccessReport |
| + json.Unmarshal([]byte(report), &got) |
| + want := "approved" |
| + switch mode { |
| + case "margin", "server_pending": |
| + want = "pending" |
| + case "offline_then_approved", "server_expired": |
| + want = "expired" |
| + } |
| + if got.State != want || gets.Load() != 1 { |
| + t.Fatal("clock overrode server or safety margin", got.State, want, gets.Load()) |
| + } |
| + if mode == "offline_then_approved" { |
| + s.Close() |
| + s, err = OpenState(ctx, dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + e.State = s |
| + online.Store(true) |
| + runctx, stop := context.WithCancel(ctx) |
| + done := make(chan struct{}) |
| + go func() { e.Run(runctx); close(done) }() |
| + deadline := time.Now().Add(3 * time.Second) |
| + for refresh.Load() == 0 && time.Now().Before(deadline) { |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + stop() |
| + <-done |
| + |
| + s.db.QueryRow("SELECT report FROM access_requests").Scan(&report) |
| + json.Unmarshal([]byte(report), &got) |
| + if got.State != "approved" || refresh.Load() != 1 { |
| + t.Fatal("local expiry lost later approval after restart", got, refresh.Load()) |
| + } |
| + } |
| + if mode == "server_expired" { |
| + _ = e.Step(ctx, c.CardID) |
| + if gets.Load() != 1 { |
| + t.Fatal("server expiry is not final") |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/thin/bridge.go b/internal/runner/thin/bridge.go| index b7b2e360..f089febd 100644 |
| --- a/internal/runner/thin/bridge.go |
| +++ b/internal/runner/thin/bridge.go |
| @@ -464,13 +464,12 @@ func (b *bridge) clone(ctx context.Context, repo string) string { |
| return "" |
| } |
| -// spoken is the link's protocol now, 0 when unknown. |
| +// spoken keeps the last negotiated protocol while disconnected, or 0 if unknown. |
| func (b *bridge) spoken() int { |
| if b.Link == nil { |
| return b.speaks |
| } |
| - p, _ := b.Link.Spoken() |
| - return p |
| + return b.Link.LastProtocol() |
| } |
| // exploreRefused answers record_task for an exploration on a connection |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index 07d646e3..399ef837 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -121,7 +121,7 @@ type Link struct { |
| tools map[string]chan wire.ToolResult |
| leaseSeq int64 |
| helloSoon bool |
| - // proto is what the current connection speaks; role what the instance |
| + // proto keeps the last negotiated version; role is what the instance |
| // said this runner is (primary at protocol 1). |
| proto int |
| role string |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 220aa65a..56431c3b 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -203,7 +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 } |
| + o.Claude.Protocol = link.LastProtocol |
| conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait} |
| conns.ClaudeUsage = o.Claude.Profile |
| conns.ClaudeStatus = func(ctx context.Context, b provider.Binding) (provider.Identity, string, error) { |
diff --git a/internal/thintest/access_round3_browser_test.go b/internal/thintest/access_round3_browser_test.go| new file mode 100644 |
| index 00000000..21ac3c7b |
| --- /dev/null |
| +++ b/internal/thintest/access_round3_browser_test.go |
| @@ -0,0 +1,48 @@ |
| +//go:build browser |
| + |
| +package thintest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "fmt" |
| + "testing" |
| +) |
| + |
| +func TestBrowserAccessFinalOutcomes(t *testing.T) { |
| + for _, width := range []int64{1280, 390} { |
| + for _, scheme := range []string{"light", "dark"} { |
| + for _, outcome := range []string{"not_owned", "already"} { |
| + t.Run(fmt.Sprintf("%d-%s-%s", width, scheme, outcome), func(t *testing.T) { |
| + r := newToolRigSaying(t, wire.ProtocolCurrent, "Fix carlos/platform") |
| + if got := r.call("access-proposal", wire.ToolRequestAccess, map[string]any{"target": "carlos/platform", "reason": "I need access to fix the build."}); got.Code != "asked" { |
| + t.Fatal(got) |
| + } |
| + r.runner.Send(r.ctx, "reply", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Please confirm."}) |
| + r.wait("reply", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied }) |
| + p := openInner(t, r.inst.URL, r.inst.Cookie(), width, 844, width == 390, scheme, "reduce") |
| + defer p.stop() |
| + p.open("/conversation") |
| + p.wait(`document.querySelector('[data-access-confirm]')`, "confirmation") |
| + p.click(`[data-access-confirm]`) |
| + _, body, err := r.runner.Expect(r.ctx, wire.FrameRequestAccess) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := body.(*wire.AccessCommand) |
| + if err := r.runner.Send(r.ctx, "final", wire.FrameAccess, wire.AccessReport{CardID: cmd.CardID, Person: cmd.Person, State: outcome}); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.wait(`document.querySelector('[data-access-state="`+outcome+`"]')`, outcome) |
| + want := "Equipo already has access." |
| + if outcome == "not_owned" { |
| + want = "Amadan can’t ask the owner of carlos for access." |
| + } |
| + p.check(`document.querySelector('[data-access-state] [role="status"]').textContent === `+fmt.Sprintf("%q", want), "clear final copy") |
| + p.check(`!document.querySelector('[data-access-confirm], [data-access-approve], [data-access-aside]')`, "no retry or approval action") |
| + p.fits(outcome) |
| + p.shot(fmt.Sprintf("access-final-%s-%d-%s", outcome, width, scheme)) |
| + }) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/wire/access.go b/internal/wire/access.go| index 29118fb4..2cf61bcc 100644 |
| --- a/internal/wire/access.go |
| +++ b/internal/wire/access.go |
| @@ -46,7 +46,7 @@ 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", "unconfirmed", "missing", "uncheckable", "authority": |
| + case "approved", "declined", "expired", "limited", "failed", "unconfirmed", "missing", "uncheckable", "authority", "not_owned", "already": |
| return true |
| } |
| return false |