Skip to content

feat: add strategy-marketplace skill#266

Open
spiritclawd wants to merge 5 commits intokeep-starknet-strange:mainfrom
spiritclawd:main
Open

feat: add strategy-marketplace skill#266
spiritclawd wants to merge 5 commits intokeep-starknet-strange:mainfrom
spiritclawd:main

Conversation

@spiritclawd
Copy link

@spiritclawd spiritclawd commented Feb 18, 2026

Summary

Adds the Strategy Marketplace skill for registering, tracking, and monetizing AI agent strategies.

Features

  • Agent Registration: ERC-8004 identity for agents
  • Performance Tracking: Track wins/losses/ROI across games
  • Strategy Marketplace: Publish and discover strategies
  • Service Offering: Offer inference as a paid service

Why This Matters

This addresses the "million dollar question" - how do agents find clients? The strategy marketplace makes agents discoverable by their track record. Agents become sellable products with verifiable performance.

Test

See /skills/strategy-marketplace/README.md for usage examples.

Related

  • Part of aircade.xyz vision
  • Addresses agent commerce discovery gap

Summary by CodeRabbit

  • New Features

    • Strategy Marketplace skill: agent registration, performance tracking, publish/discover/purchase strategies, service offerings, certification, and in-process marketplace flows.
  • Documentation

    • Added README, skill guide, API spec, certification criteria, design notes, and references with usage examples and architecture.
  • Tests

    • End-to-end test suite covering agent lifecycle, tracking, publishing/discovery/purchase, and service offers.
  • Chores

    • Project config, package manifest, build/test scripts, and example helper scripts.

spiritclawd and others added 2 commits February 18, 2026 15:56
- Agent registration with ERC-8004 identity
- Performance tracking for games/strategies
- Strategy publishing and discovery
- Service offering for inference

Part of aircade.xyz strategy marketplace vision
@omarespejel
Copy link
Collaborator

@coderabbitai review\n@greptileai review\n\nPlease review the latest commit, including nitpicks.

@coderabbitai
Copy link

coderabbitai bot commented Feb 21, 2026

📝 Walkthrough

Walkthrough

Adds a new Strategy Marketplace skill: TypeScript types, in-memory agent registry (ERC-8004-inspired), performance tracking, strategy publishing/discovery/purchase, service offerings, tests, CLI scripts, and documentation. All runtime logic is in-process with test helpers and build scripts.

Changes

Cohort / File(s) Summary
Documentation
skills/strategy-marketplace/README.md, skills/strategy-marketplace/SKILL.md, skills/strategy-marketplace/references/*
New README, skill spec, API reference, certification criteria, and design notes describing flows, architecture, and certification rules.
Package & Build
skills/strategy-marketplace/package.json, skills/strategy-marketplace/tsconfig.json
Added package manifest and TypeScript config (ESM, declaration output, build/test scripts, strict settings).
Public API Barrel
skills/strategy-marketplace/src/index.ts
New barrel exporting types, registry, tracking, and marketplace modules; includes quick-start example comments.
Types
skills/strategy-marketplace/src/types.ts
Introduced domain interfaces: AgentRegistration, RegisteredAgent, PerformanceRecord, AgentStats, StrategyListing, ServiceOffering, DiscoveryQuery, PurchaseRequest/Result.
Registry
skills/strategy-marketplace/src/registry.ts
In-memory agent registry with register/get/list/update APIs, input validation, ID/address helpers, and test reset helper.
Tracking
skills/strategy-marketplace/src/tracking.ts
In-memory performance tracking: trackPerformance, getAgentStats, getWinRate, getTopStrategies, aggregation logic, validation, and test reset.
Marketplace
skills/strategy-marketplace/src/marketplace.ts
In-memory marketplace: publishStrategy (certification check), discoverStrategies, getStrategy, purchaseStrategy (accessId/expiry), offerService, getAgentServices, price/ID helpers, and test reset.
Tests
skills/strategy-marketplace/src/strategy-marketplace.test.ts
End-to-end tests covering registration, tracking, publishing, discovery, purchase, certification, and service offerings; resets test state between groups.
Scripts
skills/strategy-marketplace/scripts/*
CLI/demo scripts: registerAgent.ts, publishStrategy.ts, trackPerformance.ts to exercise APIs and print results.

Sequence Diagram(s)

sequenceDiagram
    participant Agent
    participant Registry as Registry Module
    participant Tracking as Tracking Module
    participant Marketplace as Marketplace Module

    Agent->>Registry: registerAgent(config)
    Registry->>Registry: generateAgentId()
    Registry->>Registry: storeAgent()
    Registry-->>Agent: RegisteredAgent

    Agent->>Tracking: trackPerformance(record)
    Tracking->>Registry: getAgent(agentId)
    Tracking->>Tracking: storePerformance()
    Tracking-->>Agent: void

    Agent->>Marketplace: publishStrategy(config)
    Marketplace->>Registry: getAgent(agentId)
    Marketplace->>Tracking: getAgentStats(agentId)
    Marketplace->>Marketplace: evaluate certification & price
    Marketplace->>Marketplace: storeListing()
    Marketplace-->>Agent: StrategyListing

    Agent->>Marketplace: discoverStrategies(query)
    Marketplace->>Marketplace: filter & sort listings
    Marketplace-->>Agent: StrategyListing[]

    Agent->>Marketplace: purchaseStrategy(request)
    Marketplace->>Marketplace: validate & generate accessId
    Marketplace-->>Agent: PurchaseResult
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (1 error, 2 warnings)

Check name Status Explanation Resolution
Cross-Repo Boundary Awareness ❌ Error PR strategy-marketplace skill documentation fails to acknowledge integration dependencies with starkclaw and SISNA external repos despite cross-repo-compatibility focus. Update skill documentation to explicitly acknowledge starkclaw contract-backed persistence integration and SISNA signer boundary for payment settlement flows.
Docstring Coverage ⚠️ Warning Docstring coverage is 32.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Security Rationale For Account Semantics ⚠️ Warning PR adds 965-line session-account contract with security-critical functionality but commit message lacks required security rationale and invariant documentation for contracts/session-account/** modifications. Add detailed security rationale to PR description addressing trust assumptions, preserved invariants, ERC-8004 identity binding enforcement, and policy failure modes.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: add strategy-marketplace skill' clearly and directly describes the main change: introducing a new Strategy Marketplace skill module with agent registration, performance tracking, and strategy publishing/discovery capabilities.
Spec Impact Declaration ✅ Passed PR modifies only files in skills/strategy-marketplace/, which is not in restricted directories (contracts/session-account/, packages/, docs/, .github/workflows/), so Spec impact declaration is not required.
✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai
Copy link

coderabbitai bot commented Feb 21, 2026

@omarespejel: I'll review the latest commit with attention to detail, including nitpicks. I'll check the Strategy Marketplace skill implementation against AgentSkills specifications and examine the code quality thoroughly.


🧠 Learnings used
Learnt from: CR
Repo: keep-starknet-strange/starknet-agentic PR: 0
File: AGENT.md:0-0
Timestamp: 2026-02-15T17:03:49.347Z
Learning: Consult the `references/agentskills/` directory for AgentSkills specifications covering integration patterns, skill format, and skill definitions
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@skills/strategy-marketplace/package.json`:
- Around line 11-14: The dependencies in
skills/strategy-marketplace/package.json are incorrect and non-reproducible:
replace the wildcard "*" entries with either proper published versions or
workspace references and ensure workspace registration; specifically, change
"x402": "*" to " `@x402-starknet`": "workspace:*" (or the correct published
version) and remove or correct the non-existent "@starknet-agentic/core" (either
point it to the actual package name/version or a workspace:* entry if it
exists), and then add the skills/* pattern to pnpm-workspace.yaml so this
package is part of the workspace; update package.json dependency keys to match
the actual workspace package names (e.g., `@x402-starknet`) and use workspace:*
protocol for internal packages to enable reproducible installs.

In `@skills/strategy-marketplace/SKILL.md`:
- Around line 1-3: Add required YAML frontmatter at the very top of SKILL.md
containing the keys name, description, keywords, allowed-tools, and
user-invocable; ensure name follows the lowercase-hyphen-only format (1–64
characters) and matches the skill identity (e.g., "strategy-marketplace"),
provide a concise description string, a keywords list, an allowed-tools list,
and a boolean user-invocable flag; update SKILL.md so the frontmatter block (---
... ---) is the first content and validates against the required schema.
- Around line 22-146: The markdown has lint warnings: missing blank lines around
headings (e.g., "Register Agent", "Track Performance", "Publish Strategy",
"Offer Service", "Discover Strategies", "Purchase Strategy", "Architecture",
"Use Cases") and a fenced code block without a language tag (the ASCII tree
under "Architecture"). Fix by adding a single blank line before and after each
top-level and subheading, and add appropriate language identifiers to all fenced
code blocks (e.g., ```typescript for the examples and ```text or ```text for the
architecture tree) so markdownlint no longer flags heading spacing or missing
fence language.
- Around line 5-118: Add a "Quick Reference" section at the top of SKILL.md
summarizing common calls (registerAgent, trackPerformance, publishStrategy,
offerService, discoverStrategies, purchaseStrategy) with one-line purpose and
return values; add a "starknet.js example" section showing how to construct a
Provider and Account and use them to sign/submit marketplace operations
(reference Provider and Account symbols and show usage with
registerAgent/purchaseStrategy flow); and add an "Error Codes & Recovery" table
listing expected error codes (e.g., AGENT_NOT_FOUND, INSUFFICIENT_FUNDS,
INVALID_SIGNATURE, STRATEGY_NOT_AVAILABLE) with short recovery steps for each
(e.g., check agentId, top-up account, re-sign request, retry/publish). Ensure
these sections are placed in SKILL.md and reference the existing function names
(registerAgent, publishStrategy, purchaseStrategy) so readers can map examples
to code.
- Around line 121-216: Update the Strategy Marketplace skill docs to include the
missing references/ and scripts/ subdirectories: add entries for "references/"
(deep-dive design docs, API specs, certification criteria) and "scripts/"
(runnable examples like publishStrategy.ts, trackPerformance.ts,
registerAgent.ts) to the Architecture list and repository structure in SKILL.md;
ensure example imports (registerAgent, trackPerformance, publishStrategy) and
the "Next Steps" checklist mention where to find or add these new folders so
developers can locate design references and runnable examples.

In `@skills/strategy-marketplace/src/index.ts`:
- Line 51: The top-level console.log in skills/strategy-marketplace/src/index.ts
causes import-time side effects; remove that unconditional
console.log('[Strategy Marketplace] Skill loaded') or gate it behind an explicit
debug flag (e.g., check process.env.DEBUG_STRATEGY_MARKETPLACE or use a debug
logger) so logging only occurs when the module is intentionally invoked in debug
mode; update the top-level initialization in index.ts accordingly so imports
remain side-effect free.

In `@skills/strategy-marketplace/src/marketplace.ts`:
- Around line 21-47: Validate and enforce that the price is a numeric,
non-negative value before creating or updating listings: in publishStrategy,
convert/parse config.price to a number, ensure it's not NaN and >= 0, and throw
a descriptive error (or reject) if it fails validation; then store the validated
numeric price in the StrategyListing instead of an unchecked string. Apply the
same validation logic to any other listing update/create functions that accept
price (the other function around lines 134-154) so discovery sorting won't be
corrupted and invalid listings are prevented.
- Around line 65-74: The filters currently skip valid zero values because they
use truthy checks; update the conditionals in marketplace.ts that filter
listings (the blocks referencing query.game, query.minRoi, and query.maxPrice)
to test explicitly for undefined (e.g., use query.minRoi !== undefined and
query.maxPrice !== undefined) while preserving the existing comparisons
(l.trackRecord.avgRoi >= query.minRoi and parseFloat(l.price) <= query.maxPrice)
so 0 values are applied correctly.
- Around line 106-113: The purchase flow in purchaseStrategy currently skips
verifying the buyer agent, allowing arbitrary buyerAgentId values; before
processing payment or completing purchase, fetch and validate the buyer agent
(e.g., call the existing agent lookup function such as getAgent or findAgent
using request.buyerAgentId), throw a clear error if the agent does not exist,
and ensure subsequent steps (payment via processPayment and recording the
purchase) use the validated agent object/ID rather than the raw request value;
add this validation just after retrieving the strategy and before any payment or
persistence operations.

In `@skills/strategy-marketplace/src/registry.ts`:
- Around line 27-41: registerAgent currently ignores the network field from
AgentRegistration; update the function to persist network into the returned
RegisteredAgent object (add network: network) and ensure the RegisteredAgent
type/interface is updated to include a network property so consumers can read
chain context; locate registerAgent, AgentRegistration and RegisteredAgent
declarations and add the network field consistently (also update any code that
constructs or consumes RegisteredAgent such as
generateAgentId/getCurrentAgentAddress usages if they assume the old shape).

In `@skills/strategy-marketplace/src/types.ts`:
- Around line 86-96: The PurchaseRequest and PurchaseResult interfaces use
unsafe any types; change parameters and strategyData to safer generics or
unknowns: update PurchaseRequest to accept a generic type parameter (e.g., P =
unknown) and replace parameters?: Record<string, any> with parameters?: P or
Record<string, P> as appropriate, and update PurchaseResult to be generic (e.g.,
R = unknown) and replace strategyData: any with strategyData: R; ensure
callers/providers instantiate the generics or let them default to unknown to
preserve type safety across functions that use PurchaseRequest and
PurchaseResult.

In `@skills/strategy-marketplace/tsconfig.json`:
- Around line 3-5: Add ESM settings to this package: in package.json add "type":
"module" at the top-level, and in tsconfig.json change "module": "CommonJS" to
"ESNext" and "moduleResolution": "Node" to "bundler" so the package uses ESM
like other skills (matching packages such as starknet-anonymous-wallet and
starknet-wallet); update the tsconfig.json entries for "module" and
"moduleResolution" and ensure package.json contains the top-level "type":
"module" field so imports work with ESM-only dependencies like
`@starknet-agentic/core`.

@coderabbitai
Copy link

coderabbitai bot commented Feb 21, 2026

Warning

Rate limit exceeded

@omarespejel has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@omarespejel
Copy link
Collaborator

@coderabbitai review\n@greptileai review\n@greptile-ai review\n\nApplied all reported nitpicks (docs, typing, validations, side-effect cleanup). Please run another pass.

@coderabbitai
Copy link

coderabbitai bot commented Feb 21, 2026

@omarespejel: Thank you for addressing the nitpicks! I'll run another pass on the updated code to verify the docs, typing improvements, validations, and side-effect cleanup.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@omarespejel
Copy link
Collaborator

@greptileai review

@omarespejel
Copy link
Collaborator

@greptileai review

@greptile-apps
Copy link

greptile-apps bot commented Feb 21, 2026

Greptile Summary

Adds a comprehensive strategy marketplace skill for agent registration, performance tracking, and strategy monetization. The implementation addresses most previous review feedback with proper input validation, encapsulated state management using globalThis pattern, and comprehensive test coverage.

Key improvements from previous iterations:

  • Input validation added for all public APIs
  • Module-scope state moved to globalThis encapsulated getters to prevent shared mutable state issues
  • randomUUID() used for marketplace IDs (though agent IDs still use randomBytes as documented placeholder)
  • Comprehensive validation for numeric fields, string trimming, and edge cases

Remaining considerations for production:

  • Payment verification stub at marketplace.ts:398-408 needs X-402 integration before real transactions
  • Agent ID generation uses mock approach pending ERC-8004 contract integration (documented with env var fallback)
  • In-memory state storage suitable for demo/testing but needs contract-backed persistence for production

The skill follows AgentSkills conventions, includes proper documentation, runnable examples, and aligns with the repository's architectural patterns for Starknet agent infrastructure.

Confidence Score: 4/5

  • Safe to merge with minor risk - production deployment requires payment and persistence integration
  • Code quality is solid with proper validation, error handling, and test coverage. Previous review concerns have been addressed. Score reflects that this is a well-implemented demo/MVP layer with clearly documented placeholders for production features (ERC-8004 integration, X-402 payments, on-chain persistence). No critical bugs or security issues in the TypeScript logic itself.
  • Pay attention to marketplace.ts payment stub before production use - ensure X-402 verification is implemented

Important Files Changed

Filename Overview
skills/strategy-marketplace/src/types.ts Well-structured TypeScript interfaces for marketplace entities with proper typing
skills/strategy-marketplace/src/registry.ts Agent registration with proper input validation; addresses previous feedback on state encapsulation
skills/strategy-marketplace/src/tracking.ts Performance tracking with comprehensive validation; state properly encapsulated in global storage
skills/strategy-marketplace/src/marketplace.ts Marketplace logic with validation; payment stub requires production implementation before deployment
skills/strategy-marketplace/src/strategy-marketplace.test.ts Good test coverage with positive and negative test cases; validates the core flows

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Agent Registration] --> B[registerAgent]
    B --> C[Agent Registry Store]
    
    D[Performance Tracking] --> E[trackPerformance]
    E --> F[Performance History Store]
    E --> G[Validate Agent Exists]
    G --> C
    
    H[Strategy Publishing] --> I[publishStrategy]
    I --> J[Validate Agent]
    J --> C
    I --> K[Check Certification]
    K --> F
    I --> L[Strategy Listings Store]
    
    M[Strategy Discovery] --> N[discoverStrategies]
    N --> L
    N --> O[Filter & Sort]
    O --> P[Return Listings]
    
    Q[Strategy Purchase] --> R[purchaseStrategy]
    R --> S[Validate Buyer Agent]
    S --> C
    R --> T[Get Strategy]
    T --> L
    R --> U[verifyPaymentStub]
    U --> V{Payment OK?}
    V -->|Yes| W[Grant Access]
    V -->|No| X[Reject Purchase]
    
    Y[Service Offering] --> Z[offerService]
    Z --> AA[Validate Agent]
    AA --> C
    Z --> AB[Service Offerings Store]
    
    style U fill:#ff9,stroke:#f66,stroke-width:2px
    style V fill:#ff9,stroke:#f66,stroke-width:2px
Loading

Last reviewed commit: e22c1a6

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

16 files reviewed, 8 comments

Edit Code Review Agent Settings | Greptile

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

16 files reviewed, 4 comments

Edit Code Review Agent Settings | Greptile

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@skills/strategy-marketplace/SKILL.md`:
- Around line 24-33: Update the Quick Reference table to reflect the actual
async return types used in code: change `registerAgent` and `publishStrategy`
entries to show Promise-wrapped return types (e.g., `Promise<RegisteredAgent>`
and `Promise<StrategyListing>`), and verify the other functions
(`trackPerformance`, `offerService`, `discoverStrategies`, `purchaseStrategy`)
match their real signatures in `skills/strategy-marketplace/src/registry.ts` and
`skills/strategy-marketplace/src/marketplace.ts`, updating any other entries to
`Promise<...>` where the implementation is async so the docs match the source.
- Around line 141-150: The Account constructor call is using outdated positional
args; update the Account instantiation to the object-form constructor required
by starknet.js v8.9.1 by passing an object with keys provider, address, and
signer (i.e., replace new Account(provider, process.env.AGENT_ADDRESS!,
process.env.AGENT_PRIVATE_KEY!) with new Account({ provider, address:
process.env.AGENT_ADDRESS!, signer: process.env.AGENT_PRIVATE_KEY! })); leave
RpcProvider creation and the rest (registerAgent, purchaseStrategy imports)
unchanged.

In `@skills/strategy-marketplace/src/index.ts`:
- Around line 41-48: The example call to publishStrategy in the quick-start docs
is missing required fields and will fail validation; update the example to
include the required description and parameters properties when calling
publishStrategy (e.g., keep agentId: agent.id, name, price, game, trackRecord)
and add a descriptive description string and a parameters object/array matching
the expected shape used by the publishStrategy function so the sample matches
the function signature.

In `@skills/strategy-marketplace/src/marketplace.ts`:
- Around line 204-214: The checkCertification function contains a redundant
guard: remove the unnecessary "if (trackRecord.totalGames <= 0) return false;"
since trackRecord.totalGames < 10 already covers non‑positive and small game
counts; keep the remaining checks (minimum 10 games, avgRoi > 0, and win rate >
50%) and ensure the function still computes winRate using trackRecord.wins /
trackRecord.totalGames before returning winRate > 0.5.

In `@skills/strategy-marketplace/src/registry.ts`:
- Around line 107-110: Replace the fragile placeholder fallback in
getCurrentAgentAddress with a stricter sentinel and production safeguard: read
process.env.AGENT_ADDRESS and if missing, throw an error when
process.env.NODE_ENV === 'production' (so production runs fail fast), otherwise
return a clearly invalid sentinel like 'UNKNOWN_AGENT_ADDRESS' or '0x0' instead
of '0x...'; update the getCurrentAgentAddress function to implement this logic
and reference AGENT_ADDRESS and NODE_ENV when performing the checks.

---

Duplicate comments:
In `@skills/strategy-marketplace/package.json`:
- Around line 1-26: The package "@aircade/strategy-marketplace" lives under
skills/ but your pnpm workspace omits that path; update the workspace
configuration to include "skills/*" so this package participates in hoisting,
linking, and future inter-package deps. Open pnpm-workspace.yaml and add
skills/* to the packages list (alongside packages/*, examples/*, website) so the
Skill's package.json is managed by the monorepo tooling.

@omarespejel
Copy link
Collaborator

@coderabbitai review

@omarespejel
Copy link
Collaborator

@greptileai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 22, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@omarespejel
Copy link
Collaborator

@greptileai review

@omarespejel
Copy link
Collaborator

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 22, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@skills/strategy-marketplace/src/marketplace.ts`:
- Around line 308-347: validatePublishStrategyInput currently doesn't
runtime-validate parameters.riskLevel, so add an explicit enum check for
config.parameters.riskLevel inside validatePublishStrategyInput: define an
allowedRiskLevels array (e.g., ['low','medium','high'] or the canonical set used
elsewhere), validate config.parameters.riskLevel against that set (throw or use
a helper like requireOneOf/validateEnum), assign the validated value (e.g.,
riskLevel) and include it in the returned parameters object alongside playStyle
and minCapital so invalid riskLevel values cannot be stored.

In `@skills/strategy-marketplace/src/registry.ts`:
- Around line 160-176: validateRegistrationInput currently skips runtime
validation of the AgentRegistration.network field; update
validateRegistrationInput to require and validate config.network (e.g., via
requireNonEmptyString or similar) and check it against the supported networks
set (the canonical list used elsewhere — reference the supported network
enumeration/array used by the project) and throw a clear Error if the value is
not one of the supported networks; ensure the validated network value is
included in the returned object alongside name, description, capabilities, and
games so invalid network values cannot be stored.

In `@skills/strategy-marketplace/src/tracking.ts`:
- Around line 181-206: The validatePerformanceInput function currently doesn't
validate record.result; add validation to ensure result is a non-empty string
and is exactly one of the allowed values 'win', 'loss', or 'draw' (throw an
Error for any other value or missing result). Use the existing pattern (e.g.,
call requireNonEmptyString(record.result, 'result') or similar) then check
membership against the set {'win','loss','draw'} and throw a descriptive Error
if invalid; include the validated result in the returned object alongside
agentId, game, strategy, roi, and duration so downstream stats can't be skewed
by arbitrary strings.

Comment on lines +308 to +347
function validatePublishStrategyInput(config: {
agentId: string;
name: string;
description: string;
price: string | number;
game: string;
parameters: StrategyListing['parameters'];
trackRecord: StrategyListing['trackRecord'];
}): {
agentId: string;
name: string;
description: string;
price: string | number;
game: string;
parameters: StrategyListing['parameters'];
trackRecord: StrategyListing['trackRecord'];
} {
const agentId = requireNonEmptyString(config.agentId, 'agentId');
const name = requireNonEmptyString(config.name, 'name');
const description = requireNonEmptyString(config.description, 'description');
const game = requireNonEmptyString(config.game, 'game');
const playStyle = requireNonEmptyString(config.parameters.playStyle, 'parameters.playStyle');
const minCapital = requireNonEmptyString(config.parameters.minCapital, 'parameters.minCapital');
const trackRecord = validateTrackRecord(config.trackRecord);
parseNonNegativePrice(config.price, 'strategy price');

return {
...config,
agentId,
name,
description,
game,
parameters: {
...config.parameters,
playStyle,
minCapital
},
trackRecord
};
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Validate parameters.riskLevel.

Line 308-347: riskLevel is not runtime-validated, so invalid enum values can be stored and break UI/clients. Enforce allowed values.

🔧 Suggested fix
   const agentId = requireNonEmptyString(config.agentId, 'agentId');
   const name = requireNonEmptyString(config.name, 'name');
   const description = requireNonEmptyString(config.description, 'description');
   const game = requireNonEmptyString(config.game, 'game');
+  const riskLevel = config.parameters.riskLevel;
+  if (!['low', 'medium', 'high'].includes(riskLevel)) {
+    throw new Error('Invalid parameters.riskLevel: expected low, medium, or high');
+  }
   const playStyle = requireNonEmptyString(config.parameters.playStyle, 'parameters.playStyle');
   const minCapital = requireNonEmptyString(config.parameters.minCapital, 'parameters.minCapital');
   const trackRecord = validateTrackRecord(config.trackRecord);
   parseNonNegativePrice(config.price, 'strategy price');

   return {
     ...config,
     agentId,
     name,
     description,
     game,
     parameters: {
       ...config.parameters,
+      riskLevel,
       playStyle,
       minCapital
     },
     trackRecord
   };
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/strategy-marketplace/src/marketplace.ts` around lines 308 - 347,
validatePublishStrategyInput currently doesn't runtime-validate
parameters.riskLevel, so add an explicit enum check for
config.parameters.riskLevel inside validatePublishStrategyInput: define an
allowedRiskLevels array (e.g., ['low','medium','high'] or the canonical set used
elsewhere), validate config.parameters.riskLevel against that set (throw or use
a helper like requireOneOf/validateEnum), assign the validated value (e.g.,
riskLevel) and include it in the returned parameters object alongside playStyle
and minCapital so invalid riskLevel values cannot be stored.

Comment on lines +160 to +176
function validateRegistrationInput(config: AgentRegistration): AgentRegistration {
const name = requireNonEmptyString(config.name, 'name');
if (!SKILL_NAME_PATTERN.test(name)) {
throw new Error('Invalid name: expected lowercase letters, numbers, and hyphens (1-64 chars)');
}

const description = requireNonEmptyString(config.description, 'description');
const capabilities = requireStringArray(config.capabilities, 'capabilities');
const games = requireStringArray(config.games, 'games');

return {
...config,
name,
description,
capabilities,
games
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Validate network at registration.

Line 160-176: network is never runtime-validated, so invalid values can be stored and later break chain-specific lookups. Add an explicit check against supported networks.

🔧 Suggested fix
 function validateRegistrationInput(config: AgentRegistration): AgentRegistration {
   const name = requireNonEmptyString(config.name, 'name');
   if (!SKILL_NAME_PATTERN.test(name)) {
     throw new Error('Invalid name: expected lowercase letters, numbers, and hyphens (1-64 chars)');
   }

   const description = requireNonEmptyString(config.description, 'description');
   const capabilities = requireStringArray(config.capabilities, 'capabilities');
   const games = requireStringArray(config.games, 'games');
+  const network = config.network;
+  if (!Object.prototype.hasOwnProperty.call(MARKETPLACE_CONTRACTS, network)) {
+    throw new Error(`Invalid network: ${network}`);
+  }

   return {
     ...config,
     name,
     description,
     capabilities,
     games
   };
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function validateRegistrationInput(config: AgentRegistration): AgentRegistration {
const name = requireNonEmptyString(config.name, 'name');
if (!SKILL_NAME_PATTERN.test(name)) {
throw new Error('Invalid name: expected lowercase letters, numbers, and hyphens (1-64 chars)');
}
const description = requireNonEmptyString(config.description, 'description');
const capabilities = requireStringArray(config.capabilities, 'capabilities');
const games = requireStringArray(config.games, 'games');
return {
...config,
name,
description,
capabilities,
games
};
function validateRegistrationInput(config: AgentRegistration): AgentRegistration {
const name = requireNonEmptyString(config.name, 'name');
if (!SKILL_NAME_PATTERN.test(name)) {
throw new Error('Invalid name: expected lowercase letters, numbers, and hyphens (1-64 chars)');
}
const description = requireNonEmptyString(config.description, 'description');
const capabilities = requireStringArray(config.capabilities, 'capabilities');
const games = requireStringArray(config.games, 'games');
const network = config.network;
if (!Object.prototype.hasOwnProperty.call(MARKETPLACE_CONTRACTS, network)) {
throw new Error(`Invalid network: ${network}`);
}
return {
...config,
name,
description,
capabilities,
games
};
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/strategy-marketplace/src/registry.ts` around lines 160 - 176,
validateRegistrationInput currently skips runtime validation of the
AgentRegistration.network field; update validateRegistrationInput to require and
validate config.network (e.g., via requireNonEmptyString or similar) and check
it against the supported networks set (the canonical list used elsewhere —
reference the supported network enumeration/array used by the project) and throw
a clear Error if the value is not one of the supported networks; ensure the
validated network value is included in the returned object alongside name,
description, capabilities, and games so invalid network values cannot be stored.

Comment on lines +181 to +206
function validatePerformanceInput(record: PerformanceInput): PerformanceInput {
const duration = requireFiniteNumber(record.duration, 'duration');
if (duration < 0) {
throw new Error('Invalid duration: expected a non-negative number');
}

const roi = requireFiniteNumber(record.roi, 'roi');
const agentId = requireNonEmptyString(record.agentId, 'agentId');
const game = requireNonEmptyString(record.game, 'game');
const strategy = requireNonEmptyString(record.strategy, 'strategy');

if (record.timestamp !== undefined) {
const timestamp = requireFiniteNumber(record.timestamp, 'timestamp');
if (timestamp < 0) {
throw new Error('Invalid timestamp: expected a non-negative number');
}
}

return {
...record,
agentId,
game,
strategy,
roi,
duration
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Reject invalid result values.

Line 181-206: result is never validated, so arbitrary strings will silently skew stats. Enforce win | loss | draw in validation.

🛡️ Suggested fix
 function validatePerformanceInput(record: PerformanceInput): PerformanceInput {
   const duration = requireFiniteNumber(record.duration, 'duration');
   if (duration < 0) {
     throw new Error('Invalid duration: expected a non-negative number');
   }

   const roi = requireFiniteNumber(record.roi, 'roi');
+  const result = record.result;
+  if (result !== 'win' && result !== 'loss' && result !== 'draw') {
+    throw new Error('Invalid result: expected win, loss, or draw');
+  }
   const agentId = requireNonEmptyString(record.agentId, 'agentId');
   const game = requireNonEmptyString(record.game, 'game');
   const strategy = requireNonEmptyString(record.strategy, 'strategy');

   if (record.timestamp !== undefined) {
     const timestamp = requireFiniteNumber(record.timestamp, 'timestamp');
     if (timestamp < 0) {
       throw new Error('Invalid timestamp: expected a non-negative number');
     }
   }

   return {
     ...record,
     agentId,
     game,
     strategy,
     roi,
-    duration
+    duration,
+    result
   };
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/strategy-marketplace/src/tracking.ts` around lines 181 - 206, The
validatePerformanceInput function currently doesn't validate record.result; add
validation to ensure result is a non-empty string and is exactly one of the
allowed values 'win', 'loss', or 'draw' (throw an Error for any other value or
missing result). Use the existing pattern (e.g., call
requireNonEmptyString(record.result, 'result') or similar) then check membership
against the set {'win','loss','draw'} and throw a descriptive Error if invalid;
include the validated result in the returned object alongside agentId, game,
strategy, roi, and duration so downstream stats can't be skewed by arbitrary
strings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants