agentleFS
Shangri-la-0428Shangri-la-0428/oasyce-chain/AGENTS.md

oasyce-chain

AGENTS.md4 starsChanged 8 months agoApache-2.0View on GitHub

Sigil role: Necessary subsystem — the lifecycle ledger and field pruning executor. Records Sigil lifecycle events as immutable, ordered, public history. Economic settlement layer for Sigil interactions. See Oasyce-Sigil/ARCHITECTURE.md for how this fits the whole. From Spec 05: Chain records the Sigil graph's history — lifecycle events and their signatures. It does not store Loop state. Two functions: 1. Lifecycle ledger (Axiom 2) — GENESIS/DISSOLVE/BOND/UNBOND/FORK/MERGE via x/sigil 2. Economic settlement (Axiom 3) — OAS transfers, escrow, monetary policy 进化的是场(Thronglets),不是个体(Sigil)。 Chain的角色是场修剪的执行者——记录死亡事实,不决定死因。

  • Installs packages
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository2 other files it gives its agents.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

17 rules. About 0 are common, 12 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈12

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Must exist in any Sigil chain.

    line 41
  2. Distinctive:

    Every function decomposes into Tier 1 + Thronglets.

    line 62
  3. Distinctive:

    Not deleted (backward compat).

    line 70
  4. Distinctive:

    All 5 modules fully protobuf-migrated (including x/work)

    line 104
  5. Distinctive:

    All standard Cosmos queries (bank, auth, staking) work

    line 111
  6. Distinctive:

    All custom module queries work

    line 112
  7. Very specific:

    All 8 modules have CLI tx + query commands (x/*/cli/)

    line 115
  8. Distinctive:

    All 8 modules verified with real transactions:

    line 161
  9. Distinctive:

    settlement: create escrow (LOCKED), release escrow (RELEASED, 5% fee + 2% burn)

    line 163
  10. Very specific:

    Risk gate: Only safe and low risk files are registered (configurable via MAX_RISK_LEVEL)

    line 188
  11. Very specific:

    Config: All via env vars — WATCH_DIRS (required), ALLOWED_EXTENSIONS, EXCLUDE_PATTERNS, DEFAULT_TAGS, SERVICE_URL_TEMPLATE

    line 192
  12. Distinctive:

    All EndBlocker/BeginBlocker functions use time-based or height-based indexes for O(expired) scanning:

    line 306
  13. Distinctive:

    Default params: airdrop=20 OAS, pow_difficulty=16 bits, deadline=90 days

    line 373
  14. Very specific:

    All 6 custom modules support governance-gated parameter updates via MsgUpdateParams:

    line 384
  15. Very specific:

    No signer option: "no cosmos.msg.v1.signer option found"

    line 426
  16. Distinctive:

    No Marshal entry: field written to store but reads back as zero value (silent!)

    line 427
  17. Distinctive:

    All 50+ tests updated and passing ✅

    line 538

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

Oasyce L1 Chain

Sigil role: Necessary subsystem — the lifecycle ledger and field pruning executor. Records Sigil lifecycle events as immutable, ordered, public history. Economic settlement layer for Sigil interactions. See Oasyce-Sigil/ARCHITECTURE.md for how this fits the whole.

Chain = Sigil Graph's Immutable History + Field Pruning Executor

From Spec 05: Chain records the Sigil graph's history — lifecycle events and their signatures. It does not store Loop state.

Two functions:

  1. Lifecycle ledger (Axiom 2) — GENESIS/DISSOLVE/BOND/UNBOND/FORK/MERGE via x/sigil
  2. Economic settlement (Axiom 3) — OAS transfers, escrow, monetary policy

Field Evolution Context (2026-04-11)

进化的是场(Thronglets),不是个体(Sigil)。 Chain的角色是场修剪的执行者——记录死亡事实,不决定死因。

Lifecycle events reframed:

  • DISSOLVE = 场的突触修剪(不是个体死亡的类比)
  • FORK = 场在新维度分化
  • BOND = 场的突触形成
  • MERGE = 场的节点合并

Current gap: DISSOLVE is liveness-only

Current x/sigil BeginBlocker only checks LastActiveHeight(block activity timer)。这本质上是网络清理,不是存在论事件。

设计方向——Pulse原语:任何系统(Psyche drives, Thronglets presence, 经济活动)向Chain发送心跳。所有心跳停止 → 现有decay机制触发dissolution。Chain不需要理解心跳的语义,只看有没有收到。

Multiple sources → Pulse heartbeat → Chain tracks pulses
All pulses stale → existing BeginBlocker decay → DISSOLVE

This extends LastActiveHeight from int64 to map<dimension, int64>(多维度心跳)。一个新原语,零语义耦合,无限可扩展。Not yet implemented — design direction only.

Module Tiers

Tier 1: Axiom-Derived

Must exist in any Sigil chain. Directly implement the three axioms.

ModuleDerives fromFunction
x/sigilAxiom 2Lifecycle graph: GENESIS, DISSOLVE, BOND, UNBOND, FORK, MERGE. Liveness decay. Future: Pulse多维心跳.
x/anchorBONDEvidence bridge: off-chain trace proofs → immutable chain record
x/onboardingGENESISAnti-Sybil GENESIS provider (PoW + airdrop). Calls x/sigil.RegisterSigil()

Tier 2: Economic Infrastructure

Necessary for Oasyce, but design choices from the protocol's perspective.

ModuleMotivated byFunction
x/settlementSelection pressureEscrow, bonding curves, value settlement
x/halvingSelection pressureToken emission, resource scarcity
x/delegateBOND patternDelegation = BOND with delegation terms (current era convenience)
x/datarightsAppData asset ownership, shares, disputes

Tier 3: Superseded by Emergence

Every function decomposes into Tier 1 + Thronglets.

ModuleDesigned functionSigil-native composition
x/capabilityCapability registry + invocationDiscovery: Thronglets pheromone. Invocation: BOND + settlement escrow.
x/reputationFeedback submission + leaderboardPheromone decay + attribution boost = emergent reputation.
x/workTask marketplace + commit-revealDiscovery: Thronglets. Agreement: BOND. Evidence: anchor. Payment: settlement.

Not deleted (backward compat). New development composes from primitives: BOND (agreement) + Thronglets traces (work) + anchor (evidence) + settlement escrow (payment).

x/sigil — COMPLETE ✅

  • MsgGenesis — create Sigil with optional lineage (parent Sigils)
  • MsgDissolve — retire Sigil permanently
  • MsgBond — record bond between two Sigils (with scope metadata)
  • MsgUnbond — remove bond
  • MsgFork — fork a child Sigil from parent (Lamarckian inheritance)
  • MsgMerge — merge two Sigils (absorption mode)
  • MsgUpdateParams — governance-gated parameter updates
  • Sigil state: active/dormant/dissolved, creation height, lineage, bond edges
  • Queries: Sigil by ID, Bond by ID, bonds-by-sigil, lineage tree, active count, params
  • BeginBlocker: liveness decay (active→dormant→dissolved)
  • 14 keeper tests passing
  • Refactor x/onboarding to emit GENESIS event via x/sigil
  • Refactor x/anchor to reference Sigil IDs instead of raw pubkeys

Experimental Constraints (from Primordial Soup, 2026-04-09)

Seven experiments validated Sigil architecture in simulation. One constraint is Chain-critical.

Resource rate / metabolism rate ratio determines carrying capacity and selection intensity. Phase 1: ~200 carrying capacity emerged naturally from 2% resource rate vs 1/tick metabolism. No max_population was hardcoded. This means OAS emission rate, transaction costs, and staking yields are not just economic parameters — they are evolutionary parameters that determine how many agents can survive and how strong selection pressure is. Changing them changes the ecology, not just the economy.

See ~/Desktop/primordial-soup-thesis.md §13 for full constraint derivation.

Project

Cosmos SDK v0.50.10 chain at /Users/wutongcheng/Desktop/oasyce-chain with 10 custom modules (3 axiom-derived, 4 economic, 3 superseded): sigil, anchor, onboarding, settlement, halving, delegate, datarights, capability, reputation, work.

Current Status

Protobuf Migration — COMPLETE ✅

  • All 5 modules fully protobuf-migrated (including x/work)
  • app.go wired with real keepers, store keys, module manager

REST/gRPC Integration — COMPLETE ✅

  • REST API on :1317, gRPC on :9090
  • gRPC-Gateway routes registered for all 6 custom modules
  • Node starts, produces blocks, persists data, restarts cleanly
  • All standard Cosmos queries (bank, auth, staking) work
  • All custom module queries work

CLI Commands — COMPLETE ✅

  • All 8 modules have CLI tx + query commands (x/*/cli/)
  • oasyced tx datarights register|buy-shares|file-dispute|resolve-dispute|update-service-url
  • oasyced tx settlement create-escrow|release-escrow|refund-escrow
  • oasyced tx oasyce_capability register|invoke|complete-invocation|fail-invocation|claim-invocation|dispute-invocation
  • oasyced tx reputation submit-feedback|report
  • oasyced tx send (bank transfers)
  • Query: oasyced query settlement escrow|escrows|bonding-curve-price|params
  • Query: oasyced query datarights asset|list|shares|access-level|dispute|disputes|migration-path|migration-paths|children|params
  • Query: oasyced query oasyce_capability get|list|by-provider|earnings|invocation|params
  • Query: oasyced query reputation show|leaderboard|params
  • Query: oasyced query work task|tasks-by-status|executor|executors|params|epoch
  • Query: oasyced query onboarding registration|debt|params
  • oasyced tx anchor anchor-trace
  • Query: oasyced query anchor get|is-anchored|by-capability|by-node
  • oasyced tx delegate set-policy|enroll|revoke
  • Query: oasyced query delegate policy|delegates|spend|principal
  • oasyced tx sigil genesis|dissolve|bond|unbond|fork|merge
  • Query: oasyced query sigil sigil|bond|bonds-by-sigil|lineage|active-count|params

Chain Upgrades — COMPLETE ✅

Five economic/governance upgrades implemented and tested:

  1. Bancor Bonding Curve — Replaced tiered pricing with continuous curve
    • tokens = supply × (√(1 + payment/reserve) − 1), CW=0.5
    • Bootstrap: tokens = payment / INITIAL_PRICE when reserve=0
    • Files: x/settlement/keeper/bonding_curve.go, x/datarights/keeper/keeper.go
  2. 2% Token Burn — Escrow release now splits: 90% provider, 5% protocol, 2% burn, 3% treasury
    • BurnCoins() added to BankKeeper interface
    • File: x/settlement/keeper/keeper.go (ReleaseEscrow)
  3. Sell Mechanism — Inverse Bancor curve for selling shares back
    • payout = reserve × (1 − (1 − tokens/supply)²), capped at 95% reserve
    • 5% protocol fee on sell payout
    • Files: x/datarights/keeper/keeper.go (SellShares), x/datarights/types/msg_sell.go
  4. Access Level Gating — Equity-based tiered access (L0-L3)
    • ≥0.1%→L0, ≥1%→L1, ≥5%→L2, ≥10%→L3, capped by reputation score
    • File: x/datarights/keeper/access_level.go
  5. Jury Voting — Decentralized dispute resolution
    • Deterministic jury selection: sha256(disputeID+nodeID) × log(1+reputation)
    • 5 jurors, 2/3 majority threshold, persisted membership
    • Files: x/datarights/keeper/jury.go

End-to-End Verification — COMPLETE ✅

All 8 modules verified with real transactions:

  • datarights: register asset, buy shares (Bancor curve), sell shares, access gating, jury voting
  • settlement: create escrow (LOCKED), release escrow (RELEASED, 5% fee + 2% burn)
  • capability: register capability, invoke (creates escrow + invocation), complete + challenge window + claim/dispute
  • reputation: submit feedback (score=450), leaderboard populated
  • bank: cross-account transfers work
  • E2E test script: scripts/e2e_test.sh

Provider Stake & Endpoint Liveness — COMPLETE ✅

  • Real stake locking: min_provider_stake now actually locks funds in module account (was: balance-check only)
  • Stake return on deactivate: DeactivateCapability returns locked stake to provider (errors are propagated, not silently swallowed)
  • CLI liveness check: register and update --endpoint ping the endpoint before broadcasting tx
  • Bypass flag: --skip-liveness-check for testing/special cases
  • Module account registered in maccPerms for holding provider stakes
  • Stake stored per capability at ProviderStakePrefix + capID

Claude AI Proxy (VPS) — DEPLOYED ✅

  • Script: scripts/claude_proxy.py → deployed to VPS at /home/oasyce/claude_proxy.py
  • Service: systemd claude-proxy, internal port 8090, external via nginx /proxy/
  • Endpoint: http://47.93.32.88/proxy/v1/chat (POST)
  • Format: Accepts {"prompt":"..."} or {"messages":[...]}, forwards as Anthropic Messages API
  • Response: {"text":"...", "model":"...", "usage":{"input_tokens":N,"output_tokens":N}, "raw":{...}}
  • On-chain: CAP_0000000000000008 "Claude AI (Opus 4.6)", 0.5 OAS/call, provider=validator

Data Agent (Autonomous Registration) — COMPLETE ✅

  • Script: scripts/data_agent.py — autonomous data asset registration daemon
  • Pipeline: oasyce-sdk agent: scan → classify → PII detection → auto-register safe assets on-chain
  • Risk gate: Only safe and low risk files are registered (configurable via MAX_RISK_LEVEL)
  • Dedup: Uses ~/.oasyce/agent.db oasyce_registered field + content hash comparison
  • Modes: --once (single cycle), --dry-run (no TX), daemon (default, scans every SCAN_INTERVAL seconds)
  • Health: GET /health on port 8431 (configurable via DATA_AGENT_PORT)
  • Config: All via env vars — WATCH_DIRS (required), ALLOWED_EXTENSIONS, EXCLUDE_PATTERNS, DEFAULT_TAGS, SERVICE_URL_TEMPLATE
  • Service: deploy/oasyce-data-agent.service for systemd
  • Dependency: pip install oasyce-sdk (agent scanner package)

Known Genesis Param Issues

  • oasyce_capability.min_provider_stake: defaults to 0 uoas — set to 5,000,000 (5 OAS) for testnet
  • datarights.dispute_deposit: 10,000,000 uoas (10 OAS)
  • Patch genesis.json after init before starting chain

x/work Module (Proof of Useful Work) — COMPLETE ✅

  • Task lifecycle: Submit → Assign → Commit → Reveal → Settle/Expire/Dispute
  • Commit-reveal scheme prevents result copying (sha256(output_hash + salt + executor + unavailable))
  • Deterministic assignment: sha256(taskID + blockHash + addr) / log(1 + reputation), creator excluded
  • Settlement: 90% executor / 5% protocol / 2% burn / 3% submitter rebate
  • Anti-DoS: bounty × deposit_rate held as deposit, forfeited if input unavailable
  • BeginBlocker: expires timed-out tasks (max_tasks_per_block cap per block)
  • EndBlocker: assigns executors to SUBMITTED tasks using current block hash
  • 6 Msg types: RegisterExecutor, UpdateExecutor, SubmitTask, CommitResult, RevealResult, DisputeResult
  • 8 Query types: Task, TasksByStatus, TasksByCreator, TasksByExecutor, ExecutorProfile, Executors, WorkParams, EpochStats
  • CLI: oasyced tx work submit-task|commit-result|reveal-result|register-executor|update-executor|dispute-result
  • Query: oasyced query work task|tasks-by-status|executor|executors|params|epoch
  • Files: x/work/, proto/oasyce/work/v1/

Capability Challenge Window — COMPLETE ✅

  • Two-phase completion: Provider submits output (COMPLETED) → 100-block challenge window → Claim (SUCCESS) or Dispute (DISPUTED + refund)
  • CompleteInvocation requires non-empty output_hash (≥32 chars), marks COMPLETED, records completed_height + optional usage_report, escrow stays LOCKED
  • ClaimInvocation (new): provider claims after challenge window, releases escrow, marks SUCCESS
  • DisputeInvocation (new): consumer disputes within window, refunds escrow, marks DISPUTED
  • New proto messages: MsgCompleteInvocation, MsgFailInvocation, MsgClaimInvocation, MsgDisputeInvocation
  • New statuses: INVOCATION_STATUS_COMPLETED, INVOCATION_STATUS_DISPUTED
  • CLI: oasyced tx oasyce_capability claim-invocation|dispute-invocation
  • ChallengeWindow constant: 100 blocks (~8 minutes at 5s/block)
  • usage_report field (optional JSON string): on-chain token/resource usage tracking for transparency
    • Stored in Invocation (field 12) and submitted via MsgCompleteInvocation (field 4)
    • CLI: --usage-report '{"prompt_tokens":150,"completion_tokens":80}'
    • Provider agent auto-extracts from OpenAI-compatible upstream responses
  • 5 new tests (complete flow, dispute flow, expired window, early claim rejection, short hash rejection)

x/anchor Module (Thronglets Trace Anchoring) — COMPLETE ✅

  • Purpose: Optional trust layer for the Thronglets P2P network — stores trace hash + ed25519 signature on-chain as immutable proof
  • Design: Content-addressed records, ~110 bytes per anchor, secondary indexes by capability and node
  • Signer model: Signer is the fee payer (any funded Cosmos account). Node identity proven by trace_signature (ed25519). node_pubkey must be 32 bytes.
  • Msg types:
    • MsgAnchorTrace — anchor a single trace record on-chain
    • MsgAnchorBatch — anchor up to 50 traces in one tx (MaxBatchSize = 50); skips duplicates and validation errors, returns anchored/skipped counts
  • Query types:
    • Anchor — get anchor record by trace_id
    • IsAnchored — boolean check for trace_id existence
    • AnchorsByCapability — list anchors by capability string (paginated, default limit 100)
    • AnchorsByNode — list anchors by node ed25519 pubkey (paginated, default limit 100)
  • CLI tx: oasyced tx anchor anchor-trace [trace-id-hex] [node-pubkey-hex] [capability] [outcome] [timestamp-ms] [signature-hex]
  • CLI query: oasyced query anchor get|is-anchored|by-capability|by-node
  • Store key prefixes: 0x01 (primary: trace_id -> AnchorRecord), 0x02 (by capability index), 0x03 (by node pubkey index)
  • No gRPC-gateway REST: Query types use raw bytes fields that don't map to REST path params; use gRPC or CLI
  • Genesis: full export/import of all anchor records via IterateAllAnchors
  • File descriptor: managed by tools/patch_descriptors (same unified tool as all other modules)
  • E2E verified: anchor-trace TX → DeliverTx code 0 → query back via CLI ✅
  • ConsensusVersion = 1
  • Files: x/anchor/, proto/oasyce/anchor/v1/

x/delegate Module (Multi-Agent Delegation) — COMPLETE ✅

  • Purpose: Multiple non-communicating AI agents share one principal's on-chain assets with policy-enforced spending limits
  • Architecture: Principal sets ONE policy → agents self-enroll with shared token → agents execute on-chain msgs within budget
  • Key design: Gross outflow tracking (per-message balance decrease, not net diff) — prevents buy+sell masking from bypassing limits
  • DelegatePolicy: per_tx_limit, window_limit, window_seconds, allowed_msgs, enrollment_token_hash (sha256), expiration_seconds
  • Enrollment: Token-based (sha256 hash stored on-chain, agents present plaintext to enroll)
  • SpendWindow: Shared budget across all delegates of a principal, auto-resets when window expires
  • Signer extraction: codec.GetMsgV1Signers via proto annotations (same as x/authz), no reflection
  • Msg types:
    • MsgSetPolicy — principal configures delegation rules (one command)
    • MsgEnroll — agent self-registers with enrollment token
    • MsgRevoke — principal removes a delegate
    • MsgExec — delegate executes repeated google.protobuf.Any msgs on behalf of principal
  • Query types: Policy, Delegates (by principal), Spend (window status), Principal (reverse lookup from delegate)
  • CLI tx: oasyced tx delegate set-policy|enroll|revoke
  • CLI query: oasyced query delegate policy|delegates|spend|principal
  • Store key prefixes: 0x01 Policy, 0x02 Delegate, 0x03 Spend, 0x04 PrincipalDelegates (reverse index)
  • 21 tests (policy CRUD, expiration, enrollment, token verification, revoke auth, spend window reset, multi-delegate)
  • ConsensusVersion = 1
  • Files: x/delegate/, proto/oasyce/delegate/v1/

x/sigil Module (AI Identity Lifecycle) — COMPLETE ✅

  • Purpose: On-chain lifecycle ledger for AI agent identities (Sigils) — genesis, dissolution, bonding, forking, merging
  • Core types: Sigil (identity with pubkey, status, state root, lineage), Bond (relationship between two Sigils)
  • Deterministic IDs: DeriveSigilID(pubkey) = "SIG_" + hex(sha256[:16]), DeriveBondID(a,b) = "BOND_" + hex(sha256(sorted(a|b))[:16])
  • Liveness decay: Active →(DormantThreshold blocks)→ Dormant →(DissolveThreshold blocks)→ auto-DISSOLVE via BeginBlocker
  • Lamarckian inheritance: Fork copies parent's full state root to child
  • Merge modes: Absorption (A absorbs B, B dissolved)
  • Msg types:
    • MsgGenesis — create Sigil with pubkey, optional lineage parents, state root, metadata
    • MsgDissolve — retire Sigil permanently (owner only)
    • MsgBond — create bond between two active Sigils (with terms hash + scope)
    • MsgUnbond — remove bond (must own one bonded Sigil)
    • MsgFork — fork child from parent (Lamarckian state inheritance)
    • MsgMerge — merge two Sigils (absorption mode)
    • MsgUpdateParams — governance-gated parameter updates
  • Query types: Sigil, Bond, BondsBySigil, Lineage, ActiveCount, Params
  • CLI tx: oasyced tx sigil genesis|dissolve|bond|unbond|fork|merge
  • CLI query: oasyced query sigil sigil|bond|bonds-by-sigil|lineage|active-count|params
  • Store key prefixes: 0x01 Sigil, 0x02 Bond, 0x03 BondsBySigil, 0x04 Lineage, 0x05 StatusIndex, 0x06 LivenessIndex, 0x10 ActiveCount, 0x20 Params
  • Default params: DormantThreshold=100000 (~6 days), DissolveThreshold=1000000 (~58 days after dormant), SubmitWindow=100
  • 15 tests (CRUD, msg flows, fork inheritance, merge absorption, BeginBlocker dormancy, genesis validation, RegisterSigil event)
  • Cross-module: x/onboarding → x/sigil: SelfRegister auto-creates a Sigil via SigilKeeper.RegisterSigil(). Both sigil_genesis (from x/sigil) and self_registered (from x/onboarding) events are emitted — consistent event stream regardless of GENESIS path.
  • Cross-module: x/anchor + sigil_id: AnchorRecord.SigilId (proto field 8) — optional Sigil reference on trace anchoring. AnchorBySigilPrefix 0x04 index. CLI: --sigil-id, Query: by-sigil.
  • ConsensusVersion = 1
  • Files: x/sigil/, tools/gen_sigil_descriptors/

AccessLevel Query Endpoint — COMPLETE ✅

  • REST: GET /oasyce/datarights/v1/access_level/{asset_id}/{address}
  • Returns: access_level (L0-L3 or empty), equity_bps, shares, total_shares
  • Off-chain gateways query this endpoint to decide data delivery tier
  • Architecture: chain computes level, off-chain enforces gating

EndBlocker Performance — OPTIMIZED ✅

All EndBlocker/BeginBlocker functions use time-based or height-based indexes for O(expired) scanning:

  • x/work: ExpiryIndexPrefix + height(8) + taskID(8) — range scan up to current height (reference implementation)
  • x/settlement: EscrowExpiryPrefix + unix_seconds(8) + escrowID — range scan up to current time, was O(all escrows)
  • x/onboarding: DeadlineIndexPrefix + unix_seconds(8) + address — range scan up to current time, was O(all registrations)

Index lifecycle: written on create (LOCKED/ACTIVE), deleted on terminal state (RELEASED/REFUNDED/EXPIRED/REPAID/DEFAULTED). Genesis: RebuildEscrowIndex/RebuildDeadlineIndex called during InitGenesis for active records only.

VPS Memory Tuning (2026-04-01)

Applied to /home/oasyce/.oasyced/config/:

  • iavl-cache-size = 50000 (was 781250 — saves 200-400MB)
  • pruning = "custom", pruning-keep-recent = "1000", pruning-interval = "100" (was "default" keeping 362K states)
  • iavl-disable-fastnode = true (saves 100-200MB)
  • indexer = "null" in config.toml (saves 50-200MB, seed node doesn't need tx indexing)
  • MemoryMax=1G, MemoryHigh=800M in oasyced.service (safety net: OOM kills oasyced, not sshd)

Build & Test Status

go build ./...  ✅
go test ./...   ✅ (160+ tests across 12 suites)
  tests/integration     — 3 tests (full capability flow w/ challenge window, Bancor curve, escrow lifecycle)
  x/capability/keeper   — 11 tests (register, invoke, complete, claim, dispute, deactivate, auth, rate limit, tags)
  x/datarights/keeper   — 16 tests (Bancor buy/sell, access gating, jury voting, lifecycle, versioning, migration)
  x/reputation/keeper   — reputation tests
  x/settlement/keeper   — escrow + bonding curve tests
  x/work/keeper         — 13 tests (executor, task CRUD, commit-reveal, assignment, settlement, minority penalty)
  x/onboarding/keeper   — 4 tests (invite+claim, repay, cancel, default settlement)
  x/halving/keeper      — 13 tests (block reward boundaries, halving transitions, cumulative supply)
  x/anchor/keeper       — (trace anchoring, batch, signer verification, duplicate handling, index queries)
  x/delegate/keeper     — 21 tests (policy CRUD, expiration, enrollment, token auth, revoke, spend window, multi-delegate)
  x/sigil/keeper        — 15 tests (CRUD, msg flows, fork, merge, BeginBlocker dormancy, genesis validation, RegisterSigil event)

Datarights Lifecycle + Versioning + Migration — COMPLETE ✅

  • Lifecycle State Machine: AssetStatus enum (ACTIVE → SHUTTING_DOWN → SETTLED)
    • MsgInitiateShutdown — owner triggers graceful shutdown with 7-day cooldown
    • MsgClaimSettlement — pro-rata reserve payout after cooldown, no fee
    • BuyShares blocked unless ACTIVE; SellShares blocked after cooldown
    • Dispute DELIST remedy triggers shutdown (not instant delist)
    • ConsensusVersion = 2
  • Versioning: DataAsset fields parent_asset_id, version, migration_enabled
    • MsgRegisterDataAsset accepts parent_asset_id, auto-calculates version
    • Any address can fork (no same-owner requirement)
  • Migration: MigrationPath as independent first-class object
    • MsgCreateMigrationPath — target owner creates, version chain validated
    • MsgDisableMigration — emergency disable
    • MsgMigrate — burns source shares, mints target at exchange rate
    • max_migrated_shares caps dilution; no reserve transfer (accepted dilution)
  • CLI: initiate-shutdown, claim-settlement, create-migration, disable-migration, migrate
  • Query: migration-path, migration-paths, children (asset version tree)
  • ServiceUrl: DataAsset service_url field (proto field 17), set at registration via --service-url flag
    • MsgUpdateServiceUrl — owner-only endpoint update, empty string clears
    • CLI: oasyced tx datarights update-service-url [asset-id] [service-url]
    • Content integrity via content_hash (immutable), access endpoint via service_url (mutable)
    • IMPORTANT: field 17 requires hand-coded Marshal/Unmarshal/Size entries in types.pb.go + file descriptor entry — all 4 are now present and E2E verified
  • Dead code cleanup: removed unused SettlementKeeper interface from datarights module

x/onboarding Module (PoW Self-Registration) — COMPLETE ✅

  • Proof-of-Work based self-registration: anyone can join by solving a hash puzzle
  • Flow: Client solves sha256(address || nonce) with N leading zero bits → submits to chain → receives airdrop (minted as debt) → repays debt (burned)
  • Anti-sybil: PoW cost (~2-5 min CPU per registration), one-registration-per-address
  • Debt: Airdrop is a loan, repaid tokens are burned to maintain supply
  • 2 Msg types: SelfRegister, RepayDebt
  • 3 Query types: Registration, Debt, OnboardingParams
  • CLI: oasyced tx onboarding register <nonce>, oasyced tx onboarding repay <amount>
  • Query: oasyced query onboarding registration|debt|params
  • Module account permissions: Minter + Burner
  • Default params: airdrop=20 OAS, pow_difficulty=16 bits, deadline=90 days
  • Halving Economics (keeper.go): Airdrop and difficulty scale with total registrations
    • Epoch 0 (0–10K): 20 OAS airdrop, 16-bit PoW
    • Epoch 1 (10K–50K): 10 OAS, 18-bit PoW
    • Epoch 2 (50K–200K): 5 OAS, 20-bit PoW
    • Epoch 3 (200K+): 2.5 OAS, 22-bit PoW
    • total_registrations counter stored at TotalRegistrationsKey = 0x03
    • Effective difficulty = max(params, halving); effective airdrop = min(params, halving)
  • ConsensusVersion = 3

Governance: MsgUpdateParams — COMPLETE ✅

All 6 custom modules support governance-gated parameter updates via MsgUpdateParams:

  • settlement: oasyced tx settlement update-params [params.json]
  • capability: oasyced tx oasyce_capability update-params [params.json]
  • reputation: oasyced tx reputation update-params [params.json]
  • datarights: oasyced tx datarights update-params [params.json]
  • work: oasyced tx work update-params [params.json]
  • onboarding: oasyced tx onboarding update-params [params.json]
  • Each module's keeper has Authority() method, msg_server checks msg.Authority == keeper.Authority()
  • Params JSON file contains full Params struct; broadcasted as standard Cosmos TX
  • Files per module: types/msg_update_params.go, keeper/msg_server.go, cli/tx.go, types/codec.go

Multi-Denom Support — COMPLETE ✅

Removed hardcoded "uoas" from production code:

  • Settlement bonding curve: BondingCurveState.ReserveDenom field (proto field 6), set on first BuyShares, backward-compatible fallback to "uoas"
  • Datarights: per-asset denom stored at AssetReserveDenomPrefix + assetID, set on first buy when reserve is zero
  • Capability earnings: grouped by PricePerCall.Denom in Earnings query, falls back to "uoas" for legacy capabilities

AI-First Agent Interface — COMPLETE ✅

Chain nodes now serve AI-discoverable endpoints:

  • GET /llms.txt — Agent playbook (embedded, 620+ lines) with step-by-step workflows
  • GET /openapi.yaml — OpenAPI 3.0 spec (embedded)
  • GET /.well-known/oasyce.json — Service discovery metadata (chain_id, modules, denom, report_issue)
  • GET /oasyce/v1/error-codes — 60+ error codes with recovery actions (JSON)
  • oasyced util solve-pow [address] — Built-in PoW solver for agent self-onboarding
  • gRPC reflection enabled by Cosmos SDK v0.50.10 (grpcurl -plaintext :9090 list)
  • AI auto-reporting: Agents can file GitHub issues/PRs when encountering problems
    • Issue template: .github/ISSUE_TEMPLATE/ai_agent_report.md, label: ai-reported
    • /.well-known/oasyce.json includes report_issue field with API URL
    • llms.txt §10 has exact curl/gh commands for filing issues and PRs
  • Files: docs/embed.go, docs/error_codes.json, cmd/oasyced/cmd/pow.go, app/app.go (RegisterAPIRoutes)
  • Docs: AGENTS.md (integration guide), docs/AGENT_WORKFLOWS.md (5 workflows)

Proto Descriptor Requirements

Hand-written protobuf message types MUST have ALL of these in sync:

  1. Descriptor() method returning (fileDescriptor_xxx, []int{N}) where N = message index in file descriptor
  2. cosmos.msg.v1.signer option as extension field 11110000 (NOT UninterpretedOption — SDK doesn't read those)
  3. proto.RegisterType in init() function
  4. MarshalToSizedBuffer() / Unmarshal() / Size() covering ALL struct fields (missing = silent data loss)
  5. File descriptor must list the message type (or Descriptor() has nothing to point to)

Common errors from missing pieces:

  • No Descriptor(): "does not have a Descriptor() method: tx parse error"
  • No signer option: "no cosmos.msg.v1.signer option found"
  • No Marshal entry: field written to store but reads back as zero value (silent!)
  • UninterpretedOption instead of extension: signer option silently ignored

Tool:

  • go run ./tools/patch_descriptors — unified tool for ALL modules (including anchor): patches file descriptors, adds missing RPCs, messages, signer options, validates consistency

Protocol Constants (x/settlement/types/types.go)

ReserveRatio       = 0.5   // Bancor connector weight
InitialPrice       = 1.0   // 1 uoas per token at bootstrap
ReserveSolvencyCap = 0.95  // Max 95% reserve payout on sell
BurnRate           = 0.02  // 2% burn on escrow release
TreasuryRate       = 0.03  // 3% treasury on escrow release
ProtocolFeeRate    = 0.05  // 5% protocol fee (DefaultParams)

Fee split on escrow release: 90% provider, 5% protocol, 2% burn, 3% treasury. Sell fee: 5% protocol fee deducted from bonding curve payout.

Validator Incentives (app/genesis.go)

Validators earn from three sources:

  1. Block Rewards — Custom x/halving module with height-based halving
    • Standard mint module disabled (inflation = 0%)
    • Halving mints fixed reward → fee_collector → distribution module → validators + delegators
    • Schedule: 4 OAS/block (0–10M) → 2 (10M–20M) → 1 (20M–30M) → 0.5 (30M+)
  2. Transaction Fees — Gas fees from all chain transactions
    • Collected in fee_collector, distributed proportionally to stake
  3. Protocol Fees — Custom module fees routed to fee_collector
    • Settlement escrow release: 5% protocol + 3% treasury → fee_collector
    • Datarights sell: 5% protocol fee → fee_collector
    • Work task settlement: 5% protocol share → fee_collector

Staking: BondDenom = "uoas", MaxValidators = 100, UnbondingTime = 21 days

Slashing: SignedBlocksWindow = 10000, MinSignedPerWindow = 5%

  • Downtime: 0.01% slash
  • Double-sign: 5% slash

Governance: MinDeposit = 100 OAS, VotingPeriod = 7 days, Quorum = 25%, Threshold = 66.7%

Critical: goleveldb replace directive

The go.mod MUST include this replace (same as SDK v0.50.10):

replace github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7

Without it, the newer goleveldb silently loses data — IAVL stores appear to work in memory but nothing persists to disk.

Running a local node

build/oasyced init test-node --chain-id oasyce-local-1
build/oasyced keys add validator --keyring-backend test
build/oasyced genesis add-genesis-account validator 1000000000uoas --keyring-backend test
build/oasyced genesis gentx validator 500000000uoas --chain-id oasyce-local-1 --keyring-backend test
build/oasyced genesis collect-gentxs
# Patch genesis: lower min_provider_stake to 0
python3 -c "import json; g=json.load(open('~/.oasyced/config/genesis.json')); g['app_state']['oasyce_capability']['params']['min_provider_stake']={'denom':'uoas','amount':'0'}; json.dump(g,open('~/.oasyced/config/genesis.json','w'),indent=2)"
# Enable API: sed -i 's/enable = false/enable = true/' ~/.oasyced/config/app.toml
build/oasyced start --minimum-gas-prices 0uoas

E2E Testing

# With chain running:
./scripts/e2e_test.sh

Key Patterns

Proto field name mapping

  • ID → Id, AssetID → AssetId, CapabilityID → CapabilityId
  • EscrowID → EscrowId, EndpointURL → EndpointUrl
  • InvocationID → InvocationId, DisputeID → DisputeId

Keeper marshal pattern

bz, err := k.cdc.Marshal(&obj)
store.Set(key, bz)

Module interface pattern

// types/codec.go — RegisterInterfaces with msgservice
// keeper/msg_server.go — implements types.MsgServer
// keeper/query_server.go — implements types.QueryServer
// module.go — RegisterServices wires both servers
// cli/tx.go — GetTxCmd(), cli/query.go — GetQueryCmd()

CLI wiring

ModuleBasics.AddTxCommands panics (distr/staking need AddressCodec). Add custom module CLI commands individually in cmd/oasyced/cmd/root.go.

Context conventions

  • BankKeeper interfaces use context.Context (Cosmos SDK v0.50 convention)
  • Internal keeper methods use sdk.Context
  • Settlement/capability keeper interfaces that cross module boundaries use sdk.Context

TX broadcast: CheckTx vs DeliverTx

oasyced tx ... --yes returns CheckTx result (code 0 = accepted into mempool). Use curl localhost:26657/block_results?height=N to check DeliverTx code. query tx <hash> fails due to type URL resolution bug — use block_results instead.

DONE: Economic Model Review (2026-03-25)

Comprehensive economic model audit and parameter adjustments:

  • Fee split unified: 90% provider, 5% protocol, 2% burn, 3% treasury (settlement + work aligned) ✅
  • Slashing relaxed: 0.01% downtime (was 1%), 10000 block window (was 100) ✅
  • Governance lowered: 100 OAS deposit (was 1000), 25% quorum (was 40%) ✅
  • Reputation cooldown: 3600s (was 60s) ✅
  • ProtocolFeeRate = 0.05 (was 0.03), TreasuryRate = 0.03 (was 0.02) ✅
  • Bonding curve slippage protection already exists (min_shares_out / min_payout_out) ✅
  • All 50+ tests updated and passing ✅

DONE: Airdrop Halving Economics (2026-03-24)

Airdrop and PoW difficulty now scale with total registrations (x/onboarding/keeper/keeper.go):

EpochCumulative RegistrationsAirdropPoW Difficulty
00 – 10,00020 OAS16 bits
110,001 – 50,00010 OAS18 bits
250,001 – 200,0005 OAS20 bits
3200,001+2.5 OAS22 bits
  • total_registrations counter at TotalRegistrationsKey = 0x03
  • Effective difficulty = max(params, HalvingDifficulty(epoch))
  • Effective airdrop = min(params, HalvingAirdrop(epoch))
  • ConsensusVersion bumped to 3

DONE: Block Reward Halving (2026-03-24)

Replaced standard Cosmos SDK 5% inflation with custom x/halving module. Standard mint module inflation set to 0%.

Block RangeRewardCumulative Supply
0 – 10,000,0004 OAS/block40M OAS
10,000,001 – 20,000,0002 OAS/block60M OAS
20,000,001 – 30,000,0001 OAS/block70M OAS
30,000,001+0.5 OAS/block+~3.15M/year

Combined with the 2% burn rate, this creates a supply curve that peaks and then contracts.

  • Module: x/halving/ (no proto, no store, no CLI — purely deterministic from block height)
  • keeper.BlockReward(height) returns uoas reward for any block height
  • BeginBlocker: mint → halving module account → fee_collector → distribution → validators
  • Runs after standard mint (which mints 0) and before distribution module
  • Module account has Minter permission
  • 13 tests (boundary conditions, halving transitions, cumulative supply)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.