| 1 | import { describe, expect, it } from 'vitest';
|
| 2 | import { createIdentity, TrustEngine } from '@openclasp/core';
|
| 3 | import {
|
| 4 | CounterpartyBriefSchema,
|
| 5 | FederatedInteractionSchema,
|
| 6 | HostedMessageSchema,
|
| 7 | HostedThreadSchema,
|
| 8 | InteractionCompletionReportSchema,
|
| 9 | InteractionFeedbackSchema,
|
| 10 | LearningEligibilityDecisionSchema,
|
| 11 | PublicAgentCardSchema,
|
| 12 | canonicalHash,
|
| 13 | signObject,
|
| 14 | verifyObject,
|
| 15 | } from '@openclasp/protocol';
|
| 16 | import { toA2AAgentCard } from '@openclasp/sidecar';
|
| 17 |
|
| 18 | describe('protocol cryptography and delegation', () => {
|
| 19 | it('canonicalizes object key order and rejects tampering', () => {
|
| 20 | expect(canonicalHash({ b: 2, a: 1 })).toBe(canonicalHash({ a: 1, b: 2 }));
|
| 21 | const agent = createIdentity({
|
| 22 | agentId: 'agent:a',
|
| 23 | operatorRef: 'operator:a',
|
| 24 | capabilities: ['write'],
|
| 25 | });
|
| 26 | const signed = signObject({ action: 'write', value: 1 }, agent.keyPair);
|
| 27 | expect(verifyObject(signed, agent.identity.publicKey)).toBe(true);
|
| 28 | expect(verifyObject({ ...signed, value: 2 }, agent.identity.publicKey)).toBe(false);
|
| 29 | });
|
| 30 |
|
| 31 | it('prevents authority escalation and rejects expired delegation', () => {
|
| 32 | const engine = new TrustEngine();
|
| 33 | const parent = createIdentity({
|
| 34 | agentId: 'agent:parent',
|
| 35 | operatorRef: 'operator:x',
|
| 36 | capabilities: ['read'],
|
| 37 | });
|
| 38 | const child = createIdentity({
|
| 39 | agentId: 'agent:child',
|
| 40 | operatorRef: 'operator:x',
|
| 41 | capabilities: ['read'],
|
| 42 | parentAgentId: parent.identity.agentId,
|
| 43 | rootControllerId: parent.identity.rootControllerId,
|
| 44 | });
|
| 45 | engine.registerAgent(parent.identity);
|
| 46 | engine.registerAgent(child.identity);
|
| 47 | expect(() =>
|
| 48 | engine.createDelegation(
|
| 49 | parent.identity.agentId,
|
| 50 | child.identity.agentId,
|
| 51 | ['write'],
|
| 52 | new Date(Date.now() + 1000).toISOString(),
|
| 53 | parent.keyPair,
|
| 54 | ),
|
| 55 | ).toThrow('exceeds parent authority');
|
| 56 | const expired = engine.createDelegation(
|
| 57 | parent.identity.agentId,
|
| 58 | child.identity.agentId,
|
| 59 | ['read'],
|
| 60 | new Date(Date.now() - 1).toISOString(),
|
| 61 | parent.keyPair,
|
| 62 | );
|
| 63 | expect(engine.verifyDelegation(expired.delegationId)).toBe(false);
|
| 64 | });
|
| 65 |
|
| 66 | it('publishes an internet Agent Card and official A2A extension without private owner data', () => {
|
| 67 | const card = PublicAgentCardSchema.parse({
|
| 68 | protocolVersion: '0.1',
|
| 69 | agentId: 'agent:research',
|
| 70 | name: 'Research agent',
|
| 71 | description: 'Finds primary sources',
|
| 72 | framework: 'Codex',
|
| 73 | agentVersion: '1.2.0',
|
| 74 | capabilities: ['research'],
|
| 75 | limitations: ['no purchases'],
|
| 76 | assurance: 'oauth_authenticated',
|
| 77 | transports: [
|
| 78 | {
|
| 79 | protocol: 'A2A/1.0',
|
| 80 | protocolBinding: 'JSONRPC',
|
| 81 | endpoint: 'https://agent.example/a2a',
|
| 82 | },
|
| 83 | ],
|
| 84 | cardUrl: 'https://openclasp.vercel.app/agents/agent%3Aresearch/card.json',
|
| 85 | a2aAgentCardUrl: 'https://openclasp.vercel.app/agents/agent%3Aresearch/a2a-agent-card.json',
|
| 86 | extensionUri: 'https://openclasp.vercel.app/extensions/trust/v0.1',
|
| 87 | publishedAt: '2026-08-29T00:00:00.000Z',
|
| 88 | updatedAt: '2026-08-29T00:00:00.000Z',
|
| 89 | });
|
| 90 | expect(card).not.toHaveProperty('operatorId');
|
| 91 | expect(card).not.toHaveProperty('projectId');
|
| 92 | const a2a = toA2AAgentCard(card);
|
| 93 | expect(a2a.supportedInterfaces[0]).toMatchObject({
|
| 94 | url: 'https://agent.example/a2a',
|
| 95 | protocolBinding: 'JSONRPC',
|
| 96 | protocolVersion: '1.0',
|
| 97 | });
|
| 98 | expect(a2a.capabilities?.extensions?.[0]?.uri).toBe(card.extensionUri);
|
| 99 | });
|
| 100 |
|
| 101 | it('binds bilateral acceptances to one immutable contract hash', () => {
|
| 102 | const interactionId = crypto.randomUUID();
|
| 103 | const contract = {
|
| 104 | protocolVersion: '0.1' as const,
|
| 105 | interactionId,
|
| 106 | purpose: 'Research a market',
|
| 107 | parties: ['agent:a', 'agent:b'],
|
| 108 | taskCategory: 'research',
|
| 109 | requestedOutcome: 'A sourced brief',
|
| 110 | successCriteria: ['Primary sources included'],
|
| 111 | allowedActions: ['browse'],
|
| 112 | prohibitedActions: ['purchase'],
|
| 113 | allowedData: ['public'],
|
| 114 | prohibitedData: ['secrets'],
|
| 115 | evidenceRequirements: ['links'],
|
| 116 | delegationRules: ['explicit'],
|
| 117 | humanApprovalRequirements: [],
|
| 118 | factCheckingPolicy: 'important_claims',
|
| 119 | mediationPolicy: 'mutual_consent' as const,
|
| 120 | retentionDays: 30,
|
| 121 | completionConditions: ['brief delivered'],
|
| 122 | cancellationConditions: ['either party'],
|
| 123 | signatures: {},
|
| 124 | };
|
| 125 | const termsHash = canonicalHash(contract);
|
| 126 | const now = '2026-08-29T00:00:00.000Z';
|
| 127 | const value = FederatedInteractionSchema.parse({
|
| 128 | protocolVersion: '0.1',
|
| 129 | interactionId,
|
| 130 | initiatorAgentId: 'agent:a',
|
| 131 | responderAgentId: 'agent:b',
|
| 132 | status: 'active',
|
| 133 | contract,
|
| 134 | termsHash,
|
| 135 | acceptances: {
|
| 136 | 'agent:a': {
|
| 137 | agentId: 'agent:a',
|
| 138 | method: 'oauth_installation',
|
| 139 | termsHash,
|
| 140 | acceptedAt: now,
|
| 141 | },
|
| 142 | 'agent:b': {
|
| 143 | agentId: 'agent:b',
|
| 144 | method: 'oauth_installation',
|
| 145 | termsHash,
|
| 146 | acceptedAt: now,
|
| 147 | },
|
| 148 | },
|
| 149 | responderTransport: {
|
| 150 | protocol: 'A2A/1.0',
|
| 151 | protocolBinding: 'JSONRPC',
|
| 152 | endpoint: 'https://agent-b.example/a2a',
|
| 153 | },
|
| 154 | createdAt: now,
|
| 155 | updatedAt: now,
|
| 156 | expiresAt: '2026-08-30T00:00:00.000Z',
|
| 157 | });
|
| 158 | expect(Object.values(value.acceptances).every((item) => item.termsHash === termsHash)).toBe(
|
| 159 | true,
|
| 160 | );
|
| 161 | expect(canonicalHash({ ...contract, purpose: 'Changed terms' })).not.toBe(termsHash);
|
| 162 | });
|
| 163 |
|
| 164 | it('validates bounded hosted temporary-chat history', () => {
|
| 165 | const threadId = crypto.randomUUID();
|
| 166 | const now = new Date().toISOString();
|
| 167 | const thread = HostedThreadSchema.parse({
|
| 168 | threadId,
|
| 169 | interactionId: threadId,
|
| 170 | participantAgentIds: ['agent:temporary', 'agent:persistent'],
|
| 171 | status: 'open',
|
| 172 | privacyMode: 'openclasp_hosted_temporary',
|
| 173 | unreadCount: 1,
|
| 174 | createdAt: now,
|
| 175 | updatedAt: now,
|
| 176 | expiresAt: new Date(Date.now() + 1000).toISOString(),
|
| 177 | });
|
| 178 | const message = HostedMessageSchema.parse({
|
| 179 | messageId: crypto.randomUUID(),
|
| 180 | threadId,
|
| 181 | interactionId: threadId,
|
| 182 | senderAgentId: 'agent:persistent',
|
| 183 | recipientAgentId: 'agent:temporary',
|
| 184 | contentType: 'text/plain',
|
| 185 | content: 'Interview request',
|
| 186 | contentHash: canonicalHash('Interview request'),
|
| 187 | delivery: 'delivered',
|
| 188 | createdAt: now,
|
| 189 | });
|
| 190 | expect(thread.privacyMode).toBe('openclasp_hosted_temporary');
|
| 191 | expect(message.contentHash).toBe(canonicalHash(message.content));
|
| 192 | expect(() => HostedMessageSchema.parse({ ...message, content: 'x'.repeat(20_001) })).toThrow();
|
| 193 | });
|
| 194 |
|
| 195 | it('produces private requirement-specific counterparty briefs', () => {
|
| 196 | const now = '2026-08-29T00:00:00.000Z';
|
| 197 | const brief = CounterpartyBriefSchema.parse({
|
| 198 | briefId: crypto.randomUUID(),
|
| 199 | interactionId: crypto.randomUUID(),
|
| 200 | contractHash: canonicalHash({ purpose: 'Recruit a backend engineer' }),
|
| 201 | recipientAgentId: 'agent:candidate',
|
| 202 | subjectAgentId: 'agent:recruiter',
|
| 203 | taskCategory: 'recruiting',
|
| 204 | decision: 'CHALLENGE',
|
| 205 | requirements: [
|
| 206 | {
|
| 207 | requirementId: 'role-scope',
|
| 208 | requirement: 'Backend software engineering positions',
|
| 209 | kind: 'scope',
|
| 210 | status: 'mismatch',
|
| 211 | reason: 'The recruiter currently declares marketing roles only.',
|
| 212 | confidence: 0.98,
|
| 213 | sources: ['self_declared', 'contract'],
|
| 214 | },
|
| 215 | ],
|
| 216 | insights: [
|
| 217 | {
|
| 218 | code: 'scope_mismatch',
|
| 219 | severity: 'high',
|
| 220 | message: 'Confirm role scope before starting the interaction.',
|
| 221 | requirementReferences: ['role-scope'],
|
| 222 | confidence: 0.98,
|
| 223 | },
|
| 224 | ],
|
| 225 | relevantSampleSize: 0,
|
| 226 | historyConfidence: 0,
|
| 227 | subjectAgentVersion: '1.0.0',
|
| 228 | recommendedContractChanges: ['Require the recruiter to confirm a backend role is available.'],
|
| 229 | generatedAt: now,
|
| 230 | expiresAt: '2026-08-29T00:10:00.000Z',
|
| 231 | });
|
| 232 | expect(brief.requirements[0]?.status).toBe('mismatch');
|
| 233 | expect(brief.insights[0]?.requirementReferences).toEqual(['role-scope']);
|
| 234 | });
|
| 235 |
|
| 236 | it('accepts signed structured outcomes and rejects raw conversation fields', () => {
|
| 237 | const reporter = createIdentity({
|
| 238 | agentId: 'agent:reporter',
|
| 239 | operatorRef: 'operator:reporter',
|
| 240 | capabilities: ['recruiting'],
|
| 241 | });
|
| 242 | const interactionId = crypto.randomUUID();
|
| 243 | const report = {
|
| 244 | reportId: crypto.randomUUID(),
|
| 245 | interactionId,
|
| 246 | contractHash: canonicalHash({ interactionId, requestedOutcome: 'Find a backend role' }),
|
| 247 | reportingAgentId: reporter.identity.agentId,
|
| 248 | counterpartyAgentId: 'agent:recruiter',
|
| 249 | agentVersion: '1.0.0',
|
| 250 | outcome: 'failure' as const,
|
| 251 | summary: 'No matching backend positions were available.',
|
| 252 | requestedOutcome: 'Identify available backend software engineering positions.',
|
| 253 | criteria: [
|
| 254 | {
|
| 255 | criterion: 'Return at least one backend role',
|
| 256 | status: 'missed' as const,
|
| 257 | explanation: 'The recruiter only handled marketing roles.',
|
| 258 | },
|
| 259 | ],
|
| 260 | blockers: ['Counterparty scope mismatch'],
|
| 261 | completedAt: '2026-08-29T00:05:00.000Z',
|
| 262 | confidence: 0.99,
|
| 263 | dataSharingMode: 'structured_only' as const,
|
| 264 | };
|
| 265 | const signed = signObject(report, reporter.keyPair);
|
| 266 | expect(InteractionCompletionReportSchema.parse(signed).outcome).toBe('failure');
|
| 267 | expect(verifyObject(signed, reporter.identity.publicKey)).toBe(true);
|
| 268 | expect(
|
| 269 | InteractionCompletionReportSchema.safeParse({
|
| 270 | ...report,
|
| 271 | rawMessageBody: 'private transcript content',
|
| 272 | }).success,
|
| 273 | ).toBe(false);
|
| 274 | });
|
| 275 |
|
| 276 | it('validates bilateral feedback inputs and structured-only learning eligibility', () => {
|
| 277 | const interactionId = crypto.randomUUID();
|
| 278 | const feedback = InteractionFeedbackSchema.parse({
|
| 279 | feedbackId: crypto.randomUUID(),
|
| 280 | requestId: crypto.randomUUID(),
|
| 281 | interactionId,
|
| 282 | reviewerAgentId: 'agent:candidate',
|
| 283 | subjectAgentId: 'agent:recruiter',
|
| 284 | reviewerAgentVersion: '1.0.0',
|
| 285 | ratings: {
|
| 286 | outcome_satisfaction: 0.1,
|
| 287 | communication: 0.9,
|
| 288 | scope_adherence: 0.2,
|
| 289 | },
|
| 290 | wouldWorkAgain: 'unsure',
|
| 291 | reasonCodes: ['scope_mismatch'],
|
| 292 | confidence: 0.9,
|
| 293 | submittedAt: '2026-08-29T00:06:00.000Z',
|
| 294 | });
|
| 295 | expect(feedback.ratings.communication).toBe(0.9);
|
| 296 | expect(
|
| 297 | InteractionFeedbackSchema.safeParse({ ...feedback, ratings: { reliability: 1.1 } }).success,
|
| 298 | ).toBe(false);
|
| 299 |
|
| 300 | const eligibility = {
|
| 301 | decisionId: crypto.randomUUID(),
|
| 302 | interactionId,
|
| 303 | eligible: true,
|
| 304 | reasons: ['Signed completion report and eligible bilateral feedback'],
|
| 305 | sampleWeight: 0.8,
|
| 306 | reportIds: [crypto.randomUUID(), crypto.randomUUID()],
|
| 307 | feedbackIds: [feedback.feedbackId],
|
| 308 | contributionMode: 'local_only' as const,
|
| 309 | structuredDataOnly: true as const,
|
| 310 | decidedAt: '2026-08-29T00:07:00.000Z',
|
| 311 | };
|
| 312 | expect(LearningEligibilityDecisionSchema.parse(eligibility).eligible).toBe(true);
|
| 313 | expect(
|
| 314 | LearningEligibilityDecisionSchema.safeParse({
|
| 315 | ...eligibility,
|
| 316 | structuredDataOnly: false,
|
| 317 | }).success,
|
| 318 | ).toBe(false);
|
| 319 | });
|
| 320 | });
|