diff --git a/CLAUDE.md b/CLAUDE.md index ed212990..2719acd5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -239,7 +239,13 @@ When adding a new event type, update `RepIdUpdateInput.eventType`, the `challeng The engine reads/writes only these tables (no migrations live in this repo — schema is managed externally): -- `repid_agents` — agent state (current_repid, tier, constitution, activity_30d, erc8004_address) +- `repid_agents` — agent state (current_repid, tier, constitution, activity_30d, erc8004_address). + **Names: the `trinity-` prefix marks Sean's 12 original agents, and nothing else.** It held + until 2026-05-13, when the `normalize_agent_name()` trigger began adding `trinity-` to every + new name, so the prefix stopped telling anyone anything. The 2026-11-16 SQL (applied by Sean; check `pg_indexes` for `repid_agents_agent_name_unique` + before relying on it) gives the prefix back only to the 12, strips it from everyone else, and + makes names unique ignoring case. Until that index exists, names are NOT unique. The + forge-proof test for an original is a minted ERC-8004 token plus `active`, not the name. - `repid_score_events` — append-only audit log of every score change - `repid_badges` — milestone awards - `repid_bounties` — bounty lifecycle diff --git a/src/analytics/agent-performance.ts b/src/analytics/agent-performance.ts index a055c2ee..21ce0024 100644 --- a/src/analytics/agent-performance.ts +++ b/src/analytics/agent-performance.ts @@ -175,7 +175,7 @@ export async function getAgentsLeaderboard( const { data: agents, error } = await db .from('repid_agents') .select('agent_name') - .neq('agent_name', 'HUMAN'); + .eq('is_human', false); // was neq('agent_name','HUMAN'); human rows are no longer all named HUMAN if (error || !agents) return []; diff --git a/src/routes/agents-external.ts b/src/routes/agents-external.ts index a3b1bc27..29abf0a9 100644 --- a/src/routes/agents-external.ts +++ b/src/routes/agents-external.ts @@ -180,6 +180,14 @@ router.post('/register', async (req: Request, res: Response) => { .select('id, created_at, erc8004_token_id') .single(); + // Agent names are unique (case-insensitive) since 2026-11-16, enforced by the DB index + // repid_agents_agent_name_unique. Match on the index name: erc8004_address is unique too. + if (insertErr?.code === '23505' && String(insertErr.message).includes('repid_agents_agent_name_unique')) { + return res.status(409).json({ + error: 'agent name is already taken', + hint: 'Pick a different name, for example with a suffix.', + }); + } if (insertErr || !newAgent) { return res.status(500).json({ error: insertErr?.message ?? 'insert failed' }); } diff --git a/src/routes/agents.ts b/src/routes/agents.ts index 2145f485..b91bd830 100644 --- a/src/routes/agents.ts +++ b/src/routes/agents.ts @@ -67,7 +67,9 @@ router.post('/agents/human', async (req: Request, res: Response) => { .from('repid_agents') .insert({ erc8004_address: zkpCommitment, - agent_name: 'HUMAN', + // Agent names are unique, so each human gets its own. Independent of anonymousId, + // which is the human's secret and must never be derivable from a readable column. + agent_name: `human-${randomBytes(6).toString('hex')}`, current_repid: STARTING_REPID, tier: 'PROBATIONARY', constitution: { diff --git a/src/routes/repid.ts b/src/routes/repid.ts index f37799a2..1c6c7b4d 100644 --- a/src/routes/repid.ts +++ b/src/routes/repid.ts @@ -55,9 +55,15 @@ async function resolveAgentUuid(raw: string): Promise { if (/^\d+$/.test(id)) { query = query.eq('erc8004_token_id', id); } else { + // The trinity- form first: it is the canonical name of the 12 originals ("sophia" → + // trinity-sophia), so a row that merely holds the bare slug can never outrank one of them. + // Then the exact name, for every other agent. Same order as fetchAgentRow in agent-passport.ts. const lcName = id.toLowerCase(); - const lookupName = lcName.startsWith('trinity-') ? lcName : `trinity-${lcName}`; - query = query.eq('agent_name', lookupName); + const canonical = lcName.startsWith('trinity-') ? lcName : `trinity-${lcName}`; + const { data: hit } = await query.eq('agent_name', canonical).maybeSingle(); + if (hit && hit.id) return hit.id as string; + if (lcName === canonical) return null; + query = db.from('repid_agents').select('id').eq('agent_name', lcName); } const { data } = await query.maybeSingle(); return data && data.id ? (data.id as string) : null; diff --git a/src/routes/route.ts b/src/routes/route.ts index ed075973..a31f1ec2 100644 --- a/src/routes/route.ts +++ b/src/routes/route.ts @@ -280,14 +280,14 @@ llmRouter.post('/v1/llm/complete', llmLimiter, async (req: Request, res: Respons }; if (agent_id && typeof agent_id === 'string' && !isUuid(agent_id)) { + // The trinity- form first (canonical name of the 12 originals), then the exact name, so a + // row holding only the bare slug can never outrank an original. const lcName = agent_id.toLowerCase(); - const lookupName = lcName.startsWith('trinity-') ? lcName : `trinity-${lcName}`; + const canonical = lcName.startsWith('trinity-') ? lcName : `trinity-${lcName}`; + const lookup = (name: string) => db.from('repid_agents').select('id').eq('agent_name', name).maybeSingle(); try { - const { data } = await db - .from('repid_agents') - .select('id') - .eq('agent_name', lookupName) - .maybeSingle(); + let { data } = await lookup(canonical); + if (!data && lcName !== canonical) ({ data } = await lookup(lcName)); if (data && data.id) { resolvedAgentId = data.id; } diff --git a/src/services/agent-passport.ts b/src/services/agent-passport.ts index 32487570..ea562899 100644 --- a/src/services/agent-passport.ts +++ b/src/services/agent-passport.ts @@ -197,16 +197,17 @@ async function fetchAgentRow( if (UUID_RE.test(id)) return tryFetch('id', id); if (/^\d+$/.test(id)) return tryFetch('erc8004_token_id', id); - // Name/slug: exact match first, then the legacy trinity- prefix convention - // (parity with resolveAgentUuid in src/routes/repid.ts, minus its blind spot - // for external agents whose names don't carry the prefix). + // Name/slug: the trinity- form first, because it is the canonical name of the 12 + // original agents and a row holding only the bare slug must never outrank one of + // them; then the exact name, for every other agent. Same order as resolveAgentUuid + // (repid.ts), the /v1/llm/complete lookup (route.ts) and the task bridge + // (trinity-task-bridge.ts). (Until 2026-11-16 this was exact-first, so a sign-up + // named "sophia" stored without the prefix would have won.) const lcName = id.toLowerCase(); - const exact = await tryFetch('agent_name', lcName); - if (exact) return exact; - if (!lcName.startsWith('trinity-')) { - return tryFetch('agent_name', `trinity-${lcName}`); - } - return null; + const canonical = lcName.startsWith('trinity-') ? lcName : `trinity-${lcName}`; + const hit = await tryFetch('agent_name', canonical); + if (hit) return hit; + return lcName === canonical ? null : tryFetch('agent_name', lcName); } /** diff --git a/src/services/trinity-task-bridge.ts b/src/services/trinity-task-bridge.ts index 09b1cb8b..857ea1b3 100644 --- a/src/services/trinity-task-bridge.ts +++ b/src/services/trinity-task-bridge.ts @@ -226,11 +226,15 @@ export async function pollCompletedTasks() { metadataObj.processedBy; const agentName = normalizeAgentName(rawAgent); - const { data: agentInfo, error: agentErr } = await db - .from('repid_agents') - .select('id') - .eq('agent_name', agentName) - .maybeSingle(); + // The trinity- form first (the 12 originals), then the bare name. Since 2026-11-16 only + // the 12 keep the prefix in repid_agents, but trinity_tasks' own trigger still adds it to + // every name it stores, so "trinity-foo" here can be the agent now named "foo". + const lookupAgent = (name: string) => + db.from('repid_agents').select('id').eq('agent_name', name).maybeSingle(); + let { data: agentInfo, error: agentErr } = await lookupAgent(agentName); + if (!agentErr && !agentInfo && agentName.startsWith('trinity-')) { + ({ data: agentInfo, error: agentErr } = await lookupAgent(agentName.slice('trinity-'.length))); + } if (agentErr || !agentInfo) { console.warn(`[TrinityTaskBridge] Agent '${agentName}' not found in repid_agents for task ${task.id}, skipping`); diff --git a/tests/agent-passport.test.ts b/tests/agent-passport.test.ts index aca126cb..0c3a571a 100644 --- a/tests/agent-passport.test.ts +++ b/tests/agent-passport.test.ts @@ -382,6 +382,25 @@ describe('buildAgentPassport', () => { expect(p!.agent.agent_id).toBe(MINTED_AGENT.id); }); + test('a row holding only the bare slug never outranks the trinity- original', async () => { + // Both exist: the original "trinity-shofet" and a later sign-up stored as plain "shofet". + const IMPOSTOR = { ...MINTED_AGENT, id: '99999999-0000-4000-8000-000000000001', agent_name: 'shofet' }; + const byName: Record = { 'trinity-shofet': MINTED_AGENT, shofet: IMPOSTOR }; + const scripted = makeDb(happyScript()); + const db = { + from: (table: string) => { + if (table !== 'repid_agents') return scripted.from(table); + let name = ''; + const chain: any = { select: () => chain }; + chain.eq = (_col: string, val: string) => { name = val; return chain; }; + chain.maybeSingle = () => Promise.resolve({ data: byName[name] ?? null, error: null }); + return chain; + }, + } as any; + const p = await buildAgentPassport(db, 'shofet'); + expect(p!.agent.agent_id).toBe(MINTED_AGENT.id); + }); + test('last-real-settlement query skips hash-less rows and pins nulls last', async () => { // Live-prod finding (trinity-shofet, 2026-07-30): 47 real settlements but // last_real_settlement=null, because the newest real row had a null diff --git a/tests/agents-register.test.ts b/tests/agents-register.test.ts index fb14bddc..e67b1434 100644 --- a/tests/agents-register.test.ts +++ b/tests/agents-register.test.ts @@ -30,14 +30,24 @@ jest.mock('../src/db', () => { eq: () => chain, insert: (row: any) => { insertedRows.push({ table: tableName, row: { ...row } }); + let insertError: any = null; if (tableName === 'repid_agents') { const id = `00000000-0000-4000-8000-${String(nextId++).padStart(12, '0')}`; lastInserted = { id, created_at: '2026-05-07T00:00:00Z', erc8004_token_id: null }; + // What Postgres says when a unique index refuses the row. + const taken: Record = { + TakenName: 'repid_agents_agent_name_unique', + TakenWallet: 'repid_agents_erc8004_address_key', + }; + if (taken[row.agent_name]) { + lastInserted = null; + insertError = { code: '23505', message: `duplicate key value violates unique constraint "${taken[row.agent_name]}"` }; + } } // Return another chainable that ALSO is awaitable. const insertResult: any = { select: () => ({ - single: async () => ({ data: lastInserted, error: null }), + single: async () => ({ data: lastInserted, error: insertError }), }), then: (resolve: any) => resolve({ data: null, error: null }), }; @@ -245,6 +255,22 @@ describe('POST /api/v1/agents/register — anti-spam dedup', () => { expect(r2.body.hint).toBeTruthy(); }); + it('409s a name another agent already has (the unique name index refused it)', async () => { + const res = await request(app) + .post('/api/v1/agents/register').set('x-enterprise-key', ENTERPRISE_KEY) + .send({ name: 'TakenName' }); + expect(res.status).toBe(409); + expect(res.body.error).toMatch(/already taken/i); + }); + + it('a different unique violation (wallet) is still a 500, not "name taken"', async () => { + const res = await request(app) + .post('/api/v1/agents/register').set('x-enterprise-key', ENTERPRISE_KEY) + .send({ name: 'TakenWallet' }); + expect(res.status).toBe(500); + expect(res.body.error).toMatch(/erc8004_address/); + }); + it('does NOT 429 a different name from the same IP', async () => { const r1 = await request(app) .post('/api/v1/agents/register').set('x-enterprise-key', ENTERPRISE_KEY) diff --git a/tests/bridge-known-answer-shadow.test.ts b/tests/bridge-known-answer-shadow.test.ts index 99a74054..5d8055da 100644 --- a/tests/bridge-known-answer-shadow.test.ts +++ b/tests/bridge-known-answer-shadow.test.ts @@ -40,8 +40,12 @@ jest.mock('../src/db', () => { if (table === 'repid_agents') { return { select: () => ({ - eq: () => ({ - maybeSingle: async () => ({ data: { id: st().agent.id }, error: null }), + eq: (_col: string, val: unknown) => ({ + // knownNames unset: every name lookup hits (the original behaviour of this double). + maybeSingle: async () => ({ + data: !st().knownNames || st().knownNames.includes(val) ? { id: st().agent.id } : null, + error: null, + }), single: async () => ({ data: st().agent, error: null }), }), }), @@ -139,9 +143,10 @@ function task(metadata: Record) { } /** Run one bridge tick over one task and return everything the tick wrote. */ -async function tick(metadata: Record) { +async function tick(metadata: Record, opts: { agent?: string; knownNames?: string[] } = {}) { const st = { - tasks: [task(metadata)], + tasks: [{ ...task(metadata), ...(opts.agent ? { agent_assigned: opts.agent } : {}) }], + knownNames: opts.knownNames, agent: { id: AGENT_ID, current_repid: 1000, tier: 'ESTABLISHED', vesting_cliff_ends_at: null }, // count BEFORE the insert is 9, so (9 + 1) % 10 === 0: the every-10th-event proof trigger fires. eventCount: 9, @@ -207,6 +212,18 @@ describe('bridge: canonical is today, exactly (witness for every shadow absence expect(r.taskUpdates).toHaveLength(1); }); + test('a task recorded as trinity-foo is scored to the agent now named plain "foo"', async () => { + // trinity_tasks still prefixes every name; since 2026-11-16 only the 12 originals keep it in repid_agents. + const r = await tick({ case_id: 'ka-002' }, { agent: 'trinity-foo', knownNames: ['foo'] }); + expect(r.inserts).toHaveLength(1); + expect(r.agentUpdates).toHaveLength(1); + }); + + test('an original is still found by its trinity- name, not by a bare slug', async () => { + const r = await tick({ case_id: 'ka-003' }, { agent: 'veritas', knownNames: ['trinity-veritas'] }); + expect(r.inserts).toHaveLength(1); + }); + test("'canonical' and unset and a no-case_id task in shadow mode all write the identical row", async () => { const unset = await tick({ case_id: 'ka-001' }); process.env[ENV] = 'canonical';