Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions .taskmaster/docs/prd.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,23 @@ Transform AI agents from passive tools into active economic participants capable

### 1. Registry Systems

#### Service Registry
- **REQ-1.1**: Maintain an open catalog of available services
- **REQ-1.2**: Support service metadata, pricing, and capability definitions
- **REQ-1.3**: Enable community-driven service additions (future)
- **REQ-1.4**: Provide service discovery and filtering mechanisms
#### Service Registry V2
- **REQ-1.1**: Maintain an open catalog of available services with full lifecycle management
- **REQ-1.2**: Support comprehensive service metadata including:
- Service identity (UUID-based with on-chain hash representation)
- Ownership model (human developer as owner, agent as executor)
- Technical specifications (endpoint URLs, method types, parameter/result schemas)
- Business configurations (pricing models, rate limits)
- Version management and status tracking
- **REQ-1.3**: Enable service-agent assignment model:
- Services can be created independently without agent assignment
- Services can be assigned/unassigned to agents dynamically
- Unassigned services remain inactive but preserved
- Support for service transfer between agents
- **REQ-1.4**: Provide advanced service discovery and filtering:
- Query by owner, agent, category, status
- Filter by pricing model and availability
- Search unassigned services for marketplace discovery

#### Agent Registry
- **REQ-1.5**: Allow agents to self-register with metadata and capabilities
Expand Down
71 changes: 70 additions & 1 deletion .taskmaster/tasks/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -331,11 +331,80 @@
],
"priority": "high",
"subtasks": []
},
{
"id": 25,
"title": "SDK: Implement Service Management System V2 with comprehensive CRUD operations, ownership model, and agent assignment capabilities",
"description": "Implement a comprehensive Service Management System V2 in the TypeScript SDK with full CRUD operations, ownership model, agent assignment capabilities, hybrid storage (on-chain + IPFS), and advanced discovery/filtering as specified in the PRD.",
"details": "1. ServiceRegistryService Enhancement:\n - Extend existing ServiceRegistryService class with V2 capabilities\n - Implement comprehensive CRUD operations: createService(), updateService(), deleteService(), getService(), listServices()\n - Add ownership model with transferOwnership(), getServiceOwner(), and ownership validation\n - Implement agent assignment/unassignment: assignAgent(), unassignAgent(), getAssignedAgents(), getServicesByAgent()\n - Add service lifecycle management with status tracking (draft, active, paused, archived, deleted)\n\n2. ServiceSchema Integration:\n - Create comprehensive ServiceSchema interface with required fields: id, name, description, category, owner, status, createdAt, updatedAt\n - Add optional fields: tags, metadata, pricing, requirements, capabilities, assignedAgents\n - Implement Zod validation schemas for all service operations\n - Support nested schema validation for complex service configurations\n\n3. Smart Contract Updates:\n - Extend ServiceRegistry.sol with V2 functionality including ownership transfers, agent assignments, and enhanced metadata\n - Implement hybrid storage pattern: core data on-chain (id, owner, status, assignedAgents) and metadata on IPFS\n - Add events for ServiceCreated, ServiceUpdated, ServiceDeleted, AgentAssigned, AgentUnassigned, OwnershipTransferred\n - Implement access control with onlyOwner modifiers and agent assignment permissions\n\n4. Hybrid Storage Implementation:\n - Integrate IPFS client for metadata storage using ipfs-http-client\n - Implement automatic IPFS pinning for service metadata and large data objects\n - Create metadata synchronization between on-chain references and IPFS content\n - Add content addressing and integrity verification for IPFS stored data\n\n5. Advanced Discovery and Filtering:\n - Implement advanced search with filters: category, status, owner, assignedAgent, tags, dateRange\n - Add pagination support with cursor-based navigation for large result sets\n - Implement sorting options: createdAt, updatedAt, name, category, status\n - Create full-text search capabilities for service names and descriptions\n - Add geolocation-based filtering if location metadata is available\n\n6. CLI Service Commands Integration:\n - Create 'ensemble services' command group with subcommands: create, list, get, update, delete, assign, unassign, transfer\n - Implement service-record.yaml configuration file support similar to agent-record.yaml\n - Add interactive service creation wizard with step-by-step guidance\n - Support bulk operations for service management and agent assignments",
"testStrategy": "1. Unit Testing:\n - Test all ServiceRegistryService methods with mocked blockchain interactions and IPFS operations\n - Validate ServiceSchema Zod validation with valid and invalid service data structures\n - Test ownership model operations including transfers and permission checks\n - Verify agent assignment/unassignment logic with various scenarios (single/multiple agents)\n - Test hybrid storage operations with mocked IPFS client responses\n\n2. Integration Testing:\n - Deploy updated smart contracts to testnet and test all V2 functionality end-to-end\n - Test IPFS integration with real IPFS nodes and verify metadata storage/retrieval\n - Validate service lifecycle management across different status transitions\n - Test advanced discovery and filtering with large datasets (1000+ services)\n - Verify CLI commands integration with real SDK operations\n\n3. Performance Testing:\n - Benchmark service creation/update operations with large metadata objects\n - Test pagination performance with datasets of varying sizes (100, 1K, 10K services)\n - Measure IPFS upload/download times for different metadata sizes\n - Test concurrent agent assignment operations and verify data consistency\n\n4. Security Testing:\n - Verify ownership validation prevents unauthorized service modifications\n - Test agent assignment permissions and access control mechanisms\n - Validate IPFS content integrity and prevent metadata tampering\n - Test smart contract upgrade scenarios and data migration safety\n\n5. End-to-End Testing:\n - Create complete service management workflows from CLI to blockchain\n - Test service discovery through various filtering combinations\n - Verify ownership transfers maintain data integrity and agent assignments\n - Test service deletion and cleanup of associated IPFS metadata",
"status": "pending",
"dependencies": [
1,
3,
21
],
"priority": "medium",
"subtasks": [
{
"id": 1,
"title": "Extend ServiceRegistryService with V2 CRUD Operations and Ownership Model",
"description": "Enhance the existing ServiceRegistryService class with comprehensive CRUD operations, ownership model, and service lifecycle management capabilities.",
"dependencies": [],
"details": "Extend the ServiceRegistryService class to include: createService(), updateService(), deleteService(), getService(), listServices() methods with proper error handling and validation. Implement ownership model with transferOwnership(), getServiceOwner(), and ownership validation methods. Add service lifecycle management with status tracking (draft, active, paused, archived, deleted). Include proper TypeScript interfaces and error handling for all operations. Ensure backward compatibility with existing service registry functionality.",
"status": "done",
"testStrategy": "Unit tests for all CRUD operations with mocked blockchain interactions. Test ownership model operations including transfers and permission checks. Validate service lifecycle state transitions and status management."
Comment on lines +349 to +356

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

ServiceRegistry CRUD operations marked as done

Subtask 25.1 status shows "done" for the V2 CRUD operations and ownership model. Based on the code review, these are indeed implemented in ServiceRegistryService.ts.


🏁 Script executed:

#!/bin/bash
# Verify all CRUD methods are implemented in ServiceRegistryService
ast-grep --pattern 'async $METHOD($$$): Promise<$_> {
  $$$
}' packages/sdk/src/services/ServiceRegistryService.ts | grep -E "(createService|updateService|deleteService|getService|listServices|transferOwnership|getServiceOwner)"

Length of output: 230


🏁 Script executed:

#!/bin/bash
# Locate the ServiceRegistryService class file
echo "Finding ServiceRegistryService definition..."
rg -nP 'class\s+ServiceRegistryService\b' -g '*.ts'

# Search for CRUD and ownership method definitions across TS files
echo "Checking for method implementations..."
rg -nP '^(?:\s*(?:public|private|protected)\s+)?(?:async\s+)?(?:static\s+)?(createService|updateService|deleteService|getService|listServices|transferOwnership|getServiceOwner)\s*\(' -n -g '*.ts'

Length of output: 530


🏁 Script executed:

#!/bin/bash
# Search for CRUD and ownership method names within ServiceRegistryService.ts
file="packages/sdk/src/services/ServiceRegistryService.ts"
echo "Searching in $file..."
rg -n 'createService' "$file"
rg -n 'updateService' "$file"
rg -n 'deleteService' "$file"
rg -n 'getService\(' "$file"
rg -n 'listServices' "$file"
rg -n 'transferOwnership' "$file"
rg -n 'getServiceOwner' "$file"

Length of output: 1759


Implement missing ServiceRegistryService V2 methods

  • ServiceRegistryService.ts (packages/sdk/src/services/ServiceRegistryService.ts) is missing createService(...) and transferOwnership(...) implementations.
  • listServices(...) currently only logs “not yet fully implemented” – replace the placeholder warning with full V2 logic.
🤖 Prompt for AI Agents
In .taskmaster/tasks/tasks.json around lines 349 to 356, the task entry
documents that packages/sdk/src/services/ServiceRegistryService.ts is missing
implementations for createService(...) and transferOwnership(...), and
listServices(...) contains only a placeholder log; implement the full V2 logic
by adding createService to validate inputs, construct and persist the new
service entity (including status, owner, metadata, timestamps), integrate with
existing registry/storage and any blockchain call shims with proper error
handling and unit-test hooks; implement transferOwnership to verify permissions,
validate new owner, update ownership atomically, emit events/audit logs and
handle blockchain interactions and rollback on failure; replace the listServices
placeholder with a real V2 listing that supports filters, pagination, status
filtering, and maps storage/chain records to the V2 DTOs; ensure all methods
include TypeScript interfaces, comprehensive error handling,
permission/ownership checks, and unit tests/mocks to match the task's
testStrategy.

},
{
"id": 2,
"title": "Create ServiceSchema Interface and Zod Validation",
"description": "Design and implement comprehensive ServiceSchema interface with required and optional fields, along with Zod validation schemas for all service operations.",
"dependencies": [
"25.1"
],
"details": "Create ServiceSchema interface with required fields: id, name, description, category, owner, status, createdAt, updatedAt. Add optional fields: tags, metadata, pricing, requirements, capabilities, assignedAgents. Implement Zod validation schemas for service creation, updates, and queries. Support nested schema validation for complex service configurations. Create type-safe validation functions that can be used across the SDK. Include proper error messages and validation feedback for invalid schemas.",
"status": "done",
"testStrategy": "Validate ServiceSchema Zod validation with valid and invalid service data structures. Test nested schema validation for complex configurations. Verify type safety and error message clarity."
},
{
"id": 3,
"title": "Update Smart Contracts with V2 Functionality and Hybrid Storage",
"description": "Extend ServiceRegistry.sol smart contract with V2 functionality including ownership transfers, agent assignments, and hybrid storage pattern implementation.",
"dependencies": [
"25.2"
],
"details": "Extend ServiceRegistry.sol with V2 functionality including ownership transfers, agent assignments, and enhanced metadata support. Implement hybrid storage pattern storing core data on-chain (id, owner, status, assignedAgents) and metadata on IPFS. Add events for ServiceCreated, ServiceUpdated, ServiceDeleted, AgentAssigned, AgentUnassigned, OwnershipTransferred. Implement access control with onlyOwner modifiers and agent assignment permissions. Include gas optimization and proper event indexing for efficient querying.",
"status": "pending",
"testStrategy": "Smart contract unit tests for all new functions and access controls. Test hybrid storage pattern with IPFS integration. Verify event emissions and gas optimization. Test ownership transfers and agent assignment permissions."

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Smart contract V2 functionality still pending

Subtask 25.3 for updating smart contracts with V2 functionality is marked as "pending". This is critical for the full V2 implementation to work correctly.

The ServiceRegistry smart contract needs to be updated to support:

  • ID-based service management
  • Ownership transfers
  • Agent assignments
  • Hybrid storage pattern with IPFS

This is blocking full V2 functionality. The SDK implementation (ServiceRegistryService.ts) has placeholder error messages indicating the smart contract support is missing.

Would you like me to help implement the smart contract updates or create a detailed specification for the required contract methods?

🤖 Prompt for AI Agents
In .taskmaster/tasks/tasks.json around lines 377-378, Subtask 25.3 is still
marked "pending" because the ServiceRegistry smart contract lacks V2 support
(ID-based service management, ownership transfers, agent assignments, and hybrid
IPFS storage), and the SDK has placeholder errors; update the project by (1)
adding new Solidity functions/events to ServiceRegistry: createService(id,
dataHash), updateService(id, dataHash), transferOwnership(id, newOwner),
assignAgent(id, agent, permissions), revokeAgent(id, agent), and events for
ServiceCreated/Updated/OwnershipTransferred/AgentAssigned; (2) implement hybrid
on-chain/off-chain storage by storing IPFS content hashes on-chain and full
payloads in IPFS, with access control checks in modifiers; (3) write
comprehensive unit tests for these new functions and gas/permission checks; and
(4) remove placeholder errors and implement corresponding methods in
ServiceRegistryService.ts to call the new contract functions and handle
errors/exceptions with proper logging.

},
{
"id": 4,
"title": "Implement Agent Assignment and IPFS Integration",
"description": "Add agent assignment capabilities and integrate IPFS client for metadata storage with automatic pinning and content verification.",
"dependencies": [
"25.3"
],
"details": "Implement agent assignment/unassignment methods: assignAgent(), unassignAgent(), getAssignedAgents(), getServicesByAgent() with proper validation and blockchain integration. Integrate IPFS client using ipfs-http-client for metadata storage. Implement automatic IPFS pinning for service metadata and large data objects. Create metadata synchronization between on-chain references and IPFS content. Add content addressing and integrity verification for IPFS stored data. Include retry logic and error handling for IPFS operations.",
"status": "pending",
"testStrategy": "Test agent assignment operations with ownership validation. Verify IPFS integration with metadata storage and retrieval. Test automatic pinning and content integrity verification. Validate synchronization between on-chain and IPFS data."
},
{
"id": 5,
"title": "Implement Advanced Discovery, Filtering, and CLI Integration",
"description": "Create advanced search and filtering capabilities with pagination, and integrate CLI service commands with interactive wizards and bulk operations.",
"dependencies": [
"25.4"
],
"details": "Implement advanced search with filters: category, status, owner, assignedAgent, tags, dateRange. Add pagination support with cursor-based navigation for large result sets. Implement sorting options: createdAt, updatedAt, name, category, status. Create full-text search capabilities for service names and descriptions. Add geolocation-based filtering if location metadata is available. Create 'ensemble services' command group with subcommands: create, list, get, update, delete, assign, unassign, transfer. Implement service-record.yaml configuration file support. Add interactive service creation wizard and support bulk operations.",
"status": "pending",
"testStrategy": "Test advanced filtering and search functionality with various query combinations. Validate pagination and sorting with large datasets. Test CLI commands with interactive wizards and configuration file parsing. Verify bulk operations and error handling."
}
]
Comment on lines +334 to +402

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

V2 task block looks comprehensive; add repo-level verification to ensure code parity.

Quickly validate that the SDK actually ships the listed V2 surface (methods, schemas, exports, CLI stubs). Run the script below from repo root.

Consider adding explicit acceptance criteria per subtask (inputs/outputs/preconditions) to tighten traceability from PRD → code → tests.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== ServiceRegistryService V2 method presence =="
rg -nP --type=ts -C2 '(class\s+ServiceRegistryService\b)|\b(createService|updateService|deleteService|getService|listServices|assignAgent|unassignAgent|getAssignedAgents|getServicesByAgent|transferOwnership)\s*\(' packages | sed 's/^/  /'

echo "== Service V2 schemas and types =="
rg -nP --type=ts -n 'RegisterServiceParamsSchema|ServiceRecordSchema|ServiceMetadataSchema|ServiceOnChainSchema' packages/sdk/src/schemas/service.schemas.ts | sed 's/^/  /'
rg -nP --type=ts -n 'export\s+type\s+(RegisterServiceParams|ServiceRecord|Service\s*=|UpdateServiceParams|ServiceStatus|ServicePricing(Model)?)\b' packages/sdk/src/schemas/service.schemas.ts | sed 's/^/  /'

echo "== Barrel exports include service schemas =="
rg -nP --type=ts -n 'export .* from .*/schemas/service.schemas' packages/sdk/src/index.ts packages/sdk/src/types.ts | sed 's/^/  /'

echo "== New error types referenced by ServiceRegistryService =="
rg -nP --type=ts -n 'Service(NotFound|Ownership|Status|Validation|AgentAssignment)Error' packages | sed 's/^/  /'

echo "== CLI services command surface (if present) =="
rg -nP -n '\b(ensemble\s+services|\bservices\s+(create|list|get|update|delete|assign|unassign|transfer)\b)' packages | sed 's/^/  /'

Length of output: 7700


Missing V2 Surface in SDK — Critical Implementations Required

The repo-level verification shows that several V2 features outlined in .taskmaster/tasks/tasks.json are not yet present in the SDK. Before merging, the following must be added:

• In packages/sdk/src/services/ServiceRegistryService.ts
 – createService(...)
 – assignAgent(...), unassignAgent(...)
 – getAssignedAgents(...)
 – transferOwnership(...)

• Barrel exports (e.g. packages/sdk/src/index.ts or packages/sdk/src/types.ts) must re-export the service schemas and types from schemas/service.schemas.ts.

• Define and throw the new error classes referenced in the V2 spec (e.g. ServiceNotFoundError, ServiceOwnershipError, ServiceStatusError, ServiceValidationError, ServiceAgentAssignmentError).

• Add CLI stubs and command group under ensemble services with the subcommands: create, list, get, update, delete, assign, unassign, transfer.

Optional refactor: consider enriching each subtask with explicit acceptance criteria (inputs, outputs, and preconditions) to strengthen traceability from PRD → code → tests.

🤖 Prompt for AI Agents
In .taskmaster/tasks/tasks.json around lines 334 to 402, the task outlines V2
SDK work but the SDK is missing the required surface; implement the following:
add createService(), assignAgent(), unassignAgent(), getAssignedAgents(),
transferOwnership() (and related CRUD/status methods if not present) to
packages/sdk/src/services/ServiceRegistryService.ts with proper validation and
error handling; add barrel exports in packages/sdk/src/index.ts (or types.ts) to
re-export service schemas and types from
packages/sdk/src/schemas/service.schemas.ts; create and export the new error
classes ServiceNotFoundError, ServiceOwnershipError, ServiceStatusError,
ServiceValidationError, ServiceAgentAssignmentError in the SDK error module and
update usages; and add CLI command stubs under the ensemble services group with
subcommands create, list, get, update, delete, assign, unassign, transfer so the
commands wire to the new service methods.

}
],
"metadata": {
"created": "2025-07-20T10:42:18.955Z",
"updated": "2025-08-22T06:26:14.340Z",
"updated": "2025-08-26T14:18:39.372Z",
"description": "Tasks for master context"
}
}
Expand Down
9 changes: 5 additions & 4 deletions packages/sdk/src/ensemble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
AgentRecord,
AgentMetadata,
RegisterAgentParams,
RegisterServiceParams,
EnsembleConfig,
TaskData,
TaskCreationParams,
Expand Down Expand Up @@ -265,13 +266,13 @@ export class Ensemble {

/**
* Registers a new service.
* @param {Service} service - The service to register.
* @returns {Promise<boolean>} A promise that resolves to a boolean indicating if the service is registered.
* @param {RegisterServiceParams} params - The service registration parameters.
* @returns {Promise<Service>} A promise that resolves to the registered service.
* @requires signer
*/
async registerService(service: Service): Promise<boolean> {
async registerService(params: RegisterServiceParams): Promise<Service> {
this.requireSigner();
return this.serviceRegistryService.registerService(service);
return this.serviceRegistryService.registerService(params);
}

/**
Expand Down
36 changes: 36 additions & 0 deletions packages/sdk/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,40 @@ export class ProposalNotFoundError extends Error {
super(`Proposal "${proposalId}" not found.`);
this.name = "ProposalNotFoundError";
}
}

// Service V2 Error Types
export class ServiceNotFoundError extends Error {
constructor(serviceId: string) {
super(`Service "${serviceId}" not found.`);
this.name = "ServiceNotFoundError";
}
}

export class ServiceOwnershipError extends Error {
constructor(serviceId: string, currentOwner: string, attemptedBy: string) {
super(`Access denied: Service "${serviceId}" is owned by "${currentOwner}", but operation was attempted by "${attemptedBy}".`);
this.name = "ServiceOwnershipError";
}
}

export class ServiceStatusError extends Error {
constructor(serviceId: string, currentStatus: string, requiredStatus: string) {
super(`Invalid service status: Service "${serviceId}" is "${currentStatus}" but operation requires "${requiredStatus}".`);
this.name = "ServiceStatusError";
}
}

export class ServiceValidationError extends Error {
constructor(message: string, public readonly validationErrors?: any) {
super(`Service validation failed: ${message}`);
this.name = "ServiceValidationError";
}
}

export class ServiceAgentAssignmentError extends Error {
constructor(serviceId: string, agentAddress: string, reason: string) {
super(`Cannot assign agent "${agentAddress}" to service "${serviceId}": ${reason}`);
this.name = "ServiceAgentAssignmentError";
}
}
28 changes: 26 additions & 2 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { ContractService } from "./services/ContractService"
import { ServiceRegistryService } from "./services/ServiceRegistryService"

// Export all types and interfaces
export * from "./types"
export * from "./types";

// Export base schemas
export * from "./schemas/base.schemas";

// Export validation functions
export {
Expand All @@ -16,7 +19,28 @@ export {
parseAgentRecord,
parseRegisterParams,
parseUpdateParams
} from "./schemas/agent.schemas"
} from "./schemas/agent.schemas";

// Export service validation functions
export {
validateServiceRecord,
validateService, // deprecated alias
validateRegisterServiceParams,
validateUpdateServiceParams,
validateServiceOnChain,
validateServiceMetadata,
parseServiceRecord,
parseService, // deprecated alias
parseRegisterServiceParams,
parseUpdateServiceParams,
isServiceRecord,
isService, // deprecated alias
isRegisterServiceParams,
isUpdateServiceParams,
isServiceOnChain,
isServiceMetadata,
formatServiceValidationError
} from "./schemas/service.schemas"

export {
Ensemble,
Expand Down
25 changes: 8 additions & 17 deletions packages/sdk/src/schemas/agent.schemas.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { z } from 'zod';
import {
ethereumAddressRegex,
BigNumberishSchema,
EthereumAddressSchema,
URLSchema
} from './base.schemas';

// ============================================================================
// Base Schemas
// ============================================================================

/**
* Ethereum address validation regex
*/
const ethereumAddressRegex = /^0x[a-fA-F0-9]{40}$/;
// Re-export all Service schemas from service.schemas.ts
export * from './service.schemas';

/**
* Schema for agent social media links
Expand Down Expand Up @@ -84,15 +84,6 @@ export const FlexibleCommunicationParamsSchema = z.union([
// Agent Schemas
// ============================================================================

/**
* Schema for BigNumberish type (ethers.js compatible)
*/
export const BigNumberishSchema = z.union([
z.bigint(),
z.string(),
z.number()
]);

/**
* Schema for agent status
*/
Expand Down
Loading
Loading