@nebutra/outreach-engine 0.1.1

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.
@@ -0,0 +1,120 @@
1
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { parsePlayMarkdown } from "@nebutra/play-loader";
5
+ import { afterEach, describe, expect, it } from "vitest";
6
+ import {
7
+ buildEmailSequence,
8
+ checkEmailCompliance,
9
+ defineIcp,
10
+ OutreachEngine,
11
+ readOutreachEngineDebug,
12
+ } from "./index";
13
+
14
+ let root: string | undefined;
15
+ let engine: OutreachEngine | undefined;
16
+
17
+ afterEach(async () => {
18
+ if (engine) await engine.close();
19
+ if (root) await rm(root, { recursive: true, force: true });
20
+ root = undefined;
21
+ engine = undefined;
22
+ });
23
+
24
+ async function open(): Promise<OutreachEngine> {
25
+ root = await mkdtemp(join(tmpdir(), "outreach-engine-"));
26
+ engine = await OutreachEngine.open(root, { tenantId: "tenant_a" });
27
+ return engine;
28
+ }
29
+
30
+ describe("outreach-engine", () => {
31
+ it("turns fuzzy ICP language into a structured targeting plan", () => {
32
+ const icp = defineIcp("decision makers at mid-size D2C e-commerce companies in the US");
33
+
34
+ expect(icp.industries).toContain("e-commerce");
35
+ expect(icp.companySize).toEqual({ min: 50, max: 500 });
36
+ expect(icp.titles).toContain("Head of Growth");
37
+ expect(icp.geo).toContain("US");
38
+ });
39
+
40
+ it("builds compliance-gated email variants with unsubscribe requirements", () => {
41
+ const sequence = buildEmailSequence({
42
+ product: "Loop helps indie devs debug production issues",
43
+ sequenceLength: 3,
44
+ brandVoice: ["technical", "warm"],
45
+ });
46
+ const compliance = checkEmailCompliance(sequence[0], {
47
+ physicalAddress: "123 Market St, San Francisco, CA",
48
+ unsubscribeUrl: "https://loop.test/unsubscribe",
49
+ gdprBasis: "legitimate_interest",
50
+ });
51
+
52
+ expect(sequence).toHaveLength(3);
53
+ expect(sequence[0]?.body).toContain("unsubscribe");
54
+ expect(compliance.ok).toBe(true);
55
+ });
56
+
57
+ it("runs outreach_campaign as a draft with leads, sequence, schedule, and event", async () => {
58
+ const runtime = await open();
59
+
60
+ const campaign = await runtime.createCampaign({
61
+ tenantId: "tenant_a",
62
+ icpDescription: "decision makers at mid-size D2C e-commerce companies",
63
+ targetCount: 12,
64
+ product: "Loop helps teams debug production issues",
65
+ sequenceLength: 3,
66
+ sendPerDay: 4,
67
+ senderEmails: ["founder@loop.test"],
68
+ complianceProfile: {
69
+ physicalAddress: "123 Market St, San Francisco, CA",
70
+ unsubscribeUrl: "https://loop.test/unsubscribe",
71
+ gdprBasis: "legitimate_interest",
72
+ },
73
+ });
74
+
75
+ expect(campaign.play).toBe("outreach_campaign");
76
+ expect(campaign.status).toBe("draft");
77
+ expect(campaign.leads).toHaveLength(12);
78
+ expect(campaign.sequence).toHaveLength(3);
79
+ expect(campaign.schedule.dailyLimit).toBe(4);
80
+ expect(campaign.compliance.ok).toBe(true);
81
+ expect(campaign.eventId).toEqual(expect.any(String));
82
+ await expect(readOutreachEngineDebug(root)).resolves.toEqual(expect.any(Array));
83
+ });
84
+
85
+ it("rejects persistent campaign creation without tenant context", async () => {
86
+ const runtime = await open();
87
+
88
+ await expect(
89
+ runtime.createCampaign({
90
+ tenantId: "",
91
+ icpDescription: "SaaS CTOs",
92
+ targetCount: 5,
93
+ product: "Loop",
94
+ sequenceLength: 2,
95
+ sendPerDay: 2,
96
+ senderEmails: ["founder@loop.test"],
97
+ complianceProfile: {
98
+ physicalAddress: "123 Market St",
99
+ unsubscribeUrl: "https://loop.test/unsubscribe",
100
+ gdprBasis: "legitimate_interest",
101
+ },
102
+ }),
103
+ ).rejects.toMatchObject({
104
+ capability: "outreach-engine",
105
+ suggestion: expect.stringContaining("tenantId"),
106
+ });
107
+ });
108
+
109
+ it("keeps the outreach campaign as SKILL.md instead of a new workflow format", async () => {
110
+ const skill = await readFile(
111
+ join(process.cwd(), "plays", "outreach_campaign", "SKILL.md"),
112
+ "utf8",
113
+ );
114
+ const play = parsePlayMarkdown(skill);
115
+
116
+ expect(play.meta).toMatchObject({ name: "outreach_campaign", kind: "play" });
117
+ expect(play.requiredSkills).toContain("content_store.write");
118
+ expect(play.subAgents.map((agent) => agent.role)).toContain("lead_researcher");
119
+ });
120
+ });
package/src/index.ts ADDED
@@ -0,0 +1,316 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { appendCapabilityDebug, readCapabilityDebug } from "@nebutra/capability-kit/debug";
4
+ import { ContentStore } from "@nebutra/content-store";
5
+ import { CapabilityError } from "@nebutra/errors";
6
+ import { EventLog } from "@nebutra/event-log";
7
+ import { assetId } from "@nebutra/generation-context";
8
+
9
+ export interface IcpDefinition {
10
+ readonly industries: readonly string[];
11
+ readonly companySize: { readonly min: number; readonly max: number };
12
+ readonly titles: readonly string[];
13
+ readonly geo: readonly string[];
14
+ readonly techStack: readonly string[];
15
+ }
16
+
17
+ export interface ComplianceProfile {
18
+ readonly physicalAddress: string;
19
+ readonly unsubscribeUrl: string;
20
+ readonly gdprBasis?: "legitimate_interest" | "consent" | "existing_customer";
21
+ }
22
+
23
+ export interface EmailVariant {
24
+ readonly step: number;
25
+ readonly subject: string;
26
+ readonly body: string;
27
+ readonly daysAfterPrevious: number;
28
+ }
29
+
30
+ export interface ComplianceReport {
31
+ readonly ok: boolean;
32
+ readonly checks: {
33
+ readonly hasUnsubscribeLink: boolean;
34
+ readonly hasPhysicalAddress: boolean;
35
+ readonly hasClearSubject: boolean;
36
+ readonly gdprBasisDocumented: boolean;
37
+ };
38
+ readonly suggestion?: string;
39
+ }
40
+
41
+ export interface CampaignInput {
42
+ readonly tenantId?: string;
43
+ readonly icpDescription: string;
44
+ readonly targetCount: number;
45
+ readonly product: string;
46
+ readonly sequenceLength: number;
47
+ readonly sendPerDay: number;
48
+ readonly senderEmails: readonly string[];
49
+ readonly complianceProfile: ComplianceProfile;
50
+ }
51
+
52
+ export interface Lead {
53
+ readonly id: string;
54
+ readonly company: string;
55
+ readonly title: string;
56
+ readonly source: "local-plan";
57
+ readonly confidence: number;
58
+ }
59
+
60
+ export interface CampaignPackage {
61
+ readonly tenantId: string;
62
+ readonly play: "outreach_campaign";
63
+ readonly id: string;
64
+ readonly status: "draft";
65
+ readonly icp: IcpDefinition;
66
+ readonly leads: readonly Lead[];
67
+ readonly sequence: readonly EmailVariant[];
68
+ readonly compliance: ComplianceReport;
69
+ readonly schedule: {
70
+ readonly dailyLimit: number;
71
+ readonly senderEmails: readonly string[];
72
+ readonly requiresApprovalBeforeSend: true;
73
+ };
74
+ readonly artifactPath: string;
75
+ readonly eventId: string;
76
+ }
77
+
78
+ export interface SequenceInput {
79
+ readonly product: string;
80
+ readonly sequenceLength: number;
81
+ readonly brandVoice?: readonly string[];
82
+ }
83
+
84
+ export interface OutreachDoctorReport {
85
+ readonly capability: "outreach-engine";
86
+ readonly ok: boolean;
87
+ readonly checkedAt: string;
88
+ readonly plays: readonly string[];
89
+ readonly sendMode: "draft-only";
90
+ readonly adapters: readonly { readonly provider: string; readonly ok: boolean }[];
91
+ }
92
+
93
+ export interface OutreachEngineOptions {
94
+ readonly tenantId?: string;
95
+ readonly root?: string;
96
+ readonly debugRoot?: string;
97
+ readonly contentStore?: ContentStore;
98
+ readonly eventLog?: EventLog;
99
+ }
100
+
101
+ function requireTenant(explicit: string | undefined, fallback: string | undefined): string {
102
+ const tenantId = explicit ?? fallback;
103
+ if (!tenantId?.trim()) {
104
+ throw new CapabilityError("outreach-engine", "Outreach Engine requires tenant context", {
105
+ suggestion: "Pass tenantId before creating or persisting a campaign.",
106
+ statusCode: 400,
107
+ });
108
+ }
109
+ return tenantId;
110
+ }
111
+
112
+ function slug(value: string): string {
113
+ return value
114
+ .toLowerCase()
115
+ .replace(/[^a-z0-9]+/g, "_")
116
+ .replace(/^_+|_+$/g, "")
117
+ .slice(0, 48);
118
+ }
119
+
120
+ export function defineIcp(description: string): IcpDefinition {
121
+ const text = description.toLowerCase();
122
+ const industries =
123
+ text.includes("e-commerce") || text.includes("d2c")
124
+ ? ["e-commerce", "D2C"]
125
+ : text.includes("saas")
126
+ ? ["SaaS"]
127
+ : ["startup"];
128
+ const titles = text.includes("cto")
129
+ ? ["CTO", "VP Engineering", "Head of Engineering"]
130
+ : ["VP Marketing", "Head of Growth", "CMO"];
131
+ const companySize =
132
+ text.includes("mid-size") || text.includes("medium")
133
+ ? { min: 50, max: 500 }
134
+ : { min: 1, max: 50 };
135
+ const geo = text.includes("eu") ? ["EU"] : text.includes("us") ? ["US"] : ["US", "EU"];
136
+ const techStack = text.includes("shopify") ? ["Shopify"] : [];
137
+ return { industries, companySize, titles, geo, techStack };
138
+ }
139
+
140
+ export function buildEmailSequence(input: SequenceInput): readonly EmailVariant[] {
141
+ const length = Math.max(1, Math.min(5, input.sequenceLength));
142
+ const voice = input.brandVoice?.join(", ") ?? "clear, useful";
143
+ return Array.from({ length }, (_, index) => {
144
+ const step = index + 1;
145
+ return {
146
+ step,
147
+ subject: step === 1 ? "Quick question" : `Following up ${step}`,
148
+ body: [
149
+ `Hi {{first_name}},`,
150
+ "",
151
+ step === 1
152
+ ? `I noticed {{company}} may care about ${input.product}.`
153
+ : `Sharing one more angle on ${input.product}.`,
154
+ `Tone: ${voice}.`,
155
+ "",
156
+ "If this is not useful, unsubscribe here: {{unsubscribe_url}}.",
157
+ "{{physical_address}}",
158
+ ].join("\n"),
159
+ daysAfterPrevious: step === 1 ? 0 : step + 1,
160
+ };
161
+ });
162
+ }
163
+
164
+ export function checkEmailCompliance(
165
+ email: EmailVariant | undefined,
166
+ profile: ComplianceProfile,
167
+ ): ComplianceReport {
168
+ const body = email?.body ?? "";
169
+ const checks = {
170
+ hasUnsubscribeLink: body.includes("unsubscribe") && profile.unsubscribeUrl.startsWith("http"),
171
+ hasPhysicalAddress: profile.physicalAddress.trim().length > 4,
172
+ hasClearSubject: Boolean(email?.subject.trim()),
173
+ gdprBasisDocumented: Boolean(profile.gdprBasis),
174
+ };
175
+ const ok = Object.values(checks).every(Boolean);
176
+ return {
177
+ ok,
178
+ checks,
179
+ ...(!ok
180
+ ? {
181
+ suggestion:
182
+ "Add unsubscribe URL, physical address, clear subject, and GDPR basis before any send adapter can run.",
183
+ }
184
+ : {}),
185
+ };
186
+ }
187
+
188
+ function plannedLeads(icp: IcpDefinition, count: number): readonly Lead[] {
189
+ const size = Math.max(1, Math.min(250, count));
190
+ return Array.from({ length: size }, (_, index) => ({
191
+ id: `lead_${String(index + 1).padStart(3, "0")}`,
192
+ company: `${icp.industries[0] ?? "startup"} account ${index + 1}`,
193
+ title: icp.titles[index % icp.titles.length] ?? "Founder",
194
+ source: "local-plan",
195
+ confidence: 0.72,
196
+ }));
197
+ }
198
+
199
+ export class OutreachEngine {
200
+ readonly #tenantId: string | undefined;
201
+ readonly #debugRoot: string;
202
+ readonly #contentStore: ContentStore;
203
+ readonly #eventLog: EventLog;
204
+
205
+ private constructor(
206
+ options: OutreachEngineOptions & { contentStore: ContentStore; eventLog: EventLog },
207
+ ) {
208
+ this.#tenantId = options.tenantId;
209
+ this.#debugRoot = options.debugRoot ?? process.cwd();
210
+ this.#contentStore = options.contentStore;
211
+ this.#eventLog = options.eventLog;
212
+ }
213
+
214
+ static async open(
215
+ root = ".nebutra/outreach-engine",
216
+ options: Omit<OutreachEngineOptions, "root" | "contentStore" | "eventLog"> = {},
217
+ ): Promise<OutreachEngine> {
218
+ const tenantId = options.tenantId ?? "local";
219
+ await mkdir(root, { recursive: true });
220
+ const contentStore = await ContentStore.open(join(root, "content"), { tenantId });
221
+ const eventLog = await EventLog.open(join(root, "event-log"), { tenantId });
222
+ return new OutreachEngine({ ...options, tenantId, root, contentStore, eventLog });
223
+ }
224
+
225
+ async createCampaign(input: CampaignInput): Promise<CampaignPackage> {
226
+ const tenantId = requireTenant(input.tenantId, this.#tenantId);
227
+ const icp = defineIcp(input.icpDescription);
228
+ const sequence = buildEmailSequence({
229
+ product: input.product,
230
+ sequenceLength: input.sequenceLength,
231
+ brandVoice: ["specific", "useful", "respectful"],
232
+ });
233
+ const compliance = checkEmailCompliance(sequence[0], input.complianceProfile);
234
+ if (!compliance.ok) {
235
+ throw new CapabilityError("outreach-engine", "Campaign failed compliance checks", {
236
+ suggestion:
237
+ compliance.suggestion ??
238
+ "Add unsubscribe URL, physical address, clear subject, and GDPR basis.",
239
+ statusCode: 400,
240
+ metadata: compliance.checks,
241
+ });
242
+ }
243
+ const id = assetId("outreach_campaign", slug(input.icpDescription));
244
+ const leads = plannedLeads(icp, input.targetCount);
245
+ const artifactPath = `outreach/${id}.json`;
246
+ const draft = {
247
+ id,
248
+ status: "draft",
249
+ icp,
250
+ leads,
251
+ sequence,
252
+ schedule: {
253
+ dailyLimit: Math.max(1, Math.min(30, input.sendPerDay)),
254
+ senderEmails: input.senderEmails,
255
+ requiresApprovalBeforeSend: true,
256
+ } as const,
257
+ };
258
+ const content = `${JSON.stringify(draft, null, 2)}\n`;
259
+ await this.#contentStore.write(artifactPath, content);
260
+ const eventId = await this.#eventLog.commit({
261
+ traceId: id,
262
+ kind: "content_write",
263
+ affected: [artifactPath],
264
+ parent: null,
265
+ snapshot: { [artifactPath]: content },
266
+ });
267
+ const campaign: CampaignPackage = {
268
+ tenantId,
269
+ play: "outreach_campaign",
270
+ id,
271
+ status: "draft",
272
+ icp,
273
+ leads,
274
+ sequence,
275
+ compliance,
276
+ schedule: draft.schedule,
277
+ artifactPath,
278
+ eventId,
279
+ };
280
+ await this.#debug({ type: "campaign_draft", tenantId, campaignId: id, eventId });
281
+ return campaign;
282
+ }
283
+
284
+ async doctor(): Promise<OutreachDoctorReport> {
285
+ return {
286
+ capability: "outreach-engine",
287
+ ok: true,
288
+ checkedAt: new Date().toISOString(),
289
+ plays: ["outreach_campaign"],
290
+ sendMode: "draft-only",
291
+ adapters: [
292
+ { provider: "local-plan", ok: true },
293
+ { provider: "integration-vault-email", ok: false },
294
+ { provider: "crm-sync", ok: false },
295
+ ],
296
+ };
297
+ }
298
+
299
+ async close(): Promise<void> {
300
+ await this.#contentStore.close();
301
+ }
302
+
303
+ async #debug(entry: Record<string, unknown>): Promise<void> {
304
+ await mkdir(dirname(join(this.#debugRoot, ".nebutra", "debug", "outreach-engine.jsonl")), {
305
+ recursive: true,
306
+ });
307
+ await appendCapabilityDebug("outreach-engine", entry, { root: this.#debugRoot });
308
+ }
309
+ }
310
+
311
+ export async function readOutreachEngineDebug(
312
+ root = process.cwd(),
313
+ limit = 20,
314
+ ): Promise<unknown[]> {
315
+ return readCapabilityDebug("outreach-engine", { root, limit });
316
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": ".",
6
+ "types": ["node", "vitest"]
7
+ },
8
+ "include": ["src/**/*.ts", "examples/**/*.ts"]
9
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entry: ["src/index.ts", "src/cli.ts"],
5
+ format: ["esm"],
6
+ sourcemap: true,
7
+ dts: true,
8
+ clean: true,
9
+ target: "es2022",
10
+ external: [/^@nebutra\//],
11
+ });