From eb1693253118b9f49d9c2b2ade19c9130cc1ee5e Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:25:43 -0400 Subject: [PATCH 1/4] Accept campaign channels and promoted subject links Move the ingest_campaign_brief brief shape into campaignBriefSchema and add optional channels (up to ten distinct names) and promoted (up to twenty distinct {request_id, subject_id} pairs). The schema rejects raw URLs, file paths, asset keys, non-UUID identifiers and duplicates before authorization or any database call, so ambiguous links and private file references never reach storage; the database verifies each pair against requests the workspace already saved and keeps them as unverified promoted candidates. The RPC call, its allow-list and dispatch behaviour are unchanged, and a brief without the new fields is forwarded exactly as before. The MCP description and README state that links are candidates, not ownership or rights. Refs recoupable/app#2138 (child of recoupable/app#2116). Co-Authored-By: Claude Fable 5.1 --- lib/context/README.md | 2 +- .../__tests__/campaignBriefOperation.test.ts | 77 +++++++++++++++ .../__tests__/campaignBriefSchema.test.ts | 97 +++++++++++++++++++ lib/context/campaignBriefSchema.ts | 53 ++++++++++ lib/context/processContextOperation.ts | 13 +-- lib/mcp/oauth/contextToolOperations.ts | 3 +- 6 files changed, 232 insertions(+), 13 deletions(-) create mode 100644 lib/context/__tests__/campaignBriefSchema.test.ts create mode 100644 lib/context/campaignBriefSchema.ts diff --git a/lib/context/README.md b/lib/context/README.md index 3771d8eca..613af844c 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 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`. Raw URLs, file paths and asset references are rejected in the brief, so save promoted records first with `ingest`, `ingest_artist`, `ingest_release` or `ingest_catalog`. Campaign, company, songwriter and material subjects cannot be promoted targets, and an unverifiable target rejects the whole brief. 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..811cdb0ce --- /dev/null +++ b/lib/context/__tests__/campaignBriefSchema.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from "vitest"; +import { campaignBriefSchema } from "../campaignBriefSchema"; + +const requestId = "00000000-0000-4000-8000-000000000011"; +const subjectId = "00000000-0000-4000-8000-000000000012"; +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"], + promoted: [{ request_id: requestId, subject_id: subjectId }], + }); + expect(parsed.channels).toEqual(["Short-form video", "Radio"]); + 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/); + }); + + 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/); + }); + + 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: ["X"] })).toMatch(/channels/); + 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..7657d54ad --- /dev/null +++ b/lib/context/campaignBriefSchema.ts @@ -0,0 +1,53 @@ +import { z } from "zod"; + +const CHANNEL_LINK_PATTERN = /:\/\/|^(?:www\.|file:|\/|\\|~\/)/i; +const CHANNEL_MESSAGE = + "Channels are names, not links or files; save promoted records first and reference them in promoted"; + +const promotedSubjectSchema = z.strictObject({ + request_id: z.uuid(), + subject_id: z.uuid(), +}); + +/** + * Structured campaign brief accepted by `ingest_campaign_brief`. + * Promoted entries reference Context requests and subjects the workspace already saved; the database + * verifies each pair. Raw URLs, file paths and asset references 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(2) + .max(60) + .refine(value => !CHANNEL_LINK_PATTERN.test(value), { message: CHANNEL_MESSAGE }), + ) + .max(10) + .refine(values => new Set(values.map(value => value.toLowerCase())).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", + }); + +export type CampaignBrief = z.infer; 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..19f5634c4 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; raw URLs and files are not accepted.", readOnly: false, }, ingest_supporting_text: { From b404e862ab01d0d7d7f38e4a94964f01cdf8b426 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:36:46 -0400 Subject: [PATCH 2/4] Match database channel normalization at the campaign brief boundary The database collapses inner whitespace and rejects control characters before comparing campaign channel names, but the API only trimmed and lowercased them. Names such as "Short form" and "short form" passed the API and then failed in storage with a generic 409. The schema now applies the same rules, so these briefs get a 400 with a specific message. Co-Authored-By: Claude Opus 5.5 --- lib/context/__tests__/campaignBriefSchema.test.ts | 5 +++++ lib/context/campaignBriefSchema.ts | 8 +++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/context/__tests__/campaignBriefSchema.test.ts b/lib/context/__tests__/campaignBriefSchema.test.ts index 811cdb0ce..e03f44884 100644 --- a/lib/context/__tests__/campaignBriefSchema.test.ts +++ b/lib/context/__tests__/campaignBriefSchema.test.ts @@ -69,6 +69,11 @@ describe("campaignBriefSchema", () => { failure({ ...brief, channels: Array.from({ length: 11 }, (_, i) => `channel ${i}`) }), ).toMatch(/channels/); expect(failure({ ...brief, channels: ["X"] })).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, diff --git a/lib/context/campaignBriefSchema.ts b/lib/context/campaignBriefSchema.ts index 7657d54ad..25503482e 100644 --- a/lib/context/campaignBriefSchema.ts +++ b/lib/context/campaignBriefSchema.ts @@ -3,6 +3,9 @@ import { z } from "zod"; const CHANNEL_LINK_PATTERN = /:\/\/|^(?:www\.|file:|\/|\\|~\/)/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(), @@ -28,10 +31,13 @@ export const campaignBriefSchema = z .trim() .min(2) .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(value => value.toLowerCase())).size === values.length, { + .refine(values => new Set(values.map(channelKey)).size === values.length, { message: "Campaign channels must be distinct", }) .optional(), From c33d7b9153902a54db8904ee8dc2ca6f4d9d71d4 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:41:36 -0400 Subject: [PATCH 3/4] Accept X as a channel and reject URI-scheme channel names X is a real campaign channel, so channel names may be one character long. URI schemes such as mailto: and spotify: and drive paths are links or files, not channels, and are now rejected as the database does. The README and MCP description now say that only channels and promoted entries refuse URLs and files, because goal and audience stay free text. The schema test UUIDs now contain hex letters so the upper-case duplicate check exercises case normalization. Co-Authored-By: Claude Opus 5.5 --- lib/context/README.md | 2 +- .../__tests__/campaignBriefSchema.test.ts | 18 +++++++++++++----- lib/context/campaignBriefSchema.ts | 5 +++-- lib/mcp/oauth/contextToolOperations.ts | 2 +- 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/context/README.md b/lib/context/README.md index 613af844c..c0da4573b 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, start/end dates, up to ten distinct `channels` names 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`. Raw URLs, file paths and asset references are rejected in the brief, so save promoted records first with `ingest`, `ingest_artist`, `ingest_release` or `ingest_catalog`. Campaign, company, songwriter and material subjects cannot be promoted targets, and an unverifiable target rejects the whole brief. 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_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`. Channels and promoted entries do not accept raw URLs, URI schemes such as `mailto:` or `spotify:`, file or drive paths, and keys such as `promoted_url`, `file_path` or `assets` are rejected (goal and audience stay free text), so save promoted records first with `ingest`, `ingest_artist`, `ingest_release` or `ingest_catalog`. Campaign, company, songwriter and material subjects cannot be promoted targets, and an unverifiable target rejects the whole brief. 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__/campaignBriefSchema.test.ts b/lib/context/__tests__/campaignBriefSchema.test.ts index e03f44884..9db2d8fc9 100644 --- a/lib/context/__tests__/campaignBriefSchema.test.ts +++ b/lib/context/__tests__/campaignBriefSchema.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it } from "vitest"; import { campaignBriefSchema } from "../campaignBriefSchema"; -const requestId = "00000000-0000-4000-8000-000000000011"; -const subjectId = "00000000-0000-4000-8000-000000000012"; +// 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) { @@ -18,10 +19,10 @@ describe("campaignBriefSchema", () => { audience: "Existing listeners", start_date: "2026-10-01", end_date: "2026-10-31", - channels: [" Short-form video ", "Radio"], + channels: [" Short-form video ", "Radio", "X"], promoted: [{ request_id: requestId, subject_id: subjectId }], }); - expect(parsed.channels).toEqual(["Short-form video", "Radio"]); + expect(parsed.channels).toEqual(["Short-form video", "Radio", "X"]); expect(parsed.promoted).toEqual([{ request_id: requestId, subject_id: subjectId }]); }); @@ -54,6 +55,12 @@ describe("campaignBriefSchema", () => { /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", () => { @@ -61,6 +68,7 @@ describe("campaignBriefSchema", () => { 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("requires distinct bounded channels and promoted pairs", () => { @@ -68,7 +76,7 @@ describe("campaignBriefSchema", () => { expect( failure({ ...brief, channels: Array.from({ length: 11 }, (_, i) => `channel ${i}`) }), ).toMatch(/channels/); - expect(failure({ ...brief, channels: ["X"] })).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/, diff --git a/lib/context/campaignBriefSchema.ts b/lib/context/campaignBriefSchema.ts index 25503482e..548d13fd7 100644 --- a/lib/context/campaignBriefSchema.ts +++ b/lib/context/campaignBriefSchema.ts @@ -1,6 +1,7 @@ import { z } from "zod"; -const CHANNEL_LINK_PATTERN = /:\/\/|^(?:www\.|file:|\/|\\|~\/)/i; +// URLs, URI schemes (mailto:, spotify:, file:), drive letters and paths; 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. @@ -29,7 +30,7 @@ export const campaignBriefSchema = z z .string() .trim() - .min(2) + .min(1) .max(60) .refine(value => !CONTROL_CHARACTER_PATTERN.test(value), { message: "Channel names must not contain control characters", diff --git a/lib/mcp/oauth/contextToolOperations.ts b/lib/mcp/oauth/contextToolOperations.ts index 19f5634c4..32f4de430 100644 --- a/lib/mcp/oauth/contextToolOperations.ts +++ b/lib/mcp/oauth/contextToolOperations.ts @@ -113,7 +113,7 @@ export const contextToolOperations = { ingest_campaign_brief: { name: "import_music_campaign_brief", 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; raw URLs and files are not accepted.", + "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; channels and promoted entries do not accept raw URLs or files.", readOnly: false, }, ingest_supporting_text: { From 4de124748f87c7933f42c2385b3ba760c2c43965 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:42:26 -0400 Subject: [PATCH 4/4] State the campaign channel link check precisely Channel names are checked for obvious links only (scheme URLs, URI schemes, www. hosts, absolute, home or drive paths). The README, MCP description and schema comments claimed raw URLs and file paths were rejected generally, which overstated the check: a bare example.com/release or plan.pdf passes as a name. A test now pins that documented boundary. Also drops the unused CampaignBrief type export and documents that a retry of a saved linked brief replays after a target is cancelled. Co-Authored-By: Claude Opus 5.5 --- lib/context/README.md | 2 +- lib/context/__tests__/campaignBriefSchema.test.ts | 9 +++++++++ lib/context/campaignBriefSchema.ts | 9 ++++----- lib/mcp/oauth/contextToolOperations.ts | 2 +- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/context/README.md b/lib/context/README.md index c0da4573b..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, 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`. Channels and promoted entries do not accept raw URLs, URI schemes such as `mailto:` or `spotify:`, file or drive paths, and keys such as `promoted_url`, `file_path` or `assets` are rejected (goal and audience stay free text), so save promoted records first with `ingest`, `ingest_artist`, `ingest_release` or `ingest_catalog`. Campaign, company, songwriter and material subjects cannot be promoted targets, and an unverifiable target rejects the whole brief. 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_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__/campaignBriefSchema.test.ts b/lib/context/__tests__/campaignBriefSchema.test.ts index 9db2d8fc9..3484c729a 100644 --- a/lib/context/__tests__/campaignBriefSchema.test.ts +++ b/lib/context/__tests__/campaignBriefSchema.test.ts @@ -71,6 +71,15 @@ describe("campaignBriefSchema", () => { 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( diff --git a/lib/context/campaignBriefSchema.ts b/lib/context/campaignBriefSchema.ts index 548d13fd7..d503dcd9f 100644 --- a/lib/context/campaignBriefSchema.ts +++ b/lib/context/campaignBriefSchema.ts @@ -1,6 +1,7 @@ import { z } from "zod"; -// URLs, URI schemes (mailto:, spotify:, file:), drive letters and paths; matches the database check. +// 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"; @@ -15,8 +16,8 @@ const promotedSubjectSchema = z.strictObject({ /** * Structured campaign brief accepted by `ingest_campaign_brief`. - * Promoted entries reference Context requests and subjects the workspace already saved; the database - * verifies each pair. Raw URLs, file paths and asset references are rejected here, before authorization. + * 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({ @@ -56,5 +57,3 @@ export const campaignBriefSchema = z .refine(value => !value.start_date || !value.end_date || value.end_date >= value.start_date, { message: "Campaign end date must not precede start date", }); - -export type CampaignBrief = z.infer; diff --git a/lib/mcp/oauth/contextToolOperations.ts b/lib/mcp/oauth/contextToolOperations.ts index 32f4de430..fa1fc5a7b 100644 --- a/lib/mcp/oauth/contextToolOperations.ts +++ b/lib/mcp/oauth/contextToolOperations.ts @@ -113,7 +113,7 @@ export const contextToolOperations = { ingest_campaign_brief: { name: "import_music_campaign_brief", 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; channels and promoted entries do not accept raw URLs or files.", + "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: {