package thintest import ( "context" "crypto/rand" "encoding/json" "net/http" "regexp" "slices" "strings" "sync" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/assist" "amadan.net/oficina/equipo/internal/wire" ) // keyedProvider is an in-process provider with one write that takes a // client idempotency key: Base's contract cannot offer one yet (its // operations have no key field), so the ledger's write path is shown // through this. type keyedProvider struct { mu sync.Mutex keys []string inputs []string hold chan struct{} fail bool } func (p *keyedProvider) Name() string { return "svc:ledger" } // failNext makes the next call fail after it is counted. func (p *keyedProvider) failNext() { p.mu.Lock() p.fail = true p.mu.Unlock() } func (p *keyedProvider) List(context.Context, string) ([]assist.Operation, error) { return []assist.Operation{{Name: "ledger_write", Description: "Write one line to the test ledger.", App: "Ledger", Idempotent: true, KeyField: "client_id", Input: json.RawMessage(`{"type":"object","properties":{"line":{"type":"string"}}}`)}}, nil } func (p *keyedProvider) Invoke(ctx context.Context, _, _ string, input json.RawMessage, key string) (json.RawMessage, error) { p.mu.Lock() p.keys, p.inputs = append(p.keys, key), append(p.inputs, string(input)) hold, fail := p.hold, p.fail p.fail = false p.mu.Unlock() if fail { return nil, assist.Failure{Code: "unavailable", Message: "The ledger timed out."} } if hold != nil { select { case <-hold: case <-ctx.Done(): return nil, ctx.Err() } } return json.RawMessage(`{"written":true}`), nil } func (p *keyedProvider) calls() ([]string, []string) { p.mu.Lock() defer p.mu.Unlock() return slices.Clone(p.keys), slices.Clone(p.inputs) } // holdNext keeps every call waiting until release. func (p *keyedProvider) holdNext() (release func()) { c := make(chan struct{}) p.mu.Lock() p.hold = c p.mu.Unlock() var once sync.Once return func() { once.Do(func() { p.mu.Lock() p.hold = nil p.mu.Unlock() close(c) }) } } // opsRig is an Assistant rig whose instance allows a fake Base as its // host, with the person's primary at the Assistant's protocol (or the // rig's, newOpsRigAt). type opsRig struct { *toolRig base *FakeBase a *AssistantClient protocol int // boardRev counts the boards setBoard has given (build_off tests). boardRev int64 // lookupAnswer, when set, is the person's model answering a lookup // step that arrives while a call waits (lookup_e2e_test.go). lookupAnswer func(wire.LookupStep) wire.LookupResult } func newOpsRig(t *testing.T, providers ...assist.Provider) *opsRig { return newOpsRigAt(t, wire.ProtocolAssistant, providers...) } // newOpsRigAt is newOpsRig whose runners speak protocol. func newOpsRigAt(t *testing.T, protocol int, providers ...assist.Provider) *opsRig { base := StartFakeBase(t) r := newRigWith(t, func(i *Instance) { i.AssistantHosts = []string{base.Origin} i.Providers = providers }) runner := r.dialAt(protocol) return &opsRig{toolRig: &toolRig{rig: r, runner: runner}, base: base, a: r.client.Assistant(), protocol: protocol} } // other is a second owner on the same instance, with their own primary. func (o *opsRig) other(address string) *opsRig { o.t.Helper() if err := o.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleOwner, true, 0); err != nil { o.t.Fatal(err) } client := NewClient(o.inst.URL, o.inst.DeviceTokenFor(o.t, address)) cred := o.inst.EnrolRunnerFor(o.t, address) runner, err := DialRunnerHello(o.ctx, o.inst.URL, cred.Token, primaryAt(wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, o.protocol)) if err != nil { o.t.Fatal(err) } o.t.Cleanup(runner.Close) return &opsRig{toolRig: &toolRig{rig: o.rig, runner: runner}, base: o.base, a: client.Assistant(), protocol: o.protocol} } // connect registers the fake Base as the person's host with token. func (o *opsRig) connect(token string) wire.AssistantHost { o.t.Helper() out, err := o.a.PutHost(o.ctx, o.base.Origin, token) if err != nil { o.t.Fatal(err) } return out } // begin sends an Assistant message and makes its turn the rig's. func (o *opsRig) begin(text string) string { o.t.Helper() sent, err := o.a.Send(o.ctx, text, "a-"+rand.Text()) if err != nil { o.t.Fatal(err) } f, _, err := o.runner.Expect(o.ctx, wire.FrameMessage) if err != nil { o.t.Fatal(err) } if err := o.runner.Send(o.ctx, "ack-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { o.t.Fatal(err) } o.turn, o.attempt = sent.Turn.ID, 0 return sent.Turn.ID } // send sends one tool_call in the rig's turn and returns its call id. func (o *opsRig) send(id, name string, args any) string { o.t.Helper() raw, _ := json.Marshal(args) o.seq++ attempt := max(o.attempt, 1) call := o.turn + "/" + itoa(int(attempt)) + "/" + id if err := o.runner.Send(o.ctx, "r-tc-"+id+"-"+itoa(o.seq), wire.FrameToolCall, wire.ToolCall{CallID: call, TurnID: o.turn, Attempt: attempt, Name: name, Args: raw}); err != nil { o.t.Fatal(err) } return call } // await reads frames until each call has its one tool_result, acking // each; a second result for one of them, or one for another call, fails. func (o *opsRig) await(calls ...string) map[string]wire.ToolResult { o.t.Helper() got := map[string]wire.ToolResult{} for len(got) < len(calls) { f, body, err := o.runner.Next(o.ctx) if err != nil { o.t.Fatalf("waiting for %v: %v", calls, err) } if step, ok := body.(*wire.LookupStep); ok && o.lookupAnswer != nil { r := o.lookupAnswer(*step) r.Lookup, r.Attempt, r.Nonce, r.Stage = step.Lookup, step.Attempt, step.Nonce, step.Stage if err := o.runner.Send(o.ctx, "lr-"+f.ID, wire.FrameLookupResult, r); err != nil { o.t.Fatal(err) } continue } res, ok := body.(*wire.ToolResult) if !ok { if f.Type != wire.FrameAck { o.held = append(o.held, heldFrame{f, body, o.runner.Received[len(o.runner.Received)-1]}) } continue } if err := o.runner.Send(o.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { o.t.Fatal(err) } if _, twice := got[res.CallID]; twice || !slices.Contains(calls, res.CallID) { o.t.Fatalf("an extra result for %s (waiting for %v): %+v", res.CallID, calls, res) } if res.Person != o.person() { o.t.Fatalf("a result for %s: %+v", res.Person, res) } got[res.CallID] = *res } return got } func (o *opsRig) person() string { me, err := o.a.Snapshot(o.ctx) if err != nil { o.t.Fatal(err) } return me.Me.Address } // tool sends one call and waits for its result. func (o *opsRig) tool(id, name string, args any) wire.ToolResult { o.t.Helper() call := o.send(id, name, args) return o.await(call)[call] } func (o *opsRig) use(id, operation string, input any) wire.ToolResult { o.t.Helper() return o.tool(id, wire.ToolUse, map[string]any{"operation": operation, "input": input}) } // results is how many tool_result commands the instance queued for call. func (o *opsRig) results(call string) int { o.t.Helper() return o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameToolResult, `%"call_id":"`+call+`"%`) } func (o *opsRig) state(call string) string { o.t.Helper() var s string if err := o.inst.DB.Writer().QueryRow("SELECT coalesce(max(state), 'none') FROM chat_tool_calls WHERE call_id = ?", call).Scan(&s); err != nil { o.t.Fatal(err) } return s } // TestContractHostAllowlist: PUT /api/v1/assistant/host takes an origin // on the operator's allowlist and a printable token, never echoes the // token and stores it sealed. A second PUT replaces the first. func TestContractHostAllowlist(t *testing.T) { base := StartFakeBase(t) r := newRigWith(t, func(i *Instance) { i.AssistantHosts = []string{"https://base.example.com", base.Origin} }) url := r.inst.URL + "/api/v1/assistant/host" rows := (&toolRig{rig: r}).rows put := func(origin, token string) (int, wire.Error, []byte) { t.Helper() body, _ := json.Marshal(map[string]string{"origin": origin, "token": token}) status, _, raw := raw(t, http.MethodPut, url, r.client.Token, nil, string(body)) var e wire.Error _ = json.Unmarshal(raw, &e) return status, e, raw } token := "tok-" + strings.Repeat("a", 30) // An allowed origin (case aside) that doesn't honour the token, here // one that doesn't answer at all, doesn't count (abilities §5.3). status, e, body := put("https://Base.Example.com", token) if status != 409 || e.Code != wire.CodeHostUnverified || strings.Contains(string(body), token) { t.Fatalf("first put %d %s", status, body) } var out wire.AssistantHost second := "second-" + strings.Repeat("b", 30) base.Accept(second) if status, _, body = put(base.Origin, second); status != 200 || json.Unmarshal(body, &out) != nil || out.Origin != base.Origin || out.Revision != 1 || strings.Contains(string(body), second) || strings.Contains(string(body), `"token"`) { t.Fatalf("second put %d %s", status, body) } if n := rows("SELECT count(*) FROM chat_assistant_hosts"); n != 1 { t.Fatalf("%d host rows", n) } var stored, origin string if err := r.inst.DB.Writer().QueryRow("SELECT token, origin FROM chat_assistant_hosts").Scan(&stored, &origin); err != nil { t.Fatal(err) } if stored == "" || strings.Contains(stored, second) || strings.Contains(stored, token) || origin != base.Origin { t.Fatalf("stored token %q origin %q", stored, origin) } // The instance reads it back as it was given. if o, tok, ok, err := r.inst.Store.Chat().Host(r.ctx, Owner); err != nil || !ok || o != base.Origin || tok != second { t.Fatalf("host %q %v %v", o, ok, err) } for _, c := range []struct{ origin, token string }{ {"http://base.example.com", token}, {"https://base.example.com/api", token}, {"https://base.example.com/", token}, {"https://base.example.com?x=1", token}, {"https://base.example.com#x", token}, {"https://user@base.example.com", token}, {"https://base.example.com:99999", token}, {"ftp://base.example.com", token}, {"base.example.com", token}, {"", token}, {"https://base.example.com", strings.Repeat("a", 19)}, {"https://base.example.com", strings.Repeat("a", 513)}, {"https://base.example.com", strings.Repeat("a", 20) + "\x01"}, {"https://base.example.com", strings.Repeat("a", 20) + " b"}, {"https://base.example.com", strings.Repeat("a", 20) + "é"}, } { if status, e, body := put(c.origin, c.token); status != 422 || e.Code != "invalid_input" { t.Fatalf("%q %q: %d %s", c.origin, c.token, status, body) } } base.Accept(strings.Repeat("a", 20)) base.Accept(strings.Repeat("a", 512)) if status, _, _ := put(base.Origin, strings.Repeat("a", 20)); status != 200 { t.Fatalf("a 20-character token %d", status) } if status, _, _ := put(base.Origin, strings.Repeat("a", 512)); status != 200 { t.Fatalf("a 512-character token %d", status) } if status, e, body := put("https://other.example.com", token); status != 403 || e.Code != "host_not_allowed" || e.CopyKey != "api.host_not_allowed" { t.Fatalf("not on the allowlist %d %s", status, body) } if status, _, _ := raw(t, http.MethodPut, url, "", nil, `{"origin":"https://base.example.com","token":"`+token+`"}`); status != 401 { t.Fatalf("no bearer %d", status) } if status, _, _ := raw(t, http.MethodPut, url, "", r.inst.Cookie(), `{"origin":"https://base.example.com","token":"`+token+`"}`); status != 401 { t.Fatalf("a session cookie %d", status) } // Neither the log nor the audit ever sees a token. if logs := r.inst.Logs(); strings.Contains(logs, token) || strings.Contains(logs, second) { t.Fatal("a host token in the log") } if n := rows("SELECT count(*) FROM audit_events WHERE record_id LIKE ? OR record_id LIKE ?", "%"+token[:12]+"%", "%"+second[:12]+"%"); n != 0 { t.Fatalf("%d audits carry a token", n) } if n := rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.host' AND actor = ?", Owner); n != 3 { t.Fatalf("%d host audits", n) } // With EQUIPO_ASSISTANT_HOSTS unset, every origin is refused. closed := newRig(t) for _, origin := range []string{"https://base.example.com", base.Origin} { body, _ := json.Marshal(map[string]string{"origin": origin, "token": token}) status, _, raw := raw(t, http.MethodPut, closed.inst.URL+"/api/v1/assistant/host", closed.client.Token, nil, string(body)) if status != 403 || !strings.Contains(string(raw), `"host_not_allowed"`) { t.Fatalf("unset allowlist %s: %d %s", origin, status, raw) } } } // TestContractLook: look, describe and use reach the person's Base // outside the tool call's transaction: the call gets no result at once, // and its result arrives when Base answers. func TestContractLook(t *testing.T) { o := newOpsRig(t) o.connect(o.base.Token) o.begin("What can I do?") release := o.base.Hold("") call := o.send("l1", wire.ToolLook, map[string]any{}) o.until("Base listed", func() bool { return o.base.Calls("") == 1 }) if n := o.results(call); n != 0 || o.state(call) != "pending" { t.Fatalf("a result before Base answered: %d %s", n, o.state(call)) } release() res := o.await(call)[call] if res.IsError || !strings.HasPrefix(res.Text, "Base (base)\n") || !strings.Contains(res.Text, "\n- base_apps: List the person's apps") || !strings.Contains(res.Text, "\n- base_people: ") || !strings.Contains(res.Text, "\n- base_settings: ") { t.Fatalf("look %+v", res) } if o.state(call) != "done" || !slices.Equal(o.base.Tokens(""), []string{o.base.Token}) { t.Fatalf("state %s tokens %v", o.state(call), o.base.Tokens("")) } if res = o.tool("l2", wire.ToolLook, map[string]any{"query": "people"}); res.IsError || !strings.Contains(res.Text, "base_people") || strings.Contains(res.Text, "base_apps") { t.Fatalf("look for people %+v", res) } res = o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "base_apps"}) var op struct { Name string `json:"name"` ReadOnly bool `json:"read_only"` Destructive bool `json:"destructive"` Idempotent bool `json:"idempotent"` External bool `json:"external"` Input json.RawMessage `json:"input_schema"` } if res.IsError || json.Unmarshal([]byte(res.Text), &op) != nil || op.Name != "base_apps" || !op.ReadOnly || op.Destructive || !op.Idempotent || op.External || !strings.Contains(string(op.Input), `"type":"object"`) { t.Fatalf("describe %+v", res) } if res = o.tool("d2", wire.ToolDescribe, map[string]any{"operation": "base_nothing"}); !res.IsError || res.Code != "unknown_operation" { t.Fatalf("describe unknown %+v", res) } if res = o.tool("d3", wire.ToolDescribe, map[string]any{}); !res.IsError || res.Code != "invalid" { t.Fatalf("describe nothing %+v", res) } res = o.use("u1", "base_apps", map[string]any{}) if res.IsError || res.Text != `{"installed":[{"id":"shop","name":"Shop","address":"https://shop.example.com"}],"store":[],"oficina":[]}` || res.Replayed { t.Fatalf("use %+v", res) } if o.base.Calls("base_apps") != 1 || !slices.Equal(o.base.Inputs("base_apps"), []string{"{}"}) || !slices.Equal(o.base.Keys("base_apps"), []string{""}) { t.Fatalf("Base saw %d calls %v keys %v", o.base.Calls("base_apps"), o.base.Inputs("base_apps"), o.base.Keys("base_apps")) } // A failure Base reports comes back with its code. o.base.Fail("base_people", "rate_limited") if res = o.use("u2", "base_people", map[string]any{}); !res.IsError || res.Code != "rate_limited" { t.Fatalf("Base failing %+v", res) } if res = o.tool("u3", wire.ToolUse, map[string]any{"operation": "base_apps"}); !res.IsError || res.Code != "invalid" { t.Fatalf("use with no input %+v", res) } } // TestContractHostIsPerPerson: each person's calls carry the token they // registered, and only theirs; with none registered nothing is sent. func TestContractHostIsPerPerson(t *testing.T) { o := newOpsRig(t) other := o.other("second@example.com") other.begin("What are my apps?") if res := other.use("u1", "base_apps", map[string]any{}); !res.IsError || res.Code != "not_connected" { t.Fatalf("nobody connected %+v", res) } if o.base.Calls("") != 0 || o.base.Calls("base_apps") != 0 { t.Fatalf("Base saw %d lists and %d calls with no host", o.base.Calls(""), o.base.Calls("base_apps")) } o.connect(o.base.Token) if res := other.use("u2", "base_apps", map[string]any{"again": true}); !res.IsError || res.Code != "not_connected" { t.Fatalf("someone else connected %+v", res) } if o.base.Calls("") != 0 { t.Fatalf("another person's host was used: %v", o.base.Tokens("")) } second := o.base.Mint() other.connect(second) o.begin("What are my apps?") if res := o.use("u1", "base_apps", map[string]any{}); res.IsError { t.Fatalf("first person %+v", res) } if res := other.use("u3", "base_apps", map[string]any{}); res.IsError { t.Fatalf("second person %+v", res) } if got := o.base.Tokens("base_apps"); !slices.Equal(got, []string{o.base.Token, second}) { t.Fatalf("tokens %v", got) } if got := o.base.Tokens(""); !slices.Equal(got, []string{o.base.Token, second}) { t.Fatalf("list tokens %v", got) } } var uuidV5 = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) // TestContractAssistantRetryRunsOnce: a keyed write runs once per turn, // operation and input, whatever the call id or attempt; the key the // provider gets is derived, never the call or turn id. func TestContractAssistantRetryRunsOnce(t *testing.T) { keyed := &keyedProvider{} o := newOpsRig(t, keyed) o.connect(o.base.Token) turn := o.begin("Write milk down.") milk := map[string]any{"line": "milk"} first := o.use("w1", "ledger_write", milk) again := o.use("w2", "ledger_write", milk) o.runner.Send(o.ctx, "r-wait", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"}) o.runner.Send(o.ctx, "r-run2", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 2, State: wire.TurnRunning}) o.until("attempt 2", func() bool { return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND attempt = 2 AND state = ?", turn, wire.TurnRunning) == 1 }) o.attempt = 2 moved := o.use("w3", "ledger_write", milk) keys, inputs := keyed.calls() if first.IsError || first.Replayed || first.Text != `{"written":true}` || len(keys) != 1 { t.Fatalf("first %+v, %d calls", first, len(keys)) } for _, res := range []wire.ToolResult{again, moved} { if !res.Replayed || res.Text != first.Text || res.Code != first.Code || res.IsError != first.IsError { t.Fatalf("replay %+v, first %+v", res, first) } } if !uuidV5.MatchString(keys[0]) || strings.Contains(keys[0], turn) || strings.Contains(keys[0], "w1") || !strings.Contains(inputs[0], `"client_id":"`+keys[0]+`"`) { t.Fatalf("key %q input %s", keys[0], inputs[0]) } for _, call := range []string{turn + "/1/w1", turn + "/1/w2", turn + "/2/w3"} { if strings.Contains(inputs[0], call) || strings.Contains(keys[0], call) { t.Fatalf("a call id reached the provider: %s", call) } } // Other input is another write, with another key. if res := o.use("w4", "ledger_write", map[string]any{"line": "eggs"}); res.IsError || res.Replayed { t.Fatalf("eggs %+v", res) } if keys, _ = keyed.calls(); len(keys) != 2 || keys[1] == keys[0] || !uuidV5.MatchString(keys[1]) { t.Fatalf("keys %v", keys) } // A retry while the first is still out waits for it: one call, two // results. release := keyed.holdNext() bread := map[string]any{"operation": "ledger_write", "input": map[string]any{"line": "bread"}} w5 := o.send("w5", wire.ToolUse, bread) o.until("the write out", func() bool { k, _ := keyed.calls(); return len(k) == 3 }) w6 := o.send("w6", wire.ToolUse, bread) o.until("the retry waiting", func() bool { return o.state(w6) == "waiting" }) release() got := o.await(w5, w6) if got[w5].Replayed || !got[w6].Replayed || got[w5].Text != got[w6].Text || got[w5].IsError { t.Fatalf("held write %+v, retry %+v", got[w5], got[w6]) } if keys, _ = keyed.calls(); len(keys) != 3 { t.Fatalf("%d calls", len(keys)) } // A write that failed (it may have landed: a timeout) is not in the // ledger, so a retry runs again, and with the same key, for the // provider to make it once. keyed.failNext() jam := map[string]any{"line": "jam"} if res := o.use("w7", "ledger_write", jam); !res.IsError || res.Code != "unavailable" { t.Fatalf("failed write %+v", res) } if res := o.use("w8", "ledger_write", jam); res.IsError || res.Replayed { t.Fatalf("retried write %+v", res) } if keys, _ = keyed.calls(); len(keys) != 5 || keys[3] != keys[4] { t.Fatalf("keys after a failure %v", keys) } } // TestContractUseRefusals: what deletes, reaches outside, or writes with // no client key waits, and Base is sent nothing. func TestContractUseRefusals(t *testing.T) { o := newOpsRig(t) o.base.Add( assist.Operation{Name: "base_remove_app", Description: "Remove an app.", Destructive: true, App: "Base"}, assist.Operation{Name: "base_invite", Description: "Email someone an invitation.", External: true, App: "Base"}, assist.Operation{Name: "base_rename_app", Description: "Rename an app.", App: "Base"}, ) o.connect(o.base.Token) o.begin("Tidy my apps.") for _, c := range []struct{ op, code string }{{"base_remove_app", "not_yet"}, {"base_invite", "not_yet"}, {"base_rename_app", "write_not_supported"}, {"base_remove_app", "not_yet"}} { res := o.use(c.op, c.op, map[string]any{"app": "Shop"}) if !res.IsError || res.Code != c.code || res.Replayed || res.Text == "" { t.Fatalf("%s %+v", c.op, res) } if n := o.base.Calls(c.op); n != 0 { t.Fatalf("%s reached Base %d times", c.op, n) } } } // TestContractRemoteCallSurvivesRestart: a call out when the instance // restarts is made again by the next process, and its result is // delivered once. func TestContractRemoteCallSurvivesRestart(t *testing.T) { o := newOpsRig(t) o.connect(o.base.Token) turn := o.begin("What are my apps?") release := o.base.Hold("base_apps") defer release() call := o.send("u1", wire.ToolUse, map[string]any{"operation": "base_apps", "input": map[string]any{}}) o.until("the call out", func() bool { return o.base.Calls("base_apps") == 1 }) o.inst.Restart(t) runner, err := DialRunnerHello(o.ctx, o.inst.URL, o.rig.runner, primaryAt(wire.Hello{Generation: o.runner.Welcome.Generation, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, wire.ProtocolAssistant)) if err != nil { t.Fatal(err) } t.Cleanup(runner.Close) o.runner = runner runner.Send(o.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: turn, Attempt: 1, State: wire.TurnRunning}}}) o.until("the call made again", func() bool { return o.base.Calls("base_apps") == 2 }) if o.state(call) != "pending" || o.results(call) != 0 { t.Fatalf("before Base answered: %s, %d results", o.state(call), o.results(call)) } release() if res := o.await(call)[call]; res.IsError || !strings.Contains(res.Text, "Shop") { t.Fatalf("after restart %+v", res) } // A later call's result is the next thing: nothing more for the first. fence := o.send("n1", wire.ToolReadNotes, map[string]any{}) o.await(fence) if n := o.results(call); n != 1 || o.state(call) != "done" { t.Fatalf("%d results, %s", n, o.state(call)) } } // TestContractUseAudited: every use is audited, by operation and outcome // only: never its input or output. A read asked again runs again (R11); // a write asked again is replayed. func TestContractUseAudited(t *testing.T) { o := newOpsRig(t, &keyedProvider{}) o.base.Add(assist.Operation{Name: "base_remove_app", Description: "Remove an app.", Destructive: true, App: "Base"}) o.connect(o.base.Token) o.begin("Look after my apps.") o.use("u1", "base_apps", map[string]any{"marker": "zebra-417"}) o.use("u2", "base_apps", map[string]any{"marker": "zebra-417"}) o.use("w1", "ledger_write", map[string]any{"line": "zebra-417"}) o.use("w2", "ledger_write", map[string]any{"line": "zebra-417"}) o.use("u3", "base_remove_app", map[string]any{"marker": "zebra-417"}) o.base.Fail("base_people", "rate_limited") o.use("u4", "base_people", map[string]any{"marker": "zebra-417"}) o.tool("l1", wire.ToolLook, map[string]any{"query": "apps"}) o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "base_apps"}) rows, err := o.inst.DB.Writer().Query("SELECT actor, record_id FROM audit_events WHERE kind = 'assistant.use' ORDER BY id") if err != nil { t.Fatal(err) } defer rows.Close() var got []string for rows.Next() { var actor, record string if err := rows.Scan(&actor, &record); err != nil { t.Fatal(err) } if actor != Owner { t.Fatalf("actor %q", actor) } got = append(got, record) } if want := []string{"base_apps ok", "base_apps ok", "ledger_write ok", "ledger_write replayed", "base_remove_app not_yet", "base_people rate_limited"}; !slices.Equal(got, want) { t.Fatalf("audits %q, want %q", got, want) } if n := o.rows("SELECT count(*) FROM audit_events WHERE record_id LIKE '%zebra%' OR record_id LIKE '%Shop%' OR record_id LIKE '%apps\":%'"); n != 0 { t.Fatalf("%d audits carry a payload", n) } } // TestContractRemoteCallEndsWithTurn: a turn that ends while its call is // out gets no result; the call is recorded done. func TestContractRemoteCallEndsWithTurn(t *testing.T) { o := newOpsRig(t) o.connect(o.base.Token) turn := o.begin("What are my apps?") release := o.base.Hold("base_apps") defer release() call := o.send("u1", wire.ToolUse, map[string]any{"operation": "base_apps", "input": map[string]any{}}) o.until("the call out", func() bool { return o.base.Calls("base_apps") == 1 }) if _, err := o.a.Cancel(o.ctx, turn); err != nil { t.Fatal(err) } if _, _, err := o.runner.Expect(o.ctx, wire.FrameCancel); err != nil { t.Fatal(err) } o.runner.Send(o.ctx, "r-cancelled", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) o.until("cancelled", func() bool { return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND state = ?", turn, wire.TurnCancelled) == 1 }) release() o.until("the call done", func() bool { return o.state(call) == "done" }) if n := o.results(call); n != 0 { t.Fatalf("%d results for an ended turn", n) } } // TestContractAssistantResultsFitTheFrame: every look, describe and use // result fits the 64 KB tool frame. A long list is cut short with a note; // a schema or output too large to send is refused. func TestContractAssistantResultsFitTheFrame(t *testing.T) { const frame = 64 << 10 o := newOpsRig(t) var many []assist.Operation for i := range 200 { many = append(many, assist.Operation{Name: "base_" + itoa(i) + "_" + strings.Repeat("n", 250), Description: strings.Repeat("d", 200), ReadOnly: true, App: "Many"}) } o.base.Add(many...) o.base.Add(assist.Operation{Name: "base_schema", Description: "A large schema.", ReadOnly: true, App: "Base", Input: json.RawMessage(`{"type":"object","description":"` + strings.Repeat("s", 66<<10) + `"}`)}) o.base.Add(assist.Operation{Name: "base_quotes", Description: "A quoted answer.", ReadOnly: true, App: "Base"}) // Under the registry's 48 KB, but twice that once escaped in a frame. o.base.Answer("base_quotes", `{"s":"`+strings.Repeat(`\"`, 23<<10)+`"}`) o.connect(o.base.Token) o.begin("Show me everything.") size := func(res wire.ToolResult) int { raw, _ := json.Marshal(res); return len(raw) } look := o.tool("l1", wire.ToolLook, map[string]any{}) if look.IsError || size(look) > frame || !strings.HasPrefix(look.Text, "Base (base)\n- base_apps") || !strings.HasSuffix(look.Text, "use look with a query to narrow it.") { t.Fatalf("look of %d bytes: %.200q ... %q", size(look), look.Text, look.Text[max(0, len(look.Text)-120):]) } if res := o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "base_schema"}); !res.IsError || res.Code != "too_large" || size(res) > frame { t.Fatalf("describe a large schema %+v", res.Code) } if res := o.use("u1", "base_quotes", map[string]any{}); !res.IsError || res.Code != "too_large" || size(res) > frame { t.Fatalf("use with a large answer %d %+v", size(res), res.Code) } if res := o.use("u2", "base_apps", map[string]any{}); res.IsError { t.Fatalf("a small answer %+v", res) } } // TestContractUseReadRunsAgain (Ruling R11): a read asked again in the // turn, while the first is out or after, runs again; it is never // another call's result, replayed. func TestContractUseReadRunsAgain(t *testing.T) { o := newOpsRig(t) o.connect(o.base.Token) o.begin("What are my apps?") apps := map[string]any{"operation": "base_apps", "input": map[string]any{}} release := o.base.Hold("base_apps") first := o.send("r1", wire.ToolUse, apps) o.until("the read out", func() bool { return o.base.Calls("base_apps") == 1 }) second := o.send("r2", wire.ToolUse, apps) o.until("the second waiting", func() bool { return o.state(second) == "waiting" }) release() got := o.await(first, second) if got[first].IsError || got[second].IsError || got[first].Replayed || got[second].Replayed { t.Fatalf("reads %+v", got) } if n := o.base.Calls("base_apps"); n != 2 { t.Fatalf("%d calls to Base for two reads", n) } if third := o.use("r3", "base_apps", map[string]any{}); third.IsError || third.Replayed || o.base.Calls("base_apps") != 3 { t.Fatalf("third %+v, %d calls", third, o.base.Calls("base_apps")) } }