feat: add strategy-marketplace skill#266
feat: add strategy-marketplace skill#266spiritclawd wants to merge 5 commits intokeep-starknet-strange:mainfrom
Conversation
- 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
|
@coderabbitai review\n@greptileai review\n\nPlease review the latest commit, including nitpicks. |
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Caution Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional.
❌ Failed checks (1 error, 2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment |
|
🧠 Learnings used✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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`.
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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)
Comment |
|
@coderabbitai review\n@greptileai review\n@greptile-ai review\n\nApplied all reported nitpicks (docs, typing, validations, side-effect cleanup). Please run another pass. |
|
✅ Actions performedReview triggered.
|
|
@greptileai review |
|
@greptileai review |
Greptile SummaryAdds 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 Key improvements from previous iterations:
Remaining considerations 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
|
| 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
Last reviewed commit: e22c1a6
There was a problem hiding this comment.
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.
|
@coderabbitai review |
|
@greptileai review |
✅ Actions performedReview triggered.
|
|
@greptileai review |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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.
| 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 | ||
| }; | ||
| } |
There was a problem hiding this comment.
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.
| 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 | ||
| }; |
There was a problem hiding this comment.
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.
| 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.
| 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 | ||
| }; |
There was a problem hiding this comment.
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.
Summary
Adds the Strategy Marketplace skill for registering, tracking, and monetizing AI agent strategies.
Features
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.mdfor usage examples.Related
Summary by CodeRabbit
New Features
Documentation
Tests
Chores