Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
41 changes: 41 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Validate research engine

on:
pull_request:
push:
branches: [main]

permissions:
contents: read

concurrency:
group: validation-${{ github.ref }}
cancel-in-progress: true

jobs:
backend:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.12', '3.13']
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
- run: python -m unittest discover -s backend/tests -v
env:
PYTHONPATH: backend
- run: git diff --check
native-contract:
runs-on: macos-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-python@v7
with:
python-version: '3.12'
- run: scripts/check-ui-contract.sh
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Delegation preference

Use GPT-6 Luna as the default model for delegated agents unless the user explicitly requests a different model. This preference concerns development subagents; changing Prism's runtime model routing is a separate product decision.

Keep research and execution paper-only. Use offline fixtures for development; do not start the installed service, access credentials, or run paid research cycles unless the user asks for those actions.
49 changes: 48 additions & 1 deletion Prism/Models/RuntimeState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,40 @@ struct RuntimeState: Decodable, Sendable {
let config: RuntimeConfiguration
/// Additive cascade metadata; nil when the backend omits the key (legacy / offline fixture).
let cascade: CascadeMetadata?
let research: ResearchStatus?
}

struct ResearchStatus: Decodable, Sendable {
let phase: String?
let historicalResultsAreDevelopment: Bool?
let experimentCount: Int?
let statuses: [String: Int]?
let failureReasons: [String: Int]?
let operatingCosts: ResearchCosts?
let coverage: ResearchCoverage?
let forwardReports: [ForwardResearchReport]?
}

struct ResearchCosts: Decodable, Sendable {
let modelCostUsd: Double?
let totalCostUsd: Double?
let calls: Int?
}

struct ResearchCoverage: Decodable, Sendable {
let gaps: [String]?
let survivorshipSafe: Bool?
}

struct ForwardResearchReport: Decodable, Identifiable, Sendable {
var id: String { experimentId }
let experimentId: String
let status: String?
let sessions: Int?
let netReturn: Double?
let excessReturn: Double?
let operatingPnlUsd: Double?
let reasons: [String]?
}

// MARK: - Cascade metadata (additive; all fields optional for backward compatibility)
Expand Down Expand Up @@ -63,6 +97,7 @@ struct CascadeCollection: Decodable, Sendable {
let evidenceCount: Int
let sourceCount: Int
let collectorCount: Int
let activeCollectorCount: Int?
}

struct RuntimeStatus: Decodable, Sendable {
Expand Down Expand Up @@ -156,6 +191,8 @@ struct StrategyResult: Decodable, Identifiable, Sendable {
let createdAt: String
let agentId: String?
let spec: StrategySpecification?
let phase: String?
let experimentId: String?
}

struct StrategySpecification: Decodable, Sendable {
Expand Down Expand Up @@ -196,8 +233,12 @@ struct PaperPortfolio: Decodable, Sendable {
let pnlHistory: [PaperPnlObservation]?
let positions: [PaperPosition]
let trades: [PaperTrade]
let valuationComplete: Bool?
let riskHalted: Bool?
let warnings: [String]?
let receivables: [IncomeReceivable]?

/// Equity already includes open positions, trading costs, and accrued funding.
/// Equity includes positions, simulated trading costs, and observed income entitlements.
var totalPnl: Double? {
guard let initialEquity, initialEquity.isFinite, initialEquity > 0, equity.isFinite else { return nil }
let result = equity - initialEquity
Expand Down Expand Up @@ -232,6 +273,12 @@ struct PaperPortfolio: Decodable, Sendable {
}
}

struct IncomeReceivable: Decodable, Identifiable, Sendable {
let id: String
let amount: Double
let payableAtMs: Double?
}

struct PaperPnlObservation: Decodable, Equatable, Sendable {
let timestamp: String
let pnl: Double
Expand Down
9 changes: 9 additions & 0 deletions Prism/Views/PrismOverviewView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ struct PrismOverviewView: View {
Text(issue).font(.system(size: 11)).foregroundStyle(.secondary)
.multilineTextAlignment(.center).frame(maxWidth: 360).padding(.top, 20)
}
if runtime.state?.portfolio.valuationComplete == false {
Text("Valuation incomplete: fresh marks are missing.")
.font(.system(size: 11)).foregroundStyle(.orange).padding(.top, 12)
}
if runtime.state?.portfolio.riskHalted == true {
Text("Entries halted. Open positions may remain until observed exit prices are available.")
.font(.system(size: 11)).foregroundStyle(.orange)
.multilineTextAlignment(.center).frame(maxWidth: 360).padding(.top, 12)
}
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions Prism/Views/PrismPortfolioView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ struct PrismPortfolioView: View {
Text("Realized \(runtime.state.map { PrismFormat.money($0.portfolio.realizedPnl) } ?? "—")")
Text("Unrealized \(runtime.state.map { PrismFormat.money($0.portfolio.unrealizedPnl) } ?? "—")")
}.font(.system(size: 11)).foregroundStyle(.secondary)
if let receivables = runtime.state?.portfolio.receivables, !receivables.isEmpty {
Text("Income receivable \(PrismFormat.money(receivables.reduce(0) { $0 + $1.amount })) · Cash awaits an observed payment date")
.font(.system(size: 11)).foregroundStyle(.secondary)
}
ForEach(runtime.state?.portfolio.warnings ?? [], id: \.self) { warning in
Text(warning).font(.system(size: 11)).foregroundStyle(.orange)
}
}.padding(.vertical, 10)
VStack(alignment: .leading, spacing: 18) {
Text("Positions").font(.system(size: 13, weight: .medium))
Expand Down
2 changes: 1 addition & 1 deletion Prism/Views/PrismResearchView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ struct PrismResearchView: View {
Text("Chips, memory, networking, cloud compute, data centers, power and cooling")
.font(.system(size: 11)).foregroundStyle(.secondary)
if let collection = runtime.state?.cascade?.collection {
Text("\(collection.collectorCount) collectors · \(collection.evidenceCount) evidence records · \(collection.sourceCount) sources")
Text("\(collection.activeCollectorCount ?? collection.collectorCount) active collectors · \(collection.evidenceCount) evidence records · \(collection.sourceCount) sources")
.font(.system(size: 11)).monospacedDigit().foregroundStyle(.secondary)
}
if let sector = runtime.state?.cascade?.sector, !sector.companies.isEmpty {
Expand Down
41 changes: 39 additions & 2 deletions Prism/Views/PrismTestView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,43 @@ struct PrismTestView: View {
private var statuses: [String] { ["All results"] + Set(runtime.state?.strategies.map(\.status) ?? []).sorted() }
var body: some View {
VStack(alignment: .leading, spacing: 20) {
if let research = runtime.state?.research {
VStack(alignment: .leading, spacing: 10) {
Text("Prospective research").font(.system(size: 15, weight: .medium))
Text("Historical results are development evidence. Frozen candidates accumulate future observations in separate shadow accounts.")
.font(.system(size: 12)).foregroundStyle(.secondary)
if let count = research.experimentCount {
Text("\(count) registered experiments").font(.system(size: 12)).monospacedDigit()
}
if let cost = research.operatingCosts?.totalCostUsd ?? research.operatingCosts?.modelCostUsd {
Text("Estimated model cost: \(PrismFormat.money(cost))")
.font(.system(size: 12)).monospacedDigit()
}
ForEach((research.failureReasons ?? [:]).keys.sorted(), id: \.self) { reason in
Text("\(research.failureReasons?[reason] ?? 0) · \(reason)")
.font(.system(size: 11)).foregroundStyle(.secondary)
}
ForEach(research.coverage?.gaps ?? [], id: \.self) { gap in
Text(gap).font(.system(size: 11)).foregroundStyle(.orange)
}
ForEach(research.forwardReports ?? []) { report in
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(report.experimentId).lineLimit(1).truncationMode(.middle)
Spacer()
Text(PrismFormat.label(report.status ?? "Awaiting observations"))
}
Text("\(report.sessions ?? 0) future sessions · Net \(PrismFormat.percent(report.netReturn)) · Excess \(PrismFormat.percent(report.excessReturn))")
.monospacedDigit()
if let pnl = report.operatingPnlUsd {
Text("After operating costs: \(PrismFormat.money(pnl))")
}
Text((report.reasons ?? []).joined(separator: "; "))
.foregroundStyle(.secondary).textSelection(.enabled)
}.font(.system(size: 11)).padding(.vertical, 5)
}
}
}
Picker("Result status", selection: $statusFilter) {
ForEach(statuses, id: \.self) { status in Text(PrismFormat.label(status)).tag(status) }
}.labelsHidden().frame(width: 145)
Expand All @@ -19,13 +56,13 @@ struct PrismTestView: View {
DisclosureGroup {
VStack(alignment: .leading, spacing: 16) {
HStack(spacing: 28) {
metric("Net return", PrismFormat.percent(strategy.netReturn))
metric(strategy.phase == "development" ? "Development return" : "Historical return", PrismFormat.percent(strategy.netReturn))
metric("Sharpe", PrismFormat.number(strategy.sharpe))
metric("Drawdown", PrismFormat.percent(strategy.maxDrawdown))
metric("Trades", strategy.trades.map(String.init) ?? "—")
}
Text(strategy.reason).font(.system(size: 11)).foregroundStyle(.secondary).textSelection(.enabled)
Text("\(PrismFormat.label(strategy.family)) · \(PrismFormat.time(strategy.createdAt))")
Text("\(PrismFormat.label(strategy.family)) · \(PrismFormat.label(strategy.phase ?? "development")) · \(PrismFormat.time(strategy.createdAt))")
.font(.system(size: 10)).foregroundStyle(.tertiary)
}.padding(.vertical, 14).padding(.leading, 18)
} label: {
Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ The application has **33 agents** with fixed model routing:
| Strategize | 2 | GPT-6 Astra | High |
| Execute | 1 | GPT-6 Astra | Max |

Default concurrency is 8, configurable up to 32. The runtime uses the existing OpenAI credential integration. Gemini is not a runtime provider. Agents organize evidence and hypotheses; deterministic host code owns validation, budget reservations, paper fills and accounting.
The table describes available roles. Defaults activate six collectors and two analysts, with deterministic candidate selection and execution authorization. Optional strategist/executor calls are advisory comparisons. Unchanged evidence and daily histories skip repeated model work. Default concurrency is 8, configurable up to 32. The runtime uses the existing OpenAI credential integration; Gemini is not a runtime provider.

Historical results are **development evidence**. Candidates are registered before evaluation and run in independent prospective shadow accounts. Promotion to the aggregate paper portfolio requires future observations, operating returns, stock/market/sector comparisons, and predeclared statistical reviews. A shared daily engine owns replay and forward orders, costs, exposure budgets, corporate actions and accounting. Current public data does not establish profitability or verified historical execution coverage.

## Run

Expand Down Expand Up @@ -40,8 +42,19 @@ scripts/check-ui-contract.sh
## Documentation

- [Architecture](docs/Architecture.md): evidence flow and layer boundaries.
- [Agents](docs/Agents.md): fixed roster and responsibilities.
- [Task procedures](docs/Agents.md): evidence checks, output contracts and abstention criteria for each stage.
- [Runtime](docs/Runtime.md): catalogue, public sources and data limits.
- [Validation](docs/Validation.md): verification results and data limitations.
- [Research contract](docs/ResearchContract.md): frozen experiments, execution and promotion rules.
- [Readiness assessment](docs/ProfitabilityReadiness.md): original findings and implementation follow-up.

Evaluate a versioned vendor dataset without credentials or a running service:

```sh
python3 scripts/research.py evaluate --journal /tmp/prism-research.sqlite3 \
--dataset /path/to/dataset.json --proposals /path/to/proposals.json --output /tmp/report.json
```

Dataset requirements and the distinction between provider declarations and independently verified data are described in [Runtime](docs/Runtime.md).

The local glass prototype uses `PRISM_EXPERIMENTAL_GLASS` for private macOS rendering APIs. Remove that compilation condition to use the public `NSGlassEffectView` fallback. See [Design](docs/Design.md) and [third-party components](docs/ThirdParty.md).
3 changes: 3 additions & 0 deletions Tests/RuntimeContractCheck.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ struct RuntimeContractCheck {
let state = try decoder.decode(RuntimeState.self, from: data)
try require(state.runtime.mode == "paper", "Paper execution must be explicit.")
try require(state.runtime.status == "paused", "A new cascade must start paused.")
try require(state.research?.historicalResultsAreDevelopment == true && state.research?.experimentCount == 0,
"Development evidence and the prospective registry must reach the console.")
try require(!state.runtime.openaiConfigured, "The contract fixture must use no provider credential.")
try require(state.agents.count == 33 && Set(state.agents.map(\.id)).count == 33,
"Every cascade agent must have a stable, unique UI identity.")
Expand All @@ -37,6 +39,7 @@ struct RuntimeContractCheck {
"Discovered company identity and source provenance must decode.")
var legacy = try JSONSerialization.jsonObject(with: data) as! [String: Any]
legacy.removeValue(forKey: "cascade")
legacy.removeValue(forKey: "research")
var legacyMarkets = legacy["markets"] as! [[String: Any]]
legacyMarkets[0]["change_24h"] = NSNull()
legacy["markets"] = legacyMarkets
Expand Down
Loading
Loading