mirror of
https://github.com/coder/coder.git
synced 2026-09-22 13:10:21 +08:00
Replaces the v2.10 `PushContextState` stub with a real coderd write path. Phase 1 of the chat-side persistence story; nothing reads these rows yet. Follows [#25983](https://github.com/coder/coder/pull/25983) and unblocks [CODAGT-569](https://linear.app/codercom/issue/CODAGT-569/enable-agent-api-v210-pushcontextstate-bump-currentminor-wire-coderd). ## What ships ### Schema (`000517_workspace_agent_context.{up,down}.sql`) Two new tables plus `api_key_scope` enum extensions: - `workspace_agent_context_snapshots` (PK `workspace_agent_id` to `workspace_agents(id) ON DELETE CASCADE`): one row per agent, overwritten per push. Holds `version`, `schema_version`, `aggregate_hash`, `snapshot_error`, `received_at`. - `workspace_agent_context_resources` (PK `(workspace_agent_id, source)`): per-resource state. `body_kind` and `status` are `TEXT` + `CHECK` so adding new wire kinds (the RFC's reserved PLUGIN/HOOK/SUBAGENT/COMMAND) is a one-line CHECK update plus a Go switch case. ### SQLC queries (`coderd/database/queries/workspaceagentcontext.sql`) - `UpsertWorkspaceAgentContextSnapshot` - `UpsertWorkspaceAgentContextResource` - `DeleteStaleWorkspaceAgentContextResources` (delete-where-source-not-in) - `GetLatestWorkspaceAgentContextSnapshot` - `ListWorkspaceAgentContextResources` ### Handler (`coderd/agentapi/context.go`) `ContextAPI` is a new sub-API. `PushContextState`: 1. Rejects `schema_version > 1` with a non-`Unimplemented` error so a forward-incompatible agent fails loudly during rollout instead of slipping into the permanent fallback path the `Unimplemented` translation reserves for old coderd deployments. 2. Validates resources: no empty/duplicate sources, every variant maps to a known body kind, every status maps to a known enum value, the `Body` oneof is set (even when status is non-OK, mirroring the wire guarantee so coderd can attribute failures to a known kind). 3. Inside `Database.InTx`, reads the existing snapshot. If the push is not `initial` and `version` is not strictly greater, returns `accepted = false` and leaves stored state untouched. Otherwise upserts the snapshot row, upserts each resource, then runs the stale-source prune so the snapshot and resource rows always agree. 4. Returns `accepted = true` on success. Resource bodies are stored as `protojson(body oneof variant)` in `body JSONB` with `body_kind` as the discriminator. Adding a new field to an existing variant is zero work since `protojson` tolerates new fields; adding a new variant is a CHECK + switch case. ### RBAC + dbauthz - New `ResourceWorkspaceAgentContext` (Create/Read/Update/Delete). - New `SubjectTypeAgentContext` plus `subjectAgentContext` system role and `dbauthz.AsAgentContext` helper. The push handler elevates to this subject; the agent's own role does not get direct write access to the table. - New `workspace_agent_context:*` API key scopes registered in the enum migration; internal-only (not added to `externalLowLevel`). ### Audit These rows are agent-pushed state, not user-authored. They are intentionally not added to `AuditActionMap` and not enumerated in `enterprise/audit/table.go`, matching `boundary_logs`, `workspace_agent_memory_resource_monitor`, etc. `enterprise/audit` tests pass unchanged. ## Tests - `coderd/agentapi/context_test.go`: 12 subtests covering accepts/rejects (schema version, empty/duplicate source, unknown status, missing body), version semantics (stale dropped, same-version replay dropped, `initial=true` overwrites lower version), variant coverage, non-OK status persistence, and the empty-active-set prune case. - `coderd/database/dbauthz/dbauthz_test.go`: 5 `MethodTestSuite` cases covering the new queries. - `coderd/rbac/roles_test.go`: `WorkspaceAgentContext` permission row asserting no human role currently has access. - `coderd/database/migrations/testdata/fixtures/000517_workspace_agent_context.up.sql`: one snapshot + one resource per known body kind plus a non-OK status, so the migration test suite never lands with these tables empty. ## Out of scope (later phases) - Chat hydration (`chats.context_aggregate_hash`, `last_injected_context`). - Dirty-bit fan-out and `PUT /chats/{id}/context`. - Agent-side `POST /api/v0/context/resync` barrier and the `coder exp chat context` CLI. - `codersdk` chat-context wire types and the dashboard Sources drawer. - Removal of the chatd per-turn pull fallback. ## Compat property This is a pure write path. If anything here returns errors the agent's `RunPush` loop backs off, no chat behavior changes, and the workspace keeps behaving exactly like it did before v2.10. <details> <summary>Implementation plan and decision log</summary> Key design calls: 1. **Concurrency**: Accept iff `req.Initial || req.Version > existing.Version`. The strict RFC reading ("version comparison is authoritative") locks restarted agents out because their per-process counter resets to 1; honoring `initial=true` reflects the real reboot reality while still rejecting steady-state replays/out-of-order pushes. 2. **Body encoding**: `protojson` over the oneof variant body proto, stored in JSONB with `body_kind` discriminator. Structured at the API/Go layer, schema-tolerant at the storage layer, and Phase 2 readers round-trip back via `protojson.Unmarshal`. 3. **Schema version rejection**: returns a normal error, not `Unimplemented`. The agent's `RunPush` loop only short-circuits on `Unimplemented`; that escape hatch is reserved for old coderd deployments. A forward-incompatible agent should retry-and-back-off, not flip the connection into permanent fallback. 4. **Validation strictness**: empty sources, duplicate sources, `STATUS_UNSPECIFIED`, and missing `Body` oneof variants are rejected before any write so a misbehaving agent cannot poison the snapshot table. Phase 2 readers can trust every row maps to a known proto variant. </details> _This PR was authored by Coder Agents on Kyle Carberry's behalf._
196 lines
6.7 KiB
Go
196 lines
6.7 KiB
Go
package agentcontext_test
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
"storj.io/drpc/drpcerr"
|
|
|
|
"github.com/coder/coder/v2/agent/agentcontext"
|
|
agentproto "github.com/coder/coder/v2/agent/proto"
|
|
)
|
|
|
|
// fakeDRPCClient stubs out the DRPCAgentClient210 surface for
|
|
// the parts of the interface the adapter exercises. Only
|
|
// PushContextState is implemented; every other method panics
|
|
// because the adapter never calls them.
|
|
type fakeDRPCClient struct {
|
|
agentproto.DRPCAgentClient210
|
|
lastReq *agentproto.PushContextStateRequest
|
|
resp *agentproto.PushContextStateResponse
|
|
err error
|
|
}
|
|
|
|
func (f *fakeDRPCClient) PushContextState(_ context.Context, req *agentproto.PushContextStateRequest) (*agentproto.PushContextStateResponse, error) {
|
|
f.lastReq = req
|
|
if f.err != nil {
|
|
return nil, f.err
|
|
}
|
|
if f.resp == nil {
|
|
return &agentproto.PushContextStateResponse{Accepted: true}, nil
|
|
}
|
|
return f.resp, nil
|
|
}
|
|
|
|
func TestDRPCPusher_HappyPathSerializesAllFields(t *testing.T) {
|
|
t.Parallel()
|
|
client := &fakeDRPCClient{}
|
|
pusher := agentcontext.NewDRPCPusher(client)
|
|
|
|
req := &agentcontext.PushRequest{
|
|
Version: 7,
|
|
AggregateHash: [32]byte{0xaa, 0xbb, 0xcc},
|
|
Initial: true,
|
|
SnapshotError: "watcher degraded",
|
|
Resources: []agentcontext.Resource{
|
|
{
|
|
ID: "instruction_file:/tmp/AGENTS.md",
|
|
Kind: agentcontext.KindInstructionFile,
|
|
Source: "/tmp/AGENTS.md",
|
|
ContentHash: [32]byte{0x01, 0x02},
|
|
Payload: []byte("body"),
|
|
SizeBytes: 4,
|
|
Status: agentcontext.StatusOK,
|
|
Description: "tagline",
|
|
SourcePath: "/tmp",
|
|
},
|
|
{
|
|
ID: "skill:/tmp/.agents/skills/foo",
|
|
Kind: agentcontext.KindSkill,
|
|
Source: "/tmp/.agents/skills/foo",
|
|
Status: agentcontext.StatusInvalid,
|
|
Error: "bad frontmatter",
|
|
SizeBytes: 99,
|
|
},
|
|
{
|
|
ID: "skill:/tmp/.agents/skills/code-review",
|
|
Kind: agentcontext.KindSkill,
|
|
Source: "/tmp/.agents/skills/code-review",
|
|
ContentHash: [32]byte{0x03},
|
|
Payload: []byte("---\nname: code-review\n---\nbody\n"),
|
|
SizeBytes: 31,
|
|
Status: agentcontext.StatusOK,
|
|
Name: "code-review",
|
|
Description: "Critical review for Go PRs.",
|
|
SourcePath: "/tmp",
|
|
},
|
|
{
|
|
ID: "mcp_config:/tmp/.mcp.json",
|
|
Kind: agentcontext.KindMCPConfig,
|
|
Source: "/tmp/.mcp.json",
|
|
ContentHash: [32]byte{0x04},
|
|
SizeBytes: 412,
|
|
Status: agentcontext.StatusOK,
|
|
SourcePath: "/tmp",
|
|
},
|
|
{
|
|
ID: "mcp_server:github",
|
|
Kind: agentcontext.KindMCPServer,
|
|
Source: "github",
|
|
Name: "github",
|
|
ContentHash: [32]byte{0x05},
|
|
SizeBytes: 138,
|
|
Status: agentcontext.StatusOK,
|
|
Description: "GitHub MCP server (1 tool)",
|
|
SourcePath: "/tmp/.mcp.json",
|
|
Tools: []agentcontext.MCPTool{{
|
|
Name: "create_issue",
|
|
Description: "Create a GitHub issue",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"required": []any{"title"},
|
|
},
|
|
}},
|
|
},
|
|
},
|
|
}
|
|
|
|
resp, err := pusher.PushContextState(context.Background(), req)
|
|
require.NoError(t, err)
|
|
require.True(t, resp.Accepted)
|
|
|
|
pb := client.lastReq
|
|
require.NotNil(t, pb)
|
|
require.Equal(t, uint64(7), pb.Version)
|
|
require.Equal(t, []byte{0xaa, 0xbb, 0xcc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, pb.AggregateHash)
|
|
require.True(t, pb.Initial)
|
|
require.Equal(t, "watcher degraded", pb.SnapshotError)
|
|
|
|
require.Len(t, pb.Resources, 5)
|
|
|
|
// Instruction file: wire-flat fields plus typed body.
|
|
instr := pb.Resources[0]
|
|
require.Equal(t, "/tmp/AGENTS.md", instr.Source)
|
|
require.Equal(t, agentproto.ContextResource_OK, instr.Status)
|
|
require.NotNil(t, instr.SourcePath)
|
|
require.Equal(t, "/tmp", *instr.SourcePath)
|
|
instrBody := instr.GetInstructionFile()
|
|
require.NotNil(t, instrBody, "instruction_file body must be set")
|
|
require.Equal(t, []byte("body"), instrBody.GetContent())
|
|
require.Nil(t, instr.GetSkill())
|
|
require.Nil(t, instr.GetMcpConfig())
|
|
require.Nil(t, instr.GetMcpServer())
|
|
|
|
// Skill with INVALID status still has the skill body set so
|
|
// coderd can attribute the failure to the correct kind.
|
|
invalidSkill := pb.Resources[1]
|
|
require.Equal(t, agentproto.ContextResource_INVALID, invalidSkill.Status)
|
|
require.Equal(t, "bad frontmatter", invalidSkill.Error)
|
|
require.NotNil(t, invalidSkill.GetSkill(), "skill body must be set even when status != OK")
|
|
require.Nil(t, invalidSkill.SourcePath, "empty user source must remain optional/nil")
|
|
|
|
// OK skill: meta + name + description populated.
|
|
skill := pb.Resources[2]
|
|
skillBody := skill.GetSkill()
|
|
require.NotNil(t, skillBody)
|
|
require.Equal(t, []byte("---\nname: code-review\n---\nbody\n"), skillBody.GetMeta())
|
|
require.Equal(t, "code-review", skillBody.GetName())
|
|
require.Equal(t, "Critical review for Go PRs.", skillBody.GetDescription())
|
|
|
|
// MCP config: body present but empty. SizeBytes / ContentHash
|
|
// on the outer resource still detect changes.
|
|
mcpCfg := pb.Resources[3]
|
|
require.Equal(t, uint64(412), mcpCfg.SizeBytes)
|
|
require.NotNil(t, mcpCfg.GetMcpConfig(), "mcp_config body must be set")
|
|
|
|
// MCP server: structured tool list with input schema.
|
|
mcpSrv := pb.Resources[4]
|
|
srvBody := mcpSrv.GetMcpServer()
|
|
require.NotNil(t, srvBody)
|
|
require.Equal(t, "github", srvBody.GetServerName())
|
|
require.Equal(t, "GitHub MCP server (1 tool)", srvBody.GetDescription())
|
|
require.Len(t, srvBody.GetTools(), 1)
|
|
tool := srvBody.GetTools()[0]
|
|
require.Equal(t, "create_issue", tool.GetName())
|
|
require.Equal(t, "Create a GitHub issue", tool.GetDescription())
|
|
require.NotNil(t, tool.GetInputSchema(), "input_schema must be set when supplied")
|
|
require.Equal(t, "object", tool.GetInputSchema().GetFields()["type"].GetStringValue())
|
|
}
|
|
|
|
func TestDRPCPusher_UnimplementedTranslated(t *testing.T) {
|
|
t.Parallel()
|
|
client := &fakeDRPCClient{err: drpcerr.WithCode(drpcerr.WithCode(context.Canceled, 0), drpcerr.Unimplemented)}
|
|
pusher := agentcontext.NewDRPCPusher(client)
|
|
|
|
_, err := pusher.PushContextState(context.Background(), &agentcontext.PushRequest{})
|
|
require.ErrorIs(t, err, agentcontext.ErrPushUnimplemented)
|
|
}
|
|
|
|
func TestDRPCPusher_PropagatesOtherErrors(t *testing.T) {
|
|
t.Parallel()
|
|
want := drpcerr.WithCode(context.DeadlineExceeded, 42)
|
|
client := &fakeDRPCClient{err: want}
|
|
pusher := agentcontext.NewDRPCPusher(client)
|
|
|
|
_, err := pusher.PushContextState(context.Background(), &agentcontext.PushRequest{})
|
|
require.ErrorIs(t, err, context.DeadlineExceeded)
|
|
}
|
|
|
|
func TestDRPCPusher_NilClientErrors(t *testing.T) {
|
|
t.Parallel()
|
|
pusher := agentcontext.NewDRPCPusher(nil)
|
|
_, err := pusher.PushContextState(context.Background(), &agentcontext.PushRequest{})
|
|
require.Error(t, err)
|
|
}
|