Repository navigation
Expose scoped Context source withdrawal over HTTP and MCP #1008
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { contextOperationSchema, processContextOperation } from "../processContextOperation"; | ||
| // Isolate module initialization from hosted Supabase credentials; tests inject authorization. | ||
| vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); | ||
| const actor = "11111111-1111-4111-8111-111111111111"; | ||
| const owner = "22222222-2222-4222-8222-222222222222"; | ||
| const request = "33333333-3333-4333-8333-333333333333"; | ||
| const source = "44444444-4444-4444-8444-444444444444"; | ||
| const version = "55555555-5555-4555-8555-555555555555"; | ||
| const input = { | ||
| action: "withdraw_source", | ||
| organization_id: owner, | ||
| request_id: request, | ||
| source_id: source, | ||
| }; | ||
| const receipt = { | ||
| contract_version: "context-source-withdrawal-v1", | ||
| request_id: request, | ||
| source_id: source, | ||
| withdrawn_at: "2026-10-10T12:00:00+00:00", | ||
| already_withdrawn: false, | ||
| affected: { results: 1, documents: 1, request_ids: [request] }, | ||
| }; | ||
| describe("source withdrawal operation", () => { | ||
| it("withdraws one recorded input through the actor-scoped RPC without collection", async () => { | ||
| const rpc = vi.fn(async () => receipt); | ||
| const dispatch = vi.fn(); | ||
| const authorize = vi.fn(async () => ({ | ||
| accountId: actor, | ||
| ownerId: owner, | ||
| organizationId: owner, | ||
| })); | ||
| expect(await processContextOperation(actor, input, { rpc, dispatch, authorize })).toEqual( | ||
| receipt, | ||
| ); | ||
| expect(authorize).toHaveBeenCalledWith(actor, owner); | ||
| expect(rpc).toHaveBeenCalledExactlyOnceWith("withdraw_context_request_source", { | ||
| p_actor: actor, | ||
| p_owner: owner, | ||
| p_request: request, | ||
| p_source: source, | ||
| p_source_version: null, | ||
| }); | ||
| expect(dispatch).not.toHaveBeenCalled(); | ||
| }); | ||
| it("uses the personal workspace when no organization is selected", async () => { | ||
| const rpc = vi.fn(async () => receipt); | ||
| const authorize = vi.fn(async () => ({ | ||
| accountId: actor, | ||
| ownerId: actor, | ||
| organizationId: null, | ||
| })); | ||
| const { organization_id: _omitted, ...personal } = input; | ||
| await processContextOperation(actor, personal, { rpc, dispatch: vi.fn(), authorize }); | ||
| expect(authorize).toHaveBeenCalledWith(actor, undefined); | ||
| expect(rpc).toHaveBeenCalledExactlyOnceWith("withdraw_context_request_source", { | ||
| p_actor: actor, | ||
| p_owner: actor, | ||
| p_request: request, | ||
| p_source: source, | ||
| p_source_version: null, | ||
| }); | ||
| }); | ||
| it("withdraws by a manifest source version and returns the resolved source", async () => { | ||
| const rpc = vi.fn(async () => receipt); | ||
| const authorize = vi.fn(async () => ({ | ||
| accountId: actor, | ||
| ownerId: owner, | ||
| organizationId: owner, | ||
| })); | ||
| const { source_id: _omitted, ...byVersion } = input; | ||
| expect( | ||
| await processContextOperation( | ||
| actor, | ||
| { ...byVersion, source_version_id: version }, | ||
| { rpc, dispatch: vi.fn(), authorize }, | ||
| ), | ||
| ).toEqual(receipt); | ||
| expect(rpc).toHaveBeenCalledExactlyOnceWith("withdraw_context_request_source", { | ||
| p_actor: actor, | ||
| p_owner: owner, | ||
| p_request: request, | ||
| p_source: null, | ||
| p_source_version: version, | ||
| }); | ||
| }); | ||
| it("requires exactly one source identifier", () => { | ||
| const { source_id: _omitted, ...neither } = input; | ||
| for (const value of [neither, { ...input, source_version_id: version }]) { | ||
| const parsed = contextOperationSchema.safeParse(value); | ||
| expect(parsed.success).toBe(false); | ||
| expect(parsed.error?.issues[0]).toMatchObject({ | ||
| path: ["source_id"], | ||
| message: "Provide exactly one of source_id or source_version_id", | ||
| }); | ||
| } | ||
| }); | ||
| it("passes an idempotent replay receipt through unchanged", async () => { | ||
| const replay = { ...receipt, already_withdrawn: true }; | ||
| const rpc = vi.fn(async () => replay); | ||
| const authorize = vi.fn(async () => ({ | ||
| accountId: actor, | ||
| ownerId: owner, | ||
| organizationId: owner, | ||
| })); | ||
| expect( | ||
| await processContextOperation(actor, input, { rpc, dispatch: vi.fn(), authorize }), | ||
| ).toEqual(replay); | ||
| }); | ||
| it("does not withdraw on revoked access", async () => { | ||
| const rpc = vi.fn(); | ||
| await expect( | ||
| processContextOperation(actor, input, { | ||
| rpc, | ||
| dispatch: vi.fn(), | ||
| authorize: vi.fn(async () => { | ||
| throw new Error("Access denied"); | ||
| }), | ||
| }), | ||
| ).rejects.toThrow("Access denied"); | ||
| expect(rpc).not.toHaveBeenCalled(); | ||
| }); | ||
| it("rejects fabricated actors, missing requests and non-UUID sources", () => { | ||
| expect(contextOperationSchema.safeParse(input).success).toBe(true); | ||
| for (const changes of [ | ||
| { account_id: actor }, | ||
| { delete_original: true }, | ||
| { request_id: undefined }, | ||
| { source_id: "not-a-uuid" }, | ||
| { source_version_id: "not-a-uuid", source_id: undefined }, | ||
| { organization_id: "" }, | ||
| ]) { | ||
| const parsed = contextOperationSchema.safeParse({ ...input, ...changes }); | ||
| expect(parsed.success).toBe(false); | ||
| const key = Object.keys(changes)[0]; | ||
| const issue = parsed.error?.issues[0]; | ||
| if (key === "account_id" || key === "delete_original") | ||
| expect(issue).toMatchObject({ code: "unrecognized_keys", keys: [key] }); | ||
| else expect(issue?.path).toEqual([key]); | ||
| } | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import { afterEach, expect, it, vi } from "vitest"; | ||
| import { NextRequest } from "next/server"; | ||
| import { contextOperationHandler } from "../contextOperationHandler"; | ||
| import { registerContextTool } from "@/lib/mcp/tools/context/registerContextTool"; | ||
| import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; | ||
|
|
||
| const actor = "11111111-1111-4111-8111-111111111111"; | ||
| const owner = "22222222-2222-4222-8222-222222222222"; | ||
| const request = "33333333-3333-4333-8333-333333333333"; | ||
| const source = "44444444-4444-4444-8444-444444444444"; | ||
| vi.mock("@/lib/auth/validateAuthContext", () => ({ | ||
| validateAuthContext: vi.fn(async () => ({ accountId: actor })), | ||
| })); | ||
| vi.mock("@/lib/mcp/resolveAccountId", () => ({ | ||
| resolveAccountId: vi.fn(async () => ({ accountId: actor, error: null })), | ||
| })); | ||
| vi.mock("../authorizeContextOwner", () => ({ | ||
| authorizeContextOwner: vi.fn(async () => ({ | ||
| accountId: actor, | ||
| ownerId: owner, | ||
| organizationId: owner, | ||
| })), | ||
| })); | ||
| vi.mock("@/lib/supabase/context_requests/callContextRpc", () => ({ callContextRpc: vi.fn() })); | ||
| vi.mock("../dispatchContextRequest", () => ({ dispatchContextRequest: vi.fn() })); | ||
| vi.mock("../dispatchContextReleaseVerification", () => ({ | ||
| dispatchContextReleaseVerification: vi.fn(), | ||
| })); | ||
| vi.mock("../dispatchContextReleaseTrackIsrcs", () => ({ | ||
| dispatchContextReleaseTrackIsrcs: vi.fn(), | ||
| })); | ||
| const operation = { | ||
| action: "withdraw_source", | ||
| organization_id: owner, | ||
| request_id: request, | ||
| source_id: source, | ||
| }; | ||
| const params = { | ||
| p_actor: actor, | ||
| p_owner: owner, | ||
| p_request: request, | ||
| p_source: source, | ||
| p_source_version: null, | ||
| }; | ||
| const receipt = { | ||
| contract_version: "context-source-withdrawal-v1", | ||
| request_id: request, | ||
| source_id: source, | ||
| withdrawn_at: "2026-10-10T12:00:00+00:00", | ||
| already_withdrawn: false, | ||
| affected: { results: 1, documents: 1, request_ids: [request] }, | ||
| }; | ||
| const http = (body: unknown) => | ||
| contextOperationHandler( | ||
| new NextRequest("http://localhost/api/context", { method: "POST", body: JSON.stringify(body) }), | ||
| ); | ||
| const mcp = async (body: unknown) => { | ||
| const registerTool = vi.fn(); | ||
| registerContextTool({ registerTool } as never); | ||
| const result = await registerTool.mock.calls[0][2](body, {}); | ||
| return JSON.parse(result.content[0].text); | ||
| }; | ||
|
|
||
| afterEach(() => vi.clearAllMocks()); | ||
|
|
||
| it("HTTP and MCP withdraw through the same actor-scoped RPC", async () => { | ||
| vi.mocked(callContextRpc).mockResolvedValue(receipt); | ||
| const response = await http(operation); | ||
| expect(response.status).toBe(200); | ||
| expect(await response.json()).toEqual(receipt); | ||
| expect(callContextRpc).toHaveBeenCalledExactlyOnceWith("withdraw_context_request_source", params); | ||
| vi.mocked(callContextRpc).mockClear(); | ||
| expect(await mcp(operation)).toEqual(receipt); | ||
| expect(callContextRpc).toHaveBeenCalledExactlyOnceWith("withdraw_context_request_source", params); | ||
| }); | ||
|
|
||
| it("rejects a withdrawal without a source before any storage call", async () => { | ||
| const { source_id: _omitted, ...incomplete } = operation; | ||
| expect((await http(incomplete)).status).toBe(400); | ||
| expect(callContextRpc).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("redacts storage failures on both transports", async () => { | ||
| vi.mocked(callContextRpc).mockRejectedValue( | ||
| new Error("Context storage operation failed: Source is not an input of this request"), | ||
| ); | ||
| const response = await http(operation); | ||
| expect(response.status).toBe(409); | ||
| expect(JSON.stringify(await response.json())).not.toContain("Source is not an input"); | ||
| const result = await mcp(operation); | ||
| expect(result).toMatchObject({ success: false }); | ||
| expect(JSON.stringify(result)).not.toContain("Source is not an input"); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import type { SourceWithdrawalOperation } from "./sourceWithdrawalSchemas"; | ||
| import type { ContextSourceWithdrawalReceipt } from "./sourceWithdrawalTypes"; | ||
|
|
||
| /** Withdraw one recorded source input after shared actor/workspace authorization; no deletion or recompute. */ | ||
| export async function processSourceWithdrawalOperation( | ||
| accountId: string, | ||
| ownerId: string, | ||
| args: SourceWithdrawalOperation, | ||
| rpc: (name: string, params: Record<string, unknown>) => Promise<unknown>, | ||
| ) { | ||
| return (await rpc("withdraw_context_request_source", { | ||
| p_actor: accountId, | ||
| p_owner: ownerId, | ||
| p_request: args.request_id, | ||
| p_source: args.source_id ?? null, | ||
| p_source_version: args.source_version_id ?? null, | ||
| })) as ContextSourceWithdrawalReceipt; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3: The RPC result is cast straight to Prompt for AI agents |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { z } from "zod"; | ||
|
|
||
| /** | ||
| * Withdraw one recorded source input of a saved request, named by its source ID or by one of | ||
| * its version IDs (brief input manifests expose sourceVersionIds). Rows are kept; nothing is deleted. | ||
| */ | ||
| export const sourceWithdrawalOperationSchemas = [ | ||
| z | ||
| .strictObject({ | ||
| action: z.literal("withdraw_source"), | ||
| organization_id: z.uuid().optional(), | ||
| request_id: z.uuid(), | ||
| source_id: z.uuid().optional(), | ||
| source_version_id: z.uuid().optional(), | ||
| }) | ||
| .refine(value => (value.source_id === undefined) !== (value.source_version_id === undefined), { | ||
| message: "Provide exactly one of source_id or source_version_id", | ||
| path: ["source_id"], | ||
| }), | ||
| ] as const; | ||
| export type SourceWithdrawalOperation = z.infer<(typeof sourceWithdrawalOperationSchemas)[number]>; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| /** Receipt from withdraw_context_request_source; counts come from recorded result lineage. */ | ||
| export interface ContextSourceWithdrawalReceipt { | ||
| contract_version: "context-source-withdrawal-v1"; | ||
| request_id: string; | ||
| /** The withdrawn source, also when the caller named it by a version ID. */ | ||
| source_id: string; | ||
| withdrawn_at: string; | ||
| /** True when the source was already withdrawn; timestamps and revisions are untouched. */ | ||
| already_withdrawn: boolean; | ||
| /** Recorded lineage of the source; identical on replay. */ | ||
| affected: { | ||
| /** Saved results that depend on any version of the source; all are now withdrawn. */ | ||
| results: number; | ||
| /** Documents holding such a result; any whose current result used the source now has none. */ | ||
| documents: number; | ||
| /** Every request whose saved attempts produced those results, including this one. */ | ||
| request_ids: string[]; | ||
| }; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: Custom agent: Enforce Clear Code Style and Maintainability Practices
processContextOperation.tsis 516 lines, violating the rule’s under-100-line and single-responsibility requirements; this new branch further grows the multi-action dispatcher. Split the operation dispatch/schema wiring into smaller cohesive modules.Prompt for AI agents