Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): re-open finished opportunities when their signals move (#960)

Gökhan Geyik460242fadfd9
diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.js
index 02d9e6f10..5620f21c2 100644
--- a/server/src/lib/opportunity-generator.js
+++ b/server/src/lib/opportunity-generator.js
@@ -25,6 +25,7 @@ import {
} from './opportunity-limits.js';
import { loadClusterOpportunities } from './open-opportunities.js';
import { loadClusters } from './prompt-clusters.js';
+import { reopenStrengthened } from './opportunity-reopen.js';
import {
ASSET_TYPES,
DECISIONS,
@@ -153,7 +154,7 @@ async function loadPromptTexts(promptIds) {
/**
* @param {string} brandId
* @param {{ model?: string, onProgress?: (p: {phase: string, message: string}) => void }} [opts]
- * @returns {Promise<{ generated: number, merged: number }>}
+ * @returns {Promise<{ generated: number, merged: number, reopened?: number }>}
*/
export async function generateContentOpportunities(brandId, { model, onProgress } = {}) {
onProgress?.({ phase: 'collecting_data', message: 'Fetching clusters and metrics...' });
@@ -228,14 +229,23 @@ export async function generateContentOpportunities(brandId, { model, onProgress
return { metrics, components, score: opportunityScore(components) };
};
+ // Finished opportunities whose signals moved go back to New before any new
+ // ones are written; they keep their clusters, so nothing is duplicated.
+ let reopened = 0;
+ try {
+ reopened = await reopenStrengthened(brandId, existing, measure);
+ } catch (err) {
+ logger.error({ err, brandId }, '[opportunities] re-opening finished opportunities failed');
+ }
+
const candidates = clusters.map((c) => ({ id: c.id, topicId: c.topic_id, ...measure([c.id]) }));
const picked = pickClusters(candidates, coveredClusterIds(existing));
if (!picked.length) {
logger.info(
- { brandId, clusters: clusters.length, opportunities: existing.length },
+ { brandId, clusters: clusters.length, opportunities: existing.length, reopened },
'[opportunities] every cluster with answers already has an opportunity',
);
- return { generated: 0, merged: 0 };
+ return { generated: 0, merged: 0, reopened };
}
const { data: basketRows, error: basketErr } = await supabaseAdmin
@@ -394,8 +404,8 @@ Write every title and description in ${getLanguageName(brand.language)}.`;
if (error) throw new Error(error.message);
}
logger.info(
- { brandId, generated: inserts.length, merged, clusters: clusters.length },
+ { brandId, generated: inserts.length, merged, reopened, clusters: clusters.length },
'[opportunities] generated',
);
- return { generated: inserts.length, merged };
+ return { generated: inserts.length, merged, reopened };
}
diff --git a/server/src/lib/opportunity-reopen.js b/server/src/lib/opportunity-reopen.js
new file mode 100644
index 000000000..6dbf67fa2
--- /dev/null
+++ b/server/src/lib/opportunity-reopen.js
@@ -0,0 +1,134 @@
+/**
+ * "New signal detected": re-opening finished opportunities (#857, Phase 4).
+ *
+ * The signals under an opportunity keep moving after its work is done. When
+ * a completed, measured opportunity has a reason to be worked on again, it
+ * goes back to New — the same row, with what changed recorded on it — rather
+ * than a near-copy being generated beside it. Two reasons count:
+ *
+ * - its cluster's score rose by SCORE_RISE points since it was scored: more
+ * demand, or competitors further ahead (the spec's "strengthens");
+ * - the gain its work measured was lost: the basket's visibility fell below
+ * GAIN_LOST_RATIO of the "after" value its action measured.
+ *
+ * An opportunity is only considered once all its actions are completed and
+ * measured, so nothing re-opens in the weeks before its result is known.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+
+export const SCORE_RISE = 10;
+export const GAIN_LOST_RATIO = 0.5;
+
+/**
+ * Why a finished opportunity should be worked on again, or null.
+ *
+ * @param {{ score: number, visibility: number }} now - the cluster's current figures
+ * @param {{ previousScore: number, visibilityAfter: number|null }} then
+ */
+export function reopenReason(now, { previousScore, visibilityAfter }) {
+ if (now.score - previousScore >= SCORE_RISE) return 'score_rose';
+ if (visibilityAfter > 0 && now.visibility < visibilityAfter * GAIN_LOST_RATIO) return 'gain_lost';
+ return null;
+}
+
+/**
+ * The basket visibility an opportunity's work was measured at afterwards,
+ * or undefined while any of its actions is open or unmeasured. Null when it
+ * is measured but has no basket visibility to compare against.
+ */
+export function measuredAfter(actions) {
+ if (!actions.length) return undefined;
+ if (actions.some((a) => a.status !== 'completed' || a.outcome === 'pending_measurement')) {
+ return undefined;
+ }
+ const values = actions
+ .filter((a) => a.validation?.scope?.kind === 'basket')
+ .flatMap((a) => a.validation.metrics || [])
+ .filter((m) => m.metric === 'ai_visibility' && m.after != null)
+ .map((m) => Number(m.after));
+ return values.length ? Math.max(...values) : null;
+}
+
+/**
+ * Re-opens the brand's done opportunities that have a reason to be worked on
+ * again. `measure(clusterIds)` scores clusters as generation does.
+ *
+ * @returns {Promise<number>} how many were re-opened
+ */
+export async function reopenStrengthened(brandId, opportunities, measure) {
+ const done = opportunities.filter((o) => o.status === 'done' && o.cluster_id);
+ if (!done.length) return 0;
+
+ const { data: actions, error } = await supabaseAdmin
+ .from('actions')
+ .select('status, outcome, validation, opportunityId:payload->>opportunityId')
+ .eq('brand_id', brandId)
+ .eq('kind', 'content_opportunity')
+ .in(
+ 'payload->>opportunityId',
+ done.map((o) => o.id),
+ );
+ if (error) throw new Error(error.message);
+
+ let reopened = 0;
+ for (const opp of done) {
+ const visibilityAfter = measuredAfter(
+ (actions || []).filter((a) => a.opportunityId === opp.id),
+ );
+ if (visibilityAfter === undefined) continue;
+
+ const current = measure([opp.cluster_id, ...(opp.related_cluster_ids || [])]);
+ const previousScore = Number(opp.opportunity_score) || 0;
+ const reason = reopenReason(
+ { score: current.score, visibility: current.metrics.visibility },
+ { previousScore, visibilityAfter },
+ );
+ if (!reason) continue;
+
+ const { data: row, error: readErr } = await supabaseAdmin
+ .from('content_opportunities')
+ .select('source_data')
+ .eq('id', opp.id)
+ .single();
+ if (readErr) throw new Error(readErr.message);
+ const sd = row.source_data || {};
+
+ const { error: writeErr } = await supabaseAdmin
+ .from('content_opportunities')
+ .update({
+ status: 'new',
+ opportunity_score: current.score,
+ source_data: {
+ ...sd,
+ estAiVolume: current.metrics.demand,
+ visibilityScore: current.metrics.visibility,
+ topCompetitorVisibility: current.metrics.topCompetitorVisibility,
+ competitorGap: current.metrics.competitorGap,
+ scoreComponents: current.components,
+ // The finished work stays visible; new work can be sent.
+ actions: {},
+ pastActions: [...(sd.pastActions || []), ...Object.values(sd.actions || {})],
+ reopened: {
+ at: new Date().toISOString(),
+ reason,
+ previousScore,
+ score: current.score,
+ visibilityAfter,
+ visibility: current.metrics.visibility,
+ },
+ },
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', opp.id)
+ .eq('status', 'done');
+ if (writeErr) throw new Error(writeErr.message);
+ reopened += 1;
+ logger.info(
+ { brandId, opportunityId: opp.id, reason, previousScore, score: current.score },
+ '[opportunities] new signal detected, re-opened',
+ );
+ }
+ return reopened;
+}
diff --git a/server/src/lib/opportunity-reopen.test.js b/server/src/lib/opportunity-reopen.test.js
new file mode 100644
index 000000000..88b1e4f7b
--- /dev/null
+++ b/server/src/lib/opportunity-reopen.test.js
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+const { GAIN_LOST_RATIO, SCORE_RISE, measuredAfter, reopenReason } =
+ await import('./opportunity-reopen.js');
+
+describe('reopenReason', () => {
+ it('re-opens when the score rose enough', () => {
+ expect(
+ reopenReason(
+ { score: 70 + SCORE_RISE, visibility: 20 },
+ { previousScore: 70, visibilityAfter: 20 },
+ ),
+ ).toBe('score_rose');
+ expect(
+ reopenReason(
+ { score: 70 + SCORE_RISE - 0.1, visibility: 20 },
+ { previousScore: 70, visibilityAfter: 20 },
+ ),
+ ).toBeNull();
+ });
+
+ it('re-opens when the measured gain was lost', () => {
+ const after = 20;
+ expect(
+ reopenReason(
+ { score: 70, visibility: after * GAIN_LOST_RATIO - 0.1 },
+ { previousScore: 70, visibilityAfter: after },
+ ),
+ ).toBe('gain_lost');
+ expect(
+ reopenReason(
+ { score: 70, visibility: after * GAIN_LOST_RATIO },
+ {
+ previousScore: 70,
+ visibilityAfter: after,
+ },
+ ),
+ ).toBeNull();
+ });
+
+ it('has no gain to lose without a measured visibility', () => {
+ expect(
+ reopenReason({ score: 70, visibility: 0 }, { previousScore: 70, visibilityAfter: null }),
+ ).toBeNull();
+ expect(
+ reopenReason({ score: 70, visibility: 0 }, { previousScore: 70, visibilityAfter: 0 }),
+ ).toBeNull();
+ });
+});
+
+describe('measuredAfter', () => {
+ const basket = (after) => ({
+ status: 'completed',
+ outcome: 'improved',
+ validation: {
+ scope: { kind: 'basket' },
+ metrics: [
+ { metric: 'mentions', after: 9 },
+ { metric: 'ai_visibility', after },
+ ],
+ },
+ });
+
+ it('waits until every action is completed and measured', () => {
+ expect(measuredAfter([])).toBeUndefined();
+ expect(
+ measuredAfter([basket(10), { status: 'in_progress', outcome: 'pending_measurement' }]),
+ ).toBeUndefined();
+ expect(measuredAfter([{ ...basket(10), outcome: 'pending_measurement' }])).toBeUndefined();
+ });
+
+ it('takes the best basket visibility measured afterwards', () => {
+ expect(measuredAfter([basket(10), basket(25)])).toBe(25);
+ });
+
+ it('is null when measured on something other than the basket', () => {
+ expect(
+ measuredAfter([
+ { ...basket(10), validation: { metrics: [{ metric: 'ai_visibility', after: 10 }] } },
+ ]),
+ ).toBeNull();
+ });
+});
diff --git a/supabase/migrations/00114_opportunity_status_since_reopen.sql b/supabase/migrations/00114_opportunity_status_since_reopen.sql
new file mode 100644
index 000000000..95251d5e0
--- /dev/null
+++ b/supabase/migrations/00114_opportunity_status_since_reopen.sql
@@ -0,0 +1,61 @@
+-- A re-opened opportunity's status follows only the work sent after it
+-- re-opened (#857, Phase 4).
+--
+-- A finished opportunity whose signals move goes back to New and records
+-- when in source_data.reopened.at. Its earlier actions are complete; counted
+-- with a new one, they would show the new work as In Progress the moment it
+-- was sent. sync_opportunity_status (00106) now ignores actions created
+-- before that moment.
+
+create or replace function public.sync_opportunity_status()
+returns trigger
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ opp uuid := nullif(new.payload->>'opportunityId', '')::uuid;
+ since timestamptz;
+ next_status text;
+begin
+ if opp is null then
+ return new;
+ end if;
+
+ select nullif(source_data->'reopened'->>'at', '')::timestamptz
+ into since
+ from content_opportunities
+ where id = opp;
+
+ select case
+ when count(*) = 0 then null
+ when count(*) filter (where a.status <> 'dismissed') = 0 then 'reviewed'
+ when count(*) filter (where a.status not in ('completed', 'dismissed')) = 0 then 'done'
+ when count(*) filter (where a.status in ('in_progress', 'on_hold', 'completed')) > 0
+ then 'in_progress'
+ else 'sent'
+ end
+ into next_status
+ from actions a
+ where a.kind = 'content_opportunity'
+ and a.brand_id = new.brand_id
+ and a.payload->>'opportunityId' = opp::text
+ and (since is null or a.created_at >= since);
+
+ -- Only earlier work changed: the re-opened opportunity stays as it is.
+ if next_status is null then
+ return new;
+ end if;
+
+ update content_opportunities
+ set status = next_status, updated_at = now()
+ where id = opp
+ and brand_id = new.brand_id
+ and status in ('new', 'reviewed', 'sent', 'in_progress', 'done')
+ and status <> next_status;
+
+ return new;
+end;
+$$;
+
+revoke all on function public.sync_opportunity_status() from public, anon, authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b4ac18460..2cd6bd9d5 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -13479,3 +13479,68 @@ revoke all on function public.opportunity_basket_metrics(uuid, uuid[], text[], t
grant execute on function public.opportunity_basket_metrics(uuid, uuid[], text[], text[], text[], date, date)
to service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00114_opportunity_status_since_reopen.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- A re-opened opportunity's status follows only the work sent after it
+-- re-opened (#857, Phase 4).
+--
+-- A finished opportunity whose signals move goes back to New and records
+-- when in source_data.reopened.at. Its earlier actions are complete; counted
+-- with a new one, they would show the new work as In Progress the moment it
+-- was sent. sync_opportunity_status (00106) now ignores actions created
+-- before that moment.
+
+create or replace function public.sync_opportunity_status()
+returns trigger
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ opp uuid := nullif(new.payload->>'opportunityId', '')::uuid;
+ since timestamptz;
+ next_status text;
+begin
+ if opp is null then
+ return new;
+ end if;
+
+ select nullif(source_data->'reopened'->>'at', '')::timestamptz
+ into since
+ from content_opportunities
+ where id = opp;
+
+ select case
+ when count(*) = 0 then null
+ when count(*) filter (where a.status <> 'dismissed') = 0 then 'reviewed'
+ when count(*) filter (where a.status not in ('completed', 'dismissed')) = 0 then 'done'
+ when count(*) filter (where a.status in ('in_progress', 'on_hold', 'completed')) > 0
+ then 'in_progress'
+ else 'sent'
+ end
+ into next_status
+ from actions a
+ where a.kind = 'content_opportunity'
+ and a.brand_id = new.brand_id
+ and a.payload->>'opportunityId' = opp::text
+ and (since is null or a.created_at >= since);
+
+ -- Only earlier work changed: the re-opened opportunity stays as it is.
+ if next_status is null then
+ return new;
+ end if;
+
+ update content_opportunities
+ set status = next_status, updated_at = now()
+ where id = opp
+ and brand_id = new.brand_id
+ and status in ('new', 'reviewed', 'sent', 'in_progress', 'done')
+ and status <> next_status;
+
+ return new;
+end;
+$$;
+
+revoke all on function public.sync_opportunity_status() from public, anon, authenticated;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 89201c4b9..47d4f8cb8 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1823,7 +1823,10 @@
"alreadyInActionCenter": "Already in the Action Center",
"sendToActionCenterError": "Failed to send to the Action Center",
"markReviewed": "Mark as reviewed",
- "reviewedError": "Failed to mark as reviewed"
+ "reviewedError": "Failed to mark as reviewed",
+ "newSignal": "New signal detected",
+ "newSignalScoreRose": "Completed earlier, and its opportunity has grown since: the score rose from {from} to {to}.",
+ "newSignalGainLost": "Completed earlier, but the gain did not hold: visibility on these prompts was {after}% after the work and is {now}% now."
},
"traffic": {
"title": "AI Traffic Analytics",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
index 0690fc547..40cd18edd 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
@@ -333,6 +333,23 @@ export default function ContentDetailPage() {
</div>
</div>
+ {sd.reopened && ['new', 'reviewed'].includes(opportunity.status) && (
+ <div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
+ <p className="font-medium text-amber-700 dark:text-amber-400">{t('newSignal')}</p>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {sd.reopened.reason === 'score_rose'
+ ? t('newSignalScoreRose', {
+ from: Math.round(sd.reopened.previousScore),
+ to: Math.round(sd.reopened.score),
+ })
+ : t('newSignalGainLost', {
+ after: Math.round((sd.reopened.visibilityAfter ?? 0) * 10) / 10,
+ now: Math.round(sd.reopened.visibility * 10) / 10,
+ })}
+ </p>
+ </div>
+ )}
+
<div className="flex items-center gap-2">
<Badge variant="outline" className="text-xs">
{t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}
@@ -370,8 +387,10 @@ export default function ContentDetailPage() {
<OpportunityBasketCard opportunityId={opportunity.id} />
</div>
<div className="space-y-4">
- {sd.actions && Object.keys(sd.actions).length > 0 && (
- <OpportunityResultsCard actionIds={Object.values(sd.actions)} />
+ {(Object.keys(sd.actions ?? {}).length > 0 || (sd.pastActions ?? []).length > 0) && (
+ <OpportunityResultsCard
+ actionIds={[...(sd.pastActions ?? []), ...Object.values(sd.actions ?? {})]}
+ />
)}
<ScoreBreakdown sourceData={sd} />
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index bdb3c3f71..a7bb95663 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -983,7 +983,17 @@ export default function ContentPage() {
href={`/dashboard/content/${opp.id}`}
className="block hover:underline"
>
- <p className="text-sm font-medium line-clamp-1">{opp.title}</p>
+ <p className="text-sm font-medium line-clamp-1">
+ {opp.sourceData?.reopened && opp.status === 'new' && (
+ <Badge
+ variant="outline"
+ className="mr-1.5 border-amber-500/30 bg-amber-500/10 text-[10px] text-amber-700 dark:text-amber-400"
+ >
+ {t('newSignal')}
+ </Badge>
+ )}
+ {opp.title}
+ </p>
{opp.description && (
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
{opp.description}
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index 09b8b7206..dddf5270d 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -225,6 +225,17 @@ export interface ContentOpportunitySourceData {
assets?: OpportunityAsset[];
/** Action Center actions sent from this opportunity, by asset key ('all' for the whole). */
actions?: Record<string, string>;
+ /** Actions from before the opportunity was re-opened. */
+ pastActions?: string[];
+ /** Why a finished opportunity went back to New (#857, Phase 4). */
+ reopened?: {
+ at: string;
+ reason: 'score_rose' | 'gain_lost';
+ previousScore: number;
+ score: number;
+ visibilityAfter: number | null;
+ visibility: number;
+ };
}
export interface OpportunityPage {