diff --git a/lib/context/README.md b/lib/context/README.md index 3771d8eca..bcb35b24a 100644 --- a/lib/context/README.md +++ b/lib/context/README.md @@ -277,3 +277,38 @@ 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. + +### Document version history + +`context_documents` keeps the current pointer (`current_result_id`, `revision`); +`context_document_versions` records every revision once, written by a database +trigger so `accept_context_result`, `withdraw_context_source`, metadata saves, +enrichment completion and the entry functions are unchanged. A row is `accepted` +(the result that became current) or `cleared` (withdrawal nulled the pointer); +rows cannot be updated or deleted, one revision is recorded once, and a pointer +that moves without a new revision is rejected. The trigger is the only writer: +the service role can read history but not insert it, and each row can cite only +a result of the document's own workspace, subject and topic. Existing documents +are backfilled from their current revision with `backfilled: true`. + +Read lineage through the shared HTTP `POST /api/context` or standard MCP operation: + +```json +{ "action": "read_document_history", "document_id": "", "limit": 50 } +``` + +`document_id` comes from a brief response (`documents[].id` or +`input_manifest.documents[].documentId`). `organization_id` selects the +authorized workspace exactly like other reads; `before_revision` (1 or more) is +an exclusive cursor for older pages (`next_before`). The +result is `{state, document, versions, has_more, next_before}`; `versions` are +newest first with `result_id`, `change`, `recorded_at`, the result's current +`result_status`, `evidence_kind`, `source_version_ids` and `source_state` +(`live`, `withdrawn`, `removed`, or null for a cleared revision). A superseded +brief's manifest (`documentId`, `version`, `resultId`) therefore resolves to the +result that was current at that version. Another workspace's or an unknown +document returns `state: "not_found"` without confirming existence. Lineage is +not human review, rights approval or correction semantics; it requires the +database document-version migration before API release (production apply waits +for the CE01 deployed-schema verification) and is fixture-tested, not +live-verified. diff --git a/lib/context/__tests__/documentHistoryOperation.test.ts b/lib/context/__tests__/documentHistoryOperation.test.ts new file mode 100644 index 000000000..bd9e7992e --- /dev/null +++ b/lib/context/__tests__/documentHistoryOperation.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it, vi } from "vitest"; +import { contextOperationSchema, processContextOperation } from "../processContextOperation"; +import { processDocumentHistoryOperation } from "../processDocumentHistoryOperation"; +import { contextToolOperations } from "@/lib/mcp/oauth/contextToolOperations"; +// 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 document = "33333333-3333-4333-8333-333333333333"; +const firstResult = "44444444-4444-4444-8444-444444444444"; +const secondResult = "55555555-5555-4555-8555-555555555555"; +const history = { + document: { + id: document, + subject_id: "66666666-6666-4666-8666-666666666666", + topic: "release_metadata", + current_revision: 3, + current_result_id: null, + updated_at: "2026-10-10T12:00:00+00:00", + }, + versions: [ + { + revision: 3, + result_id: null, + change: "cleared", + backfilled: false, + recorded_at: "2026-10-10T12:00:00+00:00", + result_status: null, + evidence_kind: null, + source_version_ids: [], + source_state: null, + }, + { + revision: 2, + result_id: secondResult, + change: "accepted", + backfilled: false, + recorded_at: "2026-10-10T11:00:00+00:00", + result_status: "withdrawn", + evidence_kind: "observation", + source_version_ids: ["77777777-7777-4777-8777-777777777777"], + source_state: "withdrawn", + }, + { + revision: 1, + result_id: firstResult, + change: "accepted", + backfilled: true, + recorded_at: "2026-09-21T10:00:00+00:00", + result_status: "withdrawn", + evidence_kind: "observation", + source_version_ids: ["77777777-7777-4777-8777-777777777777"], + source_state: "withdrawn", + }, + ], + has_more: false, + next_before: null, +}; +const authorize = () => + vi.fn(async () => ({ accountId: actor, ownerId: owner, organizationId: owner })); +describe("document version history", () => { + it("reads scoped lineage through the shared operation with bounded defaults", async () => { + const rpc = vi.fn(async () => history); + const dispatch = vi.fn(); + const authorized = authorize(); + expect( + await processContextOperation( + actor, + { action: "read_document_history", document_id: document, organization_id: owner }, + { rpc, dispatch, authorize: authorized }, + ), + ).toEqual({ state: "found", ...history }); + expect(authorized).toHaveBeenCalledWith(actor, owner); + expect(rpc).toHaveBeenCalledExactlyOnceWith("read_context_document_history", { + p_owner: owner, + p_document: document, + p_before: null, + p_limit: 50, + }); + expect(dispatch).not.toHaveBeenCalled(); + }); + it("passes the exclusive revision cursor and page bound to the scoped read", async () => { + const rpc = vi.fn(async () => ({ ...history, versions: [history.versions[2]] })); + await processContextOperation( + actor, + { action: "read_document_history", document_id: document, before_revision: 2, limit: 1 }, + { rpc, dispatch: vi.fn(), authorize: authorize() }, + ); + expect(rpc).toHaveBeenCalledExactlyOnceWith("read_context_document_history", { + p_owner: owner, + p_document: document, + p_before: 2, + p_limit: 1, + }); + }); + it("reports another workspace's or an unknown document as not found without a lineage leak", async () => { + const rpc = vi.fn(async () => null); + expect( + await processDocumentHistoryOperation( + owner, + { action: "read_document_history", document_id: document, limit: 50 }, + rpc, + ), + ).toEqual({ + state: "not_found", + document: null, + versions: [], + has_more: false, + next_before: null, + }); + }); + it("keeps cleared, withdrawn and backfilled versions distinct in the typed result", async () => { + const result = await processDocumentHistoryOperation( + owner, + { action: "read_document_history", document_id: document, limit: 50 }, + vi.fn(async () => history), + ); + if (result.state !== "found") throw new Error("expected lineage"); + expect(result.document.current_result_id).toBeNull(); + expect(result.versions.map(version => [version.change, version.source_state])).toEqual([ + ["cleared", null], + ["accepted", "withdrawn"], + ["accepted", "withdrawn"], + ]); + expect(result.versions[2].backfilled).toBe(true); + expect(result.versions[1].result_id).toBe(secondResult); + }); + it("does not read on revoked access", async () => { + const rpc = vi.fn(); + await expect( + processContextOperation( + actor, + { action: "read_document_history", document_id: document, organization_id: owner }, + { + rpc, + dispatch: vi.fn(), + authorize: vi.fn(async () => { + throw new Error("Access denied"); + }), + }, + ), + ).rejects.toThrow("Access denied"); + expect(rpc).not.toHaveBeenCalled(); + }); + it("rejects caller identity, unbounded pages and cursors the API never returns", () => { + const valid = { action: "read_document_history", document_id: document }; + expect(contextOperationSchema.parse(valid)).toEqual({ ...valid, limit: 50 }); + expect(contextOperationSchema.parse({ ...valid, before_revision: 1 })).toEqual({ + ...valid, + before_revision: 1, + limit: 50, + }); + for (const changes of [ + { account_id: actor }, + { owner_id: owner }, + { limit: 0 }, + { limit: 101 }, + { limit: 1.5 }, + { before_revision: -1 }, + { before_revision: 0 }, + { document_id: "not-a-document" }, + ]) { + const parsed = contextOperationSchema.safeParse({ ...valid, ...changes }); + expect(parsed.success).toBe(false); + const key = Object.keys(changes)[0]; + const issue = parsed.error?.issues[0]; + if (key === "account_id" || key === "owner_id") + expect(issue).toMatchObject({ code: "unrecognized_keys", keys: [key] }); + else expect(issue?.path).toEqual([key]); + } + }); + it("is exposed as a read-only standard MCP operation", () => { + expect(contextToolOperations.read_document_history).toEqual({ + name: "read_music_context_document_history", + description: expect.stringContaining("revision"), + readOnly: true, + }); + }); +}); diff --git a/lib/context/__tests__/documentHistoryTransports.test.ts b/lib/context/__tests__/documentHistoryTransports.test.ts new file mode 100644 index 000000000..927c7c9cf --- /dev/null +++ b/lib/context/__tests__/documentHistoryTransports.test.ts @@ -0,0 +1,60 @@ +import { expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { contextOperationHandler } from "../contextOperationHandler"; +import { processContextOperation } from "../processContextOperation"; +import { registerContextTool } from "@/lib/mcp/tools/context/registerContextTool"; +import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; +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("@/lib/supabase/context_requests/callContextRpc", () => ({ callContextRpc: vi.fn() })); +vi.mock("../dispatchContextRequest", () => ({ dispatchContextRequest: vi.fn() })); +vi.mock("../dispatchContextReleaseVerification", () => ({ + dispatchContextReleaseVerification: vi.fn(), +})); +vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); +vi.mock("../processContextOperation", async importOriginal => ({ + ...(await importOriginal()), + processContextOperation: vi.fn(async () => ({ state: "found", versions: [] })), +})); +const operation = { + action: "read_document_history", + document_id: "11111111-1111-4111-8111-111111111111", + before_revision: 4, + limit: 2, +}; +it("HTTP and MCP share authenticated read_document_history behavior", async () => { + const response = await contextOperationHandler( + new NextRequest("http://localhost/api/context", { + method: "POST", + body: JSON.stringify(operation), + }), + ); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ state: "found", versions: [] }); + expect(processContextOperation).toHaveBeenLastCalledWith("actor", operation, expect.any(Object)); + const registerTool = vi.fn(); + registerContextTool({ registerTool } as never); + vi.mocked(processContextOperation).mockClear(); + await registerTool.mock.calls[0][2](operation, {}); + expect(resolveAccountId).toHaveBeenCalled(); + expect(processContextOperation).toHaveBeenCalledTimes(1); + expect(processContextOperation).toHaveBeenLastCalledWith("actor", operation, expect.any(Object)); +}); +it("HTTP rejects a forged caller identity on the lineage read as an identity field", async () => { + vi.mocked(processContextOperation).mockClear(); + const response = await contextOperationHandler( + new NextRequest("http://localhost/api/context", { + method: "POST", + body: JSON.stringify({ ...operation, account_id: "forged" }), + }), + ); + expect(response.status).toBe(400); + expect((await response.json()).issues).toEqual([ + expect.objectContaining({ code: "unrecognized_keys", keys: ["account_id"] }), + ]); + expect(processContextOperation).not.toHaveBeenCalled(); +}); diff --git a/lib/context/documentHistorySchemas.ts b/lib/context/documentHistorySchemas.ts new file mode 100644 index 000000000..9fed95f99 --- /dev/null +++ b/lib/context/documentHistorySchemas.ts @@ -0,0 +1,13 @@ +import { z } from "zod"; + +/** Scoped lineage read: newest revisions first, bounded, with an exclusive revision cursor. */ +export const documentHistoryOperationSchemas = [ + z.strictObject({ + action: z.literal("read_document_history"), + document_id: z.uuid(), + organization_id: z.uuid().optional(), + before_revision: z.number().int().min(1).optional(), + limit: z.number().int().min(1).max(100).default(50), + }), +] as const; +export type DocumentHistoryOperation = z.infer<(typeof documentHistoryOperationSchemas)[number]>; diff --git a/lib/context/documentHistoryTypes.ts b/lib/context/documentHistoryTypes.ts new file mode 100644 index 000000000..de5b603e5 --- /dev/null +++ b/lib/context/documentHistoryTypes.ts @@ -0,0 +1,29 @@ +/** One immutable revision of a context document; the current pointer stays on the document. */ +export interface ContextDocumentVersion { + revision: number; + result_id: string | null; + change: "accepted" | "cleared"; + backfilled: boolean; + recorded_at: string; + result_status: string | null; + evidence_kind: string | null; + source_version_ids: string[]; + source_state: "live" | "withdrawn" | "removed" | null; +} +export interface ContextDocumentHistory { + document: { + id: string; + subject_id: string; + topic: string; + current_revision: number; + current_result_id: string | null; + updated_at: string; + }; + versions: ContextDocumentVersion[]; + has_more: boolean; + next_before: number | null; +} +/** Another workspace's document reads as not found; existence is never confirmed. */ +export type ContextDocumentHistoryResult = + | ({ state: "found" } & ContextDocumentHistory) + | { state: "not_found"; document: null; versions: []; has_more: false; next_before: null }; diff --git a/lib/context/processContextOperation.ts b/lib/context/processContextOperation.ts index 7b53ac0ad..24b194b54 100644 --- a/lib/context/processContextOperation.ts +++ b/lib/context/processContextOperation.ts @@ -1,5 +1,7 @@ import { releaseCaseOperationSchemas } from "./releaseCaseOperationSchemas"; import { processReleaseCaseOperation } from "./processReleaseCaseOperation"; +import { documentHistoryOperationSchemas } from "./documentHistorySchemas"; +import { processDocumentHistoryOperation } from "./processDocumentHistoryOperation"; import { createHash } from "node:crypto"; import { z } from "zod"; import { authorizeContextOwner } from "./authorizeContextOwner"; @@ -20,6 +22,7 @@ const briefFields = { export const contextOperationSchema = z.discriminatedUnion("action", [ ...releaseCaseOperationSchemas, + ...documentHistoryOperationSchemas, z.strictObject({ action: z.literal("save_brief"), ...briefFields, @@ -199,6 +202,8 @@ export async function processContextOperation( args.action === "review_release_case" ) return processReleaseCaseOperation(accountId, ownerId, args, deps.rpc); + if (args.action === "read_document_history") + return processDocumentHistoryOperation(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 }), diff --git a/lib/context/processDocumentHistoryOperation.ts b/lib/context/processDocumentHistoryOperation.ts new file mode 100644 index 000000000..23039554f --- /dev/null +++ b/lib/context/processDocumentHistoryOperation.ts @@ -0,0 +1,19 @@ +import type { DocumentHistoryOperation } from "./documentHistorySchemas"; +import type { ContextDocumentHistory, ContextDocumentHistoryResult } from "./documentHistoryTypes"; + +/** Read immutable document lineage after shared workspace authorization; a null read never leaks existence. */ +export async function processDocumentHistoryOperation( + ownerId: string, + args: DocumentHistoryOperation, + rpc: (name: string, params: Record) => Promise, +): Promise { + const history = (await rpc("read_context_document_history", { + p_owner: ownerId, + p_document: args.document_id, + p_before: args.before_revision ?? null, + p_limit: args.limit, + })) as ContextDocumentHistory | null; + if (!history) + return { state: "not_found", document: null, versions: [], has_more: false, next_before: null }; + return { state: "found", ...history }; +} diff --git a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts index 130005c52..9ed88ec66 100644 --- a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts +++ b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts @@ -37,7 +37,7 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => { ].sort(), ); for (const tool of tools) expect(tool.inputSchema.properties).not.toHaveProperty("account_id"); - expect(tools).toHaveLength(84); + expect(tools).toHaveLength(85); for (const operation of Object.values(contextToolOperations)) { const tool = tools.find(tool => tool.name === operation.name)!; expect(Object.keys(tool.inputSchema.properties ?? {}).length).toBeGreaterThan(0); diff --git a/lib/mcp/oauth/contextToolOperations.ts b/lib/mcp/oauth/contextToolOperations.ts index d729c64ca..681d0ab24 100644 --- a/lib/mcp/oauth/contextToolOperations.ts +++ b/lib/mcp/oauth/contextToolOperations.ts @@ -36,6 +36,12 @@ export const contextToolOperations = { description: "Read a previously saved music brief.", readOnly: true, }, + read_document_history: { + name: "read_music_context_document_history", + description: + "Read the immutable revision history of one saved context document: which result was current at each revision and whether its sources are still live. Lineage is not review or rights approval.", + readOnly: true, + }, plan: { name: "plan_music_context_research", description: "Preview research modules for saved music context without running them.", diff --git a/lib/supabase/context_requests/__tests__/documentHistoryContextRpc.test.ts b/lib/supabase/context_requests/__tests__/documentHistoryContextRpc.test.ts new file mode 100644 index 000000000..c8737c319 --- /dev/null +++ b/lib/supabase/context_requests/__tests__/documentHistoryContextRpc.test.ts @@ -0,0 +1,39 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { callContextRpc } from "../callContextRpc"; +import { processContextOperation } from "@/lib/context/processContextOperation"; + +const { rpc } = vi.hoisted(() => ({ rpc: vi.fn() })); +vi.mock("../../serverClient", () => ({ default: { rpc } })); +vi.mock("@/lib/context/authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); +const account = "00000000-0000-4000-8000-000000000001"; +const document = "00000000-0000-4000-8000-000000000002"; +const readHistory = () => + processContextOperation( + account, + { action: "read_document_history", document_id: document, before_revision: 3, limit: 10 }, + { + authorize: async () => ({ accountId: account, ownerId: account, organizationId: null }), + rpc: callContextRpc, + dispatch: vi.fn(), + }, + ); +beforeEach(() => vi.clearAllMocks()); +it("passes an authorized lineage read through the real database adapter", async () => { + const history = { document: { id: document }, versions: [], has_more: false, next_before: null }; + rpc.mockResolvedValue({ data: history, error: null }); + expect(await readHistory()).toEqual({ state: "found", ...history }); + expect(rpc).toHaveBeenCalledExactlyOnceWith("read_context_document_history", { + p_owner: account, + p_document: document, + p_before: 3, + p_limit: 10, + }); +}); +it("reports a null adapter read as not found and propagates storage failures", async () => { + rpc.mockResolvedValueOnce({ data: null, error: null }); + expect(await readHistory()).toMatchObject({ state: "not_found", document: null, versions: [] }); + rpc.mockResolvedValueOnce({ data: null, error: { message: "permission denied" } }); + await expect(readHistory()).rejects.toThrow( + "Context storage operation failed: permission denied", + ); +}); diff --git a/lib/supabase/context_requests/callContextRpc.ts b/lib/supabase/context_requests/callContextRpc.ts index dab3f941d..3829f0563 100644 --- a/lib/supabase/context_requests/callContextRpc.ts +++ b/lib/supabase/context_requests/callContextRpc.ts @@ -61,6 +61,7 @@ export async function callContextRpc( "fail_context_request", "read_context_documents", "resolve_context_spotify_release", + "read_context_document_history", ]; if (!allowed.includes(name)) throw new Error("Unknown context operation"); const rpc = supabase.rpc.bind(supabase) as unknown as (