Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/analytics/agent-performance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [];

Expand Down
8 changes: 8 additions & 0 deletions src/routes/agents-external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
}
Expand Down
4 changes: 3 additions & 1 deletion src/routes/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
10 changes: 8 additions & 2 deletions src/routes/repid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,15 @@ async function resolveAgentUuid(raw: string): Promise<string | null> {
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;
Comment thread
DealAppSeo marked this conversation as resolved.
Resolved
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;
Expand Down
12 changes: 6 additions & 6 deletions src/routes/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
18 changes: 9 additions & 9 deletions src/services/agent-passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,16 +197,16 @@ 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
// in src/routes/repid.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);
Comment thread
DealAppSeo marked this conversation as resolved.
Resolved
}

/**
Expand Down
19 changes: 19 additions & 0 deletions tests/agent-passport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any> = { '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
Expand Down
28 changes: 27 additions & 1 deletion tests/agents-register.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {
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 }),
};
Expand Down Expand Up @@ -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)
Expand Down
Loading