Repository navigation
feat(see): link cards to bounded run traces (TASK-499) #2686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
752173a
feat(traces): link native messages to bounded run audit
lilyshen0722 598e021
fix(traces): limit reads and align Chinese numeral spacing
lilyshen0722 3e834e0
test: pin run trace provenance through native output and approvals
lilyshen0722 6d41f36
fix: match trace controls and localized disclosure to Signal
lilyshen0722 5b26532
fix: preserve hosted approval trace origins and place trace links aft…
lilyshen0722 5980903
Record refused native message posts as failed trace calls
lilyshen0722 0f0d8cf
fix: restrict run trace authorization identities to pod members
lilyshen0722 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| /** Read joins must execute against real PostgreSQL, not only pg-mem. */ | ||
| const ToolCall = require('../../models/ToolCall'); | ||
| const { pool } = require('../../config/db-pg'); | ||
| const run = process.env.INTEGRATION_TEST === 'true' ? describe : describe.skip; | ||
| const grantId = `lark-trace-${Date.now()}`; | ||
| const podId = `${grantId}-pod`; | ||
| run('run trace attribution on real PostgreSQL', () => { | ||
| afterAll(async () => { await pool.query('DELETE FROM tool_calls WHERE grant_id = $1', [grantId]); }); | ||
| it('reads only referenced calls in the authorized pod, with current approval outcome', async () => { | ||
| const record = (id, over = {}) => ({ callId: `${grantId}-${id}`, grantId, podId, | ||
| agentUserId: 'agent', credentialOwnerId: 'credential-owner', tool: 'vendor.read', | ||
| argsDigest: 'a'.repeat(64), outcome: 'ok', ...over }); | ||
| await ToolCall.create(record('ok')); | ||
| await ToolCall.create(record('pending', { outcome: 'pending_approval', approvalId: 'approval' })); | ||
| await ToolCall.create(record('resolved', { outcome: 'failed', approvalId: 'approval' })); | ||
| await ToolCall.create(record('foreign', { podId: 'another-pod' })); | ||
| const ids = ['ok', 'pending', 'foreign'].map((id) => `${grantId}-${id}`); | ||
| const rows = await ToolCall.listRunReferences(podId, ids); | ||
| expect(rows).toHaveLength(2); | ||
| expect(rows.find((r) => r.callId.endsWith('-ok'))).toMatchObject({ grantId, credentialOwnerId: 'credential-owner', outcome: 'ok' }); | ||
| expect(rows.find((r) => r.callId.endsWith('-pending')).outcome).toBe('superseded'); | ||
| expect(await ToolCall.listRunReferences(podId, [])).toEqual([]); | ||
| }); | ||
| }); |
26 changes: 26 additions & 0 deletions
26
backend/__tests__/unit/models/ApprovalAction.runTrace.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| const mongoose = require('mongoose'); | ||
| const { setupMongoDb, closeMongoDb } = require('../../utils/testUtils'); | ||
| const ApprovalAction = require('../../../models/ApprovalAction'); | ||
|
|
||
| beforeAll(setupMongoDb); | ||
| afterAll(closeMongoDb); | ||
|
|
||
| test('the originating run persists across an approval save, reload and transition', async () => { | ||
| const runId = new mongoose.Types.ObjectId(); | ||
| const runPodId = new mongoose.Types.ObjectId(); | ||
| const action = await ApprovalAction.create({ | ||
| podId: new mongoose.Types.ObjectId(), ownerUserId: new mongoose.Types.ObjectId(), | ||
| agentName: 'trace-seat', actionType: 'create_pod', params: { name: 'Research' }, | ||
| summary: 'Create a research pod', runId, runPodId, | ||
| }); | ||
| const loaded = await ApprovalAction.findById(action._id); | ||
| expect(String(loaded.runId)).toBe(String(runId)); | ||
| expect(String(loaded.runPodId)).toBe(String(runPodId)); | ||
| loaded.status = 'resolved'; | ||
| loaded.decision = 'declined'; | ||
| await loaded.save(); | ||
| const resolved = await ApprovalAction.findById(action._id).lean(); | ||
| expect(String(resolved.runId)).toBe(String(runId)); | ||
| expect(String(resolved.runPodId)).toBe(String(runPodId)); | ||
| expect(resolved.status).toBe('resolved'); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| jest.mock('../../../config/db-pg', () => { | ||
| const { newDb } = require('pg-mem'); | ||
| const { Pool } = newDb().adapters.createPg(); | ||
| return { pool: new Pool() }; | ||
| }); | ||
| const express = require('express'); | ||
| const request = require('supertest'); | ||
| const mongoose = require('mongoose'); | ||
| const { MongoMemoryServer } = require('mongodb-memory-server'); | ||
|
|
||
| jest.mock('../../../middleware/auth', () => (req, res, next) => { | ||
| if (!req.get('x-user')) return res.sendStatus(401); | ||
| req.user = { id: req.get('x-user') }; | ||
| return next(); | ||
| }); | ||
| const AgentRun = require('../../../models/AgentRun'); | ||
| const Pod = require('../../../models/Pod'); | ||
| const User = require('../../../models/User'); | ||
| const ToolCall = require('../../../models/ToolCall'); | ||
| const { pool } = require('../../../config/db-pg'); | ||
| const { boundRunValue, RUN_TRACE_BYTES } = require('../../../services/agentRunLimits'); | ||
| const { BSON } = require('mongodb'); | ||
| const MEMBER = new mongoose.Types.ObjectId(); | ||
| const POD = new mongoose.Types.ObjectId(); | ||
| const OTHER = new mongoose.Types.ObjectId(); | ||
| let mongo; | ||
| let app; | ||
| let run; | ||
| beforeAll(async () => { | ||
| mongo = await MongoMemoryServer.create(); | ||
| await mongoose.connect(mongo.getUri()); | ||
| app = express(); | ||
| app.use('/api/pods', require('../../../routes/runTraces')); | ||
| }); | ||
| afterAll(async () => { await mongoose.disconnect(); await mongo.stop(); }); | ||
| beforeEach(async () => { | ||
| await AgentRun.deleteMany({}); | ||
| await Pod.deleteMany({}); | ||
| await User.deleteMany({}); | ||
| await Pod.create({ _id: POD, name: 'Trace pod', type: 'team', members: [MEMBER], createdBy: MEMBER }); | ||
| run = await AgentRun.create({ | ||
| podId: POD, agentName: 'trace-seat', instanceId: 'default', trigger: 'mention', status: 'succeeded', | ||
| startedAt: new Date('2020-01-01'), | ||
| turns: [{ turnIndex: 0, model: 'model', elapsedMs: 1, llmResponseText: 'private prompt', | ||
| toolCalls: [{ name: 'vendor.read', args: { secret: 'PRIVATE_ARGS' }, result: 'PRIVATE_RESULT', callId: 'trace-call', outcome: 'ok' }] }], | ||
| }); | ||
| await ToolCall.create({ callId: `unused-${run.id}`, grantId: 'grant', podId: String(POD), agentUserId: 'seat', tool: 'vendor.read', argsDigest: 'a'.repeat(64), outcome: 'ok' }); | ||
| await pool.query('DELETE FROM tool_calls WHERE call_id IN ($1, $2)', ['trace-call', 'foreign-call']); | ||
| await ToolCall.create({ callId: 'trace-call', grantId: 'grant', podId: String(POD), credentialOwnerId: 'owner', agentUserId: 'seat', tool: 'vendor.read', argsDigest: 'a'.repeat(64), outcome: 'ok' }); | ||
| await ToolCall.create({ callId: 'foreign-call', grantId: 'foreign-grant', podId: String(OTHER), credentialOwnerId: 'foreign-owner', agentUserId: 'seat', tool: 'vendor.read', argsDigest: 'a'.repeat(64), outcome: 'failed' }); | ||
| }); | ||
| const get = (pod = POD, id = run.id, user = MEMBER) => request(app).get(`/api/pods/${pod}/runs/${id}`).set('x-user', String(user)); | ||
|
|
||
| test('requires authentication and current pod access, not knowledge of a run ID', async () => { | ||
| expect((await request(app).get(`/api/pods/${POD}/runs/${run.id}`)).status).toBe(401); | ||
| expect((await get(POD, run.id, OTHER)).status).toBe(404); | ||
| expect((await get(OTHER)).status).toBe(404); | ||
| expect((await get(POD, 'bad-id')).status).toBe(404); | ||
| }); | ||
| test('returns durable turn + PG attribution after card retention without content', async () => { | ||
| const res = await get(); | ||
| expect(res.status).toBe(200); | ||
| expect(res.headers['cache-control']).toBe('no-store'); | ||
| expect(res.body.run.turns[0].toolCalls[0].trail).toMatchObject({ callId: 'trace-call', grantId: 'grant', credentialOwnerId: 'owner', outcome: 'ok' }); | ||
| expect(JSON.stringify(res.body)).not.toMatch(/PRIVATE_|private prompt|argsDigest/); | ||
| expect(res.body.retention).toEqual({ cardDefaultDays: 30, traceExpiresAt: null }); | ||
| }); | ||
| test.each(['global admin', 'agent-dm observer'])( | ||
| 'returns trace metadata without authorization identities to a non-member %s', async (viewerType) => { | ||
| if (viewerType === 'global admin') { | ||
| await User.create({ _id: OTHER, username: 'trace-admin', email: 'trace-admin@example.test', | ||
| role: 'admin', authProviders: [{ provider: 'github', providerId: 'trace-admin' }] }); | ||
| } else { | ||
| await Pod.updateOne({ _id: POD }, { $set: { type: 'agent-dm' } }); | ||
| await Pod.create({ name: 'Shared team', type: 'team', members: [MEMBER, OTHER], createdBy: MEMBER }); | ||
| } | ||
| const res = await get(POD, run.id, OTHER); | ||
| expect(res.status).toBe(200); | ||
| expect(res.headers['cache-control']).toBe('no-store'); | ||
| const call = res.body.run.turns[0].toolCalls[0]; | ||
| expect(call.outcome).toBe('ok'); | ||
| expect(call.trail).toEqual({ callId: 'trace-call', tool: 'vendor.read', outcome: 'ok', | ||
| at: expect.any(String), durationMs: null }); | ||
| expect(JSON.stringify(res.body)).not.toMatch(/grantId|credentialOwnerId|PRIVATE_|private prompt|argsDigest/); | ||
| }, | ||
| ); | ||
| test('cross-pod references never join a foreign trail', async () => { | ||
| run.turns[0].toolCalls[0].callId = 'foreign-call'; | ||
| await run.save(); | ||
| const res = await get(); | ||
| expect(res.status).toBe(200); | ||
| expect(res.body.run.turns[0].toolCalls[0]).toMatchObject({ outcome: 'unavailable', trail: null }); | ||
| expect(JSON.stringify(res.body)).not.toMatch(/foreign-owner|foreign-grant/); | ||
| }); | ||
| test('PG failure is explicit instead of an empty audit', async () => { | ||
| jest.spyOn(ToolCall, 'listRunReferences').mockRejectedValueOnce(new Error('db offline')); | ||
| expect((await get()).status).toBe(503); | ||
| }); | ||
| test('save caps UTF-8 args/results, response text and aggregate BSON size', async () => { | ||
| const huge = '界'.repeat(10000); | ||
| run.turns = Array.from({ length: 140 }, (_, turnIndex) => ({ | ||
| turnIndex, model: 'm', elapsedMs: 1, llmResponseText: huge, | ||
| toolCalls: Array.from({ length: turnIndex === 0 ? 70 : 0 }, () => ({ name: 'read', elapsedMs: 1, args: huge, result: huge })), | ||
| })); | ||
| await run.save(); | ||
| const stored = await AgentRun.findById(run.id).lean(); | ||
| expect(stored.traceTruncated).toBe(true); | ||
| expect(stored.turns[0].toolCalls[0].args).toEqual({ truncated: true, originalBytes: Buffer.byteLength(JSON.stringify(huge)) }); | ||
| expect(stored.omittedTurns).toBeGreaterThan(0); | ||
| expect(stored.omittedToolCalls).toBeGreaterThan(0); | ||
| expect(Buffer.byteLength(JSON.stringify(stored.turns))).toBeLessThan(RUN_TRACE_BYTES); | ||
| expect(BSON.calculateObjectSize(JSON.parse(JSON.stringify(stored)))).toBeLessThan(8 * 1024 * 1024); | ||
| expect(boundRunValue({ small: 'kept' })).toEqual({ small: 'kept' }); | ||
| expect(boundRunValue([...[...Array(300)].map(() => 0)])).toMatchObject({ truncated: true }); | ||
| await run.save(); | ||
| expect(run.omittedTurns).toBe(stored.omittedTurns); | ||
| }); | ||
|
|
||
|
|
||
| test('aggregate budget caps many individually valid values before Mongo insert', async () => { | ||
| run.turns = Array.from({ length: 80 }, (_, turnIndex) => ({ | ||
| turnIndex, model: 'm', elapsedMs: 1, | ||
| toolCalls: Array.from({ length: 10 }, () => ({ name: 'read', elapsedMs: 1, | ||
| args: 'x'.repeat(4000), result: 'y'.repeat(4000) })), | ||
| })); | ||
| await run.save(); | ||
| const stored = await AgentRun.findById(run.id).lean(); | ||
| expect(stored.omittedToolCalls).toBeGreaterThan(0); | ||
| expect(BSON.calculateObjectSize(JSON.parse(JSON.stringify(stored.turns)))).toBeLessThan(RUN_TRACE_BYTES); | ||
| }); | ||
|
|
||
|
|
||
| test('limits repeated trace reads before authentication and database work', async () => { | ||
| let status; | ||
| for (let attempt = 0; attempt < 125 && status !== 429; attempt += 1) { | ||
| status = (await request(app).get(`/api/pods/${POD}/runs/bad-id`)).status; | ||
| } | ||
| expect(status).toBe(429); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔎 Supported by static analysis
Script executed:
Repository: Team-Commonly/commonly
Length of output: 2215
Script executed:
Repository: Team-Commonly/commonly
Length of output: 24054
Script executed:
Repository: Team-Commonly/commonly
Length of output: 39377
Cover the
runIdwriter, forwarding, and persistence paths.The changed test checks only
buildCardPayloadwith a hand-built row. ExistingproposeActiontests cover the general create and message flow, but they do not pass or assertrunId. AddrunIdassertions to that flow and add a realApprovalActionsave/reload check.