diff --git a/lib/context/README.md b/lib/context/README.md index 3771d8eca..a25f04b00 100644 --- a/lib/context/README.md +++ b/lib/context/README.md @@ -14,7 +14,7 @@ Part of recoupable/app#2116. Spotify metadata now flows through shared authentic - `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_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. +- `ingest_campaign_brief`: submit a private brief with a name and goal, plus optional audience, start/end dates, up to ten distinct `channels` names (1–60 characters, such as `X` or `radio`) and up to twenty distinct `promoted` entries. Each promoted entry is a `{request_id, subject_id}` pair for an artist, recording, release or catalog subject the selected workspace already saved through a completed or partial Context request; the database verifies the pair and stores it as a `promoted_candidate` with `ownership_verified=false`. Promoted entries accept only those ID pairs, never URLs or files, and keys such as `promoted_url`, `file_path` or `assets` are rejected, so save promoted records first with `ingest`, `ingest_artist`, `ingest_release` or `ingest_catalog`. Channel names that look like links are rejected: scheme URLs, URI schemes such as `mailto:` or `spotify:`, `www.` hosts, and absolute, home or drive paths. This guards against obvious links and is not a complete URL or file detector (a bare `example.com/release` or `plan.pdf` passes as a name); channel names are never fetched or linked. Goal and audience stay free text. Only artist, recording, release and catalog subjects can be promoted targets (video, campaign, company, songwriter and material subjects are rejected), and an unverifiable target rejects the whole brief. Retrying a saved brief with the same idempotency key returns the stored request even if a target request was cancelled later; a new key re-checks every target. Briefs without channels or promoted keep the `campaign-brief-v1` fingerprint so earlier saved briefs replay unchanged; linked briefs use `campaign-brief-v2`. Output gaps stay explicit: promoted ownership and rights are not verified, supplied assets are not inventoried, and an unlinked brief says so. `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 migrations in PR77 and `20261010213800_context_campaign_brief_promoted_links.sql`. - `ingest_supporting_text`: submit a title and up to 20,000 characters of text to the selected workspace. The request retains a content fingerprint; the text itself is private customer evidence and is treated as data, not instructions. It is not linked to an artist, song, release, campaign or company. `plan` shows material extraction as unimplemented and does not dispatch it. File, image and audio intake need separate storage and access checks; the existing `files` table requires an artist account. Requires the companion database migration in PR77. - `list_release_tracks`: provide the saved release `request_id` and `subject_id`, optional organization scope, `after_slot` cursor and `limit` (1–100). Returns the selected workspace's track positions from the **current result for that request**, with Spotify track IDs and source-result references. `not_collected` means no current valid result; `needs_reconciliation` means the result exists but its position rows are incomplete. The read never fetches Spotify or repairs rows. Requires database PR77's release-track read migration. - `verify_release_tracks`: submit the saved release `request_id` and `subject_id`, plus optional organization scope, to queue ISRC observation lookups for its current Spotify track positions. This authenticated action is **off by default** (`CONTEXT_SPOTIFY_RELEASE_TRACK_ISRC_ENABLED=true`). It accepts only 1–100 fully materialized positions, checks workspace access and source stability, then uses a dedicated workflow step and a source-specific saved execution node to claim one attempt before fetching and save successful provider responses with source lineage. The execution can be found with `list_executions` and inspected with `read_execution`; a claimed node without an outcome needs reconciliation. Missing ISRCs and failed lookups remain explicit gaps. A prior or uncertain attempt is never fetched again automatically. This path is locally fixture-tested, not live-verified or deployed. diff --git a/lib/context/__tests__/campaignBriefOperation.test.ts b/lib/context/__tests__/campaignBriefOperation.test.ts index cd10c87fe..c4f638da6 100644 --- a/lib/context/__tests__/campaignBriefOperation.test.ts +++ b/lib/context/__tests__/campaignBriefOperation.test.ts @@ -60,3 +60,80 @@ it("rejects reversed dates and invented campaign fields before storage", async ( expect(authorize).not.toHaveBeenCalled(); expect(rpc).not.toHaveBeenCalled(); }); + +const promoted = [ + { + request_id: "00000000-0000-4000-8000-000000000011", + subject_id: "00000000-0000-4000-8000-000000000012", + }, +]; + +it("forwards channels and already-saved promoted subjects to the database without dispatch", async () => { + const rpc = vi.fn(async () => ({ id: "request", status: "partial" })); + const dispatch = vi.fn(); + const authorize = vi.fn(async () => ({ + accountId: actor, + ownerId: workspace, + organizationId: workspace, + })); + const linked = { ...brief, channels: ["Short-form video", "Radio"], promoted }; + await processContextOperation( + actor, + { + action: "ingest_campaign_brief", + brief: linked, + organization_id: workspace, + idempotency_key: "campaign-links", + }, + { authorize, rpc, dispatch }, + ); + expect(rpc).toHaveBeenCalledWith("create_context_campaign_brief_request", { + p_owner: workspace, + p_actor: actor, + p_brief: linked, + p_key: "campaign-links", + }); + expect(dispatch).not.toHaveBeenCalled(); +}); + +it("rejects raw links, file references and ambiguous promoted entries before authorization", async () => { + const authorize = vi.fn(); + const rpc = vi.fn(); + for (const invalid of [ + { ...brief, promoted_url: "https://example.com/release" }, + { ...brief, promoted: ["https://example.com/release"] }, + { ...brief, promoted: [{ request_id: "https://example.com/release", subject_id: workspace }] }, + { ...brief, promoted: [{ ...promoted[0], url: "https://example.com/release" }] }, + { ...brief, promoted: [promoted[0], promoted[0]] }, + { ...brief, file_path: "/private/artwork.png" }, + { ...brief, channels: ["file:plan.pdf"] }, + { ...brief, channels: ["TikTok", "tiktok"] }, + { ...brief, channels: Array.from({ length: 11 }, (_, i) => `channel ${i}`) }, + ]) { + await expect( + processContextOperation( + actor, + { action: "ingest_campaign_brief", brief: invalid, idempotency_key: "campaign-links" }, + { authorize, rpc, dispatch: vi.fn() }, + ), + ).rejects.toThrow(); + } + expect(authorize).not.toHaveBeenCalled(); + expect(rpc).not.toHaveBeenCalled(); +}); + +it("forwards a legacy brief without link fields unchanged", async () => { + const rpc = vi.fn(async () => ({ id: "request", status: "partial" })); + const authorize = vi.fn(async () => ({ + accountId: actor, + ownerId: workspace, + organizationId: workspace, + })); + await processContextOperation( + actor, + { action: "ingest_campaign_brief", brief, idempotency_key: "campaign-legacy" }, + { authorize, rpc, dispatch: vi.fn() }, + ); + const call = rpc.mock.calls[0] as unknown as [string, { p_brief: Record }]; + expect(Object.keys(call[1].p_brief).sort()).toEqual(Object.keys(brief).sort()); +}); diff --git a/lib/context/__tests__/campaignBriefSchema.test.ts b/lib/context/__tests__/campaignBriefSchema.test.ts new file mode 100644 index 000000000..3484c729a --- /dev/null +++ b/lib/context/__tests__/campaignBriefSchema.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "vitest"; +import { campaignBriefSchema } from "../campaignBriefSchema"; + +// Hex letters make the upper-case duplicate check below meaningful. +const requestId = "00000000-0000-4000-a000-0000000000aa"; +const subjectId = "00000000-0000-4000-a000-0000000000bb"; +const brief = { name: "Release campaign", goal: "Promote the single" }; + +function failure(input: unknown) { + const parsed = campaignBriefSchema.safeParse(input); + if (parsed.success) throw new Error(`Expected rejection: ${JSON.stringify(input)}`); + return parsed.error.issues.map(issue => `${issue.path.join(".")}: ${issue.message}`).join("\n"); +} + +describe("campaignBriefSchema", () => { + it("accepts channels and already-saved promoted subjects, keeping the brief shape", () => { + const parsed = campaignBriefSchema.parse({ + ...brief, + audience: "Existing listeners", + start_date: "2026-10-01", + end_date: "2026-10-31", + channels: [" Short-form video ", "Radio", "X"], + promoted: [{ request_id: requestId, subject_id: subjectId }], + }); + expect(parsed.channels).toEqual(["Short-form video", "Radio", "X"]); + expect(parsed.promoted).toEqual([{ request_id: requestId, subject_id: subjectId }]); + }); + + it("leaves a legacy brief without channels or promoted keys untouched", () => { + const parsed = campaignBriefSchema.parse(brief); + expect(Object.keys(parsed)).toEqual(["name", "goal"]); + expect(campaignBriefSchema.safeParse({ ...brief, channels: [], promoted: [] }).success).toBe( + true, + ); + }); + + it("rejects ambiguous links instead of guessing what is promoted", () => { + expect(failure({ ...brief, promoted_url: "https://example.com/release" })).toMatch( + /promoted_url/, + ); + expect(failure({ ...brief, promoted: ["https://example.com/release"] })).toMatch(/promoted/); + expect(failure({ ...brief, promoted: [{ url: "https://example.com/release" }] })).toMatch( + /request_id|subject_id|url/, + ); + expect( + failure({ + ...brief, + promoted: [{ request_id: requestId, subject_id: subjectId, url: "https://example.com" }], + }), + ).toMatch(/url/); + expect( + failure({ ...brief, promoted: [{ request_id: "spotify:album:1", subject_id: subjectId }] }), + ).toMatch(/request_id/); + expect(failure({ ...brief, channels: ["https://example.com/channel"] })).toMatch( + /Channels are names/, + ); + expect(failure({ ...brief, channels: ["www.example.com"] })).toMatch(/Channels are names/); + expect(failure({ ...brief, channels: ["mailto:team@example.com"] })).toMatch( + /Channels are names/, + ); + expect(failure({ ...brief, channels: ["spotify:album:example"] })).toMatch( + /Channels are names/, + ); + }); + + it("rejects private file references; material intake is a separate action", () => { + expect(failure({ ...brief, file_path: "/private/artwork.png" })).toMatch(/file_path/); + expect(failure({ ...brief, assets: ["artwork.png"] })).toMatch(/assets/); + expect(failure({ ...brief, channels: ["/private/plan.pdf"] })).toMatch(/Channels are names/); + expect(failure({ ...brief, channels: ["file:plan.pdf"] })).toMatch(/Channels are names/); + expect(failure({ ...brief, channels: ["C:\\plans\\brief.pdf"] })).toMatch(/Channels are names/); + }); + + it("catches obvious links only, as documented; channel names are never fetched or linked", () => { + const parsed = campaignBriefSchema.parse({ + ...brief, + channels: ["example.com/release", "plan.pdf"], + }); + expect(parsed.channels).toEqual(["example.com/release", "plan.pdf"]); + expect(parsed.promoted).toBeUndefined(); + }); + + it("requires distinct bounded channels and promoted pairs", () => { + expect(failure({ ...brief, channels: ["TikTok", "tiktok "] })).toMatch(/distinct/); + expect( + failure({ ...brief, channels: Array.from({ length: 11 }, (_, i) => `channel ${i}`) }), + ).toMatch(/channels/); + expect(failure({ ...brief, channels: [" "] })).toMatch(/channels/); + // The database collapses inner whitespace before comparing, so the boundary must agree. + expect(failure({ ...brief, channels: ["Short form video", "short form video"] })).toMatch( + /distinct/, + ); + expect(failure({ ...brief, channels: ["Radio\tpress"] })).toMatch(/control characters/); + expect( + failure({ + ...brief, + promoted: [ + { request_id: requestId, subject_id: subjectId }, + { request_id: requestId.toUpperCase(), subject_id: subjectId }, + ], + }), + ).toMatch(/distinct/); + expect( + failure({ + ...brief, + promoted: Array.from({ length: 21 }, (_, i) => ({ + request_id: requestId, + subject_id: `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`, + })), + }), + ).toMatch(/promoted/); + }); + + it("keeps the date ordering rule", () => { + expect(failure({ ...brief, start_date: "2026-10-31", end_date: "2026-10-01" })).toMatch( + /end date/, + ); + }); +}); diff --git a/lib/context/campaignBriefSchema.ts b/lib/context/campaignBriefSchema.ts new file mode 100644 index 000000000..d503dcd9f --- /dev/null +++ b/lib/context/campaignBriefSchema.ts @@ -0,0 +1,59 @@ +import { z } from "zod"; + +// Obvious links only: scheme URLs, URI schemes (mailto:, spotify:, file:), www. hosts, and absolute, home or +// drive paths. Not a full URL or file detector; channel names are never fetched. Matches the database check. +const CHANNEL_LINK_PATTERN = /:\/\/|^(?:www\.|\/|\\|~\/)|^[a-z][a-z0-9+.-]*:\S/i; +const CHANNEL_MESSAGE = + "Channels are names, not links or files; save promoted records first and reference them in promoted"; +// Matches the database: control characters are rejected and inner whitespace is collapsed before comparing. +const CONTROL_CHARACTER_PATTERN = /\p{Cc}/u; +const channelKey = (value: string) => value.replace(/\s+/g, " ").toLowerCase(); + +const promotedSubjectSchema = z.strictObject({ + request_id: z.uuid(), + subject_id: z.uuid(), +}); + +/** + * Structured campaign brief accepted by `ingest_campaign_brief`. + * Promoted entries are only `{request_id, subject_id}` pairs the workspace already saved; the database + * verifies each pair. Channel names that look like links are rejected here, before authorization. + */ +export const campaignBriefSchema = z + .strictObject({ + name: z.string().trim().min(2).max(200), + goal: z.string().trim().min(2).max(2000), + audience: z.string().trim().max(500).optional(), + start_date: z.iso.date().optional(), + end_date: z.iso.date().optional(), + channels: z + .array( + z + .string() + .trim() + .min(1) + .max(60) + .refine(value => !CONTROL_CHARACTER_PATTERN.test(value), { + message: "Channel names must not contain control characters", + }) + .refine(value => !CHANNEL_LINK_PATTERN.test(value), { message: CHANNEL_MESSAGE }), + ) + .max(10) + .refine(values => new Set(values.map(channelKey)).size === values.length, { + message: "Campaign channels must be distinct", + }) + .optional(), + promoted: z + .array(promotedSubjectSchema) + .max(20) + .refine( + values => + new Set(values.map(value => `${value.request_id}:${value.subject_id}`.toLowerCase())) + .size === values.length, + { message: "Promoted subjects must be distinct" }, + ) + .optional(), + }) + .refine(value => !value.start_date || !value.end_date || value.end_date >= value.start_date, { + message: "Campaign end date must not precede start date", + }); diff --git a/lib/context/processContextOperation.ts b/lib/context/processContextOperation.ts index 7b53ac0ad..501c51823 100644 --- a/lib/context/processContextOperation.ts +++ b/lib/context/processContextOperation.ts @@ -4,6 +4,7 @@ import { createHash } from "node:crypto"; import { z } from "zod"; import { authorizeContextOwner } from "./authorizeContextOwner"; import { contextIngestSchema } from "./schema"; +import { campaignBriefSchema } from "./campaignBriefSchema"; import { parseContextUrl } from "./parseContextUrl"; import { parseContextReleaseUrl } from "./parseContextReleaseUrl"; import type { ContextBriefDocument } from "./selectContextDocuments"; @@ -126,17 +127,7 @@ export const contextOperationSchema = z.discriminatedUnion("action", [ }), z.strictObject({ action: z.literal("ingest_campaign_brief"), - brief: z - .strictObject({ - name: z.string().trim().min(2).max(200), - goal: z.string().trim().min(2).max(2000), - audience: z.string().trim().max(500).optional(), - start_date: z.iso.date().optional(), - end_date: z.iso.date().optional(), - }) - .refine(value => !value.start_date || !value.end_date || value.end_date >= value.start_date, { - message: "Campaign end date must not precede start date", - }), + brief: campaignBriefSchema, organization_id: z.uuid().optional(), idempotency_key: contextIngestSchema.shape.idempotency_key, }), diff --git a/lib/mcp/oauth/contextToolOperations.ts b/lib/mcp/oauth/contextToolOperations.ts index d729c64ca..fa1fc5a7b 100644 --- a/lib/mcp/oauth/contextToolOperations.ts +++ b/lib/mcp/oauth/contextToolOperations.ts @@ -112,7 +112,8 @@ export const contextToolOperations = { }, ingest_campaign_brief: { name: "import_music_campaign_brief", - description: "Save a structured music campaign brief as context.", + description: + "Save a structured music campaign brief as context, optionally naming channels and already-saved workspace subjects being promoted. Links are candidates, not ownership or rights; promoted entries take only saved request and subject IDs, and channel names that look like links or paths are rejected.", readOnly: false, }, ingest_supporting_text: {