diff --git a/lib/context/README.md b/lib/context/README.md index 3771d8eca..364633d50 100644 --- a/lib/context/README.md +++ b/lib/context/README.md @@ -12,6 +12,7 @@ Part of recoupable/app#2116. Spotify metadata now flows through shared authentic - `list_executions`: provide a saved `request_id` and optional organization scope. Returns that request's execution IDs, policy versions, creation times, and planned/saved node counts; open an ID with `read_execution`. Requires database PR77. - `list_catalog_members`: provide a saved catalog `request_id`, its catalog `subject_id`, optional organization scope, `after_isrc` cursor and `limit` (1–100). Returns an owner-checked page of ISRCs from the current catalog membership. Membership does not assert roster, artist identity or rights. This is a read-only expansion primitive; it does not create recording subjects or run enrichment. Requires database PR77. - `ingest_release`: submit a Spotify album URL, including a single's album container, to save an unverified release locator. `verify_release` is a separate, default-off action that checks Spotify album metadata in a dedicated workflow. With database PR77's release-slot migration, each newly saved result links observed Spotify track IDs to that release within the selected workspace. These links preserve source result and slot position; they do not create recording identities, assert ISRCs, or verify ownership. Reused results from another request do not create new slot rows automatically. +- `ingest_video`: submit a single YouTube music-video URL (`youtu.be`, `watch?v=`, `shorts` or `embed`) with an idempotency key to save an explicitly unresolved private video locator in the selected workspace. The saved request is `partial` with one `video` subject and distinct gaps: video metadata `uncollected`, uploader attribution `unresolved` (the uploading channel is never assumed to be the artist, a performer or a credited artist), recording match `unresolved`, captions `uncollected` (no lyrics are inferred), media version `unknown` and video narrative `unavailable`. It creates no artist, recording, roster or lyrics rows, attaches nothing to a song or artist brand document, fetches nothing and spends nothing; a different workspace saving the same video gets its own request and document. Spotify tracks still use `ingest`; `plan` rejects a video entry as unsupported. Metadata verification, captions/language retention, recording and artist attribution review, and artist-research reuse are separate, default-off follow-ups. Requires the companion database migration `20261010213100_context_video_entry.sql`. - `ingest_songwriter_name`: submit a name and idempotency key in the selected workspace. The saved name is private customer evidence and an unresolved candidate, never a confirmed person, artist, composition, credit, or rights claim. `plan` shows songwriter research as unimplemented and does not dispatch it. Requires the companion database migration in PR77. - `ingest_company_name`: submit a business name and idempotency key in the selected workspace. The saved name is private customer evidence, not a verified business identity, organization membership, roster link or ownership claim. `plan` shows company research as unimplemented and does not dispatch it. Requires the companion database migration in PR77. - `ingest_campaign_brief`: submit a private brief with a name and goal, plus optional audience and start/end dates. The saved brief does not link promoted artists, songs, releases, companies or assets; those relationships need separate verification. `plan` shows campaign context collection as unimplemented and does not dispatch it. This is separate from Recoup's legacy funnel `campaigns` table and requires the companion database migration in PR77. diff --git a/lib/context/__tests__/videoLocatorBoundaries.test.ts b/lib/context/__tests__/videoLocatorBoundaries.test.ts new file mode 100644 index 000000000..b1f4b7f99 --- /dev/null +++ b/lib/context/__tests__/videoLocatorBoundaries.test.ts @@ -0,0 +1,89 @@ +import { expect, it, vi } from "vitest"; +import { compileContextBrief } from "../compileContextBrief"; +import { planStoredContextModules } from "../planning/planStoredContextModules"; +import type { ContextBriefDocument } from "../selectContextDocuments"; + +const { authorize, rpc, targets } = vi.hoisted(() => ({ + authorize: vi.fn(), + rpc: vi.fn(), + targets: vi.fn(), +})); +vi.mock("@/lib/context/authorizeContextOwner", () => ({ authorizeContextOwner: authorize })); +vi.mock("@/lib/supabase/context_requests/callContextRpc", () => ({ callContextRpc: rpc })); +vi.mock("@/lib/supabase/context_requests/listContextRequestTargets", () => ({ + listContextRequestTargets: targets, +})); + +const actor = "00000000-0000-4000-8000-000000000001"; +const owner = "00000000-0000-4000-8000-000000000002"; +const songRequest = "00000000-0000-4000-8000-000000000003"; +const videoRequest = "00000000-0000-4000-8000-000000000004"; +const recording = "00000000-0000-4000-8000-000000000005"; +const video = "00000000-0000-4000-8000-000000000006"; + +const document = ( + id: string, + subjectId: string, + topic: string, + evidenceKind: ContextBriefDocument["evidenceKind"], + text: string, +): ContextBriefDocument => ({ + id, + ownerId: owner, + subjectId, + topic, + version: 1, + status: "accepted", + evidenceKind, + text, + sourceVersionIds: [`${id}-source`], + coverage: "partial", +}); + +it("does not plan or dispatch collection for a saved video locator", async () => { + authorize.mockResolvedValue({ ownerId: owner }); + rpc.mockResolvedValue({ + id: videoRequest, + owner_id: owner, + status: "partial", + input: { + kind: "video", + url: "https://www.youtube.com/watch?v=AbCdEfGhI_1", + videoId: "AbCdEfGhI_1", + identityConfirmed: false, + }, + }); + await expect(planStoredContextModules(actor, owner, videoRequest)).rejects.toThrow( + "Unsupported saved context entry", + ); + expect(targets).not.toHaveBeenCalled(); +}); + +it.each(["creative_direction", "playlist_pitch", "company_onboarding"] as const)( + "keeps a video locator out of song and artist evidence in a %s brief", + purpose => { + const lyrics = document("lyrics", recording, "lyrics", "observation", "Observed song lyrics."); + const locator = document( + "locator", + video, + "video_locator", + "customer_assertion", + "Submitted video URL; uploader, recording match and captions unresolved.", + ); + const brief = compileContextBrief({ + ownerId: owner, + requests: [ + { id: songRequest, subjectIds: [recording] }, + { id: videoRequest, subjectIds: [video] }, + ], + documents: [lyrics, locator], + purpose, + maxCharacters: 8000, + }); + expect(brief.documents.map(doc => doc.topic)).not.toContain("video_locator"); + expect(brief.text).not.toContain("Submitted video URL"); + expect(brief.input_manifest.excludedTopics).toContain("video_locator"); + const videoCoverage = brief.request_coverage.find(item => item.requestId === videoRequest); + expect(videoCoverage?.readiness).toBe("partial"); + }, +); diff --git a/lib/context/__tests__/videoOperation.test.ts b/lib/context/__tests__/videoOperation.test.ts new file mode 100644 index 000000000..0729e5619 --- /dev/null +++ b/lib/context/__tests__/videoOperation.test.ts @@ -0,0 +1,151 @@ +import { expect, it, vi } from "vitest"; +import { parseContextVideoUrl } from "../parseContextVideoUrl"; +import { processContextOperation } from "../processContextOperation"; +vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); + +const account = "00000000-0000-4000-8000-000000000001"; +const workspace = "00000000-0000-4000-8000-000000000002"; +const video = "AbCdEfGhI_1"; +const canonical = `https://www.youtube.com/watch?v=${video}`; +const track = "https://open.spotify.com/track/2ay96C6SLNv9urvXKD3ecB"; +const notOneVideo = [ + track, + "https://open.spotify.com/album/2ay96C6SLNv9urvXKD3ecB", + "https://www.youtube.com/playlist?list=PLexample", + `https://www.youtube.com/watch?v=${video}&v=OtherIdAB_2`, + `http://www.youtube.com/watch?v=${video}`, + `https://www.youtube.com.evil.test/watch?v=${video}`, + `https://user:secret@youtu.be/${video}`, + "https://www.youtube.com/channel/UCexample", +]; + +it.each([ + `https://youtu.be/${video}?t=4`, + `https://www.youtube.com/watch?v=${video}&si=sharing`, + `https://youtube.com/shorts/${video}`, + `https://m.youtube.com/watch?v=${video}`, +])("canonicalizes one video locator to its watch URL: %s", url => { + expect(parseContextVideoUrl(url)).toEqual({ id: video, url: canonical }); +}); + +it.each(notOneVideo)("rejects anything that is not exactly one YouTube video: %s", url => { + expect(() => parseContextVideoUrl(url)).toThrow(); +}); + +it("points a Spotify track at ingest instead of silently accepting it as a video", () => { + expect(() => parseContextVideoUrl(track)).toThrow("Spotify tracks use ingest"); +}); + +it("saves a video locator in the selected workspace without dispatching any worker", async () => { + const saved = { + id: "request", + status: "partial", + input: { kind: "video", url: canonical, videoId: video, identityConfirmed: false }, + }; + const rpc = vi.fn(async () => saved); + const dispatch = vi.fn(); + const dispatchRelease = vi.fn(); + const authorize = vi.fn(async () => ({ + accountId: account, + ownerId: workspace, + organizationId: workspace, + })); + const result = await processContextOperation( + account, + { + action: "ingest_video", + url: `https://youtu.be/${video}?t=4`, + organization_id: workspace, + idempotency_key: "video-test", + }, + { authorize, rpc, dispatch, dispatchRelease }, + ); + expect(authorize).toHaveBeenCalledWith(account, workspace); + expect(rpc).toHaveBeenCalledTimes(1); + expect(rpc).toHaveBeenCalledWith("create_context_video_request", { + p_owner: workspace, + p_actor: account, + p_video: video, + p_key: "video-test", + }); + expect(dispatch).not.toHaveBeenCalled(); + expect(dispatchRelease).not.toHaveBeenCalled(); + expect("request" in result ? result.request : null).toEqual(saved); +}); + +it("uses the personal workspace when no organization is selected", async () => { + const rpc = vi.fn(async () => ({ id: "request", status: "partial" })); + await processContextOperation( + account, + { action: "ingest_video", url: canonical, idempotency_key: "personal" }, + { + authorize: async () => ({ accountId: account, ownerId: account, organizationId: null }), + rpc, + dispatch: vi.fn(), + }, + ); + expect(rpc).toHaveBeenCalledWith("create_context_video_request", { + p_owner: account, + p_actor: account, + p_video: video, + p_key: "personal", + }); +}); + +it("rejects a track, playlist or lookalike host before authorization or storage", async () => { + const authorize = vi.fn(); + const rpc = vi.fn(); + const dispatch = vi.fn(); + for (const url of notOneVideo) + await expect( + processContextOperation( + account, + { action: "ingest_video", url, idempotency_key: "bad" }, + { authorize, rpc, dispatch }, + ), + ).rejects.toMatchObject({ + issues: [ + { + code: "custom", + path: ["url"], + message: "Use a single YouTube video URL; Spotify tracks use ingest", + }, + ], + }); + expect(authorize).not.toHaveBeenCalled(); + expect(rpc).not.toHaveBeenCalled(); + expect(dispatch).not.toHaveBeenCalled(); +}); + +it("does not accept research topics or direction that would imply collection", async () => { + const rpc = vi.fn(); + for (const extra of [{ topics: ["lyrics"] }, { direction: "transcribe the lyrics" }]) + await expect( + processContextOperation( + account, + { action: "ingest_video", url: canonical, idempotency_key: "strict", ...extra }, + { authorize: vi.fn(), rpc, dispatch: vi.fn() }, + ), + ).rejects.toMatchObject({ + issues: [{ code: "unrecognized_keys", keys: Object.keys(extra), path: [] }], + }); + expect(rpc).not.toHaveBeenCalled(); +}); + +it("keeps track ingest Spotify-only and names ingest_video for a YouTube URL", async () => { + const rpc = vi.fn(); + const dispatch = vi.fn(); + await expect( + processContextOperation( + account, + { action: "ingest", url: canonical, idempotency_key: "track-path" }, + { + authorize: async () => ({ accountId: account, ownerId: account, organizationId: null }), + rpc, + dispatch, + }, + ), + ).rejects.toThrow("ingest_video"); + expect(rpc).not.toHaveBeenCalled(); + expect(dispatch).not.toHaveBeenCalled(); +}); diff --git a/lib/context/parseContextVideoUrl.ts b/lib/context/parseContextVideoUrl.ts new file mode 100644 index 000000000..5581b28d9 --- /dev/null +++ b/lib/context/parseContextVideoUrl.ts @@ -0,0 +1,9 @@ +import { parseContextUrl } from "./parseContextUrl"; + +/** Parse one submitted YouTube video locator without routing it through Spotify track ingestion. */ +export function parseContextVideoUrl(input: string) { + const resource = parseContextUrl(input); + if (resource.provider !== "youtube" || resource.kind !== "video") + throw new Error("Use a single YouTube video URL; Spotify tracks use ingest"); + return { id: resource.id, url: resource.url }; +} diff --git a/lib/context/processContextOperation.ts b/lib/context/processContextOperation.ts index 7b53ac0ad..406bff537 100644 --- a/lib/context/processContextOperation.ts +++ b/lib/context/processContextOperation.ts @@ -1,5 +1,7 @@ import { releaseCaseOperationSchemas } from "./releaseCaseOperationSchemas"; import { processReleaseCaseOperation } from "./processReleaseCaseOperation"; +import { videoOperationSchemas } from "./videoOperationSchemas"; +import { processVideoOperation } from "./processVideoOperation"; 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, + ...videoOperationSchemas, 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 === "ingest_video") + return processVideoOperation(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 }), @@ -430,7 +435,9 @@ export async function processContextOperation( if (args.action === "ingest") { const resource = parseContextUrl(args.url); if (resource.provider !== "spotify") - throw new Error("Only Spotify tracks are enabled in this pilot"); + throw new Error( + "Only Spotify tracks are enabled for ingest; use ingest_video for a YouTube music video", + ); const normalized = { url: resource.url, topics: [ diff --git a/lib/context/processVideoOperation.ts b/lib/context/processVideoOperation.ts new file mode 100644 index 000000000..d126594d4 --- /dev/null +++ b/lib/context/processVideoOperation.ts @@ -0,0 +1,24 @@ +import type { ContextRequestRecord } from "./runContextRequest"; +import { parseContextVideoUrl } from "./parseContextVideoUrl"; +import type { VideoOperation } from "./videoOperationSchemas"; + +export type ContextVideoRequestRecord = Omit & { + input: { kind: "video"; url: string; videoId: string; identityConfirmed: false }; +}; + +/** Save one YouTube video locator in the selected workspace after shared authorization; nothing is fetched, inferred or dispatched. */ +export async function processVideoOperation( + accountId: string, + ownerId: string, + args: VideoOperation, + rpc: (name: string, params: Record) => Promise, +) { + const video = parseContextVideoUrl(args.url); + const request = (await rpc("create_context_video_request", { + p_owner: ownerId, + p_actor: accountId, + p_video: video.id, + p_key: args.idempotency_key, + })) as ContextVideoRequestRecord; + return { request }; +} diff --git a/lib/context/videoOperationSchemas.ts b/lib/context/videoOperationSchemas.ts new file mode 100644 index 000000000..f677aa6f7 --- /dev/null +++ b/lib/context/videoOperationSchemas.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; +import { contextIngestSchema } from "./schema"; +import { parseContextVideoUrl } from "./parseContextVideoUrl"; + +/** A video locator accepts no topics or direction: nothing is collected or interpreted when it is saved. */ +export const videoOperationSchemas = [ + z.strictObject({ + action: z.literal("ingest_video"), + url: z + .url() + .max(2048) + .refine(value => { + try { + parseContextVideoUrl(value); + return true; + } catch { + return false; + } + }, "Use a single YouTube video URL; Spotify tracks use ingest"), + organization_id: z.uuid().optional(), + idempotency_key: contextIngestSchema.shape.idempotency_key, + }), +] as const; +export type VideoOperation = z.infer<(typeof videoOperationSchemas)[number]>; 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..41b81f642 100644 --- a/lib/mcp/oauth/contextToolOperations.ts +++ b/lib/mcp/oauth/contextToolOperations.ts @@ -126,6 +126,12 @@ export const contextToolOperations = { description: "Create a context request from a Spotify release URL.", readOnly: false, }, + ingest_video: { + name: "import_music_video_context", + description: + "Save one YouTube music-video URL as an unresolved private locator. The uploading channel is not treated as the artist; no captions, lyrics, recording match or artist research are collected or inferred.", + readOnly: false, + }, verify_release: { name: "verify_music_release", description: "Start provider verification for a saved release context request.", diff --git a/lib/mcp/tools/context/registerContextTool.ts b/lib/mcp/tools/context/registerContextTool.ts index 5b3af1711..1c6a27c14 100644 --- a/lib/mcp/tools/context/registerContextTool.ts +++ b/lib/mcp/tools/context/registerContextTool.ts @@ -17,7 +17,7 @@ export function registerContextTool(server: McpServer) { "context", { description: - "Use list_release_cases and read_release_case to inspect saved release metadata without provider calls. review_release_case records metadata review only (reviewed or needs_changes), requires the exact current fingerprint and an idempotency key; it never approves rights or distribution. read_release_case_review retrieves an authorized historical receipt, withholding withdrawn evidence. Save reusable context from a Spotify track URL, read request progress, or compile a creative-direction/playlist-pitch evidence brief. For brief or save_brief, use request_id and optional additional_request_ids from the same workspace to combine saved song context without recollection. save_brief also requires idempotency_key and freezes the server-compiled output; use read_brief with brief_id for exact historical output. An unavailable snapshot withholds withdrawn evidence. Briefs include bounded text, per-request coverage and an input-version manifest. Inspect gaps; audio, lyrics, artwork analysis and research may be unavailable. Never treat partial context as full song understanding.", + "Use list_release_cases and read_release_case to inspect saved release metadata without provider calls. review_release_case records metadata review only (reviewed or needs_changes), requires the exact current fingerprint and an idempotency key; it never approves rights or distribution. read_release_case_review retrieves an authorized historical receipt, withholding withdrawn evidence. Save reusable context from a Spotify track URL, read request progress, or compile a creative-direction/playlist-pitch evidence brief. ingest_video saves one YouTube music-video URL as an unresolved private locator: the uploading channel is never assumed to be the artist, and no captions, lyrics, recording match or artist research are collected or inferred. For brief or save_brief, use request_id and optional additional_request_ids from the same workspace to combine saved song context without recollection. save_brief also requires idempotency_key and freezes the server-compiled output; use read_brief with brief_id for exact historical output. An unavailable snapshot withholds withdrawn evidence. Briefs include bounded text, per-request coverage and an input-version manifest. Inspect gaps; audio, lyrics, artwork analysis and research may be unavailable. Never treat partial context as full song understanding.", inputSchema: contextOperationSchema, }, async (args, extra) => { diff --git a/lib/supabase/context_requests/callContextRpc.ts b/lib/supabase/context_requests/callContextRpc.ts index dab3f941d..4b66a3cd4 100644 --- a/lib/supabase/context_requests/callContextRpc.ts +++ b/lib/supabase/context_requests/callContextRpc.ts @@ -29,6 +29,7 @@ export async function callContextRpc( "create_context_campaign_brief_request", "create_context_supporting_text_request", "create_context_release_request", + "create_context_video_request", "read_context_request", "list_context_request_targets", "list_context_artist_request_target",