Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): persona builder — two-pass build so big personas stay big

Salman Qureshi5fa95c85055c
diff --git a/src/bots/persona-template.test.ts b/src/bots/persona-template.test.ts
index 5db33ed9..ba1b0428 100644
--- a/src/bots/persona-template.test.ts
+++ b/src/bots/persona-template.test.ts
@@ -66,4 +66,49 @@ describe('refinePersona (convert to template)', () => {
const throwing = { ...stubProvider(), generateText: async () => { throw new Error('HTTP 500'); } } as any;
expect(await refinePersona('raw persona text', 'R', throwing)).toBeNull();
});
+
+ it('big personas get the two-pass build: inventory extraction, then drafting against it', async () => {
+ const calls: string[] = [];
+ const recording = {
+ ...stubProvider(),
+ generateText: async (prompt: string) => {
+ calls.push(prompt);
+ return {
+ text: scriptedResponses.shift() ?? '',
+ inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub', provider: 'stub',
+ };
+ },
+ } as any;
+ scriptedResponses.push('- verifies repos are active\n- never recommends unverified sources\n- prefers depth over volume');
+ scriptedResponses.push(goodTemplate);
+ // >4000 chars of raw persona triggers the inventory pass.
+ const longRaw = 'I want a research bot. '.repeat(200) + 'It verifies repos are active before recommending, never recommends unverified sources, prefers depth over volume, and reports with a one-line summary.';
+ expect(longRaw.length).toBeGreaterThan(4_000);
+ const result = await refinePersona(longRaw, 'Research', recording);
+ expect(result).toContain('## Standing instructions');
+ // Pass 1 = extraction, pass 2 = draft carrying the inventory checklist.
+ expect(calls).toHaveLength(2);
+ expect(calls[0]).toContain('checklist');
+ expect(calls[1]).toContain('Requirements inventory');
+ expect(calls[1]).toContain('verifies repos are active');
+ });
+
+ it('a failing inventory pass falls back to the single-pass build', async () => {
+ let calls = 0;
+ const flakyInventory = {
+ ...stubProvider(),
+ generateText: async (prompt: string) => {
+ calls++;
+ if (prompt.includes('checklist')) throw new Error('HTTP 500');
+ return {
+ text: goodTemplate,
+ inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub', provider: 'stub',
+ };
+ },
+ } as any;
+ const longRaw = 'Detailed research persona. '.repeat(200) + 'Be skeptical.';
+ const result = await refinePersona(longRaw, 'Research', flakyInventory);
+ expect(calls).toBe(2);
+ expect(result).toContain('# Research');
+ });
});
\ No newline at end of file
diff --git a/src/bots/persona-template.ts b/src/bots/persona-template.ts
index 6f3b0f96..b5554dd5 100644
--- a/src/bots/persona-template.ts
+++ b/src/bots/persona-template.ts
@@ -6,25 +6,77 @@ export interface PersonaRefinement {
text: string | null;
}
+/** Hard cap on accepted raw persona text (big personas are legitimate). */
+const RAW_CAP = 24_000;
+/** Above this length the build is two-pass: extract a requirements inventory
+ * first, then draft against it — a single call over a long persona would
+ * summarize details away, and every dropped rule is a silent behavior change. */
+const INVENTORY_THRESHOLD = 4_000;
+const MIN_OUTPUT = 80;
+const MAX_OUTPUT = 20_000;
+
/**
- * "Convert to template" — turn a user's free-form persona text into the
- * structured format that produces good bot behavior (Character / Standing
- * instructions / Output, the same sections as the onboarding template).
+ * Persona builder — turn a user's free-form persona text into the structured
+ * format that produces good bot behavior (Character / Standing instructions /
+ * Output, the same sections as the onboarding template). Long personas get an
+ * extra LLM pass: the first call extracts an exhaustive inventory of the
+ * user's requirements, the second drafts the template file against that
+ * checklist, so nothing the user wrote is lost in compression.
*
- * Hard rule: refinement only RESTRUCTURES. It may not add capabilities,
- * permissions, or instructions the user didn't give — an LLM quietly
- * widening a bot's mandate would be a silent privilege grant.
+ * Hard rule: the builder only RESTRUCTURES. It may not add capabilities,
+ * permissions, or instructions the user didn't give — an LLM quietly widening
+ * a bot's mandate would be a silent privilege grant.
*/
export async function refinePersona(raw: string, botName: string, provider: BaseProvider): Promise<string | null> {
+ const source = raw.slice(0, RAW_CAP);
+ try {
+ let inventory: string | null = null;
+ if (source.length > INVENTORY_THRESHOLD) {
+ inventory = await extractInventory(source, botName, provider);
+ // Inventory failure is non-fatal — fall back to the single-pass build.
+ }
+ return await draftPersona(source, inventory, botName, provider);
+ } catch (err: any) {
+ logger.warn({ botName, err: err?.message }, 'Persona refinement failed — keeping raw persona');
+ return null;
+ }
+}
+
+/** Pass 1 (long personas): exhaustive requirement checklist from the raw text. */
+async function extractInventory(source: string, botName: string, provider: BaseProvider): Promise<string | null> {
try {
const result = await provider.generateText(
- `Convert this free-form bot persona into a structured persona file. Bot name: ${botName}.
+ `Extract an exhaustive checklist of requirements from this free-form bot persona. Bot name: ${botName}.
+
+One bullet per distinct requirement, rule, restriction, preference, tone note, output expectation, or fact about the bot. Include EVERYTHING the text states — nothing may be dropped or merged away. No preamble, no numbering, no sections — just the bullets.
-User's persona (preserve every explicit requirement, restructure only):
-"""
-${raw.slice(0, 4000)}
"""
+${source}
+"""`,
+ 'You extract complete requirement checklists. Return ONLY the bullet list.',
+ );
+ const text = (result.text ?? '').trim();
+ if (!text.includes('-') || text.length < 20) return null;
+ return text;
+ } catch (err: any) {
+ logger.warn({ botName, err: err?.message }, 'Persona inventory extraction failed — drafting without it');
+ return null;
+ }
+}
+
+/** Pass 2: draft the template persona (single-pass when the raw text is short). */
+async function draftPersona(source: string, inventory: string | null, botName: string, provider: BaseProvider): Promise<string | null> {
+ const result = await provider.generateText(
+ `Turn this free-form bot persona into a complete, high-grade persona file. Bot name: ${botName}.
+User's persona (the ground truth):
+"""
+${source}
+"""
+${inventory ? `
+Requirements inventory — every item below MUST appear in the draft; these are extracted from the user's text and none may be dropped:
+${inventory}
+` : ''}
Output ONLY markdown, in exactly this shape:
# ${botName}
@@ -33,27 +85,29 @@ Output ONLY markdown, in exactly this shape:
## Character
-<personality, voice, expertise boundaries>
+<personality, voice, tone, expertise boundaries — concrete enough to steer the bot>
## Standing instructions
-- <each behavioral requirement as a bullet, including every rule the user wrote>
+- <one bullet per behavioral requirement from the user's text; include EVERY rule they wrote, and turn vague statements into precise, testable instructions>
## Output
-<output format expectations>
+<output format expectations: shape, length, evidence, tone>
-Rules: never invent new capabilities, tools, or permissions; keep the bot's stated restrictions verbatim in meaning; 100-300 words; no preamble, no code fences.`,
- 'You write precise bot persona files. Restructure only; never add or remove requirements.',
- );
- const text = (result.text ?? '').trim();
- if (!text.startsWith('#') || text.length < 80 || text.length > 5000 || !text.includes('##')) {
- logger.debug({ botName }, 'Persona refinement produced unusable output — keeping raw');
- return null;
- }
- return text.endsWith('\n') ? text : text + '\n';
- } catch (err: any) {
- logger.warn({ botName, err: err?.message }, 'Persona refinement failed — keeping raw persona');
+Rules: keep length proportional to the source material — a rich persona stays rich, never compress requirements away; never invent new capabilities, tools, or permissions; keep stated restrictions verbatim in meaning; no preamble, no code fences.`,
+ 'You write precise bot persona files. Restructure only; never add or remove requirements.',
+ );
+ const text = (result.text ?? '').trim();
+ if (
+ !text.startsWith('#')
+ || text.length < MIN_OUTPUT
+ || text.length > MAX_OUTPUT
+ || !text.includes('## Character')
+ || !text.includes('## Standing instructions')
+ ) {
+ logger.debug({ botName }, 'Persona refinement produced unusable output — keeping raw');
return null;
}
+ return text.endsWith('\n') ? text : text + '\n';
}
\ No newline at end of file