mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 09:07:20 +01:00
feat(cat): ask for permission by name, check its own record, and select sections by turn (#967)
ADR-0006 D5, D6, and the section-selection mechanism — the three items left open after #964 — plus the fix that lets the eval that gates them actually run. D5, a first run that can do something. Most of it had already shipped as grant-on-confirm (20260910203000_confirming_can_also_allow.sql): a denial for a non-payment, non-high-risk action becomes a consent card reading "Allow and confirm". What was missing was the other half of the conversation. The model was told a plain "waiting for confirmation", so its reply announced a done deal while the card asked for a permission the reply never mentioned. summariseForModel now says NOT YET ALLOWED, names the category, and says one tap allows it; a hard denial names the category to allow instead of "tell the user what to grant" with nothing to say. Two measured corrections with it. update_profile sat in the default-on 'context' category with requiresConfirmation: false — a brand-new user's Cat could rewrite their public @handle and bio on a stray sentence. It is now 'entities' and confirmed, and reaches a new user through the consent card. And 'settings' was a permission category with zero actions in it: a switch in the UI governing nothing. Removed from the app; the Postgres enum value is left orphaned (cannot be dropped in place, no row references it). The class is closed by a test — every listed category must govern at least one enabled action. D6, Cat can check its own work. track-record.ts already derived proposed → published → funded plus setbacks from cat_action_log; it was ambient context only. It is now also the read tool check_my_track_record, answered as prose by formatTrackRecordForModel, which states Cat's own pattern as a fact to act on: "3 things drafted, none published — offer to finish ONE before creating anything new"; "2 published but nothing funded — the gap is reach or pricing"; "2 proposals never confirmed — ask what held them back". A null record says "could not be read — do not reconstruct from memory", never "nothing yet". Scoped to Cat's own actions in the router; the user's own numbers stay with query_my_data. Section selection, mechanism built, flag off. Two things were found by trying to enable it. Nothing anywhere produced a turnDescriptor — the env flag was a double gate that changed nothing when set. services/cat/turn-descriptor.ts now builds one in chat-prepare from facts the caller has: the message, whether history is empty (fetched before the brief now, so first-message is read not guessed), the page, the entity. And selection ran BEFORE the capability strip, so flag-on + actionsVia 'none' + a greeting threw: selection had already removed an instruction section the strip then demanded. Strip runs first now. Measured on the tools path: unselected 32,019 chars; a first-message greeting 23,097; a pricing question 18,824. The eval that is supposed to validate the flip has not run since 2026-09-10. It logged "free-model budget 0/0 remaining — SKIPPED" every night. From the box: OpenRouter answers HTTP 200 on the free model and sends NO x-ratelimit-* headers; Number(null) is 0 and 0 is finite, so a missing header read as an exhausted budget and the eval stood down to protect a reserve that was never in danger — the exact thing the comment above that code says it must not do. Header parsing is now scripts/eval-rate-limit.mjs, absent means unknown means proceed, and the run logs when the budget is unknown so silence cannot read as "checked". Unit-tested. Gates proved by mutation: 16 mutants, 16 killed, sources sha256-verified restored. Three survived the first pass and were diagnosed rather than excused: two had matched update_entity's identical four-line block before update_profile's (re-anchored on a unique comment), one kept both phrases the test looked for (test now asserts a null record never reads "nothing yet"). Not built, stated in the ADR: the loop does not resume after confirmation; the card confirms, the action runs, a system message reports it. Claude-Session: https://claude.ai/code/session_01MWgvHV9KSt3nLn812C2fxm Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
28a25d00a6
commit
e2f8779837
19 files changed
+875
-56
No files matched your search
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { CAT_ACTIONS, ACTION_CATEGORIES, ACTION_CATEGORY_KEYS } from '@/config/cat-actions';
|
||||
import { DEFAULT_PERMISSIONS } from '@/services/cat/permission-service';
|
||||
import { summariseForModel } from '@/services/cat/action-loop';
|
||||
import { canGrantOnConfirm } from '@/services/cat/action-types';
|
||||
|
||||
/**
|
||||
* ADR-0006 D5 — a first run that can do something.
|
||||
*
|
||||
* The consent card ("Allow and confirm") shipped as grant-on-confirm. What was
|
||||
* missing was the other half of the conversation: the model was told a plain
|
||||
* "waiting for confirmation" and announced a done deal, while the card asked
|
||||
* for a permission the reply never mentioned. Plus two measured corrections:
|
||||
* update_profile was default-on with no confirmation, and 'settings' was a
|
||||
* permission switch governing zero actions.
|
||||
*/
|
||||
|
||||
describe('a permission category is never empty', () => {
|
||||
// The class, not the instance: 'settings' existed for months with no action
|
||||
// in it — a switch in the UI that governed nothing. Any category listed
|
||||
// must have at least one enabled action, or it is UI without a referent.
|
||||
const enabled = Object.values(CAT_ACTIONS).filter(a => a.enabled);
|
||||
|
||||
it.each(ACTION_CATEGORY_KEYS)('%s governs at least one enabled action', category => {
|
||||
expect(enabled.some(a => a.category === category)).toBe(true);
|
||||
});
|
||||
|
||||
it('has no settings category anywhere the app reads', () => {
|
||||
expect(Object.keys(ACTION_CATEGORIES)).not.toContain('settings');
|
||||
expect(Object.keys(DEFAULT_PERMISSIONS)).not.toContain('settings');
|
||||
expect(enabled.some(a => (a.category as string) === 'settings')).toBe(false);
|
||||
});
|
||||
|
||||
it('defaults are declared for exactly the categories that exist', () => {
|
||||
// A default for a category that does not exist is the same drift in the
|
||||
// other direction.
|
||||
for (const key of Object.keys(DEFAULT_PERMISSIONS)) {
|
||||
expect(ACTION_CATEGORY_KEYS).toContain(key);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('update_profile is an entity action, not free context', () => {
|
||||
const action = CAT_ACTIONS.update_profile;
|
||||
|
||||
it('is default-off and confirmed every time', () => {
|
||||
expect(action.category).toBe('entities');
|
||||
expect(action.requiresConfirmation).toBe(true);
|
||||
expect(DEFAULT_PERMISSIONS.entities).toBe(false);
|
||||
});
|
||||
|
||||
it('still reaches a new user through the consent card rather than a dead end', () => {
|
||||
// Medium risk, not payments: the first use is a question, not a refusal.
|
||||
expect(canGrantOnConfirm(action, 'permission_denied')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what the model is told when permission is the blocker', () => {
|
||||
it('asks for the grant by name when the card is a consent card', () => {
|
||||
const out = summariseForModel('create_product', {
|
||||
status: 'pending_confirmation',
|
||||
data: { description: 'Create product "Mugs"', pendingAction: { grantOnConfirm: true } },
|
||||
});
|
||||
expect(out).toContain('NOT YET ALLOWED');
|
||||
expect(out).toContain('Entities actions');
|
||||
expect(out).toContain('one tap allows it');
|
||||
expect(out).toContain('Nothing has been created or changed');
|
||||
expect(out).not.toContain('it is ready');
|
||||
});
|
||||
|
||||
it('keeps the plain wording for an ordinary confirmation', () => {
|
||||
const out = summariseForModel('create_product', {
|
||||
status: 'pending_confirmation',
|
||||
data: { description: 'Create product "Mugs"', pendingAction: { grantOnConfirm: false } },
|
||||
});
|
||||
expect(out).toContain('WAITING FOR THE USER TO CONFIRM');
|
||||
expect(out).not.toContain('NOT YET ALLOWED');
|
||||
});
|
||||
|
||||
it('names the category to allow on a hard denial instead of "what to grant"', () => {
|
||||
const out = summariseForModel('send_payment', {
|
||||
status: 'denied',
|
||||
error: 'Permission not granted',
|
||||
});
|
||||
expect(out).toContain('NOT PERMITTED');
|
||||
expect(out).toContain('allow Payments actions in their Cat settings');
|
||||
expect(out).not.toContain('tell the user what to grant');
|
||||
});
|
||||
|
||||
it('still says something useful for an action the registry does not know', () => {
|
||||
const out = summariseForModel('not_a_real_action', { status: 'denied' });
|
||||
expect(out).toContain('tell the user what to grant');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { buildTurnDescriptor, isNoSpecificRequest } from '@/services/cat/turn-descriptor';
|
||||
import { CORE_SECTIONS } from '@/config/cat-prompt-sections';
|
||||
import { CAT_ACTIONS } from '@/config/cat-actions';
|
||||
|
||||
/**
|
||||
* Section selection, with the flag ON.
|
||||
*
|
||||
* Every earlier test of selection ran with the flag off, or called the
|
||||
* selector directly. Nothing proved the assembled prompt under the flag, and
|
||||
* nothing at all produced a turn descriptor — so the flag was a double gate
|
||||
* that changed nothing when set. Two things are pinned here:
|
||||
*
|
||||
* 1. the producer (turn-descriptor.ts) emits the markers the section
|
||||
* config already expects, from facts the caller has;
|
||||
* 2. selection composes with actionsVia in every combination without
|
||||
* throwing. The first version threw on flag-on + 'none' + a greeting,
|
||||
* because it selected first and then demanded a heading selection had
|
||||
* already removed. That exact turn is the first case below.
|
||||
*/
|
||||
|
||||
describe('buildTurnDescriptor', () => {
|
||||
it('marks the first message from the conversation, not from wording', () => {
|
||||
expect(buildTurnDescriptor({ message: 'sell my bike', historyLength: 0 })).toContain(
|
||||
'first-message'
|
||||
);
|
||||
expect(buildTurnDescriptor({ message: 'sell my bike', historyLength: 3 })).not.toContain(
|
||||
'first-message'
|
||||
);
|
||||
});
|
||||
|
||||
it('marks a greeting as no specific request, and a request as one', () => {
|
||||
for (const m of ['hi', 'Hello there!', 'hey cat', '', 'привет']) {
|
||||
expect(isNoSpecificRequest(m), m).toBe(true);
|
||||
}
|
||||
for (const m of ['hi, sell my bike', 'publish my project', 'how much should I charge?']) {
|
||||
expect(isNoSpecificRequest(m), m).toBe(false);
|
||||
}
|
||||
expect(buildTurnDescriptor({ message: 'hi', historyLength: 2 })).toContain(
|
||||
'no-specific-request'
|
||||
);
|
||||
});
|
||||
|
||||
it('carries the page and entity so "make it cheaper" on a product page finds the right sections', () => {
|
||||
const d = buildTurnDescriptor({
|
||||
message: 'make it cheaper',
|
||||
historyLength: 1,
|
||||
currentPath: '/dashboard/store/abc',
|
||||
currentEntity: { type: 'product', ref: 'abc' },
|
||||
});
|
||||
expect(d).toContain('my product');
|
||||
expect(d).toContain('/dashboard/store/abc');
|
||||
expect(d.startsWith('make it cheaper')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('selection with the flag on, composed with actionsVia', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
async function loadWithFlagOn() {
|
||||
vi.stubEnv('CAT_PROMPT_SECTION_SELECTION', '1');
|
||||
vi.resetModules();
|
||||
return import('@/services/cat/system-prompt');
|
||||
}
|
||||
|
||||
const greeting = buildTurnDescriptor({ message: 'hi', historyLength: 0 });
|
||||
const pricing = buildTurnDescriptor({ message: 'how much should I charge?', historyLength: 4 });
|
||||
|
||||
it('does not throw on the turn that used to throw: none + a greeting', async () => {
|
||||
const { buildCatSystemPrompt, SECTION_SELECTION_ENABLED } = await loadWithFlagOn();
|
||||
expect(SECTION_SELECTION_ENABLED).toBe(true);
|
||||
expect(() => buildCatSystemPrompt({ actionsVia: 'none', turnDescriptor: greeting })).not.toThrow();
|
||||
});
|
||||
|
||||
it.each(['prose', 'tools', 'none'] as const)(
|
||||
'keeps every core section and every action on the %s path for a greeting',
|
||||
async actionsVia => {
|
||||
const { buildCatSystemPrompt, ACTION_PROSE_SECTION_HEADINGS } = await loadWithFlagOn();
|
||||
const out = buildCatSystemPrompt({ actionsVia, turnDescriptor: greeting });
|
||||
const dropped = new Set<string>(actionsVia === 'prose' ? [] : ACTION_PROSE_SECTION_HEADINGS);
|
||||
for (const heading of CORE_SECTIONS) {
|
||||
if (dropped.has(heading)) {
|
||||
continue; // removed by capability, on purpose, before selection
|
||||
}
|
||||
expect(out, heading).toContain(`## ${heading}`);
|
||||
}
|
||||
if (actionsVia === 'prose') {
|
||||
for (const a of Object.values(CAT_ACTIONS).filter(a => a.enabled)) {
|
||||
expect(out.includes(`**${a.id}(`) || out.includes(`"actionId": "${a.id}"`), a.id).toBe(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('actually drops a situational section a greeting does not need, and keeps it when asked for', async () => {
|
||||
const { buildCatSystemPrompt } = await loadWithFlagOn();
|
||||
const unselected = buildCatSystemPrompt({ actionsVia: 'tools' });
|
||||
const onGreeting = buildCatSystemPrompt({ actionsVia: 'tools', turnDescriptor: greeting });
|
||||
const onPricing = buildCatSystemPrompt({ actionsVia: 'tools', turnDescriptor: pricing });
|
||||
expect(onGreeting).not.toContain('## Pricing Guidance');
|
||||
expect(onPricing).toContain('## Pricing Guidance');
|
||||
expect(onGreeting).toContain('## Opening a Conversation');
|
||||
expect(onPricing).not.toContain('## Opening a Conversation');
|
||||
// Measured 2026-09-11 on the tools path: unselected 32,019; a first-message
|
||||
// greeting 23,097 (it pulls three orientation sections, so it is the
|
||||
// LONGER of the two); a pricing question 18,824. The claim is that each
|
||||
// turn is materially smaller than sending everything — not that one kind
|
||||
// of turn is smaller than another.
|
||||
expect(unselected.length - onGreeting.length).toBeGreaterThan(5_000);
|
||||
expect(unselected.length - onPricing.length).toBeGreaterThan(5_000);
|
||||
});
|
||||
|
||||
it('puts the cannot-act notice last even when selection ran', async () => {
|
||||
const { buildCatSystemPrompt } = await loadWithFlagOn();
|
||||
const out = buildCatSystemPrompt({ actionsVia: 'none', turnDescriptor: pricing });
|
||||
const notice = out.lastIndexOf('## You Cannot Execute Actions On This Turn');
|
||||
expect(notice).toBeGreaterThan(out.lastIndexOf('## Critical Rules'));
|
||||
expect(out).not.toContain('## Managing Existing Entities');
|
||||
});
|
||||
|
||||
it('is a no-op without a descriptor, flag or not', async () => {
|
||||
const { buildCatSystemPrompt } = await loadWithFlagOn();
|
||||
expect(buildCatSystemPrompt({ actionsVia: 'tools' })).toBe(
|
||||
buildCatSystemPrompt({ actionsVia: 'tools', turnDescriptor: undefined })
|
||||
);
|
||||
expect(buildCatSystemPrompt({ actionsVia: 'tools' })).toContain('## Pricing Guidance');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { PLATFORM_TOOL_DEFINITION } from '@/services/cat/tool-use-detection';
|
||||
import { isCatActionTool } from '@/services/cat/action-as-tool';
|
||||
import { formatTrackRecordForModel, type CatTrackRecord } from '@/services/cat/track-record';
|
||||
|
||||
/**
|
||||
* ADR-0006 D6 — Cat can check its own work.
|
||||
*
|
||||
* The track record already existed as ambient context. This makes it a READ
|
||||
* TOOL the model can call, so "what did you do for me?" is answered from the
|
||||
* action log, and so Cat can see its own pattern (drafted, never published)
|
||||
* before proposing more of the same.
|
||||
*/
|
||||
|
||||
const ROOT = join(__dirname, '../../..');
|
||||
const stripComments = (s: string) =>
|
||||
s.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^[ \t]*\/\/.*$/gm, '');
|
||||
|
||||
const TOOL = 'check_my_track_record';
|
||||
|
||||
function record(overrides: Partial<CatTrackRecord> = {}): CatTrackRecord {
|
||||
return {
|
||||
proposed: 0,
|
||||
published: 0,
|
||||
funded: 0,
|
||||
totalFundedBtc: 0,
|
||||
entries: [],
|
||||
setbacks: { failed: 0, denied: 0, unconfirmed: 0, recent: [] },
|
||||
windowDays: 90,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('check_my_track_record is wired as a read tool', () => {
|
||||
it('is offered as a zero-argument tool definition', () => {
|
||||
const def = PLATFORM_TOOL_DEFINITION.find(t => t.function.name === TOOL);
|
||||
expect(def).toBeDefined();
|
||||
expect(def!.function.parameters).toEqual({ type: 'object', properties: {} });
|
||||
// Disambiguation is in the description, not left to luck: the sibling
|
||||
// tool query_my_data owns the user's own numbers.
|
||||
expect(def!.function.description).toContain('query_my_data');
|
||||
});
|
||||
|
||||
it('is a read tool, so the action registry never claims the name', () => {
|
||||
expect(isCatActionTool(TOOL)).toBe(false);
|
||||
});
|
||||
|
||||
it('is dispatched by the executor and described to the router', () => {
|
||||
// Call syntax, comment-stripped: a mention in a comment cannot satisfy this.
|
||||
const executor = stripComments(readFileSync(join(ROOT, 'src/services/cat/tool-executor.ts'), 'utf8'));
|
||||
expect(executor).toContain(`if (toolName === '${TOOL}') {`);
|
||||
expect(executor).toContain('handleCheckMyTrackRecord(supabase, userId, toolCall, onToolCall)');
|
||||
|
||||
const router = stripComments(readFileSync(join(ROOT, 'src/services/cat/tool-use.ts'), 'utf8'));
|
||||
expect(router).toContain(`'- ${TOOL}: `);
|
||||
|
||||
// Without a label the chip would read "Done (3)" for a self-audit.
|
||||
const chip = readFileSync(
|
||||
join(ROOT, 'src/components/ai-chat/ModernChatPanel/components/ToolCallChip.tsx'),
|
||||
'utf8'
|
||||
);
|
||||
expect(chip).toContain(`${TOOL}: {`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatTrackRecordForModel', () => {
|
||||
it('admits when the record could not be read, and forbids reconstruction', () => {
|
||||
const out = formatTrackRecordForModel(null);
|
||||
expect(out).toContain('could not be read');
|
||||
expect(out).toContain('do not reconstruct it from memory');
|
||||
// Unknown is not empty: a null record must never read as a clean slate.
|
||||
expect(out).not.toContain('nothing yet');
|
||||
});
|
||||
|
||||
it('says "nothing yet" plainly on an empty window rather than inventing history', () => {
|
||||
const out = formatTrackRecordForModel(record());
|
||||
expect(out).toContain('nothing yet');
|
||||
expect(out).toContain('do not invent history');
|
||||
expect(out).not.toContain('PATTERN');
|
||||
});
|
||||
|
||||
it('lists what was created with its real state, including deletions', () => {
|
||||
const out = formatTrackRecordForModel(
|
||||
record({
|
||||
proposed: 2,
|
||||
published: 1,
|
||||
funded: 1,
|
||||
totalFundedBtc: 0.002,
|
||||
entries: [
|
||||
{
|
||||
entityType: 'service',
|
||||
entityId: 'a',
|
||||
title: 'Haircuts',
|
||||
createdAt: '2026-09-01T10:00:00Z',
|
||||
status: 'active',
|
||||
fundedBtc: 0.002,
|
||||
payments: 2,
|
||||
},
|
||||
{
|
||||
entityType: 'product',
|
||||
entityId: 'b',
|
||||
title: 'Mugs',
|
||||
createdAt: '2026-08-20T10:00:00Z',
|
||||
status: null,
|
||||
fundedBtc: 0,
|
||||
payments: 0,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
expect(out).toContain('proposed 2, published 1');
|
||||
expect(out).toContain('service "Haircuts" — status active, 0.002 BTC from 2 payment(s)');
|
||||
expect(out).toContain('product "Mugs" — deleted since');
|
||||
expect(out).toContain('Amounts are BTC');
|
||||
});
|
||||
|
||||
it('names the drafted-never-published pattern so Cat finishes one instead of adding a fourth', () => {
|
||||
const draft = (title: string) => ({
|
||||
entityType: 'project' as const,
|
||||
entityId: title,
|
||||
title,
|
||||
createdAt: '2026-09-01T00:00:00Z',
|
||||
status: 'draft',
|
||||
fundedBtc: 0,
|
||||
payments: 0,
|
||||
});
|
||||
const out = formatTrackRecordForModel(
|
||||
record({ proposed: 3, entries: [draft('A'), draft('B'), draft('C')] })
|
||||
);
|
||||
expect(out).toContain('PATTERN: 3 things drafted, none published');
|
||||
expect(out).toContain('before creating anything new');
|
||||
});
|
||||
|
||||
it('names the published-but-unfunded gap and the unconfirmed-proposals pattern', () => {
|
||||
const out = formatTrackRecordForModel(
|
||||
record({
|
||||
proposed: 2,
|
||||
published: 2,
|
||||
setbacks: {
|
||||
failed: 0,
|
||||
denied: 0,
|
||||
unconfirmed: 2,
|
||||
recent: [
|
||||
{ actionId: 'create_event', kind: 'expired', reason: null, at: '2026-09-02T00:00:00Z' },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(out).toContain('2 published but nothing funded yet');
|
||||
expect(out).toContain('2 proposals the user never confirmed');
|
||||
expect(out).toContain('- create_event: expired (2026-09-02)');
|
||||
expect(out).toContain('Own the setbacks in the first person');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the executor runs it end to end', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('returns the formatted record and reports the count on the chip', async () => {
|
||||
vi.doMock('@/services/cat/track-record', async () => {
|
||||
const real = await vi.importActual<typeof import('@/services/cat/track-record')>(
|
||||
'@/services/cat/track-record'
|
||||
);
|
||||
return {
|
||||
...real,
|
||||
getCatTrackRecord: vi.fn(async () =>
|
||||
record({
|
||||
proposed: 1,
|
||||
entries: [
|
||||
{
|
||||
entityType: 'cause',
|
||||
entityId: 'c',
|
||||
title: 'Trees',
|
||||
createdAt: '2026-09-03T00:00:00Z',
|
||||
status: 'draft',
|
||||
fundedBtc: 0,
|
||||
payments: 0,
|
||||
},
|
||||
],
|
||||
})
|
||||
),
|
||||
};
|
||||
});
|
||||
const { executeToolCall } = await import('@/services/cat/tool-executor');
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const result = await executeToolCall(
|
||||
{} as never,
|
||||
'user-1',
|
||||
{ id: 'call-1', type: 'function', function: { name: TOOL, arguments: '{}' } } as never,
|
||||
'what have you done for me?',
|
||||
e => events.push(e as unknown as Record<string, unknown>)
|
||||
);
|
||||
expect(result.role).toBe('tool');
|
||||
expect(result.content).toContain('TRACK RECORD (last 90 days');
|
||||
expect(result.content).toContain('cause "Trees" — status draft');
|
||||
expect(events.map(e => e.status)).toEqual(['running', 'completed']);
|
||||
expect(events[1].resultCount).toBe(1);
|
||||
});
|
||||
|
||||
it('fails honestly when the record cannot be derived', async () => {
|
||||
vi.doMock('@/services/cat/track-record', async () => {
|
||||
const real = await vi.importActual<typeof import('@/services/cat/track-record')>(
|
||||
'@/services/cat/track-record'
|
||||
);
|
||||
return {
|
||||
...real,
|
||||
getCatTrackRecord: vi.fn(async () => {
|
||||
throw new Error('db down');
|
||||
}),
|
||||
};
|
||||
});
|
||||
const { executeToolCall } = await import('@/services/cat/tool-executor');
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const result = await executeToolCall(
|
||||
{} as never,
|
||||
'user-1',
|
||||
{ id: 'call-2', type: 'function', function: { name: TOOL, arguments: '{}' } } as never,
|
||||
'what have you done for me?',
|
||||
e => events.push(e as unknown as Record<string, unknown>)
|
||||
);
|
||||
expect(result.content).toContain('cannot see your history right now');
|
||||
expect(result.content).toContain('do not reconstruct it from memory');
|
||||
expect(events.map(e => e.status)).toEqual(['running', 'failed']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
// @ts-expect-error — plain ESM script module, no types on purpose.
|
||||
import { readRateLimitHeaders } from '../../../scripts/eval-rate-limit.mjs';
|
||||
|
||||
/**
|
||||
* The nightly Cat eval stood down every night from 2026-09-10 with
|
||||
* "free-model budget 0/0 remaining — SKIPPED". The free model was answering
|
||||
* fine; OpenRouter had simply stopped sending x-ratelimit-* headers, and
|
||||
* `Number(null)` is 0, which is finite. Unknown was laundered into empty and
|
||||
* the gate that validates prompt changes silently never ran.
|
||||
*/
|
||||
|
||||
const headers = (map: Record<string, string>) => new Headers(map);
|
||||
|
||||
describe('readRateLimitHeaders', () => {
|
||||
it('returns null when the headers are absent — unknown is not empty', () => {
|
||||
expect(readRateLimitHeaders(headers({}))).toBeNull();
|
||||
expect(readRateLimitHeaders(headers({ 'content-type': 'application/json' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when remaining is present but not a number', () => {
|
||||
expect(readRateLimitHeaders(headers({ 'x-ratelimit-remaining': 'unlimited' }))).toBeNull();
|
||||
expect(readRateLimitHeaders(headers({ 'x-ratelimit-remaining': '' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('reads a real zero as zero — the reserve check must still be able to fire', () => {
|
||||
expect(
|
||||
readRateLimitHeaders(headers({ 'x-ratelimit-remaining': '0', 'x-ratelimit-limit': '50' }))
|
||||
).toEqual({ limit: 50, remaining: 0, reset: null });
|
||||
});
|
||||
|
||||
it('reads a full set of headers', () => {
|
||||
expect(
|
||||
readRateLimitHeaders(
|
||||
headers({
|
||||
'x-ratelimit-remaining': '37',
|
||||
'x-ratelimit-limit': '50',
|
||||
'x-ratelimit-reset': '1789150000000',
|
||||
})
|
||||
)
|
||||
).toEqual({ limit: 50, remaining: 37, reset: 1789150000000 });
|
||||
});
|
||||
|
||||
it('keeps remaining when only the limit is missing', () => {
|
||||
expect(readRateLimitHeaders(headers({ 'x-ratelimit-remaining': '12' }))).toEqual({
|
||||
limit: null,
|
||||
remaining: 12,
|
||||
reset: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -136,26 +136,51 @@ before the handler. A missing required field becomes a typed rejection the model
|
||||
can _see and correct_ on the next loop step — which only becomes useful once D2
|
||||
exists, and which is what makes a larger registry safe.
|
||||
|
||||
### D5 — A first run that can do something.
|
||||
### D5 — A first run that can do something. BUILT.
|
||||
|
||||
A new user's Cat has `context` only: it cannot create, message, or pay. It looks
|
||||
broken, and the fix is buried in settings. Replace with an **inline grant** — the
|
||||
first time Cat wants a capability it does not have, it asks in the conversation,
|
||||
with the specific action named, and the grant applies from that turn on.
|
||||
|
||||
Two corrections while in here, both measured: `update_profile` sits in the
|
||||
default-on `context` category with `requiresConfirmation: false`, so a brand-new
|
||||
user's Cat can rewrite their handle and bio with no grant and no confirmation —
|
||||
it moves to `entities` and requires confirmation. And the `settings` permission
|
||||
category has zero actions referencing it: a dead row in the permissions UI.
|
||||
Most of this shipped as *grant-on-confirm* (`20260910203000_confirming_can_also_allow.sql`,
|
||||
`canGrantOnConfirm` in `action-types.ts`): a denial for a non-payment,
|
||||
non-high-risk action becomes a pending action with `grant_on_confirm`, the card
|
||||
reads "Allow and confirm", and confirming grants the category (still
|
||||
confirm-each-time). What was missing was the other half of the conversation:
|
||||
`summariseForModel` told the model a plain "waiting for confirmation", so the
|
||||
reply announced a done deal while the card asked for a permission the reply
|
||||
never mentioned. It now says NOT YET ALLOWED, names the category, and says one
|
||||
tap allows it. A hard denial names the category to allow instead of "tell the
|
||||
user what to grant" with nothing to say.
|
||||
|
||||
### D6 — Cat can check its own work.
|
||||
Two corrections while in here, both measured: `update_profile` sat in the
|
||||
default-on `context` category with `requiresConfirmation: false`, so a brand-new
|
||||
user's Cat could rewrite their handle and bio with no grant and no confirmation —
|
||||
it is now `entities` and requires confirmation, and reaches a new user through
|
||||
the consent card. And the `settings` permission category had zero actions
|
||||
referencing it: a dead switch in the permissions UI. Removed from the app; the
|
||||
Postgres enum value is left orphaned (an enum value cannot be dropped in place,
|
||||
and no row references it). The class is closed by a test: every category listed
|
||||
must govern at least one enabled action.
|
||||
|
||||
Not built: the loop does not RESUME after confirmation — the card confirms, the
|
||||
action runs, and a system message reports it; Cat does not get a follow-up turn
|
||||
with the result. That is the remaining gap between D2's "resumes" and today.
|
||||
|
||||
### D6 — Cat can check its own work. BUILT.
|
||||
|
||||
`track-record.ts` already joins `cat_action_log` against current entity status
|
||||
and settled payments to derive proposed → published → funded, plus setbacks.
|
||||
Today it is context only. Make it a read tool so Cat can answer "what did you do
|
||||
for me?" and, more usefully, notice its own pattern: _"the last three projects I
|
||||
drafted for you never got published — want me to finish one?"_
|
||||
It was context only. It is now also the read tool `check_my_track_record`
|
||||
(zero arguments, no permission gate — it reads Cat's own log), answered as
|
||||
prose by `formatTrackRecordForModel`, which names the pattern as a fact the
|
||||
model must act on: _"3 things drafted, none published — offer to finish ONE of
|
||||
them before creating anything new"_, _"2 published but nothing funded yet — the
|
||||
gap is reach or pricing, not more listings"_, _"2 proposals the user never
|
||||
confirmed — ask what held them back"_. The routing prompt scopes it to Cat's own
|
||||
actions; the user's own numbers stay with `query_my_data`. A null record says
|
||||
"could not be read — do not reconstruct it from memory", never "nothing yet".
|
||||
|
||||
### D7 — The prompt diet is a separate lever — and it is 3x bigger than estimated. BUILT.
|
||||
|
||||
@@ -244,8 +269,19 @@ inside a parse-and-fire loop still cannot see its own results.
|
||||
prose first would have removed Cat's verb. They ship together.
|
||||
4. **D5** — the first run.
|
||||
5. **D6** — self-knowledge.
|
||||
6. **Section selection** — validate and enable `SECTION_SELECTION_ENABLED`
|
||||
against the eval. This, not D7, is what closes the Groq gap.
|
||||
6. **Section selection** — MECHANISM BUILT, flag off pending the eval.
|
||||
Two things were found by trying to enable it. First, nothing anywhere
|
||||
produced a `turnDescriptor`, so the env flag was a double gate that changed
|
||||
nothing when set; `services/cat/turn-descriptor.ts` now builds one in
|
||||
chat-prepare from facts the caller has (the message, whether history is
|
||||
empty, the page and entity). Second, selection ran BEFORE the capability
|
||||
strip, so flag-on + `actionsVia: 'none'` + a greeting threw — selection had
|
||||
already removed an instruction section the strip then demanded. Strip now
|
||||
runs first. Measured 2026-09-11 on the tools path (base prompt, before
|
||||
few-shot text): unselected 32,019; a first-message greeting 23,097; a
|
||||
pricing question 18,824. To enable: `CAT_PROMPT_SECTION_SELECTION=1` in the
|
||||
box's runtime `.env`; the nightly `orangecat-cat-eval.timer` (04:30 UTC) is
|
||||
the gate, failing under 7/8 on either axis.
|
||||
|
||||
## Related
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { signInWithPassword, buildAuthCookie } from './eval-auth.mjs';
|
||||
import { readRateLimitHeaders } from './eval-rate-limit.mjs';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Env
|
||||
@@ -545,12 +546,10 @@ const FREE_TIER_RESERVE = Number(process.env.CAT_EVAL_FREE_RESERVE || 20);
|
||||
async function freeModelBudget() {
|
||||
const key = process.env.OPENROUTER_API_KEY;
|
||||
if (!key) {return null;}
|
||||
const read = h => {
|
||||
const limit = Number(h.get('x-ratelimit-limit'));
|
||||
const remaining = Number(h.get('x-ratelimit-remaining'));
|
||||
const reset = Number(h.get('x-ratelimit-reset'));
|
||||
return Number.isFinite(remaining) ? { limit, remaining, reset } : null;
|
||||
};
|
||||
// Header parsing lives in eval-rate-limit.mjs, and is tested there: the
|
||||
// inline version read a MISSING header as 0 remaining and skipped the eval
|
||||
// every night from 2026-09-10 while the free model was answering fine.
|
||||
const read = readRateLimitHeaders;
|
||||
try {
|
||||
const res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
@@ -574,9 +573,12 @@ async function main() {
|
||||
`eval-cat: target=${BASE_URL} user=${EVAL_EMAIL} provider=${EVAL_PROVIDER} model=${EVAL_MODEL}`
|
||||
);
|
||||
const budget = await freeModelBudget();
|
||||
if (!budget) {
|
||||
console.error('eval-cat: free-model budget unknown (no rate-limit headers) — proceeding');
|
||||
}
|
||||
if (budget) {
|
||||
console.error(
|
||||
`eval-cat: free-model budget ${budget.remaining}/${budget.limit} remaining (reserve ${FREE_TIER_RESERVE})`
|
||||
`eval-cat: free-model budget ${budget.remaining}/${budget.limit ?? '?'} remaining (reserve ${FREE_TIER_RESERVE})`
|
||||
);
|
||||
if (budget.remaining < FREE_TIER_RESERVE + PROBES.length) {
|
||||
console.error(
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Read OpenRouter's rate-limit headers into a budget, or admit you cannot.
|
||||
*
|
||||
* Extracted from scripts/eval-cat.mjs because it hid a bug that silenced the
|
||||
* nightly Cat eval for days: `Number(headers.get('x-ratelimit-remaining'))`
|
||||
* turns a MISSING header into 0, and 0 is finite, so "OpenRouter sent no
|
||||
* rate-limit headers" was read as "0 of 0 requests remaining" and the eval
|
||||
* stood down every night to protect a reserve that was not in danger.
|
||||
* Measured 2026-09-11 from the box: HTTP 200, the free model answering, and no
|
||||
* x-ratelimit-* header on the response at all.
|
||||
*
|
||||
* Unknown is not the same as empty. Absent headers -> null -> the run proceeds.
|
||||
* A pure function so it can be tested without the script's env preconditions.
|
||||
*
|
||||
* @param {{ get(name: string): string | null }} headers
|
||||
* @returns {{ limit: number | null, remaining: number, reset: number | null } | null}
|
||||
*/
|
||||
export function readRateLimitHeaders(headers) {
|
||||
const rawRemaining = headers.get('x-ratelimit-remaining');
|
||||
if (rawRemaining === null || rawRemaining === undefined || rawRemaining === '') {
|
||||
return null;
|
||||
}
|
||||
const remaining = Number(rawRemaining);
|
||||
if (!Number.isFinite(remaining)) {
|
||||
return null;
|
||||
}
|
||||
const rawLimit = headers.get('x-ratelimit-limit');
|
||||
const rawReset = headers.get('x-ratelimit-reset');
|
||||
const limit = rawLimit === null || rawLimit === '' ? null : Number(rawLimit);
|
||||
const reset = rawReset === null || rawReset === '' ? null : Number(rawReset);
|
||||
return {
|
||||
limit: Number.isFinite(limit) ? limit : null,
|
||||
remaining,
|
||||
reset: Number.isFinite(reset) ? reset : null,
|
||||
};
|
||||
}
|
||||
@@ -53,6 +53,12 @@ const TOOL_LABELS: Record<string, ToolLabel> = {
|
||||
noResults: 'Nothing on file',
|
||||
failed: "Couldn't read your data",
|
||||
},
|
||||
check_my_track_record: {
|
||||
running: 'Checking my own track record',
|
||||
completed: n => (n === 0 ? 'Nothing on my record yet' : `Checked my record (${n} created)`),
|
||||
noResults: 'Nothing on my record yet',
|
||||
failed: "Couldn't read my record",
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_LABEL: ToolLabel = {
|
||||
|
||||
@@ -46,8 +46,12 @@ export type ActionCategory =
|
||||
| 'communication' // Timeline posts, messages
|
||||
| 'payments' // Bitcoin transactions
|
||||
| 'organization' // Group/org management
|
||||
| 'settings' // User settings
|
||||
| 'context'; // Managing My Cat's context
|
||||
// 'settings' was a category with ZERO actions in it — a switch in the
|
||||
// permissions UI that governed nothing. Removed from the app (ADR-0006 D5).
|
||||
// The Postgres enum public.cat_action_category still carries the value; an
|
||||
// enum value cannot be dropped in place and no row references it, so it is
|
||||
// left orphaned rather than migrated. Do not add it back without an action.
|
||||
|
||||
export type ActionRiskLevel = 'low' | 'medium' | 'high';
|
||||
|
||||
@@ -1751,10 +1755,16 @@ export const CAT_ACTIONS: Record<string, CatAction> = {
|
||||
name: 'Update Profile',
|
||||
description:
|
||||
"Update the user's public profile — handle, name, bio, background, location, or website. Changing the @handle IS supported: the old one keeps redirecting and still receives payments. To make someone findable for a TOPIC use publish_interest instead, which adds a searchable interest rather than rewriting their bio.",
|
||||
category: 'context',
|
||||
// ADR-0006 D5. This sat in 'context' (granted by default) with no
|
||||
// confirmation, so a brand-new user's Cat could rewrite their public
|
||||
// @handle and bio on the strength of a stray sentence. A public profile is
|
||||
// an entity of the user's, not Cat's context: default-off, confirm each
|
||||
// time. First use goes through grant-on-confirm like any other entity
|
||||
// action — one tap allows it, still confirmed every time.
|
||||
category: 'entities',
|
||||
icon: Settings,
|
||||
riskLevel: 'medium',
|
||||
requiresConfirmation: false,
|
||||
requiresConfirmation: true,
|
||||
parameters: [
|
||||
{
|
||||
name: 'username',
|
||||
@@ -1825,11 +1835,6 @@ export const ACTION_CATEGORIES: Record<
|
||||
description: 'Create and manage organizations',
|
||||
icon: Users,
|
||||
},
|
||||
settings: {
|
||||
name: 'Settings',
|
||||
description: 'Manage your account settings',
|
||||
icon: Settings,
|
||||
},
|
||||
context: {
|
||||
name: 'Context',
|
||||
description: 'Manage what your Cat knows about you',
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
* the outcome, not WHO is allowed to cause it.
|
||||
*/
|
||||
|
||||
import { CAT_ACTIONS } from '@/config/cat-actions';
|
||||
import { CAT_ACTIONS, ACTION_CATEGORIES } from '@/config/cat-actions';
|
||||
import { logger } from '@/utils/logger';
|
||||
import { actionToolDefinitions, type ActionToolDefinition } from './action-schemas';
|
||||
|
||||
@@ -99,12 +99,27 @@ export function summariseForModel(
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
}
|
||||
case 'pending_confirmation':
|
||||
case 'pending_confirmation': {
|
||||
// The user has not agreed yet. If the model reads this as success it
|
||||
// will tell them something happened that is still waiting on a tap.
|
||||
const pending = data?.pendingAction as { grantOnConfirm?: boolean } | undefined;
|
||||
if (pending?.grantOnConfirm) {
|
||||
// ADR-0006 D5: the first time Cat wants a capability it does not
|
||||
// have, it asks in the conversation, with the action named. The card
|
||||
// already carries "Allow and confirm"; this is what lets the reply
|
||||
// match the card instead of announcing a done deal.
|
||||
const categoryName = action ? ACTION_CATEGORIES[action.category].name : 'this kind of';
|
||||
return `${label}: NOT YET ALLOWED — you do not have permission for ${categoryName} actions, so a card is asking the user to allow them and confirm this one. Nothing has been created or changed. Tell them plainly what you want to do and that one tap allows it; they will still confirm each action. Do not say it is done, and do not retry.`;
|
||||
}
|
||||
return `${label}: WAITING FOR THE USER TO CONFIRM. Nothing has been created or changed yet. Tell them it is ready and needs their confirmation — do not say it is done.`;
|
||||
case 'denied':
|
||||
return `${label}: NOT PERMITTED — ${result.error ?? 'permission denied'}. Do not retry it; tell the user what to grant.`;
|
||||
}
|
||||
case 'denied': {
|
||||
const categoryName = action ? ACTION_CATEGORIES[action.category].name : null;
|
||||
const grant = categoryName
|
||||
? `tell the user to allow ${categoryName} actions in their Cat settings if they want this`
|
||||
: 'tell the user what to grant';
|
||||
return `${label}: NOT PERMITTED — ${result.error ?? 'permission denied'}. Do not retry it; ${grant}.`;
|
||||
}
|
||||
case 'failed':
|
||||
default:
|
||||
return `${label}: FAILED — ${result.error ?? 'unknown error'}. If this was a bad parameter you may correct it and try once more; otherwise tell the user plainly.`;
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
import { buildCatSystemPrompt, type ActionsVia } from '@/services/cat/system-prompt';
|
||||
import { buildTurnDescriptor } from '@/services/cat/turn-descriptor';
|
||||
import { getCustomInstructions } from '@/services/cat/custom-instructions';
|
||||
import { buildReplyLanguageDirective } from '@/services/cat/reply-language';
|
||||
import { getCatFewShotExamplesText } from '@/services/cat/few-shot-examples';
|
||||
@@ -137,8 +138,10 @@ export async function prepareCatChat(
|
||||
// user. The per-turn reply-language directive goes DEAD LAST: weak models
|
||||
// weight the prompt tail most, and burying the language rule mid-prompt
|
||||
// let them default to the browser locale's language.
|
||||
const systemPrompt = `${buildCatSystemPrompt({ userContext: contextString || undefined, customInstructions, actionsVia: opts.actionsVia })}${groundingRules}\n\n${getCatFewShotExamplesText()}${buildReplyLanguageDirective(message)}`;
|
||||
|
||||
// History is resolved BEFORE the brief is built: whether this is the first
|
||||
// message of the conversation is an input to section selection (the
|
||||
// orientation sections fire on `first-message`), and it must be a fact read
|
||||
// from the conversation, not inferred from the wording.
|
||||
let conversationId: string | null = null;
|
||||
let historyMessages: Array<{ role: 'user' | 'assistant'; content: string }> = [];
|
||||
try {
|
||||
@@ -152,6 +155,15 @@ export async function prepareCatChat(
|
||||
/* Non-fatal — continue without history */
|
||||
}
|
||||
|
||||
const turnDescriptor = buildTurnDescriptor({
|
||||
message,
|
||||
historyLength: historyMessages.length,
|
||||
currentPath: hints.currentPath,
|
||||
currentEntity: hints.currentEntity,
|
||||
});
|
||||
|
||||
const systemPrompt = `${buildCatSystemPrompt({ userContext: contextString || undefined, customInstructions, actionsVia: opts.actionsVia, turnDescriptor })}${groundingRules}\n\n${getCatFewShotExamplesText()}${buildReplyLanguageDirective(message)}`;
|
||||
|
||||
return {
|
||||
systemPrompt,
|
||||
messages: [
|
||||
|
||||
@@ -81,7 +81,6 @@ export const DEFAULT_PERMISSIONS: Partial<Record<ActionCategory, boolean>> = {
|
||||
communication: false,
|
||||
payments: false, // High risk - never default
|
||||
organization: false,
|
||||
settings: false,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -48,10 +48,16 @@ interface CatSystemPromptContext {
|
||||
export type ActionsVia = 'tools' | 'prose' | 'none';
|
||||
|
||||
/**
|
||||
* Section selection is off until it can be validated against the 8-probe eval,
|
||||
* which needs free-model capacity the platform does not currently have. The
|
||||
* machinery, the classification and the invariants all ship now; flipping this
|
||||
* on is then a one-line change made with a safety net rather than a guess.
|
||||
* Per-turn section selection. Off by default; `CAT_PROMPT_SECTION_SELECTION=1`
|
||||
* in the box's runtime .env turns it on, and the nightly eval
|
||||
* (scripts/eval-cat.mjs via orangecat-cat-eval.timer, 04:30 UTC) is the gate:
|
||||
* it scores 8 probes against production and exits non-zero under 7/8 on
|
||||
* either axis, so a regression from a section the regexes missed shows up the
|
||||
* next morning and the flip is one line to revert.
|
||||
*
|
||||
* Until 2026-09-11 this flag was a double gate: nothing anywhere produced a
|
||||
* turnDescriptor, so setting the env var changed nothing. chat-prepare now
|
||||
* builds one (services/cat/turn-descriptor.ts).
|
||||
*/
|
||||
export const SECTION_SELECTION_ENABLED = process.env.CAT_PROMPT_SECTION_SELECTION === '1';
|
||||
|
||||
@@ -661,29 +667,35 @@ If you call prefill_entity_form or suggest_offers, your reply should be SHORT an
|
||||
export const BASE_SYSTEM_PROMPT_FOR_TEST = BASE_SYSTEM_PROMPT;
|
||||
|
||||
export function buildCatSystemPrompt(context: CatSystemPromptContext = {}): string {
|
||||
const selected =
|
||||
SECTION_SELECTION_ENABLED && context.turnDescriptor
|
||||
? selectSectionsFromPrompt(BASE_SYSTEM_PROMPT, context.turnDescriptor)
|
||||
: BASE_SYSTEM_PROMPT;
|
||||
|
||||
// Default 'prose' so a caller that says nothing gets exactly the prompt it
|
||||
// got before this existed. Omitting the catalog is the change; keeping it is
|
||||
// the status quo, and an un-migrated caller should not silently lose Cat's
|
||||
// only way of acting.
|
||||
const actionsVia: ActionsVia = context.actionsVia ?? 'prose';
|
||||
const base =
|
||||
|
||||
// Order matters and is load-bearing: strip by CAPABILITY first (which always
|
||||
// sees the whole prompt, so its hard-fail on a missing heading stays
|
||||
// meaningful), then select by TURN (which may only ever drop what is still
|
||||
// present). The reverse order threw on flag-on + 'none' + a greeting, because
|
||||
// selection had already removed an instruction section the strip then
|
||||
// demanded. The cannot-act notice is appended after both, so it is last —
|
||||
// recency on the side of the truth — and never subject to selection.
|
||||
const byCapability =
|
||||
actionsVia === 'prose'
|
||||
? selected
|
||||
? BASE_SYSTEM_PROMPT
|
||||
: actionsVia === 'tools'
|
||||
? stripActionProseSections(selected)
|
||||
: [
|
||||
stripSections(selected, [
|
||||
...ACTION_PROSE_SECTION_HEADINGS,
|
||||
...ACTION_INSTRUCTION_SECTION_HEADINGS,
|
||||
]),
|
||||
// Last, so recency is on the side of the truth.
|
||||
CANNOT_ACT_NOTICE,
|
||||
].join('\n\n');
|
||||
? stripActionProseSections(BASE_SYSTEM_PROMPT)
|
||||
: stripSections(BASE_SYSTEM_PROMPT, [
|
||||
...ACTION_PROSE_SECTION_HEADINGS,
|
||||
...ACTION_INSTRUCTION_SECTION_HEADINGS,
|
||||
]);
|
||||
|
||||
const byTurn =
|
||||
SECTION_SELECTION_ENABLED && context.turnDescriptor
|
||||
? selectSectionsFromPrompt(byCapability, context.turnDescriptor)
|
||||
: byCapability;
|
||||
|
||||
const base = actionsVia === 'none' ? [byTurn, CANNOT_ACT_NOTICE].join('\n\n') : byTurn;
|
||||
|
||||
const parts = [base];
|
||||
if (context.customInstructions) {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { generateOffers } from './offer-engine';
|
||||
import { resolveAiAssistTarget } from '@/lib/ai/assist-target';
|
||||
import { isValidEntityType, type EntityType } from '@/config/entity-registry';
|
||||
import { PREFILLABLE_ENTITY_TYPES } from './tool-use-detection';
|
||||
import { handleExploreTopic, handleQueryMyData } from './tool-handlers-lookup';
|
||||
import { handleExploreTopic, handleQueryMyData, handleCheckMyTrackRecord } from './tool-handlers-lookup';
|
||||
import { fetchWebsiteText, resolveRequestedUrl } from './website-analysis';
|
||||
import { runCatHealthProbes } from './health-probes';
|
||||
import type {
|
||||
@@ -242,6 +242,9 @@ Explain this to the user in plain language: which provider is healthy, degraded,
|
||||
if (toolName === 'query_my_data') {
|
||||
return handleQueryMyData(supabase, userId, toolCall, onToolCall);
|
||||
}
|
||||
if (toolName === 'check_my_track_record') {
|
||||
return handleCheckMyTrackRecord(supabase, userId, toolCall, onToolCall);
|
||||
}
|
||||
|
||||
// ── search_platform ──────────────────────────────────────────────────────
|
||||
// ── forget_memories ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Lookup tool handlers — the READ side of Cat's tool surface: explore a topic
|
||||
* (discovery) and read the user's own data. Neither mutates anything.
|
||||
* (discovery), read the user's own data, and read Cat's own track record. None
|
||||
* of them mutates anything.
|
||||
*
|
||||
* Split from tool-executor.ts (500-line service limit) along the natural seam:
|
||||
* lookups here; generative/mutating tools (prefill, website analysis, offers,
|
||||
@@ -158,3 +159,49 @@ export async function handleQueryMyData(
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleCheckMyTrackRecord(
|
||||
supabase: AnySupabaseClient,
|
||||
userId: string,
|
||||
toolCall: RawToolCall,
|
||||
onToolCall?: OnToolCall
|
||||
): Promise<ToolResultMessage> {
|
||||
const toolName = 'check_my_track_record';
|
||||
// ── check_my_track_record ────────────────────────────────────────────────
|
||||
// ADR-0006 D6: Cat can check its OWN work. The same derivation that feeds
|
||||
// the ambient "Track Record" context section, but on demand — so "what did
|
||||
// you do for me?" is answered from the action log and entity tables, and
|
||||
// Cat can notice its own pattern (drafted, never published) before
|
||||
// proposing more of the same. Read-only; no permission gate; no arguments.
|
||||
onToolCall?.({ id: toolCall.id, name: toolName, status: 'running' });
|
||||
try {
|
||||
const { getCatTrackRecord, formatTrackRecordForModel } = await import('./track-record');
|
||||
const record = await getCatTrackRecord(supabase, userId);
|
||||
const proposed = record?.proposed ?? 0;
|
||||
onToolCall?.({
|
||||
id: toolCall.id,
|
||||
name: toolName,
|
||||
status: 'completed',
|
||||
resultCount: proposed,
|
||||
results: [],
|
||||
});
|
||||
return {
|
||||
role: 'tool',
|
||||
tool_call_id: toolCall.id,
|
||||
content: formatTrackRecordForModel(record),
|
||||
};
|
||||
} catch (err) {
|
||||
onToolCall?.({
|
||||
id: toolCall.id,
|
||||
name: toolName,
|
||||
status: 'failed',
|
||||
error: err instanceof Error ? err.message : 'unknown',
|
||||
});
|
||||
return {
|
||||
role: 'tool',
|
||||
tool_call_id: toolCall.id,
|
||||
content:
|
||||
'Reading your own track record failed — tell the user honestly that you cannot see your history right now, and do not reconstruct it from memory.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -428,4 +428,13 @@ export const PLATFORM_TOOL_DEFINITION = [
|
||||
parameters: { type: 'object', properties: {} },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'check_my_track_record',
|
||||
description:
|
||||
"What YOU (the Cat) have done for this user and what became of it: the entities you created in the last 90 days — proposed → published → funded, with real BTC amounts — plus your own setbacks (failed or denied actions, proposals the user never confirmed). Call when the user asks what you did for them, how your suggestions worked out, or whether to trust you; and call it BEFORE proposing something new when you may have proposed the same kind before. Read-only. Takes no arguments. NOT for the user's own numbers or listings — that is query_my_data.",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -281,6 +281,7 @@ async function runToolLoop(args: {
|
||||
'- explore_topic: when the user expresses an INTEREST or curiosity rather than naming a specific thing to find ("I\'m interested in longevity", "anyone working on Bitcoin education?", "introduce me to people doing X"). Pass the topic in their own words. Use this, NOT search_platform, for interests — it also finds the people behind the work so an introduction is possible.\n' +
|
||||
'- query_my_data: when the user asks about their OWN stuff or numbers — earnings/sales ("how much did I earn?"), their listings ("what am I selling?"), bookings, wallet balances/goals, unread notifications, open tasks, or a general catch-up ("how am I doing?", "catch me up"). Read-only. Pick the closest topic (listings, earnings, bookings, wallets, notifications, tasks) or "overview" for a broad question.\n' +
|
||||
'- check_cat_health: ONLY when the user asks why the Cat/AI is failing, slow, or not answering, or asks about a system notification mentioning provider failures, eval/harness errors, or Cat health (e.g. "why is my Cat not answering?", "what does this eval error notification mean?"). Takes no arguments.\n' +
|
||||
'- check_my_track_record: when the user asks what YOU did for them or how it went (e.g. "what have you done for me?", "did any of your ideas work?", "why should I trust you?"), or before you propose another thing of a kind you may already have proposed. It is about YOUR actions and their outcomes, not the user\'s own numbers (that is query_my_data). Takes no arguments.\n' +
|
||||
'You may also call any ACTION tool (create_project, update_entity, …) when the user clearly asks you to DO that thing — not to explore it. An action WRITES, so call it only on a clear instruction; its result comes back to you before you reply, so never claim something is done until you have seen that result.\n' +
|
||||
'NEVER call search_platform for a create/sell/offer intent — describing your own thing to list is prefill_entity_form, not a search. If neither clearly applies, call no tool. Only decide and call tools — do not write a chat reply.',
|
||||
},
|
||||
|
||||
@@ -303,3 +303,80 @@ async function getSetbacks(
|
||||
.slice(0, MAX_SETBACKS),
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== TOOL OUTPUT ====================
|
||||
|
||||
/**
|
||||
* The track record as prose for the model, when Cat CALLS for it (ADR-0006 D6)
|
||||
* rather than receiving it as ambient context. Separate from
|
||||
* context-sections.renderTrackRecord on purpose: that rendering is pinned by a
|
||||
* snapshot test and tuned as a background section; this one answers a direct
|
||||
* question ("what did you do for me?") and, more usefully, names Cat's own
|
||||
* pattern so it can act on it — "three drafted, none published" is a fact Cat
|
||||
* should notice before proposing a fourth.
|
||||
*
|
||||
* Prose, not JSON: weak models paraphrase prose and echo JSON.
|
||||
*/
|
||||
export function formatTrackRecordForModel(tr: CatTrackRecord | null): string {
|
||||
if (!tr) {
|
||||
return 'TRACK RECORD: could not be read (the action log was unavailable). Tell the user you cannot see your own history right now — do not reconstruct it from memory.';
|
||||
}
|
||||
const setbackCount = tr.setbacks.failed + tr.setbacks.denied + tr.setbacks.unconfirmed;
|
||||
if (tr.proposed === 0 && setbackCount === 0) {
|
||||
return `TRACK RECORD (last ${tr.windowDays} days): nothing yet. You have not created anything for this user in this window and nothing failed. Say so plainly; do not invent history.`;
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(
|
||||
`TRACK RECORD (last ${tr.windowDays} days, real outcomes): proposed ${tr.proposed}, published ${tr.published} (active now), funded ${tr.funded}` +
|
||||
(tr.funded > 0 ? ` for ${tr.totalFundedBtc} BTC in total.` : '.')
|
||||
);
|
||||
|
||||
if (tr.entries.length > 0) {
|
||||
lines.push('What you created, most recent first:');
|
||||
for (const e of tr.entries) {
|
||||
const state = e.status === null ? 'deleted since' : `status ${e.status}`;
|
||||
const money = e.payments > 0 ? `, ${e.fundedBtc} BTC from ${e.payments} payment(s)` : '';
|
||||
lines.push(`- ${e.entityType} "${e.title}" — ${state}${money} (created ${e.createdAt.slice(0, 10)})`);
|
||||
}
|
||||
}
|
||||
|
||||
if (setbackCount > 0) {
|
||||
lines.push(
|
||||
`Setbacks: ${tr.setbacks.failed} failed, ${tr.setbacks.denied} denied (permission or spend cap), ${tr.setbacks.unconfirmed} never confirmed by the user.`
|
||||
);
|
||||
for (const sb of tr.setbacks.recent) {
|
||||
lines.push(`- ${sb.actionId}: ${sb.kind}${sb.reason ? ` — ${sb.reason}` : ''} (${sb.at.slice(0, 10)})`);
|
||||
}
|
||||
}
|
||||
|
||||
// The pattern is the point. State it as a fact so the model acts on it
|
||||
// instead of re-proposing the same thing a fourth time.
|
||||
const drafts = tr.entries.filter(e => e.status === 'draft').length;
|
||||
const patterns: string[] = [];
|
||||
if (drafts >= 2 && tr.published === 0) {
|
||||
patterns.push(
|
||||
`${drafts} things drafted, none published — offer to finish ONE of them (name it) before creating anything new.`
|
||||
);
|
||||
} else if (drafts >= 2) {
|
||||
patterns.push(`${drafts} drafts are sitting unpublished — worth offering to finish one.`);
|
||||
}
|
||||
if (tr.published > 0 && tr.funded === 0) {
|
||||
patterns.push(
|
||||
`${tr.published} published but nothing funded yet — the gap is reach or pricing, not more listings.`
|
||||
);
|
||||
}
|
||||
if (tr.setbacks.unconfirmed >= 2) {
|
||||
patterns.push(
|
||||
`${tr.setbacks.unconfirmed} proposals the user never confirmed — ask what held them back before proposing the same kind again.`
|
||||
);
|
||||
}
|
||||
if (patterns.length > 0) {
|
||||
lines.push('PATTERN: ' + patterns.join(' '));
|
||||
}
|
||||
|
||||
lines.push(
|
||||
'Answer from THESE lines only. Amounts are BTC. Own the setbacks in the first person; never claim an outcome not listed here.'
|
||||
);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* The turn descriptor — what one turn is "about", for prompt section selection.
|
||||
*
|
||||
* config/cat-prompt-sections classifies every situational section of Cat's
|
||||
* brief with a trigger regex, matched against this string. Until now nothing
|
||||
* produced it: the flag existed, the selector existed, the tests exercised it,
|
||||
* and no caller ever passed a descriptor — so the flag was a double gate that
|
||||
* could not be flipped on. This is the producer.
|
||||
*
|
||||
* It is the user's message plus a few coarse markers the regexes already
|
||||
* expect (`first-message`, `no-specific-request`), plus the page they are on,
|
||||
* so a turn opened from a product page reaches the entity-management sections
|
||||
* even when the message itself is "make it cheaper".
|
||||
*
|
||||
* Deliberately dumb: no classification, no model call. Markers are facts the
|
||||
* caller already knows. A miss costs one situational section for one turn;
|
||||
* the core sections — every action, every rule — are never subject to this.
|
||||
*/
|
||||
|
||||
export interface TurnDescriptorInput {
|
||||
message: string;
|
||||
/** Messages already in the conversation before this one. */
|
||||
historyLength: number;
|
||||
currentPath?: string;
|
||||
currentEntity?: { type: string; ref: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* A message that names nothing to do. Short, and made of greeting/filler words
|
||||
* only. "hi", "hello there", "hey cat" — not "hi, sell my bike".
|
||||
*/
|
||||
const NO_REQUEST = /^[\s\p{P}]*(hi|hello|hey|yo|hola|hallo|salut|ciao|привет|good (morning|afternoon|evening)|there|cat|you)?(\s+(hi|hello|hey|there|cat|you|again))*[\s\p{P}]*$/iu;
|
||||
|
||||
export function isNoSpecificRequest(message: string): boolean {
|
||||
const m = message.trim();
|
||||
return m.length === 0 || (m.length <= 24 && NO_REQUEST.test(m));
|
||||
}
|
||||
|
||||
export function buildTurnDescriptor(input: TurnDescriptorInput): string {
|
||||
const parts: string[] = [input.message];
|
||||
if (input.historyLength === 0) {
|
||||
parts.push('first-message');
|
||||
}
|
||||
if (isNoSpecificRequest(input.message)) {
|
||||
parts.push('no-specific-request');
|
||||
}
|
||||
if (input.currentEntity?.type) {
|
||||
parts.push(`my ${input.currentEntity.type}`);
|
||||
}
|
||||
if (input.currentPath) {
|
||||
parts.push(input.currentPath);
|
||||
}
|
||||
return parts.join(' | ');
|
||||
}
|
||||
Reference in new issue
Block a user