Skip to content

Multi-agent trading organization: departments, state machine, skills, and venue adapters - #105

Open
leostelon wants to merge 11 commits into
mainfrom
trading-org
Open

leostelon wants to merge 11 commits into
mainfrom
trading-org

Conversation

@leostelon

Copy link
Copy Markdown
Contributor

What this is

A company-style, multi-agent trading organization layered on the existing spine (strategize → thesis → trade-execution → position-management), chartered in docs/org/ORGANIZATION.md. Four commits:

  1. feat(hyperliquid) — eight new read subcommands wrapping already-integrated SDK methods (order-status, funding-history, predicted-fundings, candles, portfolio, ledger, user-fees, rate-limit) plus client-order-id support (--cloid on trade-perp/trade-spot, cloid cancels). No new provider, no new key. order-status + cloid make order submission idempotent and verifiable — previously a timed-out order was indistinguishable from a dropped one.
  2. feat(org) — the organization: 5 departments + a second-line Compliance Officer under a Head of Desk; 24 role definitions in .agents/ (the existing desk-* debate desk becomes the Decision Review Board); an 8-state artifact machine (observation → … → portfolio-position) with single-owner promotion contracts, 6 terminal states, per-asset serialization, session recovery passes, and runtime state under gitignored .tribes/org/; 37 atomic skills mapped to verified tribes-cli commands and registered in the AGENTS.md routing map (CI-enforced).
  3. feat(org-cli) — tribes-cli org validate: zod machine-validation of artifact envelopes and acks (TTL rules, UUID filename joins, timestamp sanity, reject-reasons).
  4. feat(org) integration — the additive pieces of Build a multi-asset research platform #74, adapted: compliance skill/role, documentation-first provider due diligence, model-validation discipline (pre-registration, reproduce-before-promote), verbatim dissent preservation + evidence-type vocabulary in the envelope, and three Workflow scripts (morning-brief, ic-review, token-dd) rewritten for this platform.

Approval boundaries (unchanged, made explicit)

No order without per-trade user confirmation or pre-granted standing authorization with every thesis gate passed; fund movements always human; insufficient margin freezes an instruction (never deposit-and-retry); venue-resident bracket exits mandatory on every org entry; Engineering has no trading authority; a blocked compliance verdict halts promotion.

Deliberately not done

Liquidation feeds, long/short ratios, a shorts-capable backtest engine, websockets, a scheduler/dead-man switch, sub-account segregation, historical macro series, and #74's new billed providers (Alchemy/Helius/Moralis/NewsData) — all recorded in the charter's Open-gaps table with interim answers, since each needs a new billed provider, a control-plane change, or a product decision.

Verification

  • bun run lint (zero warnings), bun run typecheck, bun run format:check clean; 606/606 tests across 36 files, including the skills-contract suite over all 69 skill directories and the AGENTS.md routing map.
  • Design and files were adversarially reviewed by three critique passes (spec-compliance, repo-reality, safety/state-machine; then command-accuracy, charter-consistency, spine-coherence, role-file audits) — ~80 findings folded back in, including real money-path bugs (wrong trade-perp flags, a Review-Board path that could bypass the intent journal, a rule that would have rejected every stop-loss instruction).

Relationship to #74: supersedes its org/skills layer (this design is grounded in the current CLI and CI contracts); its portable governance ideas are integrated in commit 4 and credited above.

🤖 Generated with Claude Code

leostelon and others added 11 commits July 30, 2026 11:59
…er ids

Wrap eight InfoClient methods the harness never surfaced — order-status
(oid/cloid, explicit unknownOid), funding-history, predicted-fundings,
candles, portfolio, ledger, user-fees, rate-limit — and add --cloid to
trade-perp/trade-spot placement plus cloid-based cancel-order and
cancel-order-spot (cancelByCloid). Order submission and verification can
now be idempotent: a cloid keyed to the caller's intent survives
timeouts, and order-status is the safe confirmation surface instead of
resubmission. Documented in the hyperliquid skill via a new
references/account-data.md read-on-trigger file.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A company-style org over the existing spine, chartered in
docs/org/ORGANIZATION.md: Market Intelligence (with Data Validation),
Strategy Research, Portfolio Management, Execution Desk, and Engineering
under the Head of Desk, with the desk-* debate files serving as the
Decision Review Board. Decision flow is an eight-state artifact machine
(observation -> validated-signal -> strategy-proposal -> approved-strategy
-> trade-instruction -> submitted-order -> confirmed-fill ->
portfolio-position) with single-owner promotion contracts, terminal
states, per-asset serialization, and session recovery passes — mechanics
specified once in the org-protocol skill, runtime state under gitignored
.tribes/org/.

Ships 35 atomic skills (intel-*, validate-*, research-*, exec-*,
portfolio-*, eng-*, org-protocol) mapped to verified tribes-cli commands,
23 pi-subagent role definitions in .agents/, and the AGENTS.md
routing-map entries the skills contract requires. Existing spine skills
and MultiAssetPolicy-pinned files are extended, never rewritten; gaps
with no integrated provider (liquidations, long/short, richer backtest
engine, scheduler) are flagged in the charter instead of implemented.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…idate

Zod schemas for the organization's artifact envelope (15 states, freshness
classes, evidence types, dissents) and handoff acks, plus structural rules
the prose spec could not enforce: TTL required on signals, strategies, and
instructions; execution-chain filenames must equal the instruction UUID;
source_ts never after retrieved_at; reject-acks must carry a reason. Acks
auto-detect via the .ack.json suffix; invalid files print a structured
error list and exit 1. Ported from the validation idea in PR #74, adapted
to this repo's slice conventions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Port the genuinely additive pieces of the multi-asset research platform
proposal (PR #74), adapted to the org's conventions:

- Compliance as a second-line function: org-compliance skill +
  compliance-officer role — restricted-list screening, licensing hygiene,
  single-source claim quarantine, and a state-machine bypass audit whose
  blocked verdict halts promotion; first line may dissent, never edit.
- eng-provider-dd: documentation-first provider due diligence with a
  docs-reviewed -> live-tested status ladder for the Integration Engineer.
- Validation discipline folded into research skills: pre-registration and
  falsification criteria, reproduce-before-promote, restart-on-resubmission.
- org-protocol envelope gains dissents[] (verbatim, never softened), the
  six-value evidence-type vocabulary, quality-flag language rules, and the
  mandate to run tribes-cli org validate on every artifact write.
- Book-integrity rules: "mostly ties" is a list of breaks; unresolved
  breaks cap P&L-attribution confidence.
- Three Workflow scripts rewritten for this platform under
  .claude/workflows/: morning-brief, ic-review, token-dd (eslint ignores
  the directory — workflow scripts use the runtime's top-level return).

Deliberately not ported: its provider adapters and registry (superseded by
the current architecture or needing control-plane billing entries) and the
fi-credit/ops-treasury desks — recorded as charter open-gap rows instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
candlesPerpSources gives the capability router an authoritative Hyperliquid
leg: BTC or dex-qualified xyz:AAPL forms, all seven asset timeframes mapped
to venue intervals, a ~200-candle window mirroring the GeckoTerminal cap,
and rows converted into the shared {t,o,h,l,c,v} contract. asset candles now
covers every asset class — token, coin, stock, pool, and perp (incl. HIP-3
stocks/commodities) — in one payload shape, so ta backtest consumes
venue-native perp series directly; the research skills drop the
mandatory-transform caveat, which now applies only to raw hyperliquid
candles for longer windows.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Make `asset candles` the single candle surface for stocks, coins and token
contracts, then retire the provider-named commands it now supersedes.

Stock timeframes
- Wire Marketstack /v2/intraday into StocksService and map every AssetTimeframe
  to a source: 1m/5m/15m/1h are native intervals, 4h is rolled up from 1hour
  (Marketstack has no 4hour), 1d is EOD, 1w is EOD rolled up to ISO weeks.
  Ported from the retired UnifiedOhlcvHelper.toMarketStackPlan (terminal #2621).
- Rollups bucket by TIME BOUNDARY, not by grouping N consecutive rows. Index
  grouping drifts off the grid at the first missing bar, and equities close
  every night.
- 1m/5m are gated behind a higher Marketstack plan and surface as http_403 in
  the router's `attempted` trail.

Windowing
- Add --from/--to (YYYY-MM-DD or ISO 8601) and --limit (1-1000, default 200) to
  `asset candles`, for every identifier except --id, whose CoinGecko endpoint
  only has the rolling --days window.
- One canonical epoch-ms window converted per provider: BirdEye and
  GeckoTerminal take epoch seconds, Marketstack calendar dates, Hyperliquid ms.
- Clip client-side so the range and bar count mean the same thing whichever
  provider answered; providers honour windows only approximately.
- Replaces the hardcoded 200-bar ceiling, which made long backtests impossible.
- Add beforeTimestamp to getPoolOhlcv for parity with getTokenOhlcv.

Fix
- Marketstack EOD rows carry `close: null` on some sessions, and a required
  z.number() rejected the whole page, so `asset candles --ticker` failed with
  parse_error against live AAPL data. OHLC legs are now nullish and incomplete
  rows are dropped at mapping time rather than back-filled.

Retire
- `stocks candles`, `coin ohlc`, `token-data ohlcv` and their option schemas.
  The services stay as router plumbing. `onchain pool-ohlcv` and `hyperliquid
  candles` are kept: they expose intervals and window depths AssetTimeframe's
  7-value enum cannot express, so retiring them would delete capability rather
  than move it.
- Repoint 11 skill docs, including frontmatter and command tables that
  advertised candles as a capability of the retiring groups.

Known limitation: on the current Marketstack plan intraday open/high/low/close
are reported at SESSION level and repeat across every bar in a session; only
volume and last price vary. Close-based indicators are fine, ATR/stochastic/
VWAP/swing-levels are not. Documented in stock-analyst; 1d/1w are unaffected.

Verified live against Marketstack: 15m/1h/4h/1d/1w all return data, --limit 1000
reaches 2022-08-04, and --from/--to on Q1 2026 returns exactly its 61 trading
days. typecheck, lint --max-warnings 0, prettier and 648 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
… repoint the org call sites

Merges origin/main (#107 R2 sync channel, #109 skill removal) into trading-org
and finishes the rewrite for the org/desk surface that only exists on this branch.

Why the merge rather than a fresh deletion: the three skills were already removed
on main, and the sync mechanism the removal depends on lives there too. This
branch's scripts/skills-upgrade.mjs still fetched a codeload tarball of
tribes-protocol/ai-harness-setup, which was retired frozen at 7 skills and has no
zipbox-notify — so no sync run on this branch could ever have produced it. #107
replaced that channel with the content-addressed, digest-verified R2 release at
skills.zipbox.ai. Re-implementing either commit here would have duplicated
reviewed work and diverged the two branches.

skills/.synced.json therefore moves from ai-harness-setup 696490a (7 skills) to
terminal 0ab39f0 / contentSha256 1e741e4 (12 skills). The catalog is vendored as
one atomic release — upstreamSlugs() takes every zipbox-* directory in the
tarball — so zipbox-api-keys, zipbox-desktop, zipbox-geo, and zipbox-image arrive
with zipbox-notify. That set cannot be narrowed without defeating the manifest.

Rewritten here, applying #109's rule unchanged — a skill POINTER becomes the
zipbox slug, a `tribes-cli` COMMAND mention stays verbatim, because the
web-search and notify command groups (src/cli/WebSearch.ts, src/cli/Notify.ts)
are still composed into the binary and are the only path outside a sandbox:

- `notify` -> `zipbox-notify` in eng-diagnose, eng-repair-integration,
  eng-triage, eng-verify-change, exec-onchain-swap, exec-order-lifecycle,
  exec-place-order, org-compliance, org-protocol, portfolio-reconcile,
  portfolio-triggers, and .agents/{eng-integration,eng-lead,pm-position-monitor,
  pm-triggers}.md, docs/org/ORGANIZATION.md. No caveat clause: zipbox-notify
  routes trading boxes straight back to `tribes-cli notify`, so nothing is lost.
- eng-provider-dd and intel-social-sentiment: pointers repointed AND the runnable
  examples rewritten to the zipbox-websearch curl form, each carrying the
  non-sandbox `tribes-cli web-search` equivalent.
- .claude/workflows/token-dd.js cited skills/web-search/SKILL.md, a path this
  change deletes — repointed to skills/zipbox-websearch/SKILL.md.
- docs/org/ORGANIZATION.md: catalog list, the two backing-command tables, and the
  snapshot gap row.

Snapshot parity, checked rather than assumed: `tribes-cli web-search` has no
--out and writes JSON to stdout; zipbox-websearch is a plain curl that also
writes JSON to stdout. The stdout redirect into .tribes/org/snapshots/ is
therefore unchanged on both transports, and ORGANIZATION.md now says so instead
of naming a deleted skill. intel-social-sentiment's free-path step keeps its
redirect verbatim in the new curl form.

Left alone deliberately: research-analyst's two bare `web-search` mentions name
CLI subcommands (#109 settled this); src/utils/{Osc,Tty}.ts comments describe the
notify CLI; plans/ are historical records.

Also formats .pi/extensions/tribes/AuthBootstrap.ts. That file was already
failing `prettier --check` on trading-org before this change — verified against
the pristine eb15c8a blob, exit 1 — and CI runs format:check on every file, so
the branch could not go green without it. Whitespace only, by `bun run format`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The wrapped inline code span put `search --query …` at column 0 inside a
numbered step, which renders as a new paragraph and detaches the caveat from
the step it qualifies. Reworded so the line fits; same content.
…nd upstream

The registry pin sat on tribes-protocol/ai-harness-setup at 696490a for three
weeks while the catalog moved into tribes-protocol/terminal and grew from seven
skills to twelve. Nothing went red. The abandoned repo kept serving its last
snapshot with a 200, and every guard we had was hermetic: SyncedSkills.test.ts
proves the files on disk match .synced.json, skills-release-verify.test.mjs
proves the download path verifies its bytes, and neither has ever asked upstream
what the current release is. A pin that stops moving looks, to both of them, like
a healthy repository. It surfaced only because someone deleting a duplicate skill
went looking for the replacement and could not find one.

scripts/skills-drift-check.mjs closes that. It compares one string: the release
channel is content-addressed, so .synced.json's contentSha256 and latest.json's
either name the same catalog or genuinely different ones. No tree diff, no false
positive from a version bump that changed nothing — which is what makes failing
hard safe here.

Five verdicts, and the distinctions are the point:

  0  IN SYNC     the pin is the published release
  0  AHEAD       the pin is NEWER than the pointer (deliberate --pin, or a
                 rolled-back pointer) — not drift
  0  UNVERIFIED  upstream could not be consulted: DNS, reset, timeout, 429, 5xx.
                 A busy bucket must never read as a changed catalog.
  1  DRIFTED     the pin is behind, naming which slugs were added, retired, or
                 changed
  1  UNPUBLISHED the pinned release is not in the bucket. A 404 is deterministic,
                 not transient: the vendored catalog has no verifiable provenance.

Retries use exponential backoff with a cap and jitter and honour Retry-After,
bounded because the terminal state on exhaustion is UNVERIFIED rather than
failure — a CI step must not hang on a slow edge, nor turn one red.

test/skills-drift-check.test.mjs drives all five against a stub bucket on
loopback, including a positive control so "fails on everything" cannot pass for
"fails on drift". Against the live bucket the check goes red on the pre-fix
.synced.json this branch started from and green on the current pin.

Also: skills:upgrade skipped rewriting the manifest whenever the vendored file
set was unchanged. Those hashes are taken after prettier, so an upstream release
that only moved whitespace prettier normalizes away would land as an unchanged
file set under a new contentSha256 — leaving a stale pin the drift check would
then fail on forever, with no upgrade able to clear it. The skip now requires the
content address to match too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants