@sellable/mcp 0.1.335 → 0.1.336

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -96,17 +96,8 @@ startup/auth update check and tells the agent to run
96
96
  `curl -fsSL "https://app.sellable.dev/api/v2/cli/install" | sh` when the
97
97
  installed runtime is behind npm.
98
98
 
99
- First-run login is the normal auth path. Install Sellable, launch a workflow in
100
- Claude Code or Codex, and let the agent complete the browser magic-link login.
101
- If the browser login page shows a manual fallback, paste:
102
-
103
- ```bash
104
- sellable auth set <token> --workspace-id <workspace_id>
105
- ```
106
-
107
- For CI/env-only scripted installs, operators can set `SELLABLE_TOKEN` and
108
- `SELLABLE_WORKSPACE_ID` before running the curl installer. The public path
109
- remains:
99
+ For CI/scripted installs, set `SELLABLE_TOKEN` and `SELLABLE_WORKSPACE_ID`
100
+ before running the curl installer. The public path remains:
110
101
 
111
102
  ```bash
112
103
  curl -fsSL "https://app.sellable.dev/api/v2/cli/install" | sh
@@ -126,17 +117,11 @@ and publishes with a temporary npm config file. Prefer `NPM_TOKEN=<npm token>` i
126
117
  `prod.env`; `NODE_AUTH_TOKEN`, `SELLABLE_NPM_TOKEN`, and `NPM_PUBLISH_TOKEN` are
127
118
  also supported.
128
119
 
129
- ### 2. First-Run Login
120
+ ### 2. Generate API Token
130
121
 
131
- Launch a Sellable workflow after install. The agent will start first-run login,
132
- send the magic link, wait for browser confirmation, and write canonical auth to
133
- `~/.sellable/config.json`.
134
-
135
- If the browser confirmation page shows a scripted fallback, paste:
136
-
137
- ```bash
138
- sellable auth set <token> --workspace-id <workspace_id>
139
- ```
122
+ 1. Go to https://app.sellable.dev/settings
123
+ 2. Click "Generate Token"
124
+ 3. Copy the token (starts with `skt_live_`)
140
125
 
141
126
  ### 3. Claude Setup Fallback
142
127
 
@@ -150,9 +135,17 @@ Install MCP server manually:
150
135
  claude mcp add --transport stdio sellable -- npm exec --yes --package @sellable/mcp@latest -- sellable-mcp
151
136
  ```
152
137
 
153
- Do not hand-edit auth JSON for normal setup. Use first-run login or the
154
- `sellable auth set <token> --workspace-id <workspace_id>` fallback so the
155
- canonical config shape stays consistent.
138
+ Create auth config at `~/.sellable/config.json`:
139
+
140
+ ```json
141
+ {
142
+ "token": "skt_live_your_token_here",
143
+ "activeWorkspaceId": "your_workspace_id"
144
+ }
145
+ ```
146
+
147
+ The token is provided when you generate it. Use `list_workspaces` +
148
+ `set_active_workspace` to choose a workspace if you don't know the ID yet.
156
149
 
157
150
  ### 4. Codex Setup
158
151
 
@@ -531,21 +524,13 @@ generation is not part of these inbox tools.
531
524
 
532
525
  ### "Sellable not configured" Error
533
526
 
534
- Run a Sellable workflow to start first-run login. If the browser login page
535
- shows a manual fallback, paste:
536
-
537
- ```bash
538
- sellable auth set <token> --workspace-id <workspace_id>
539
- ```
527
+ Create `~/.sellable/config.json` with your token. Get one at https://app.sellable.dev/settings?tab=integrations.
540
528
 
541
529
  ### Token Not Working
542
530
 
543
531
  1. Make sure token starts with `skt_`
544
532
  2. Check token is not revoked
545
- 3. If the token came from an older Settings flow and returns 403 on campaign or
546
- enrichment writes, regenerate through first-run login or the scripted
547
- fallback command above
548
- 4. Verify activeWorkspaceId matches your workspace (or run list_workspaces + set_active_workspace)
533
+ 3. Verify activeWorkspaceId matches your workspace (or run list_workspaces + set_active_workspace)
549
534
 
550
535
  ## Support
551
536
 
package/dist/api.js CHANGED
@@ -19,11 +19,9 @@ export class SellableApi {
19
19
  const missingWorkspace = status === 400 && errorText.includes("Workspace");
20
20
  const guidance = isAuthError
21
21
  ? "Sellable authentication failed.\n\n" +
22
- "Run the first-run Sellable login flow from a Sellable workflow, then retry.\n\n" +
23
- "If the browser login page shows a manual fallback command, use:\n" +
24
- "sellable auth set <token> --workspace-id <workspace_id>\n\n" +
25
- `Current config path: ${getConfigPath()}\n\n` +
26
- "Older copied Settings tokens can be stale, restricted, or missing write/credit permissions. Sign in again so Sellable mints the current agent token."
22
+ `Update ${getConfigPath()} with a valid token from Sellable Settings -> Integrations, then retry.\n\n` +
23
+ "NOTE: If the token was just updated via the LLM (editing the config file), " +
24
+ "the change should take effect immediately. If it still fails, restart Claude Code to restart the MCP server."
27
25
  : missingWorkspace
28
26
  ? "No active workspace selected.\n\n" +
29
27
  "Run list_workspaces then set_active_workspace to choose a workspace."
package/dist/auth.js CHANGED
@@ -48,16 +48,6 @@ export function getConfigPath() {
48
48
  }
49
49
  return candidates[0];
50
50
  }
51
- function getConfigWritePath() {
52
- const explicitConfigPath = process.env.SELLABLE_CONFIG_PATH?.trim();
53
- if (explicitConfigPath) {
54
- return path.resolve(explicitConfigPath);
55
- }
56
- if (configFileName === "sellable.json") {
57
- return path.join(os.homedir(), ".sellable", "config.json");
58
- }
59
- return getConfigPath();
60
- }
61
51
  function normalizeConfig(raw) {
62
52
  return {
63
53
  ...raw,
@@ -76,12 +66,14 @@ export function getConfig() {
76
66
  const configPath = getConfigPath();
77
67
  if (!fs.existsSync(configPath)) {
78
68
  throw new Error("Sellable not configured.\n\n" +
79
- "Run a Sellable workflow to start first-run login, for example /sellable:create-campaign in Claude Code or $sellable:create-campaign in Codex.\n\n" +
80
- "If the browser login page shows a manual fallback command, paste it in your terminal:\n" +
81
- "sellable auth set <token> --workspace-id <workspace_id>\n\n" +
82
- `Preferred config path: ${getConfigWritePath()}\n\n` +
69
+ `Create ${configPath} with your token:\n` +
70
+ "{\n" +
71
+ ' "token": "skt_live_..."\n' +
72
+ "}\n\n" +
83
73
  "Config path resolution order:\n" +
84
- `${renderConfigPathOrder(configPathCandidates)}`);
74
+ `${renderConfigPathOrder(configPathCandidates)}\n\n` +
75
+ "Get your token at: https://app.sellable.dev/settings?tab=integrations\n" +
76
+ "Then run list_workspaces + set_active_workspace to select a workspace.");
85
77
  }
86
78
  try {
87
79
  const content = fs.readFileSync(configPath, "utf-8");
@@ -126,8 +118,7 @@ export function updateActiveWorkspace(params) {
126
118
  fs.mkdirSync(configDir, { recursive: true });
127
119
  }
128
120
  if (!fs.existsSync(configPath)) {
129
- throw new Error("Sellable not configured. Run a Sellable workflow to start first-run login, " +
130
- "or paste the browser fallback command: sellable auth set <token> --workspace-id <workspace_id>.");
121
+ throw new Error(`Sellable not configured. Create ${configPath} with your token first.`);
131
122
  }
132
123
  const content = fs.readFileSync(configPath, "utf-8");
133
124
  let raw;
@@ -167,8 +158,7 @@ export function updateActiveWorkspace(params) {
167
158
  function readRawConfigFile() {
168
159
  const configPath = getConfigPath();
169
160
  if (!fs.existsSync(configPath)) {
170
- throw new Error("Sellable not configured. Run a Sellable workflow to start first-run login, " +
171
- "or paste the browser fallback command: sellable auth set <token> --workspace-id <workspace_id>.");
161
+ throw new Error(`Sellable not configured. Create ${configPath} with your token first.`);
172
162
  }
173
163
  const content = fs.readFileSync(configPath, "utf-8");
174
164
  try {
@@ -207,36 +197,15 @@ function writeRawConfigFile(configPath, raw) {
207
197
  * new config without an MCP server restart.
208
198
  */
209
199
  export function writeNewConfig(opts) {
210
- const configPath = getConfigWritePath();
211
- let raw = {};
212
- if (fs.existsSync(configPath)) {
213
- const content = fs.readFileSync(configPath, "utf-8");
214
- try {
215
- raw = JSON.parse(content);
216
- }
217
- catch (error) {
218
- if (error instanceof SyntaxError) {
219
- throw new Error(`Invalid JSON in ${configPath}: ${error.message}`);
220
- }
221
- throw error;
222
- }
223
- }
224
- const authFields = {
200
+ const configPath = getConfigPath();
201
+ const raw = {
225
202
  token: opts.token,
226
203
  activeWorkspaceId: opts.activeWorkspaceId,
227
204
  apiUrl: opts.apiUrl,
228
205
  };
229
- if (opts.activeWorkspaceName)
230
- authFields.activeWorkspaceName = opts.activeWorkspaceName;
231
- const { envConfig, set } = getActiveEnvConfigRef(raw);
232
- const nextEnvConfig = {
233
- ...envConfig,
234
- ...authFields,
235
- };
236
- if (!opts.activeWorkspaceName) {
237
- delete nextEnvConfig.activeWorkspaceName;
206
+ if (opts.activeWorkspaceName) {
207
+ raw.activeWorkspaceName = opts.activeWorkspaceName;
238
208
  }
239
- set(nextEnvConfig);
240
209
  writeRawConfigFile(configPath, raw);
241
210
  return { configPath };
242
211
  }
package/dist/index-dev.js CHANGED
File without changes
package/dist/index.js CHANGED
File without changes
package/dist/server.js CHANGED
@@ -6,9 +6,8 @@ import { getAuthStatus } from "./tools/auth.js";
6
6
  import { handleAddColumn, handleCommitBlueprint, } from "./tools/blueprint-commit.js";
7
7
  import { bootstrapCreateCampaign } from "./tools/bootstrap.js";
8
8
  import { prepareCampaignAbTest } from "./tools/campaign-ab-test.js";
9
- import { fillCampaignHorizon } from "./tools/campaign-horizon-fill.js";
10
9
  import { cancelPrepareCampaignMessages, getPrepareCampaignMessagesStatus, startPrepareCampaignMessages, } from "./tools/campaign-message-preparation.js";
11
- import { getCampaignTableSchema, queueCampaignCells, reviseMessageTemplateAndRerun, selectCampaignCells, waitForCampaignProcessing, } from "./tools/campaign-processing.js";
10
+ import { getCampaignTableSchema, queueCampaignCells, recordCampaignReviewBatch, reviseMessageTemplateAndRerun, selectCampaignCells, waitForCampaignProcessing, } from "./tools/campaign-processing.js";
12
11
  import { createCampaign, duplicateCampaign, getCampaign, getCampaignMessagesPreview, getCampaigns, pauseCampaign, startCampaign, updateCampaign, updateCampaignBrief, } from "./tools/campaigns.js";
13
12
  import { queueCells, updateCell } from "./tools/cells.js";
14
13
  import { handleStartCliLogin, handleWaitForCliLogin, } from "./tools/cli-login.js";
@@ -179,12 +178,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
179
178
  case "get_campaign_messages_preview":
180
179
  result = await getCampaignMessagesPreview(args);
181
180
  break;
182
- case "fill_campaign_horizon":
183
- result = await fillCampaignHorizon(args);
184
- if (args?.campaignId) {
185
- markCampaignContextDirty(args.campaignId, "fill_campaign_horizon");
186
- }
187
- break;
188
181
  case "start_campaign_message_preparation":
189
182
  case "start_prepare_campaign_messages":
190
183
  result = await startPrepareCampaignMessages(args);
@@ -219,6 +212,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
219
212
  markCampaignContextDirty(args.campaignId, "queue_campaign_cells");
220
213
  }
221
214
  break;
215
+ case "record_campaign_review_batch":
216
+ result = await recordCampaignReviewBatch(args);
217
+ break;
222
218
  case "wait_for_campaign_processing":
223
219
  result = await waitForCampaignProcessing(args);
224
220
  break;
@@ -9,7 +9,6 @@ type StartPrepareMessagesInput = PrepareMessagesBaseInput & {
9
9
  targetPreparedMessages?: number;
10
10
  maxRowsToCheck?: number;
11
11
  batchSize?: number;
12
- maxBatchRows?: number;
13
12
  approvalMode?: ApprovalMode;
14
13
  autoContinue?: boolean;
15
14
  disableLowPassRateStop?: boolean;
@@ -46,12 +45,6 @@ export declare const campaignMessagePreparationToolDefinitions: ({
46
45
  maximum: number;
47
46
  description: string;
48
47
  };
49
- maxBatchRows: {
50
- type: string;
51
- minimum: number;
52
- maximum: number;
53
- description: string;
54
- };
55
48
  approvalMode: {
56
49
  type: string;
57
50
  enum: string[];
@@ -88,7 +81,6 @@ export declare const campaignMessagePreparationToolDefinitions: ({
88
81
  targetPreparedMessages?: undefined;
89
82
  maxRowsToCheck?: undefined;
90
83
  batchSize?: undefined;
91
- maxBatchRows?: undefined;
92
84
  approvalMode?: undefined;
93
85
  autoContinue?: undefined;
94
86
  disableLowPassRateStop?: undefined;
@@ -6,7 +6,7 @@ async function postPrepareMessages(body) {
6
6
  export const campaignMessagePreparationToolDefinitions = [
7
7
  {
8
8
  name: "start_campaign_message_preparation",
9
- description: 'Start a bounded campaign message preparation job for a CampaignOffer campaignId. Use this after lead/message approval when the user asks to "fill up", "load", or "prepare" sends for attached senders. It never launches the campaign, sends messages, or directly writes scheduledFor. The job queues pending Enrich Prospect cells first, lets ICP/rubric and Generate Message cascade, then marks ready or approves only the bounded cohort. Prepared/approved/ready rows are intermediate only; scheduled completion requires a later re-read proving scheduler-owned scheduled cells with non-null scheduledFor. Omit maxRowsToCheck and batchSize for the adaptive default: calibrate on at least 100 actually-enriched rows, estimate the row budget from observed rubric/pass yield, cap rows at 300, and process at most 100 newly checked rows at a time. The worker will not pull another row batch while the current checked batch still has queueable or active cells. Do not interpret checkedRows as enriched rows; use progress.enrichedRows, needsEnrichRows, activeCellCount, preparedMessages, approvedMessages, and stopReason.',
9
+ description: 'Start a bounded campaign message preparation job for a CampaignOffer campaignId. Use this after lead/message approval when the user asks to "fill up", "load", "prepare", or "schedule" sends for attached senders. It never launches the campaign. The job queues pending Enrich Prospect cells first, lets ICP/rubric and Generate Message cascade, then marks ready or approves only the bounded cohort. Omit maxRowsToCheck and batchSize for the adaptive default: calibrate on at least 100 actually-enriched rows, estimate the row budget from observed rubric/pass yield, cap rows at 2500, then use batches up to 250 once the sample is strong enough. Do not interpret checkedRows as enriched rows; use progress.enrichedRows, needsEnrichRows, activeCellCount, preparedMessages, and stopReason.',
10
10
  inputSchema: {
11
11
  type: "object",
12
12
  properties: {
@@ -19,25 +19,19 @@ export const campaignMessagePreparationToolDefinitions = [
19
19
  maxRowsToCheck: {
20
20
  type: "number",
21
21
  minimum: 1,
22
- maximum: 300,
23
- description: "Optional override capped by the backend at 300. Omit this for adaptive sample-based row budgeting.",
22
+ maximum: 2500,
23
+ description: "Optional override capped by the backend at 2500. Omit this for adaptive sample-based row budgeting.",
24
24
  },
25
25
  batchSize: {
26
26
  type: "number",
27
27
  minimum: 1,
28
- maximum: 100,
29
- description: "Optional first-batch override capped by the backend at 100. Omit this to sample 100 rows.",
30
- },
31
- maxBatchRows: {
32
- type: "number",
33
- minimum: 1,
34
- maximum: 100,
35
- description: "Optional max rows to add in any single preparation batch. Capped by the backend at 100.",
28
+ maximum: 250,
29
+ description: "Optional first-batch override capped by the backend at 250. Omit this to sample 100 rows before larger batches.",
36
30
  },
37
31
  approvalMode: {
38
32
  type: "string",
39
33
  enum: ["mark_ready", "approve"],
40
- description: "Defaults to mark_ready. Use approve only when the user explicitly asks to flip Approved cells. Approval is not scheduling; it only makes the bounded cohort eligible for downstream scheduler ownership.",
34
+ description: "Defaults to mark_ready. Use approve only when the user explicitly asks to flip Approved cells.",
41
35
  },
42
36
  autoContinue: { type: "boolean" },
43
37
  disableLowPassRateStop: {
@@ -84,7 +78,6 @@ export function startPrepareCampaignMessages(input) {
84
78
  targetPreparedMessages: input.targetPreparedMessages,
85
79
  maxRowsToCheck: input.maxRowsToCheck,
86
80
  batchSize: input.batchSize,
87
- maxBatchRows: input.maxBatchRows,
88
81
  approvalMode: input.approvalMode,
89
82
  autoContinue: input.autoContinue,
90
83
  disableLowPassRateStop: input.disableLowPassRateStop,
@@ -42,6 +42,11 @@ type ReviseTemplateInput = SchemaInput & {
42
42
  rowSelector?: RowSelector;
43
43
  limit?: number;
44
44
  };
45
+ type RecordReviewBatchInput = SchemaInput & {
46
+ tableId: string;
47
+ rowIds: string[];
48
+ enrichCellIds?: string[];
49
+ };
45
50
  type ReviseTemplateResponse = Record<string, unknown> & {
46
51
  approvalsReset?: number;
47
52
  };
@@ -99,6 +104,8 @@ export declare const campaignProcessingToolDefinitions: ({
99
104
  templateRevision?: undefined;
100
105
  timeoutMs?: undefined;
101
106
  intervalMs?: undefined;
107
+ rowIds?: undefined;
108
+ enrichCellIds?: undefined;
102
109
  templateMarkdown?: undefined;
103
110
  approvedMessageTemplate?: undefined;
104
111
  };
@@ -154,6 +161,8 @@ export declare const campaignProcessingToolDefinitions: ({
154
161
  templateRevision?: undefined;
155
162
  timeoutMs?: undefined;
156
163
  intervalMs?: undefined;
164
+ rowIds?: undefined;
165
+ enrichCellIds?: undefined;
157
166
  templateMarkdown?: undefined;
158
167
  approvedMessageTemplate?: undefined;
159
168
  };
@@ -213,6 +222,8 @@ export declare const campaignProcessingToolDefinitions: ({
213
222
  templateRevision?: undefined;
214
223
  timeoutMs?: undefined;
215
224
  intervalMs?: undefined;
225
+ rowIds?: undefined;
226
+ enrichCellIds?: undefined;
216
227
  templateMarkdown?: undefined;
217
228
  approvedMessageTemplate?: undefined;
218
229
  };
@@ -252,12 +263,52 @@ export declare const campaignProcessingToolDefinitions: ({
252
263
  limit?: undefined;
253
264
  forceRerun?: undefined;
254
265
  reason?: undefined;
266
+ rowIds?: undefined;
267
+ enrichCellIds?: undefined;
255
268
  templateMarkdown?: undefined;
256
269
  approvedMessageTemplate?: undefined;
257
270
  };
258
271
  additionalProperties: boolean;
259
272
  required?: undefined;
260
273
  };
274
+ } | {
275
+ name: string;
276
+ description: string;
277
+ inputSchema: {
278
+ type: string;
279
+ properties: {
280
+ tableId: {
281
+ type: string;
282
+ };
283
+ rowIds: {
284
+ type: string;
285
+ items: {
286
+ type: string;
287
+ };
288
+ };
289
+ enrichCellIds: {
290
+ type: string;
291
+ items: {
292
+ type: string;
293
+ };
294
+ };
295
+ campaignId?: undefined;
296
+ columnRole?: undefined;
297
+ rowSelector?: undefined;
298
+ limit?: undefined;
299
+ forceRerun?: undefined;
300
+ reason?: undefined;
301
+ minPassedCount?: undefined;
302
+ minGeneratedMessages?: undefined;
303
+ templateRevision?: undefined;
304
+ timeoutMs?: undefined;
305
+ intervalMs?: undefined;
306
+ templateMarkdown?: undefined;
307
+ approvedMessageTemplate?: undefined;
308
+ };
309
+ required: string[];
310
+ additionalProperties: boolean;
311
+ };
261
312
  } | {
262
313
  name: string;
263
314
  description: string;
@@ -308,6 +359,8 @@ export declare const campaignProcessingToolDefinitions: ({
308
359
  templateRevision?: undefined;
309
360
  timeoutMs?: undefined;
310
361
  intervalMs?: undefined;
362
+ rowIds?: undefined;
363
+ enrichCellIds?: undefined;
311
364
  };
312
365
  required: string[];
313
366
  additionalProperties: boolean;
@@ -316,6 +369,7 @@ export declare const campaignProcessingToolDefinitions: ({
316
369
  export declare function getCampaignTableSchema(input: SchemaInput): Promise<CampaignProcessingSchemaResponse>;
317
370
  export declare function selectCampaignCells(input: SelectInput): Promise<unknown>;
318
371
  export declare function queueCampaignCells(input: QueueInput): Promise<unknown>;
372
+ export declare function recordCampaignReviewBatch(input: RecordReviewBatchInput): Promise<unknown>;
319
373
  export declare function reviseMessageTemplateAndRerun(input: ReviseTemplateInput): Promise<ReviseTemplateResponse>;
320
374
  export declare function waitForCampaignProcessing(input: WaitInput): Promise<{
321
375
  ready: boolean;
@@ -142,6 +142,20 @@ export const campaignProcessingToolDefinitions = [
142
142
  additionalProperties: false,
143
143
  },
144
144
  },
145
+ {
146
+ name: "record_campaign_review_batch",
147
+ description: "Record a fresh campaign-table review batch from explicit row IDs. Use for same-source new-sample recovery after a zero-pass bounded filter run; do not use for new lead sourcing.",
148
+ inputSchema: {
149
+ type: "object",
150
+ properties: {
151
+ tableId: { type: "string" },
152
+ rowIds: { type: "array", items: { type: "string" } },
153
+ enrichCellIds: { type: "array", items: { type: "string" } },
154
+ },
155
+ required: ["tableId", "rowIds"],
156
+ additionalProperties: false,
157
+ },
158
+ },
145
159
  {
146
160
  name: "revise_message_template_and_rerun",
147
161
  description: "Update the approved message template in the campaign brief, mark prior generated messages stale, reset unsent approvals, and force-rerun Generate Message cells. Does not directly overwrite row message cells.",
@@ -192,6 +206,12 @@ export async function queueCampaignCells(input) {
192
206
  ...input,
193
207
  });
194
208
  }
209
+ export async function recordCampaignReviewBatch(input) {
210
+ return postCampaignProcessing({
211
+ action: "recordReviewBatch",
212
+ ...input,
213
+ });
214
+ }
195
215
  export async function reviseMessageTemplateAndRerun(input) {
196
216
  const result = await postCampaignProcessing({
197
217
  action: "reviseTemplateAndRerun",
@@ -245,28 +265,36 @@ function buildProcessingTimeoutRecovery({ input, schema, stats, minPassedCount,
245
265
  },
246
266
  });
247
267
  }
248
- if (!passFloorMet && pendingWorkCount === 0 && campaignId) {
268
+ if (!passFloorMet && pendingWorkCount === 0) {
249
269
  suggestedToolCalls.push({
250
- tool: "search_signals",
251
- reason: "The checked sample missed the validation floor; revise the source before Settings.",
270
+ tool: "get_rows_minimal",
271
+ reason: "The checked sample missed the validation floor; inspect compact row miss patterns before choosing rubric revision, same-source new sample, or source revision.",
252
272
  args: {
253
- campaignOfferId: campaignId,
254
- currentStep: "signal-discovery",
255
- currentStepTransition: "revise-source-after-validation",
273
+ ...(campaignId ? { campaignId } : { tableId: schema.tableId }),
256
274
  },
257
275
  });
276
+ suggestedToolCalls.push({
277
+ tool: "record_campaign_review_batch",
278
+ reason: "If the source is still viable but this slice was unrepresentative, record explicit same-source rowIds as a fresh review batch, then queue enrich on rowSelector reviewBatch.",
279
+ args: {
280
+ tableId: schema.tableId,
281
+ rowIds: ["<choose unprocessed same-source row ids>"],
282
+ },
283
+ });
284
+ }
285
+ if (!passFloorMet && pendingWorkCount === 0 && campaignId) {
258
286
  suggestedToolCalls.push({
259
287
  tool: "update_campaign",
260
- reason: "If the user chooses a non-source revision path, persist the chosen recovery step explicitly.",
288
+ reason: "Persist the chosen recovery step explicitly; do not jump straight to source revision unless rubric relaxation and same-source sampling are not viable.",
261
289
  args: {
262
290
  campaignId,
263
- currentStep: "signal-discovery",
264
- currentStepTransition: "revise-source-after-validation",
291
+ currentStep: "apply-icp-rubric",
292
+ currentStepTransition: "sample-needs-revision",
265
293
  },
266
294
  });
267
295
  }
268
296
  const nextAction = !passFloorMet && pendingWorkCount === 0
269
- ? "revise-source-or-filters"
297
+ ? "revise-rubric-new-sample-or-source"
270
298
  : !generatedFloorMet
271
299
  ? "queue-or-retry-message-generation"
272
300
  : pendingWorkCount > 0
@@ -404,7 +432,7 @@ export async function waitForCampaignProcessing(input) {
404
432
  minGeneratedMessages,
405
433
  },
406
434
  recovery,
407
- guidance: "Surface this partial validation checkpoint before taking another action. Use recovery.suggestedToolCalls to retry processing, queue missing work, or revise source/filter/message quality instead of moving to Settings on a weak sample.",
435
+ guidance: "Surface this partial validation checkpoint before taking another action. Use recovery.suggestedToolCalls to retry processing, queue missing work, revise rubrics, record a fresh same-source sample, revise source, or revise message quality instead of moving to Settings on a weak sample.",
408
436
  stats: lastStats,
409
437
  };
410
438
  }
@@ -441,7 +441,7 @@ export const campaignToolDefinitions = [
441
441
  },
442
442
  {
443
443
  name: "start_campaign",
444
- description: "Start a paused campaign, enabling the sweeper to send messages. This is an explicit human launch/start action and must not be used as part of fill-send-horizon, message preparation, or scheduling-proof flows.",
444
+ description: "Start a paused campaign, enabling the sweeper to send messages.",
445
445
  inputSchema: {
446
446
  type: "object",
447
447
  properties: {
@@ -371,7 +371,7 @@ export function getPostFindLeadsScoutRegistry() {
371
371
  codex: 'After confirm_lead_list copies source rows and the initial campaign-table execution slice exists, ask the filter-choice question immediately. Do not spawn anything before that question. After the answer, launch only Message Drafting. The filter-choice answer is the post-import user gate for this single worker; do not ask another question about starting it in step-wise or YOLO mode. The registry lookup is not a launch: after get_post_find_leads_scout_registry, immediately invoke Task/spawn_agent or the host background-agent mechanism before loading filter-leads.md, before saving rubrics, and before treating skip-filters as ready for message review. Both choices route through this kickoff; do not let filters_skipped jump straight from filter-choice to message-generation. If filters are chosen, the parent stays on Filter Rules and drafts/saves rubrics with MCP tools while Message Drafting runs in the background. If filters are skipped, move to Messages/message review only after Message Drafting has started or is ready; update_campaign(currentStep=messages) is not proof of launch. If the named Message Drafting custom agent is unavailable, spawn a generic gpt-5.5 xhigh Message Drafting background agent with the same lean campaign/table basis. When the background worker starts, persist workerDetails.messageDraftBuilder with statusSource "branch", status "branch-running", runId, startedAt, updatedAt, basisToken when known, and basis containing campaignId, selectedLeadListId, workflowTableId, filterChoice, and reviewBatchRowHash or reviewBatchRowIds; workerStatuses.messageDraftBuilder may be "running" as a simple badge only. Never put rich proof under workerStatuses and never use workerStatuses.messageDrafting. If no background-agent tool is callable, start the same full message branch inline before filter drafting or before skip-filter message review, record workerDetails.messageDraftBuilder with statusSource "parent-thread-fallback" and status "fallback-active", and require the same live context, prompt, assets, and validation gate before message review; do not wait until filters are saved and then call the registry.',
372
372
  claude: "After confirm_lead_list copies source rows and the initial campaign-table execution slice exists, ask the filter-choice question immediately. Do not invoke any Task/Agent before that question. After the answer, invoke only Message Drafting. If filters are chosen, parent drafts/saves rubrics with MCP tools while Message Drafting runs, asks filter approval, then joins Message Drafting. If filters are skipped, invoke only Message Drafting and move to Messages/message review.",
373
373
  parentThreadRule: 'Named agents are optional acceleration, but message drafting is not optional. The only normal background worker is Message Drafting. The filter-choice answer is the campaign-scoped go-ahead for this single post-import worker; do not ask another question to start it in step-wise or YOLO mode. If a named agent is unavailable, use a generic gpt-5.5 xhigh Message Drafting background agent. source work and filter work stay in the parent thread with MCP tools. If post-find-leads-message-scout is available, run it as the background Message Draft Builder after the filter-choice answer. The registry lookup is not a launch: get_post_find_leads_scout_registry only identifies the worker, and Message Drafting counts as started only after Task/spawn_agent or the host background-agent tool is invoked, or after the parent begins the same full message branch inline because no background-agent tool is callable. This launch must happen before loading filter-leads.md, save_rubrics, filter approval, or skip-filter message review; currentStep=messages is not proof of launch. If post-find-leads-message-scout is absent, do not customer-surface install status. Do not silently treat message drafting as started; the main thread must either launch the background worker or execute the same message branch from CampaignOffer state, selected source state, workflowTableId, and initial campaign-table execution slice rows. For a spawned worker, record workerDetails.messageDraftBuilder with statusSource branch / status branch-running, runId, startedAt, updatedAt, and basis containing campaignId, selectedLeadListId, workflowTableId, filterChoice, and reviewBatchRowHash or reviewBatchRowIds. workerStatuses.messageDraftBuilder is optional simple badge text only ("running", "ready", "blocked", "idle"); never put runId/statusSource/basis under workerStatuses and never use workerStatuses.messageDrafting. If no background-agent tool is callable, start that same full message branch inline before filter drafting or before skip-filter message review, record workerDetails.messageDraftBuilder with statusSource parent-thread-fallback / status fallback-active then ready, and require the same live context, prompt, assets, and validation gate before message review; do not report that as a background worker failure. If neither branch nor inline fallback can run, return blocked/retry-needed; do not wait until filters are saved and then call the registry. The Message Drafting handoff must be lean. Do not paste copied row counts, brief hashes, review-batch hashes, full reviewBatchRowIds, broad row data, or local debug artifacts into the spawn prompt. Local markdown/json files are not normal-path inputs. The filter-choice question is the first post-import user gate; do not load post-lead registries or filter references before it. Message drafting starts after the filter-choice answer, must load get_subskill_prompt({ subskillName: "generate-messages" }), and must load every required message asset named by generate-messages Mode 0 through get_subskill_asset before drafting. Reference Asset Loading means loading the required pre-draft reference pack before drafting; return blocked/retry-needed if required assets cannot be loaded; load ai-tells.md because it is never optional. The branch or parent-thread fallback loads the full generate-messages prompt and every referenced asset through get_subskill_asset. After generating/revising the candidate and before returning ready, must load get_subskill_prompt({ subskillName: "create-campaign-v2-validation" }) as the final internal validation gate, must read live campaign table state through scoped MCP/product tools, and must reject mismatched selectedLeadListId/workflowTableId/campaign/workspace input. Do not block when filters were chosen but leadScoringRubrics are not yet visible in the branch read; the parent owns save_rubrics and filter approval in parallel, so Message Drafting should return status ready with basisStatus usable_initial when campaign/list/table identity and the non-empty execution slice match. Do not use any alternate, local-artifact, or examples-only message prompt. User copy feedback, message QA, or rewrite requests before approve-message must be routed back to Message Drafting with the current recommendation, lean campaign/table basis, and latest user text; the parent must not rewrite or QA the template from memory and must not call update_campaign_brief before approve-message. The worker validates internally and returns only templateRecommendation, tokenFillRules, renderedGoodSample, status, approveOrReviseRecommendation, validationStatus, outputAt, outputHash, and blocked/retry detail. Do not render renderedFallbackSample, risk notes, or a qaReceipt on the normal happy path. On the filter path, save_rubrics keeps the browser on Filter Rules after save_rubrics so the user can approve the saved criteria; after saved-filter approval, move to Filter Leads with currentStep=apply-icp-rubric whether Message Drafting is ready or still running. Wait there for message approval. Enrichment, filtering, Generate Message cells, sender setup, sequence attach, and launch wait for template approval on the Use Template path. On the skip path, move to Messages/message review after Message Drafting has started or is ready and wait for message approval before enrichment or Settings. Do not render message review from checklist or shortcut instructions; message review requires a messageDraftRecommendation whose basis proves the generate-messages prompt, required message assets, and validation gate ran for the current campaign/table execution slice. Do not automatically rerun Message Drafting after filters/enrichment finish; show the initial draft by default and offer an enriched rewrite only with explicit user opt-in. Handoff and recommendation output are Markdown with labeled fields, not raw JSON.',
374
- prepareMessagesRule: 'Default create-campaign stays on the existing reviewBatchLimit:15 first campaign-table execution slice. Only call start_campaign_message_preparation when the user explicitly asks for more prepared messages, a send count, or to fill up/load sends for senders. Treat "fill up/load sends" as capacity-fill preparation: calculate the bounded target from sender capacity when needed, then let the job queue pending Enrich Prospect cells first, wait for ICP/rubric and Generate Message to cascade, and mark ready or approve only the target cohort. Do not interpret checkedRows as enriched rows; it is only the table cursor. Poll get_campaign_message_preparation_status and summarize enrichedRows, needsEnrichRows, activeCellCount, passed/prepared/approved count, target, estimated row budget remaining, and stopReason. Prepared, approved, and ready_to_schedule rows are intermediate states; never call them scheduled unless a re-read proves scheduler-owned scheduled cells with non-null scheduledFor. For "prepare/generate X messages", set targetPreparedMessages:X, omit maxRowsToCheck so the backend calibrates on at least 100 actually-enriched rows, estimates the row budget from observed rubric/pass yield, caps maxRowsToCheck at 300, and use approvalMode:mark_ready. After the calibration sample settles, the backend continues in batches capped at 100 newly checked rows and will not pull another row batch while the current checked batch still has queueable or active cells. For "approve X messages", use approvalMode:approve but still do not launch. For "schedule X sends" or "fill sender sends", use approvalMode:approve only when the user explicitly asked for approval, approve exactly the bounded X-message cohort during preparation, then re-read campaign/table scheduled counts; if scheduler-owned scheduledFor cells are not present, report prepared/approved/ready - awaiting scheduler instead of success. Do not call start_campaign as part of fill/schedule horizon. Launch/start is a separate explicit human action after the operator intentionally wants sends to go out, and it must still verify that the bounded cohort is the only approved cohort and must not broad approve-all. campaignId is CampaignOffer.id. If the user asks to stop preparation, the target is wrong, or status shows the wrong campaign/table, call cancel_campaign_message_preparation; otherwise do not cancel a healthy prepare run. cancel_campaign_message_preparation cancels the same pending workflow-table cells as the UI Cancel Pending Cells action. Low-level selectors are diagnostics and recovery only for this lane. start_campaign remains forbidden until explicit launch/start approval outside fill-horizon.',
374
+ prepareMessagesRule: 'Default create-campaign stays on the existing reviewBatchLimit:15 first campaign-table execution slice. Only call start_campaign_message_preparation when the user explicitly asks for more prepared messages, a send count, or to fill up/load sends for senders. Treat "fill up/load sends" as capacity-fill preparation: calculate the bounded target from sender capacity when needed, then let the job queue pending Enrich Prospect cells first, wait for ICP/rubric and Generate Message to cascade, and mark ready or approve only the target cohort. Do not interpret checkedRows as enriched rows; it is only the table cursor. Poll get_campaign_message_preparation_status and summarize enrichedRows, needsEnrichRows, activeCellCount, passed/prepared/approved count, target, estimated row budget remaining, and stopReason. For "prepare/generate X messages", set targetPreparedMessages:X, omit maxRowsToCheck so the backend calibrates on at least 100 actually-enriched rows, estimates the row budget from observed rubric/pass yield, caps maxRowsToCheck at 2500, and use approvalMode:mark_ready. After the calibration sample settles, the backend adapts later batches up to 250 rows while recalculating yield. For "approve X messages", use approvalMode:approve but still do not launch. For "schedule X sends" or "fill sender sends", use approvalMode:approve to approve exactly the bounded X-message cohort during preparation, then continue through sender, sequence, and final launch greenlight; final launch must verify that bounded cohort and must not broad approve-all. campaignId is CampaignOffer.id. If the user asks to stop preparation, the target is wrong, or status shows the wrong campaign/table, call cancel_campaign_message_preparation; otherwise do not cancel a healthy prepare run. cancel_campaign_message_preparation cancels the same pending workflow-table cells as the UI Cancel Pending Cells action. Low-level selectors are diagnostics and recovery only for this lane. start_campaign remains forbidden until final launch greenlight.',
375
375
  },
376
376
  };
377
377
  }