Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions lib/context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,54 @@ withdrawal, replay and history behavior applies.

This requires the database company-assessment purpose migration before API release.
Local fixtures cover compile/save/reopen; they do not prove a hosted Records trial.

### Withdraw a source

Use the same HTTP `POST /api/context` or MCP Context operation to withdraw one
recorded source input of a saved request, for example a private note or an
incorrect page that must stop informing briefs:

```json
{
"action": "withdraw_source",
"request_id": "<existing request UUID>",
"source_version_id": "<a sourceVersionIds entry from a brief input_manifest>"
}
```

Name the source with exactly one of `source_id` or `source_version_id`; brief
and saved-brief input manifests expose version IDs as `sourceVersionIds`, and the
receipt returns the resolved `source_id`. Add `organization_id` for the existing authorized
organization scope; membership is rechecked inside the transaction. The source
must belong to the workspace and be recorded as an input of `request_id` through
saved result lineage; arbitrary IDs and sources only linked to other requests are
rejected. The operation calls the existing `withdraw_context_source` primitive:
every saved result that depends on any version of the source is relabelled
`withdrawn` (replacing its earlier status, such as `stale` or `partial`; rows are
kept), documents whose current result depended on it lose that result (revision
bumped), and `read_context_documents`, `accept_context_result` and
`read_context_brief` withhold the evidence on the next read, so saved briefs that
depend on it return `state: unavailable`.

The withdrawal is sticky for that workspace, source kind and URL. Writers re-create
sources through the active-source index, so a database trigger makes any later
row with the same owner, kind and URL born withdrawn, after waiting for an
in-flight withdrawal to commit. A slow older job or a new ingestion therefore
cannot republish the source: writers that need that evidence accepted fail closed
with an acceptance conflict, and evidence kept against a born-withdrawn row stays
history that reads never return. Other workspaces and
other source kinds are unaffected. There is no restore operation yet, so delegated
MCP marks `withdraw_music_context_source` destructive.

The receipt (`context-source-withdrawal-v1`) reports `withdrawn_at`,
`already_withdrawn` and the source's recorded lineage in `affected`: results that
depend on it, documents holding such a result, and the request IDs whose attempts
produced them. Replaying the same withdrawal returns the same receipt without
touching timestamps or revisions. A writer that already holds a document lock can
deadlock with a concurrent withdrawal; PostgreSQL aborts one transaction, the API
returns 409 and the caller retries.

This does not delete original bytes or storage objects, correct or refresh
evidence, recompute briefs, de-duplicate articles, or spend credits; those remain
separate lifecycle work. It requires the database source-withdrawal migration
before API release. Fixture-tested only; not hosted-verified.
142 changes: 142 additions & 0 deletions lib/context/__tests__/sourceWithdrawalOperation.test.ts
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]);
}
});
});
93 changes: 93 additions & 0 deletions lib/context/__tests__/sourceWithdrawalTransports.test.ts
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");
});
5 changes: 5 additions & 0 deletions lib/context/processContextOperation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { releaseCaseOperationSchemas } from "./releaseCaseOperationSchemas";
import { processReleaseCaseOperation } from "./processReleaseCaseOperation";
import { sourceWithdrawalOperationSchemas } from "./sourceWithdrawalSchemas";
import { processSourceWithdrawalOperation } from "./processSourceWithdrawalOperation";
import { createHash } from "node:crypto";
import { z } from "zod";
import { authorizeContextOwner } from "./authorizeContextOwner";
Expand All @@ -20,6 +22,7 @@ const briefFields = {

export const contextOperationSchema = z.discriminatedUnion("action", [
...releaseCaseOperationSchemas,
...sourceWithdrawalOperationSchemas,
z.strictObject({
action: z.literal("save_brief"),
...briefFields,
Expand Down Expand Up @@ -199,6 +202,8 @@ export async function processContextOperation(
args.action === "review_release_case"
)
return processReleaseCaseOperation(accountId, ownerId, args, deps.rpc);
if (args.action === "withdraw_source")

Copy link
Copy Markdown

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.ts is 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
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/processContextOperation.ts, line 205:

<comment>`processContextOperation.ts` is 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.</comment>

<file context>
@@ -199,6 +202,8 @@ export async function processContextOperation(
     args.action === "review_release_case"
   )
     return processReleaseCaseOperation(accountId, ownerId, args, deps.rpc);
+  if (args.action === "withdraw_source")
+    return processSourceWithdrawalOperation(accountId, ownerId, args, deps.rpc);
   if (args.action === "read_brief")
</file context>

return processSourceWithdrawalOperation(accountId, ownerId, args, deps.rpc);
if (args.action === "read_brief")
return {
snapshot: await deps.rpc("read_context_brief", { p_owner: ownerId, p_brief: args.brief_id }),
Expand Down
18 changes: 18 additions & 0 deletions lib/context/processSourceWithdrawalOperation.ts
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The RPC result is cast straight to ContextSourceWithdrawalReceipt with no runtime validation and then returned verbatim to both POST /api/context and the MCP tool. If the DB returns a null payload or a receipt that doesn't match the declared contract_version, affected counts, or already_withdrawn shape, clients receive it as if it were a valid receipt. The migration defining withdraw_context_request_source is external to this repo, so the shape is asserted blindly. Parse the result with a small Zod receiver schema (mirroring how verify_release in processContextOperation.ts validates RPC output with z.strictObject(...).parse(...)) before returning it; at minimum verify contract_version === "context-source-withdrawal-v1".

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/processSourceWithdrawalOperation.ts, line 16:

<comment>The RPC result is cast straight to `ContextSourceWithdrawalReceipt` with no runtime validation and then returned verbatim to both `POST /api/context` and the MCP tool. If the DB returns a null payload or a receipt that doesn't match the declared `contract_version`, `affected` counts, or `already_withdrawn` shape, clients receive it as if it were a valid receipt. The migration defining `withdraw_context_request_source` is external to this repo, so the shape is asserted blindly. Parse the result with a small Zod receiver schema (mirroring how `verify_release` in `processContextOperation.ts` validates RPC output with `z.strictObject(...).parse(...)`) before returning it; at minimum verify `contract_version === "context-source-withdrawal-v1"`.</comment>

<file context>
@@ -0,0 +1,17 @@
+    p_owner: ownerId,
+    p_request: args.request_id,
+    p_source: args.source_id,
+  })) as ContextSourceWithdrawalReceipt;
+}
</file context>

}
21 changes: 21 additions & 0 deletions lib/context/sourceWithdrawalSchemas.ts
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]>;
19 changes: 19 additions & 0 deletions lib/context/sourceWithdrawalTypes.ts
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[];
};
}
Loading
Loading