fullstackgtm 0.39.0 → 0.41.0
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/CHANGELOG.md +74 -0
- package/README.md +42 -1
- package/dist/cli.js +615 -6
- package/dist/connectors/atsBoards.d.ts +60 -0
- package/dist/connectors/atsBoards.js +179 -0
- package/dist/connectors/prospectSources.d.ts +7 -5
- package/dist/connectors/prospectSources.js +82 -47
- package/dist/draft.d.ts +182 -0
- package/dist/draft.js +333 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/judge.d.ts +209 -0
- package/dist/judge.js +490 -0
- package/dist/judgeEval.d.ts +141 -0
- package/dist/judgeEval.js +331 -0
- package/dist/llm.d.ts +13 -0
- package/dist/llm.js +18 -2
- package/dist/schedule.js +11 -1
- package/dist/signals.d.ts +197 -0
- package/dist/signals.js +515 -0
- package/docs/api.md +2 -2
- package/package.json +1 -1
- package/src/cli.ts +696 -7
- package/src/connectors/atsBoards.ts +242 -0
- package/src/connectors/prospectSources.ts +94 -43
- package/src/draft.ts +463 -0
- package/src/index.ts +94 -0
- package/src/judge.ts +661 -0
- package/src/judgeEval.ts +459 -0
- package/src/llm.ts +31 -2
- package/src/schedule.ts +11 -1
- package/src/signals.ts +685 -0
package/src/draft.ts
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import { forcedToolCall, type LlmCallOptions } from "./llm.ts";
|
|
2
|
+
import { isGroundedSpan, type JudgeDecision } from "./judge.ts";
|
|
3
|
+
import { normalizeAccountDomain, type Signal } from "./signals.ts";
|
|
4
|
+
import type { GtmEvidence, GtmObjectType, PatchOperation, PatchPlan } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The draft layer: turn a judge `send` decision into ONE trigger-grounded opener
|
|
8
|
+
* per hot account, emitted as a governed `create_task` PatchOperation so it flows
|
|
9
|
+
* through the existing `plans approve` → `apply` chain. This is the last thin
|
|
10
|
+
* piece of the brain: signals (when) → judge (who) → DRAFT (what to say) →
|
|
11
|
+
* governed apply (sent only on approval).
|
|
12
|
+
*
|
|
13
|
+
* GOVERNANCE — structural, forever: a draft is a PROPOSAL, never a send. `draft`
|
|
14
|
+
* stages a `needs_approval` PatchPlan of `create_task` ops carrying the opener
|
|
15
|
+
* text; it calls NO email/LinkedIn send API and adds none. `apply` writes the
|
|
16
|
+
* draft into the CRM (as a task for a human/downstream sender to act on); it does
|
|
17
|
+
* not transmit a message. `riskLevel: "low"` (a draft is reversible — it's text
|
|
18
|
+
* in a task) but `approvalRequired: true` ALWAYS, so a draft is never auto-applied
|
|
19
|
+
* even under a scheduled run.
|
|
20
|
+
*
|
|
21
|
+
* EVIDENCE GATE — structural: the opener's FIRST LINE must contain a verbatim
|
|
22
|
+
* normalized-whitespace span (≥12 chars) of the decision's `whyNow` (itself a
|
|
23
|
+
* verbatim span of a credited signal quote, gated by the judge). A draft whose
|
|
24
|
+
* line 1 does not ground in the trigger is REJECTED, not saved — the self-discard
|
|
25
|
+
* rule: "if the message could have gone out last month unchanged, throw it away."
|
|
26
|
+
*
|
|
27
|
+
* NO-KEY PATH — honestly degraded: without an LLM key, `draft` emits a clearly
|
|
28
|
+
* labeled template stub (`[[DRAFT - no LLM key]] ...`) rather than fake authored
|
|
29
|
+
* copy, so an operator without a key sees the structure but is never handed wooden
|
|
30
|
+
* copy passed off as a real draft.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Types
|
|
35
|
+
|
|
36
|
+
export type DraftChannel = "email" | "linkedin" | "task";
|
|
37
|
+
|
|
38
|
+
export const DRAFT_CHANNELS: DraftChannel[] = ["email", "linkedin", "task"];
|
|
39
|
+
|
|
40
|
+
/** A single authored opener for one hot account, before it becomes a patch op. */
|
|
41
|
+
export type Draft = {
|
|
42
|
+
accountDomain: string;
|
|
43
|
+
/** The full opener body. */
|
|
44
|
+
opener: string;
|
|
45
|
+
/** The decision this draft was authored from. */
|
|
46
|
+
decision: JudgeDecision;
|
|
47
|
+
/** The credited signal whose quote grounds the opener (the trigger anchor). */
|
|
48
|
+
signal: Signal;
|
|
49
|
+
/** "deterministic" (the labeled stub) | "llm:<provider>:<model>". */
|
|
50
|
+
producedBy: string;
|
|
51
|
+
/** True when the grounding signal is older than the freshness window. */
|
|
52
|
+
staleTrigger: boolean;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** A draft that failed the first-line evidence gate — surfaced, never saved. */
|
|
56
|
+
export type RejectedDraft = {
|
|
57
|
+
accountDomain: string;
|
|
58
|
+
opener: string;
|
|
59
|
+
reason: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type DraftResult = {
|
|
63
|
+
plan: PatchPlan;
|
|
64
|
+
drafts: Draft[];
|
|
65
|
+
rejected: RejectedDraft[];
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// Stable hashing (FNV-1a) — duplicated to keep this file importable without the
|
|
70
|
+
// audit engine (the judge.ts/signals.ts/market.ts/enrich.ts precedent).
|
|
71
|
+
|
|
72
|
+
function fnv1a(value: string): string {
|
|
73
|
+
let hash = 0x811c9dc5;
|
|
74
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
75
|
+
hash ^= value.charCodeAt(i);
|
|
76
|
+
hash = Math.imul(hash, 0x01000193);
|
|
77
|
+
}
|
|
78
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Stable patch-operation id for a draft op (mirrors enrich's `op_enr_<hash>`). */
|
|
82
|
+
export function draftOperationId(channel: string, accountDomain: string): string {
|
|
83
|
+
return `op_draft_${fnv1a(`${channel}:${accountDomain}`)}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Stable evidence id for the signal a draft is grounded in. */
|
|
87
|
+
export function draftEvidenceId(signalId: string): string {
|
|
88
|
+
return `ev_draft_${fnv1a(signalId)}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
// Freshness / stale-trigger
|
|
93
|
+
|
|
94
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Default freshness window for the self-discard rule. A draft whose grounding
|
|
98
|
+
* signal's `firstSeen` is older than this is flagged `staleTrigger` so the human
|
|
99
|
+
* reviewer catches a manufactured-relevance opener before approving it. 14 days
|
|
100
|
+
* mirrors the judge's `FRESH_SIGNAL_DAYS`.
|
|
101
|
+
*/
|
|
102
|
+
export const DEFAULT_FRESHNESS_DAYS = 14;
|
|
103
|
+
|
|
104
|
+
export function isStaleTrigger(firstSeen: string, now: Date, windowDays = DEFAULT_FRESHNESS_DAYS): boolean {
|
|
105
|
+
const seen = Date.parse(firstSeen);
|
|
106
|
+
if (!Number.isFinite(seen)) return true; // an undateable trigger can't be proven fresh — treat as stale
|
|
107
|
+
return now.getTime() - seen > windowDays * DAY_MS;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// Voice rules / opener hygiene (the editable prompt's mechanically-checkable contract)
|
|
112
|
+
|
|
113
|
+
export const DEFAULT_DRAFT_PROMPT = `You are writing ONE cold opener for a single hot account, grounded in a real, fresh trigger.
|
|
114
|
+
The opener's FIRST LINE must quote the trigger back in the buyer's own words — copy a verbatim span of the why-now below into line 1. Never open with "Hi {{firstName}}" or any greeting placeholder.
|
|
115
|
+
Rules (the operator owns these — edit this prompt to change them):
|
|
116
|
+
- Line 1: open on the real trigger, in the buyer's words. It MUST contain a verbatim span of the why-now quote.
|
|
117
|
+
- One sentence tying the trigger to ONE problem you solve. Specific, not generic.
|
|
118
|
+
- End with ONE low-friction ask. No fake urgency, no "circling back".
|
|
119
|
+
- No em dashes. No "Hi {{firstName}}". Keep it short — a real trigger does not need nine sentences.`;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Strip em dashes (voice rule), collapse runs of whitespace WITHIN a line while
|
|
123
|
+
* preserving line breaks (line 1 grounding depends on the first line surviving
|
|
124
|
+
* intact), and trim trailing whitespace. Returns the cleaned opener.
|
|
125
|
+
*/
|
|
126
|
+
export function sanitizeOpener(opener: string): string {
|
|
127
|
+
return opener
|
|
128
|
+
.replace(/—/g, "-")
|
|
129
|
+
.split("\n")
|
|
130
|
+
.map((line) => line.replace(/[ \t]+/g, " ").trimEnd())
|
|
131
|
+
.join("\n")
|
|
132
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
133
|
+
.trim();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The first non-empty line of an opener — the line the evidence gate checks. */
|
|
137
|
+
export function firstLine(opener: string): string {
|
|
138
|
+
for (const line of opener.split("\n")) {
|
|
139
|
+
if (line.trim()) return line.trim();
|
|
140
|
+
}
|
|
141
|
+
return "";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Does the opener's first line contain a verbatim ≥12-char normalized span of the
|
|
146
|
+
* decision's whyNow? This is the self-discard gate: a draft that doesn't ground
|
|
147
|
+
* line 1 in the trigger is rejected, not saved.
|
|
148
|
+
*/
|
|
149
|
+
export function firstLineGroundedInTrigger(opener: string, whyNow: string): boolean {
|
|
150
|
+
return isGroundedSpan(whyNow, firstLine(opener));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Reject openers that lead with a banned greeting placeholder. */
|
|
154
|
+
export function hasBannedGreeting(opener: string): boolean {
|
|
155
|
+
return /\bhi\s+\{\{\s*firstname\s*\}\}/i.test(opener) || /^\s*hi\s+\{\{/i.test(opener);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
// Evidence builder (evidenceFor idiom)
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Build a `GtmEvidence` from the signal a draft is grounded in — the trigger that
|
|
163
|
+
* justified the opener. `sourceSystem` is "web" for fetched signals (ATS boards
|
|
164
|
+
* via global fetch) and "manual" for ingested ones; `text` is the VERBATIM signal
|
|
165
|
+
* quote (the evidence anchor reused all the way from `signals fetch`).
|
|
166
|
+
*/
|
|
167
|
+
export function draftEvidence(signal: Signal, capturedAt: string): GtmEvidence {
|
|
168
|
+
const fetched = signal.source !== "ingest";
|
|
169
|
+
return {
|
|
170
|
+
id: draftEvidenceId(signal.id),
|
|
171
|
+
sourceSystem: fetched ? "web" : "manual",
|
|
172
|
+
sourceObjectType: "signal",
|
|
173
|
+
sourceObjectId: signal.id,
|
|
174
|
+
title: `${signal.bucket} signal for ${signal.accountDomain}: ${signal.trigger}`,
|
|
175
|
+
text: signal.quote,
|
|
176
|
+
capturedAt,
|
|
177
|
+
metadata: {
|
|
178
|
+
bucket: signal.bucket,
|
|
179
|
+
trigger: signal.trigger,
|
|
180
|
+
sourceUrl: signal.sourceUrl,
|
|
181
|
+
firstSeen: signal.firstSeen,
|
|
182
|
+
signalSource: signal.source,
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
// Opener authoring: deterministic stub + gated LLM path
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The no-key, honestly-degraded baseline. Emits a clearly-labeled template stub
|
|
192
|
+
* — NEVER fake authored copy. Line 1 is the verbatim whyNow (so the first-line
|
|
193
|
+
* evidence gate passes by construction), followed by the play (if any) as the
|
|
194
|
+
* "what to say" scaffold the operator fills in once they add a key.
|
|
195
|
+
*/
|
|
196
|
+
export function deterministicOpener(decision: JudgeDecision): string {
|
|
197
|
+
const whyNow = decision.whyNow.trim();
|
|
198
|
+
const play = decision.play.trim();
|
|
199
|
+
const tail = play ? `\n→ ${play}` : "";
|
|
200
|
+
return `[[DRAFT - no LLM key]] ${whyNow}${tail}`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export const DRAFT_SCHEMA = {
|
|
204
|
+
type: "object",
|
|
205
|
+
required: ["opener"],
|
|
206
|
+
properties: {
|
|
207
|
+
opener: {
|
|
208
|
+
type: "string",
|
|
209
|
+
description:
|
|
210
|
+
"The full cold opener. The FIRST line MUST contain a verbatim span copied from the why-now quote. " +
|
|
211
|
+
"One problem sentence, one low-friction ask. No greeting, no 'Hi {{firstName}}', no em dashes.",
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
} as const;
|
|
215
|
+
|
|
216
|
+
type DraftLlmResult = { opener?: string };
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The LLM drafter for one account. Forced tool call with `DRAFT_SCHEMA` + the
|
|
220
|
+
* editable prompt; then the FIRST-LINE evidence gate: line 1 must contain a
|
|
221
|
+
* verbatim ≥12-char span of the decision's whyNow. Retry once with corrective
|
|
222
|
+
* feedback (the judge/market idiom), then — rather than store an ungrounded
|
|
223
|
+
* opener — fall back to the deterministic stub. The brain NEVER ships an opener
|
|
224
|
+
* whose first line isn't grounded in the trigger.
|
|
225
|
+
*/
|
|
226
|
+
export async function draftOpenerLlm(
|
|
227
|
+
decision: JudgeDecision,
|
|
228
|
+
signal: Signal,
|
|
229
|
+
promptTemplate: string,
|
|
230
|
+
llm: LlmCallOptions,
|
|
231
|
+
): Promise<{ opener: string; producedBy: string; grounded: boolean }> {
|
|
232
|
+
const model = llm.model ?? "claude-haiku-4-5";
|
|
233
|
+
const producedBy = `llm:${llm.provider}:${model}`;
|
|
234
|
+
const basePrompt = `${promptTemplate}
|
|
235
|
+
|
|
236
|
+
Account: ${decision.accountDomain}
|
|
237
|
+
Why now (your FIRST line must contain a verbatim span of THIS): "${decision.whyNow}"
|
|
238
|
+
The trigger quote (verbatim source): "${signal.quote}"${
|
|
239
|
+
decision.play ? `\nA play the judge suggested (do not copy verbatim): ${decision.play}` : ""
|
|
240
|
+
}`;
|
|
241
|
+
|
|
242
|
+
const attempt = async (feedback: string): Promise<string | null> => {
|
|
243
|
+
const result = (await forcedToolCall(
|
|
244
|
+
feedback ? `${basePrompt}\n${feedback}` : basePrompt,
|
|
245
|
+
"draft_opener",
|
|
246
|
+
DRAFT_SCHEMA,
|
|
247
|
+
model,
|
|
248
|
+
llm,
|
|
249
|
+
)) as DraftLlmResult;
|
|
250
|
+
const opener = sanitizeOpener((result.opener ?? "").trim());
|
|
251
|
+
if (!opener) return null;
|
|
252
|
+
if (hasBannedGreeting(opener)) return null;
|
|
253
|
+
if (!firstLineGroundedInTrigger(opener, decision.whyNow)) return null; // gate failed
|
|
254
|
+
return opener;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const first = await attempt("");
|
|
258
|
+
if (first) return { opener: first, producedBy, grounded: true };
|
|
259
|
+
const retried = await attempt(
|
|
260
|
+
"\nYour previous opener's FIRST line did NOT contain a verbatim span of the why-now quote " +
|
|
261
|
+
"(or it used a banned greeting). Copy a span character-for-character from the why-now into line 1 and rewrite.",
|
|
262
|
+
);
|
|
263
|
+
if (retried) return { opener: retried, producedBy, grounded: true };
|
|
264
|
+
|
|
265
|
+
// Both attempts ungrounded — never store an ungrounded opener. Fall back to the
|
|
266
|
+
// labeled deterministic stub (grounded by construction), but stamp the path that
|
|
267
|
+
// ran so the operator can see the model was reached and gated.
|
|
268
|
+
return { opener: deterministicOpener(decision), producedBy, grounded: false };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
// Orchestration: judge decisions → drafts → governed plan
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Author one opener per hot account and stage them as a `needs_approval` plan of
|
|
276
|
+
* `create_task` PatchOperations, each carrying a `GtmEvidence` (the signal quote)
|
|
277
|
+
* on `plan.evidence` and referenced via `op.evidenceIds`. Read-only: builds the
|
|
278
|
+
* plan in memory; the caller persists it via `createFilePlanStore().save(plan)`
|
|
279
|
+
* only on `--save`. NEVER sends.
|
|
280
|
+
*
|
|
281
|
+
* - Takes decisions with `decision === "send"` and `score >= minScore`.
|
|
282
|
+
* - Picks the credited signal whose quote grounds the whyNow as the trigger
|
|
283
|
+
* anchor (the evidence the opener traces back to).
|
|
284
|
+
* - Authors the opener: LLM (gated, first-line evidence) when `llm` is provided,
|
|
285
|
+
* else the labeled deterministic stub.
|
|
286
|
+
* - First-line evidence gate: an opener whose line 1 doesn't ground in the whyNow
|
|
287
|
+
* is REJECTED (surfaced in `rejected`, never an op). The deterministic stub and
|
|
288
|
+
* the LLM fallback are grounded by construction, so they always pass.
|
|
289
|
+
* - Stale-trigger: a draft whose grounding signal is older than the freshness
|
|
290
|
+
* window gets a `staleTrigger` warning appended to the op `reason`.
|
|
291
|
+
*/
|
|
292
|
+
export function draft(opts: {
|
|
293
|
+
decisions: JudgeDecision[];
|
|
294
|
+
/** Credited signals by id — supplies the verbatim quote each opener grounds in. */
|
|
295
|
+
signalsById: Map<string, Signal>;
|
|
296
|
+
minScore?: number;
|
|
297
|
+
channel?: DraftChannel;
|
|
298
|
+
/** Pre-authored openers by accountDomain (the LLM path runs in the async caller). */
|
|
299
|
+
openers?: Map<string, { opener: string; producedBy: string; grounded: boolean; signalId: string }>;
|
|
300
|
+
freshnessDays?: number;
|
|
301
|
+
now?: Date;
|
|
302
|
+
}): DraftResult {
|
|
303
|
+
const now = opts.now ?? new Date();
|
|
304
|
+
const nowIso = now.toISOString();
|
|
305
|
+
const minScore = opts.minScore ?? 80;
|
|
306
|
+
const channel: DraftChannel = opts.channel ?? "task";
|
|
307
|
+
const freshnessDays = opts.freshnessDays ?? DEFAULT_FRESHNESS_DAYS;
|
|
308
|
+
// `task`/`email`/`linkedin` all write a CRM task through the same gate; the
|
|
309
|
+
// object the task hangs off is the contact when known, else the account.
|
|
310
|
+
const objectType: GtmObjectType = "contact";
|
|
311
|
+
|
|
312
|
+
const hot = opts.decisions
|
|
313
|
+
.filter((d) => d.decision === "send" && d.score >= minScore)
|
|
314
|
+
.sort((a, b) => b.score - a.score || a.accountDomain.localeCompare(b.accountDomain));
|
|
315
|
+
|
|
316
|
+
const operations: PatchOperation[] = [];
|
|
317
|
+
const evidence: GtmEvidence[] = [];
|
|
318
|
+
const drafts: Draft[] = [];
|
|
319
|
+
const rejected: RejectedDraft[] = [];
|
|
320
|
+
|
|
321
|
+
for (const decision of hot) {
|
|
322
|
+
const domain = normalizeAccountDomain(decision.accountDomain);
|
|
323
|
+
const signal = creditedTriggerSignal(decision, opts.signalsById);
|
|
324
|
+
if (!signal) {
|
|
325
|
+
// No credited signal quote grounds the whyNow — we cannot trace this opener
|
|
326
|
+
// to a trigger, so we cannot draft it. Surface, never emit.
|
|
327
|
+
rejected.push({
|
|
328
|
+
accountDomain: domain,
|
|
329
|
+
opener: "",
|
|
330
|
+
reason: "no credited signal quote grounds the why-now — cannot anchor an opener",
|
|
331
|
+
});
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const authored = opts.openers?.get(domain);
|
|
336
|
+
const opener = authored ? authored.opener : deterministicOpener(decision);
|
|
337
|
+
const producedBy = authored ? authored.producedBy : "deterministic";
|
|
338
|
+
|
|
339
|
+
// First-line evidence gate — the self-discard rule. The deterministic stub and
|
|
340
|
+
// the LLM fallback are grounded by construction; an LLM opener that reached here
|
|
341
|
+
// already passed in draftOpenerLlm, but we re-check defensively (a caller could
|
|
342
|
+
// inject any opener).
|
|
343
|
+
if (!firstLineGroundedInTrigger(opener, decision.whyNow)) {
|
|
344
|
+
rejected.push({
|
|
345
|
+
accountDomain: domain,
|
|
346
|
+
opener,
|
|
347
|
+
reason: "first line does not contain a verbatim span of the why-now trigger",
|
|
348
|
+
});
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const stale = isStaleTrigger(signal.firstSeen, now, freshnessDays);
|
|
353
|
+
const ev = draftEvidence(signal, nowIso);
|
|
354
|
+
evidence.push(ev);
|
|
355
|
+
|
|
356
|
+
const reasonBase = `Signal-grounded opener for ${domain}: "${signal.trigger}"`;
|
|
357
|
+
const reason = stale
|
|
358
|
+
? `${reasonBase} [staleTrigger: grounding signal first seen ${signal.firstSeen}, older than ${freshnessDays}d — could this have gone out last month unchanged?]`
|
|
359
|
+
: reasonBase;
|
|
360
|
+
|
|
361
|
+
operations.push({
|
|
362
|
+
id: draftOperationId(channel, domain),
|
|
363
|
+
objectType,
|
|
364
|
+
objectId: domain,
|
|
365
|
+
operation: "create_task",
|
|
366
|
+
field: "follow_up_task",
|
|
367
|
+
beforeValue: null,
|
|
368
|
+
afterValue: opener.slice(0, 255),
|
|
369
|
+
reason,
|
|
370
|
+
sourceRuleOrPolicy: `draft:${channel}`,
|
|
371
|
+
riskLevel: "low",
|
|
372
|
+
approvalRequired: true,
|
|
373
|
+
rollback: "Close or delete the created task; nothing was sent.",
|
|
374
|
+
evidenceIds: [ev.id],
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
drafts.push({
|
|
378
|
+
accountDomain: domain,
|
|
379
|
+
opener,
|
|
380
|
+
decision,
|
|
381
|
+
signal,
|
|
382
|
+
producedBy,
|
|
383
|
+
staleTrigger: stale,
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const plan: PatchPlan = {
|
|
388
|
+
id: `draft_${fnv1a(`${channel}:${nowIso}:${operations.map((o) => o.id).join(",")}`)}`,
|
|
389
|
+
title: `Draft openers (${channel}) — ${operations.length} hot account(s)`,
|
|
390
|
+
createdAt: nowIso,
|
|
391
|
+
status: operations.length > 0 ? "needs_approval" : "draft",
|
|
392
|
+
dryRun: true,
|
|
393
|
+
summary:
|
|
394
|
+
`${operations.length} drafted opener(s) staged as create_task proposals` +
|
|
395
|
+
`${rejected.length ? `; ${rejected.length} rejected (ungrounded first line)` : ""}. ` +
|
|
396
|
+
"A draft is a proposal — nothing is sent until plans approve -> apply.",
|
|
397
|
+
findings: [],
|
|
398
|
+
evidence,
|
|
399
|
+
operations,
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
return { plan, drafts, rejected };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Pick the credited signal whose quote grounds the decision's whyNow — the
|
|
407
|
+
* trigger the opener traces back to. Prefers a signal whose quote verbatim
|
|
408
|
+
* contains the whyNow span; falls back to the first resolvable credited signal so
|
|
409
|
+
* the evidence chain is never empty when a credit exists.
|
|
410
|
+
*/
|
|
411
|
+
export function creditedTriggerSignal(
|
|
412
|
+
decision: JudgeDecision,
|
|
413
|
+
signalsById: Map<string, Signal>,
|
|
414
|
+
): Signal | undefined {
|
|
415
|
+
let firstResolved: Signal | undefined;
|
|
416
|
+
for (const id of decision.evidence) {
|
|
417
|
+
const signal = signalsById.get(id);
|
|
418
|
+
if (!signal) continue;
|
|
419
|
+
if (!firstResolved) firstResolved = signal;
|
|
420
|
+
if (isGroundedSpan(decision.whyNow, signal.quote)) return signal;
|
|
421
|
+
}
|
|
422
|
+
return firstResolved;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Author openers for the hot decisions via the LLM path (or the deterministic
|
|
427
|
+
* stub when no `llm` is provided), returning the map `draft()` consumes. Kept
|
|
428
|
+
* separate from `draft()` so the plan-assembly stays pure/synchronous and the
|
|
429
|
+
* async authoring is testable in isolation.
|
|
430
|
+
*/
|
|
431
|
+
export async function authorOpeners(opts: {
|
|
432
|
+
decisions: JudgeDecision[];
|
|
433
|
+
signalsById: Map<string, Signal>;
|
|
434
|
+
minScore?: number;
|
|
435
|
+
promptTemplate?: string;
|
|
436
|
+
llm?: LlmCallOptions;
|
|
437
|
+
}): Promise<Map<string, { opener: string; producedBy: string; grounded: boolean; signalId: string }>> {
|
|
438
|
+
const minScore = opts.minScore ?? 80;
|
|
439
|
+
const out = new Map<string, { opener: string; producedBy: string; grounded: boolean; signalId: string }>();
|
|
440
|
+
for (const decision of opts.decisions) {
|
|
441
|
+
if (decision.decision !== "send" || decision.score < minScore) continue;
|
|
442
|
+
const domain = normalizeAccountDomain(decision.accountDomain);
|
|
443
|
+
const signal = creditedTriggerSignal(decision, opts.signalsById);
|
|
444
|
+
if (!signal) continue;
|
|
445
|
+
if (opts.llm && opts.promptTemplate) {
|
|
446
|
+
const { opener, producedBy, grounded } = await draftOpenerLlm(
|
|
447
|
+
decision,
|
|
448
|
+
signal,
|
|
449
|
+
opts.promptTemplate,
|
|
450
|
+
opts.llm,
|
|
451
|
+
);
|
|
452
|
+
out.set(domain, { opener, producedBy, grounded, signalId: signal.id });
|
|
453
|
+
} else {
|
|
454
|
+
out.set(domain, {
|
|
455
|
+
opener: deterministicOpener(decision),
|
|
456
|
+
producedBy: "deterministic",
|
|
457
|
+
grounded: true,
|
|
458
|
+
signalId: signal.id,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return out;
|
|
463
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -353,6 +353,100 @@ export {
|
|
|
353
353
|
type ScheduleStore,
|
|
354
354
|
} from "./schedule.ts";
|
|
355
355
|
export { suggestValues, type SuggestionConfidence, type ValueSuggestion } from "./suggest.ts";
|
|
356
|
+
export {
|
|
357
|
+
buildSignalsFromAts,
|
|
358
|
+
computeWeights,
|
|
359
|
+
createFileSignalStore,
|
|
360
|
+
DEFAULT_SIGNALS_CONFIG,
|
|
361
|
+
dedupKey,
|
|
362
|
+
dedupeSignals,
|
|
363
|
+
loadSignalsConfig,
|
|
364
|
+
makeOutcome,
|
|
365
|
+
normalizeAccountDomain,
|
|
366
|
+
parseSignalsConfig,
|
|
367
|
+
recencyFactor,
|
|
368
|
+
SIGNAL_BUCKETS,
|
|
369
|
+
SIGNALS_CONFIG_FILE_NAME,
|
|
370
|
+
signalId,
|
|
371
|
+
signalRunId,
|
|
372
|
+
signalsDir,
|
|
373
|
+
signalWeight,
|
|
374
|
+
type Signal,
|
|
375
|
+
type SignalBucket,
|
|
376
|
+
type SignalBucketConfig,
|
|
377
|
+
type SignalOutcome,
|
|
378
|
+
type SignalOutcomeResult,
|
|
379
|
+
type SignalRun,
|
|
380
|
+
type SignalsConfig,
|
|
381
|
+
type SignalStore,
|
|
382
|
+
} from "./signals.ts";
|
|
383
|
+
export {
|
|
384
|
+
fetchAtsJobs,
|
|
385
|
+
snippetFor,
|
|
386
|
+
type AtsBoardSource,
|
|
387
|
+
type AtsJob,
|
|
388
|
+
} from "./connectors/atsBoards.ts";
|
|
389
|
+
export {
|
|
390
|
+
scoreBand,
|
|
391
|
+
judgeRunId,
|
|
392
|
+
normalizeSpan,
|
|
393
|
+
isGroundedSpan,
|
|
394
|
+
scoreAccount,
|
|
395
|
+
accountRecentlyTouched,
|
|
396
|
+
bestContactForAccount,
|
|
397
|
+
deterministicDecision,
|
|
398
|
+
deterministicWhyNow,
|
|
399
|
+
JUDGE_SCHEMA,
|
|
400
|
+
DEFAULT_JUDGE_PROMPT,
|
|
401
|
+
judgeDecisionLlm,
|
|
402
|
+
judgeSignals,
|
|
403
|
+
judgeDir,
|
|
404
|
+
createFileJudgeStore,
|
|
405
|
+
type JudgeDecisionKind,
|
|
406
|
+
type JudgeDecision,
|
|
407
|
+
type JudgeRun,
|
|
408
|
+
type JudgeBand,
|
|
409
|
+
type AccountScore,
|
|
410
|
+
type JudgeStore,
|
|
411
|
+
} from "./judge.ts";
|
|
412
|
+
export {
|
|
413
|
+
draft,
|
|
414
|
+
authorOpeners,
|
|
415
|
+
draftOpenerLlm,
|
|
416
|
+
deterministicOpener,
|
|
417
|
+
creditedTriggerSignal,
|
|
418
|
+
draftEvidence,
|
|
419
|
+
sanitizeOpener,
|
|
420
|
+
firstLine,
|
|
421
|
+
firstLineGroundedInTrigger,
|
|
422
|
+
hasBannedGreeting,
|
|
423
|
+
isStaleTrigger,
|
|
424
|
+
draftOperationId,
|
|
425
|
+
draftEvidenceId,
|
|
426
|
+
DRAFT_CHANNELS,
|
|
427
|
+
DRAFT_SCHEMA,
|
|
428
|
+
DEFAULT_DRAFT_PROMPT,
|
|
429
|
+
DEFAULT_FRESHNESS_DAYS,
|
|
430
|
+
type Draft,
|
|
431
|
+
type RejectedDraft,
|
|
432
|
+
type DraftResult,
|
|
433
|
+
type DraftChannel,
|
|
434
|
+
} from "./draft.ts";
|
|
435
|
+
export {
|
|
436
|
+
DEFAULT_GOLDEN_SET,
|
|
437
|
+
DEFAULT_MIN_ACCURACY,
|
|
438
|
+
HOT_SCORE,
|
|
439
|
+
defaultJudgeFn,
|
|
440
|
+
gradeAgainstOutcomes,
|
|
441
|
+
gradeJudge,
|
|
442
|
+
parseGoldenSet,
|
|
443
|
+
type Confusion,
|
|
444
|
+
type EvalJudgeFn,
|
|
445
|
+
type GoldenHistory,
|
|
446
|
+
type GoldenRow,
|
|
447
|
+
type GradeResult,
|
|
448
|
+
type OutcomeCalibration,
|
|
449
|
+
} from "./judgeEval.ts";
|
|
356
450
|
export type {
|
|
357
451
|
ApprovalStatus,
|
|
358
452
|
AuditFinding,
|