Skip to content

feat: production-grade agent tracing, auditing, and execution - #243

Merged
Nursca merged 1 commit into
OracleDesk:developfrom
ada-nwali:feat/issues-113-116-agents-trading-tracing
Oct 21, 2026
Merged

Nursca merged 1 commit into
OracleDesk:developfrom
ada-nwali:feat/issues-113-116-agents-trading-tracing

Conversation

@ada-nwali

Copy link
Copy Markdown

Summary

Implements four interconnected features to establish production-grade accountability, safety, and observability for agent trading and trace management on OracleDesk.

Issue #116: Trace Availability Monitor
Issue #115: Agent Budget Ledger for Paid Signal Purchases
Issue #114: Decision Replay and Audit CLI
Issue #113: Execution Algorithms for Large Trade Slicing

Feature Overview

1. Trace Availability Monitor (#116)

File: oracledesk-stellar/x402/trace-availability-monitor.ts

Enumerates all published traces from the registry and probes their availability:

  • Scans traces incrementally with configurable concurrency to respect RPC rate limits
  • Probes each CID through the primary IPFS gateway and multiple fallbacks
  • Verifies retrieved bytes against the on-chain trace_hash
  • Re-pins content from a trusted archive when retrieval fails
  • Alerts subscribers when a trace becomes genuinely unrecoverable
  • Persists scan state so runs are incremental and scale linearly

Usage:

const monitor = new TraceAvailabilityMonitor({
  repository,
  ipfsGateway: "https://ipfs.io/ipfs",
  fallbackGateways: ["https://gateway.pinata.cloud/ipfs"],
  pinArchiveUrl: "https://archive.example.com",
  scanIntervalMs: 3600000,
});

monitor.on('trace', (event) => {
  if (event.status === 'unretrievable') {
    console.log(`Alert: trace ${event.traceId} is unavailable`);
  }
});

await monitor.start();

2. Agent Budget Ledger for Paid Signal Purchases (#115)

File: oracledesk-stellar/x402/agent-budget-ledger.ts

Enables agents to safely buy paid signals within an on-chain-capped data budget:

  • Uses a separate low-value spending key for purchases (never the treasury agent key)
  • Enforces daily budget limits that survive a crash mid-payment
  • Optionally backs limits with an on-chain allowance contract
  • Records which paid inputs informed decisions by hash and source (content-agnostic)
  • Verifies OracleDesk trace purchases against the reasoning-registry hash
  • Prevents republication of vendor content by recording hashes, not content

Usage:

const ledger = new AgentBudgetLedger(treasuryAddress, rpcUrl);
ledger.initializeAgentBudget(
  agentAddress,
  BigInt(1_000_000), // daily cap in USDc
  spendingKeyPublic,
  onChainAllowanceContractId,
);

// Buy a signal
await ledger.recordPurchase(
  agentAddress,
  traceId,
  "signal-provider.example.com",
  BigInt(50_000), // cost in USDc
  txHash,
);

// Verify the budget
console.log(ledger.getRemainingBudget(agentAddress));
ledger.recordPaidInput(traceId, source, contentHash);

3. Decision Replay and Audit CLI (#114)

File: oracledesk-stellar/agents/bin/audit.ts

Re-executes agent decisions from published traces to verify accountability:

  • Fetches the on-chain record and IPFS trace content by traceId
  • Verifies trace content against the on-chain sha256 hash
  • Re-executes the recorded strategy version on the recorded inputs
  • Compares the re-derived decision against the recorded decision and actual on-chain effect
  • Generates signed, machine-readable audit reports
  • Supports auditing individual traces or all traces for a market

Usage:

# Audit a single trace
./agents/bin/audit.ts trace 12345

# Audit all Buy decisions on a market
./agents/bin/audit.ts market 7 --agent 0xclient

# Output: audit-report-{reportId}.json with verdicts (match|deviation|mismatch|unverifiable)

Report format:

{
  "reportId": "abc123def456",
  "entries": [
    {
      "traceId": "12345",
      "verdict": "match",
      "recordedDecision": { "action": "buy", "amount": "100" },
      "reDerivedDecision": { "action": "buy", "amount": "100" },
      "onChainEffect": { "txHash": "...", "amount": "100" }
    }
  ],
  "summary": {
    "totalTraces": 100,
    "matchedCount": 98,
    "deviationCount": 2,
    "mismatchCount": 0
  }
}

4. Execution Algorithms for Trade Slicing (#113)

File: oracledesk-stellar/agents/core/execution-algorithms.ts

Slices large parent orders into child orders across ledgers with tight risk control:

TWAP Executor:

  • Divides target shares uniformly across a time window
  • Re-quotes on-chain before each child order submission
  • Sets tight per-child min_shares_out derived from fresh quote minus slippage
  • Respects treasury collateral caps across all children
  • Cleans up gracefully if an edge disappears mid-execution

Participation-Limited Executor:

  • Adapts slice size based on market depth and participation rate
  • Stops submitting when the fair-value edge drops below the limit price
  • Minimizes market impact by limiting each slice to a configurable % of market volume
  • Re-quotes continuously to detect edge disappearance

Usage:

const executor = new TWAPExecutor(quoteFunction, sliceDurationMs, orderIntervalMs);

const parentOrder: ParentOrder = {
  id: "parent-1",
  targetShares: BigInt(1_000_000),
  maxCollateral: BigInt(600_000),
  limitPrice: 0.6,
  fairValue: 0.5,
  requiredEdge: 0.01,
  createdAt: Date.now(),
  status: "pending",
  executedShares: BigInt(0),
  spentCollateral: BigInt(0),
  childOrders: [],
};

await executor.executeParentOrder(parentOrder, "market-1");

const state = executor.getState();
console.log(`Executed ${parentOrder.executedShares} / ${parentOrder.targetShares}`);

Key Design Decisions

  • Crash Safety: Parent and child order state persists so crashes mid-execution resume cleanly
  • Observability: All modules emit structured logs and events for monitoring
  • Scalability: Trace monitor uses incremental scans; execution respects on-chain rate limits
  • Accountability: Audit trail is deterministic and independently verifiable
  • Content Agnosticism: Agent traces record paid input hashes, not the vendor content

Testing

All modules include comprehensive unit tests:

  • trace-availability-monitor.test.ts
  • agent-budget-ledger.test.ts
  • execution-algorithms.test.ts

Run tests with:

npm test

Integration

These features integrate seamlessly with existing systems:

  • Trace monitor works with any TraceRepository implementation
  • Budget ledger is compatible with the x402 payment coordinator
  • Audit CLI uses the same trace-verification utilities as the x402 server
  • Execution algorithms integrate with the runtime trader task

Closes #116
Closes #115
Closes #114
Closes #113

…nd execution algorithms

Implements four interconnected features for production-grade agent accountability and safe trading:

1. Trace Availability Monitor (OracleDesk#116)
   - Enumerates all published traces from the registry
   - Probes CIDs through multiple independent gateways
   - Verifies bytes against on-chain hash
   - Re-pins from trusted archive when retrieval fails
   - Alerts on genuinely unrecoverable traces
   - Persists state for incremental scans under RPC rate limits

2. Agent Budget Ledger for Paid Signal Purchases (OracleDesk#115)
   - Separate spending key for agent purchases (never treasury key)
   - Crash-safe daily budget with optional on-chain cap
   - Verifies OracleDesk trace purchases against reasoning-registry hash
   - Records paid inputs by hash and source without embedding content
   - Supports multiple gateways and archive re-pinning

3. Decision Replay and Audit CLI (OracleDesk#114)
   - agents/bin/audit.ts: re-derives agent actions from published traces
   - Fetches on-chain record and trace content via IPFS
   - Verifies hash and re-executes recorded strategy on recorded inputs
   - Compares re-derived decision with recorded decision and on-chain effect
   - Generates signed, machine-readable audit reports
   - Supports tracing individual decisions or all traces for a market

4. Execution Algorithms for Trade Slicing (OracleDesk#113)
   - TWAP executor: uniform time-weighted average price across ledgers
   - Participation-limited executor: adaptive slicing respecting market impact
   - Parent orders with target outcome, max collateral, and limit price
   - Re-quotes on-chain before each child order submission
   - Sets tight per-child min_shares_out respecting treasury caps
   - Crash-safe state persistence for mid-execution recovery
   - Adaptive stopping when edge disappears

All modules include comprehensive tests and are designed for crash-safety,
observability, and seamless integration with existing agent runtime.
@drips-wave

drips-wave Bot commented Oct 21, 2026

Copy link
Copy Markdown

@ada-nwali Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@Nursca
Nursca merged commit f1900f4 into OracleDesk:develop Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants