From 49106e0f63744a929c328b7fa78c28dcf21f1082 Mon Sep 17 00:00:00 2001 From: chou-godaddy Date: Thu, 8 Oct 2026 11:49:36 -0700 Subject: [PATCH] fix(hcs-25): resolve ans trust discovery agents by uid The ans-trust-discovery collector looked agents up by the UAID nativeId, but ANS Trust Index providers key the registered-agent endpoint by the ANS agent id, which HCS-14 carries as the UAID uid parameter. Every lookup returned 404, so no ANS agent received signals. - Resolve the agent id from metadata.uid, then the uid parameter of metadata.uaidFull or the subject id. nativeId is no longer used, and parameters are parsed without a regular expression. - Apply the collector and the scoring adapter to the ans and godaddy-ans registries by default: ans is the HCS-14 registry value and godaddy-ans is the Registry Broker namespace for the same agents. - Clear stored scores when the provider returns 404 for the agent. - Skip collection while stored signals are fresh (24 hours after a success, 1 hour after a failure) unless forced, so batch refreshes stay within provider rate limits. - Retry network errors and HTTP 5xx twice. HTTP 429 is not retried. - Correct the collector test that asserted the nativeId URL, and cover id resolution, 404 clearing, retries, rate limiting, caching and registry applicability. Refs: hashgraph-online/standards-sdk#184 Signed-off-by: chou-godaddy --- ...cs-25-adapters-ans-trust-discovery.test.ts | 11 +- __tests__/hcs-25/hcs-25-collectors.test.ts | 338 +++++++++++++++++- src/hcs-25/adapters/ans-trust-discovery.ts | 13 +- src/hcs-25/collectors/ans-trust-discovery.ts | 168 ++++++--- 4 files changed, 480 insertions(+), 50 deletions(-) diff --git a/__tests__/hcs-25/hcs-25-adapters-ans-trust-discovery.test.ts b/__tests__/hcs-25/hcs-25-adapters-ans-trust-discovery.test.ts index c8aacdc..1122203 100644 --- a/__tests__/hcs-25/hcs-25-adapters-ans-trust-discovery.test.ts +++ b/__tests__/hcs-25/hcs-25-adapters-ans-trust-discovery.test.ts @@ -57,7 +57,7 @@ describe('HCS-25 ANS trust discovery adapter', () => { expect(adapter.id).toBe('ans-trust-discovery'); expect(adapter.contributionMode).toBe('scoped'); expect(adapter.weight).toBe(1); - expect(adapter.includeRegistries).toEqual(['ans']); + expect(adapter.includeRegistries).toEqual(['ans', 'godaddy-ans']); expect(adapter.defaultComponentKey).toBe('ans-trust-discovery.certtype'); expect(adapter.components.map(component => component.name)).toEqual([ 'certtype', @@ -194,7 +194,14 @@ describe('HCS-25 ANS trust discovery adapter', () => { } }); - test('applies only to subjects in the ans registry', () => { + test('applies only to subjects in the ans and godaddy-ans registries', () => { + const broker = scoreOne( + createAnsTrustDiscoveryAdapter(), + ansSubject(FULL_SIGNALS, 'godaddy-ans'), + ); + expect(broker.breakdown.adapters[0]?.applicable).toBe(true); + expect(broker.trustScores['ans-trust-discovery.certtype']).toBe(100); + const other = scoreOne( createAnsTrustDiscoveryAdapter(), ansSubject(FULL_SIGNALS, 'agentverse'), diff --git a/__tests__/hcs-25/hcs-25-collectors.test.ts b/__tests__/hcs-25/hcs-25-collectors.test.ts index 8d5ed28..fd197bf 100644 --- a/__tests__/hcs-25/hcs-25-collectors.test.ts +++ b/__tests__/hcs-25/hcs-25-collectors.test.ts @@ -32,6 +32,7 @@ import { Hcs25CollectorHttpError, isTimeoutError, requestJson, + type Hcs25AnsTrustDiscoverySignalAdapterOptions, type Hcs25Fetch, type Hcs25SignalAdapter, } from '../../src/hcs-25/collectors'; @@ -1014,8 +1015,12 @@ describe('isTimeoutError', () => { }); describe('ans trust discovery signal adapter', () => { - const UAID = - 'uaid:aid:7bU8xK;uid=b8d9425f-fd9f-47a5-ae5d-8ab51bda04c9;registry=ans;proto=a2a;nativeId=support-agent.example.com;version=v1.0.0'; + const AGENT_ID = 'b8d9425f-fd9f-47a5-ae5d-8ab51bda04c9'; + const UAID = `uaid:aid:7bU8xK;uid=${AGENT_ID};registry=ans;proto=a2a;nativeId=support-agent.example.com;version=v1.0.0`; + const NOW = new Date('2026-08-18T01:58:17.623Z'); + const HOUR = 60 * 60 * 1000; + const hoursAgo = (hours: number): string => + new Date(NOW.getTime() - hours * HOUR).toISOString(); const providerResponse = { signals: { @@ -1030,6 +1035,57 @@ describe('ans trust discovery signal adapter', () => { }, }; + interface RecordedCall { + url: string; + headers?: Record; + } + + const recordingFetch = ( + respond: () => ReturnType, + ): { fetch: Hcs25Fetch; calls: RecordedCall[] } => { + const calls: RecordedCall[] = []; + return { + calls, + fetch: async (url, init) => { + calls.push({ url, headers: init?.headers }); + return respond(); + }, + }; + }; + + const collectAns = ( + subject: Hcs25Subject, + fetchImpl: Hcs25Fetch, + options: Hcs25AnsTrustDiscoverySignalAdapterOptions = {}, + force?: boolean, + ) => + collectHcs25Signals(subject, { + adapters: [createAnsTrustDiscoverySignalAdapter(options)], + fetch: fetchImpl, + now: NOW, + force, + }); + + const storedFields = (subject: Hcs25Subject): Record => + subject.metadata?.ansTrustDiscovery as Record; + + const withStored = ( + updatedAt: string, + status = 'ok', + registry = 'ans', + ): Hcs25Subject => ({ + id: UAID, + registry, + metadata: { + ansTrustDiscovery: { + 'ans-trust-discovery.certtype': 60, + 'ans-trust-discovery.dnssecurity': 100, + ansTrustDiscoveryStatus: status, + ansTrustDiscoveryUpdatedAt: updatedAt, + }, + }, + }); + test('stores provider scores and the scoring adapter consumes them', async () => { let requested = ''; const fetchImpl: Hcs25Fetch = async url => { @@ -1050,7 +1106,7 @@ describe('ans trust discovery signal adapter', () => { ); expect(requested).toBe( - 'https://ans.example.com/v1/ans/registered-agents/support-agent.example.com', + `https://ans.example.com/v1/ans/registered-agents/${AGENT_ID}`, ); const stored = collection.subject.metadata?.ansTrustDiscovery as Record< string, @@ -1076,6 +1132,134 @@ describe('ans trust discovery signal adapter', () => { expect(record.trustScores.total).toBe(86.43); }); + test('resolves the agent id from metadata.uid before UAID parameters', async () => { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + await collectAns( + { + id: 'uaid:aid:Qx7Lm2', + registry: 'godaddy-ans', + metadata: { + uid: AGENT_ID, + uaidFull: + 'uaid:aid:Qx7Lm2;uid=11111111-1111-4111-8111-111111111111;registry=godaddy-ans', + nativeId: 'ans://v1.0.0.support-agent.example.com', + }, + }, + fetch, + ); + expect(calls.map(call => call.url)).toEqual([ + `https://api.godaddy.com/v1/ans/registered-agents/${AGENT_ID}`, + ]); + }); + + test('falls back to the uid of metadata.uaidFull, then of the subject id', async () => { + for (const subject of [ + { + id: 'uaid:aid:Qx7Lm2', + registry: 'godaddy-ans', + metadata: { + uaidFull: `uaid:aid:Qx7Lm2;uid=${AGENT_ID};registry=godaddy-ans`, + }, + }, + { id: UAID, registry: 'ans' }, + ]) { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + await collectAns(subject, fetch); + expect(calls.map(call => call.url)).toEqual([ + `https://api.godaddy.com/v1/ans/registered-agents/${AGENT_ID}`, + ]); + } + }); + + test('never uses nativeId as the agent id', async () => { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + const collection = await collectAns( + { + id: 'uaid:aid:7bU8xK;registry=ans;nativeId=support-agent.example.com', + registry: 'ans', + metadata: { nativeId: 'support-agent.example.com' }, + }, + fetch, + ); + expect(calls).toHaveLength(0); + expect(collection.snapshot['ans-trust-discovery.certtype'].status).toBe( + 'missing', + ); + expect(collection.subject.metadata?.ansTrustDiscovery).toBeUndefined(); + }); + + test('treats an empty or unspecified uid as absent', async () => { + for (const subject of [ + { id: 'uaid:aid:x;uid=0;registry=ans', registry: 'ans' }, + { id: 'uaid:aid:x;uid=;registry=ans', registry: 'ans' }, + { id: 'uaid:aid:x', registry: 'ans', metadata: { uid: '0' } }, + ]) { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + await collectAns(subject, fetch); + expect(calls).toHaveLength(0); + } + }); + + test('encodes the agent id and passes request options through', async () => { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + const adapter = createAnsTrustDiscoverySignalAdapter({ timeoutMs: 5000 }); + expect(adapter.timeoutMs).toBe(5000); + + await collectAns({ id: 'agent:a', registry: 'ans' }, fetch, { + resolveAgentId: () => 'a/b c', + headers: { Authorization: 'Bearer token' }, + }); + expect(calls[0]?.url).toBe( + 'https://api.godaddy.com/v1/ans/registered-agents/a%2Fb%20c', + ); + expect(calls[0]?.headers?.Authorization).toBe('Bearer token'); + }); + + test('stores null for missing, absent, and non-numeric signals and ignores unlisted ones', async () => { + const { fetch } = recordingFetch(async () => + okResponse({ + signals: { + certtype: { score: 25, missing: false }, + agentcard: { score: 0, missing: true }, + httpsrecord: { score: 'present', missing: false }, + domainvalidation: { score: 100, missing: false }, + }, + }), + ); + const collection = await collectAns({ id: UAID, registry: 'ans' }, fetch); + const stored = storedFields(collection.subject); + + expect(stored['ans-trust-discovery.certtype']).toBe(25); + expect(stored['ans-trust-discovery.agentcard']).toBeNull(); + expect(stored['ans-trust-discovery.dnssecurity']).toBeNull(); + expect(stored['ans-trust-discovery.httpsrecord']).toBeNull(); + expect(stored).not.toHaveProperty('ans-trust-discovery.domainvalidation'); + expect( + collection.snapshot['ans-trust-discovery.domainvalidation'], + ).toBeUndefined(); + expect(stored.ansTrustDiscoveryStatus).toBe('ok'); + }); + + test('is missing when the provider returns no signals', async () => { + const { fetch } = recordingFetch(async () => okResponse({})); + const collection = await collectAns({ id: UAID, registry: 'ans' }, fetch); + const stored = storedFields(collection.subject); + + expect(stored['ans-trust-discovery.certtype']).toBeNull(); + expect(stored['ans-trust-discovery.certificatehygiene']).toBeNull(); + expect(stored.ansTrustDiscoveryStatus).toBe('missing'); + }); + test('is missing when the subject has no ANS agent id', async () => { const collection = await collectHcs25Signals( { id: 'agent:plain', registry: 'ans' }, @@ -1111,6 +1295,27 @@ describe('ans trust discovery signal adapter', () => { expect(collection.results[0]?.status).toBe('missing'); }); + test('clears stored scores when the provider no longer knows the agent', async () => { + const collection = await collectAns( + withStored(hoursAgo(48)), + fetchWithStatus(404), + ); + const stored = storedFields(collection.subject); + + expect(stored['ans-trust-discovery.certtype']).toBeNull(); + expect(stored['ans-trust-discovery.dnssecurity']).toBeNull(); + expect(stored.ansTrustDiscoveryStatus).toBe('missing'); + expect(stored.ansTrustDiscoveryUpdatedAt).toBe(NOW.toISOString()); + + const record = computeTrustScore({ + subject: collection.subject, + snapshot: collection.snapshot, + config: { version: 1, adapters: [createAnsTrustDiscoveryAdapter()] }, + }); + expect(record.breakdown.adapters[0]?.unavailable).toHaveLength(8); + expect(record.trustScores.total).toBe(0); + }); + test('stores timeout and error without a score', async () => { for (const [name, status] of [ ['TimeoutError', 'timeout'], @@ -1124,7 +1329,7 @@ describe('ans trust discovery signal adapter', () => { const collection = await collectHcs25Signals( { id: UAID, registry: 'ans' }, { - adapters: [createAnsTrustDiscoverySignalAdapter()], + adapters: [createAnsTrustDiscoverySignalAdapter({ maxRetries: 0 })], fetch: fetchImpl, }, ); @@ -1143,6 +1348,103 @@ describe('ans trust discovery signal adapter', () => { } }); + test('retries server errors, then keeps earlier scores with an error status', async () => { + const { fetch, calls } = recordingFetch(async () => ({ + ok: false, + status: 503, + json: async () => ({}), + })); + const collection = await collectAns(withStored(hoursAgo(48)), fetch); + const stored = storedFields(collection.subject); + + expect(calls).toHaveLength(3); + expect(stored['ans-trust-discovery.certtype']).toBe(60); + expect(stored.ansTrustDiscoveryStatus).toBe('error'); + expect(stored.ansTrustDiscoveryUpdatedAt).toBe(NOW.toISOString()); + }); + + test('does not retry rate-limited requests', async () => { + const { fetch, calls } = recordingFetch(async () => ({ + ok: false, + status: 429, + json: async () => ({}), + })); + const collection = await collectAns({ id: UAID, registry: 'ans' }, fetch); + + expect(calls).toHaveLength(1); + expect(storedFields(collection.subject).ansTrustDiscoveryStatus).toBe( + 'error', + ); + }); + + test('skips the request while stored signals are within their interval', async () => { + const fresh = recordingFetch(async () => okResponse(providerResponse)); + const updatedAt = hoursAgo(23); + const collection = await collectAns(withStored(updatedAt), fresh.fetch); + + expect(fresh.calls).toHaveLength(0); + const certtype = collection.snapshot['ans-trust-discovery.certtype']; + expect(certtype.status).toBe('ok'); + expect(certtype.value).toBe(60); + expect(certtype.fetchedAt).toBe(updatedAt); + expect(collection.snapshot['ans-trust-discovery.agentage'].status).toBe( + 'missing', + ); + expect(storedFields(collection.subject).ansTrustDiscoveryUpdatedAt).toBe( + updatedAt, + ); + + const failed = recordingFetch(async () => okResponse(providerResponse)); + const afterFailure = await collectAns( + withStored( + new Date(NOW.getTime() - 30 * 60 * 1000).toISOString(), + 'error', + ), + failed.fetch, + ); + expect(failed.calls).toHaveLength(0); + expect(afterFailure.snapshot['ans-trust-discovery.certtype'].status).toBe( + 'error', + ); + }); + + test('refreshes once the interval elapses or when forced', async () => { + const cases: Array<{ + subject: Hcs25Subject; + options?: Hcs25AnsTrustDiscoverySignalAdapterOptions; + force?: boolean; + }> = [ + { subject: withStored(hoursAgo(25)) }, + { subject: withStored(hoursAgo(2), 'error') }, + { subject: withStored(hoursAgo(1)), force: true }, + { subject: withStored(hoursAgo(2)), options: { ttlMs: HOUR } }, + ]; + for (const { subject, options, force } of cases) { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + const collection = await collectAns(subject, fetch, options, force); + expect(calls).toHaveLength(1); + expect(storedFields(collection.subject).ansTrustDiscoveryUpdatedAt).toBe( + NOW.toISOString(), + ); + } + }); + + test('applies to the ans and godaddy-ans registries only', async () => { + for (const [registry, applicable] of [ + ['ans', true], + ['godaddy-ans', true], + ['agentverse', false], + ] as const) { + const collection = await collectAns( + { id: UAID, registry }, + fetchReturning(providerResponse), + ); + expect(collection.results[0]?.applicable).toBe(applicable); + } + }); + test('does not apply outside the ans registry', async () => { const collection = await collectHcs25Signals( { id: UAID, registry: 'agentverse' }, @@ -1154,6 +1456,34 @@ describe('ans trust discovery signal adapter', () => { expect(collection.results[0]?.applicable).toBe(false); expect(collection.snapshot['ans-trust-discovery.certtype']).toBeUndefined(); }); + + test('scores a Registry Broker subject end to end', async () => { + const { fetch, calls } = recordingFetch(async () => + okResponse(providerResponse), + ); + const { record } = await collectAndScoreTrustScore( + { + id: 'uaid:aid:Qx7Lm2', + registry: 'godaddy-ans', + metadata: { + uid: AGENT_ID, + nativeId: 'ans://v1.0.0.support-agent.example.com', + }, + }, + { + adapters: [createAnsTrustDiscoverySignalAdapter()], + fetch, + now: NOW, + config: { version: 1, adapters: [createAnsTrustDiscoveryAdapter()] }, + }, + ); + + expect(calls.map(call => call.url)).toEqual([ + `https://api.godaddy.com/v1/ans/registered-agents/${AGENT_ID}`, + ]); + expect(record.trustScores['ans-trust-discovery.certtype']).toBe(100); + expect(record.trustScores.total).toBe(86.43); + }); }); describe('adapter coverage mapping', () => { diff --git a/src/hcs-25/adapters/ans-trust-discovery.ts b/src/hcs-25/adapters/ans-trust-discovery.ts index 2d93067..b63ecc9 100644 --- a/src/hcs-25/adapters/ans-trust-discovery.ts +++ b/src/hcs-25/adapters/ans-trust-discovery.ts @@ -17,13 +17,17 @@ import { * Options for the ANS Trust Discovery adapter. */ export interface Hcs25AnsTrustDiscoveryAdapterOptions { - /** Registries whose subjects carry ANS Trust Index signals. */ + /** + * Registries whose subjects carry ANS Trust Index signals. Default + * `['ans', 'godaddy-ans']`: `ans` is the HCS-14 registry value and + * `godaddy-ans` is the Registry Broker namespace for the same agents. + */ includeRegistries?: readonly string[]; } const ADAPTER_ID = 'ans-trust-discovery'; -const DEFAULT_INCLUDED_REGISTRIES: readonly string[] = ['ans']; +const DEFAULT_INCLUDED_REGISTRIES: readonly string[] = ['ans', 'godaddy-ans']; const MISSING: Hcs25NormalizedValue = { value: 0, status: 'missing' }; @@ -76,8 +80,9 @@ function normalizeAnsTrustSignal( * signals the provider could not compute are excluded from the adapter * total, which is the mean of the remaining components. * - * Applies to subjects whose `registry` is `ans` (the UAID `registry` - * parameter); callers set `subject.registry` when building the subject. + * Applies to subjects whose `registry` is `ans` (the HCS-14 UAID `registry` + * value) or `godaddy-ans` (the Registry Broker namespace); callers set + * `subject.registry` when building the subject. */ export function createAnsTrustDiscoveryAdapter( options: Hcs25AnsTrustDiscoveryAdapterOptions = {}, diff --git a/src/hcs-25/collectors/ans-trust-discovery.ts b/src/hcs-25/collectors/ans-trust-discovery.ts index ea5fe10..820b9e0 100644 --- a/src/hcs-25/collectors/ans-trust-discovery.ts +++ b/src/hcs-25/collectors/ans-trust-discovery.ts @@ -1,6 +1,12 @@ import type { Hcs25JsonValue, Hcs25Subject } from '../types'; -import { readString } from '../signals'; +import { + readMetadataRecord, + readNumber, + readString, + type Hcs25JsonObject, +} from '../signals'; import { HCS25_ANS_TRUST_DISCOVERY_SIGNALS } from '../signals/ans-trust-discovery'; +import { shouldRefreshStoredFields } from './freshness'; import { Hcs25CollectorHttpError, isTimeoutError, @@ -20,6 +26,8 @@ import type { */ const DEFAULT_ANS_BASE_URL = 'https://api.godaddy.com'; +const SOURCE_ID = 'ans-trust-discovery'; + const SIGNAL_IDS = HCS25_ANS_TRUST_DISCOVERY_SIGNALS.map( signal => `ans-trust-discovery.${signal}`, ); @@ -37,18 +45,37 @@ export interface Hcs25AnsTrustDiscoverySignalAdapterOptions { /** Extra request headers, such as a provider credential. */ headers?: Record; /** - * Resolves the provider agent id. Default reads `metadata.nativeId`, - * then the `nativeId` parameter of a UAID in `subject.id` or - * `metadata.uaidFull`. + * Resolves the provider agent id: the ANS agent id carried as the UAID + * `uid` parameter (HCS-14 `ans-dns-web` profile). Default reads + * `metadata.uid`, then the `uid` parameter of the UAID in + * `metadata.uaidFull`, then of `subject.id`. `nativeId` is not an agent id + * and is never used. */ resolveAgentId?: (subject: Hcs25Subject) => string | null; timeoutMs?: number; + /** Refresh interval after a successful collection. Default 24 hours. */ + ttlMs?: number; + /** Refresh interval after a failed collection. Default 1 hour. */ + failureTtlMs?: number; + /** + * Retries for network errors and HTTP 5xx. Default 2. HTTP 429 is not + * retried; the refresh intervals bound the request rate instead. + */ + maxRetries?: number; + /** + * Default `['ans', 'godaddy-ans']`: `ans` is the HCS-14 registry value and + * `godaddy-ans` is the Registry Broker namespace for the same agents. + */ includeRegistries?: readonly string[]; excludeRegistries?: readonly string[]; appliesTo?: (subject: Hcs25Subject) => boolean; } -const DEFAULT_INCLUDED_REGISTRIES: readonly string[] = ['ans']; +const DEFAULT_INCLUDED_REGISTRIES: readonly string[] = ['ans', 'godaddy-ans']; + +const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; +const DEFAULT_FAILURE_TTL_MS = 60 * 60 * 1000; +const DEFAULT_MAX_RETRIES = 2; interface AnsSignalPayload { score?: unknown; @@ -59,27 +86,37 @@ interface AnsTrustResponse { signals?: Record; } -function nativeIdFromUaid(value: string | null): string | null { - if (!value) { - return null; - } - const nativeId = value.match(/(?:^|;)nativeId=([^;]+)(?:;|$)/i)?.[1]?.trim(); - if (!nativeId) { +/** + * Reads one parameter from a UAID's `;key=value` list. Parameter names are + * case-sensitive, as in HCS-14. + */ +function readUaidParam(uaid: string | null, key: string): string | null { + if (!uaid) { return null; } - try { - return decodeURIComponent(nativeId); - } catch { - return nativeId; + for (const param of uaid.split(';').slice(1)) { + const separator = param.indexOf('='); + if (separator > 0 && param.slice(0, separator) === key) { + return param.slice(separator + 1); + } } + return null; +} + +/** + * Treats an empty or unspecified (`0`) agent id as absent. + */ +function agentIdOrNull(value: string | null): string | null { + const trimmed = value?.trim(); + return trimmed && trimmed !== '0' ? trimmed : null; } function defaultResolveAgentId(subject: Hcs25Subject): string | null { const metadata = subject.metadata ?? {}; return ( - readString(metadata, 'nativeId') ?? - nativeIdFromUaid(subject.id) ?? - nativeIdFromUaid(readString(metadata, 'uaidFull')) + agentIdOrNull(readString(metadata, 'uid')) ?? + agentIdOrNull(readUaidParam(readString(metadata, 'uaidFull'), 'uid')) ?? + agentIdOrNull(readUaidParam(subject.id, 'uid')) ); } @@ -99,25 +136,15 @@ function statusResult( now: string, url: string | undefined, agentId: string | undefined, + values?: Record, ): Hcs25SignalAdapterResult[] { const provenance = { - source: 'ans-trust-discovery', + source: SOURCE_ID, sourceUrl: url, subjectId: agentId, fetchedAt: now, }; - const fields = - status === 'missing' - ? undefined - : [ - { - scope: 'ansTrustDiscovery', - values: { - ansTrustDiscoveryStatus: status, - ansTrustDiscoveryUpdatedAt: now, - }, - }, - ]; + const fields = values ? [{ scope: 'ansTrustDiscovery', values }] : undefined; return SIGNAL_IDS.map((signalId, index) => ({ signalId, status, @@ -126,6 +153,48 @@ function statusResult( })); } +/** + * Stored fields for an agent the provider does not know (HTTP 404): every + * score is cleared so earlier values stop counting. + */ +function clearedValues(now: string): Record { + const values: Record = {}; + for (const signalId of SIGNAL_IDS) { + values[signalId] = null; + } + values.ansTrustDiscoveryStatus = 'missing'; + values.ansTrustDiscoveryUpdatedAt = now; + return values; +} + +/** + * Reports the stored signals without a request while they are within their + * refresh interval. + */ +function storedResult( + record: Hcs25JsonObject, + url: string, + agentId: string, +): Hcs25SignalAdapterResult[] { + const storedStatus = readString(record, 'ansTrustDiscoveryStatus'); + const provenance = { + source: SOURCE_ID, + sourceUrl: url, + subjectId: agentId, + fetchedAt: readString(record, 'ansTrustDiscoveryUpdatedAt') ?? undefined, + }; + return SIGNAL_IDS.map((signalId): Hcs25SignalAdapterResult => { + if (storedStatus === 'timeout' || storedStatus === 'error') { + return { signalId, status: storedStatus, provenance }; + } + const score = readNumber(record, signalId); + if (score === null) { + return { signalId, status: 'missing', provenance }; + } + return { signalId, status: 'ok', value: score, provenance }; + }); +} + /** * Creates the `ans-trust-discovery` signal adapter: reads the eight ANS * Trust Index signals from a provider's registered-agent endpoint and @@ -136,6 +205,9 @@ export function createAnsTrustDiscoverySignalAdapter( ): Hcs25SignalAdapter { const resolveAgentId = options.resolveAgentId ?? defaultResolveAgentId; const baseUrl = stripTrailingSlashes(options.baseUrl ?? DEFAULT_ANS_BASE_URL); + const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; + const failureTtlMs = options.failureTtlMs ?? DEFAULT_FAILURE_TTL_MS; + const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES; const collect = async ( subject: Hcs25Subject, @@ -148,6 +220,22 @@ export function createAnsTrustDiscoverySignalAdapter( } const url = `${baseUrl}/v1/ans/registered-agents/${encodeURIComponent(agentId)}`; + const stored = readMetadataRecord(subject, 'ansTrustDiscovery'); + if ( + stored && + !shouldRefreshStoredFields(subject, { + scope: 'ansTrustDiscovery', + statusKey: 'ansTrustDiscoveryStatus', + updatedAtKey: 'ansTrustDiscoveryUpdatedAt', + ttlMs, + failureTtlMs, + now: context.now, + force: context.force, + }) + ) { + return storedResult(stored, url, agentId); + } + let data: AnsTrustResponse; try { data = await requestJson(url, { @@ -155,17 +243,17 @@ export function createAnsTrustDiscoverySignalAdapter( headers: options.headers, timeoutMs: context.timeoutMs, signal: context.signal, + maxRetries, }); } catch (error) { if (error instanceof Hcs25CollectorHttpError && error.status === 404) { - return statusResult('missing', now, url, agentId); + return statusResult('missing', now, url, agentId, clearedValues(now)); } - return statusResult( - isTimeoutError(error) ? 'timeout' : 'error', - now, - url, - agentId, - ); + const status = isTimeoutError(error) ? 'timeout' : 'error'; + return statusResult(status, now, url, agentId, { + ansTrustDiscoveryStatus: status, + ansTrustDiscoveryUpdatedAt: now, + }); } const signals = data.signals; @@ -189,7 +277,7 @@ export function createAnsTrustDiscoverySignalAdapter( status: score === null ? 'missing' : 'ok', value: score ?? undefined, provenance: { - source: 'ans-trust-discovery', + source: SOURCE_ID, sourceUrl: url, subjectId: agentId, fetchedAt: now, @@ -205,7 +293,7 @@ export function createAnsTrustDiscoverySignalAdapter( }; return { - id: 'ans-trust-discovery', + id: SOURCE_ID, produces: SIGNAL_IDS, timeoutMs: options.timeoutMs, includeRegistries: options.includeRegistries ?? DEFAULT_INCLUDED_REGISTRIES,