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
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Allow bounded E2 campaign approvals in the durable operation ledger."""

from __future__ import annotations

from alembic import op

revision: str = "0045"
down_revision: str | None = "0044"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None


def upgrade() -> None:
"""Permit both E1 runs and E2 campaigns in the shared approval-operation ledger."""
op.execute(
"""SET LOCAL lock_timeout = '10s';
ALTER TABLE evolution_approval_operations
DROP CONSTRAINT evolution_approval_operations_tool_name_check;
ALTER TABLE evolution_approval_operations
ADD CONSTRAINT evolution_approval_operations_tool_name_check
CHECK (tool_name IN ('evolver.run_evolution','evolver.run_event_campaign'));"""
)


def downgrade() -> None:
"""Remove E2 recovery rows before restoring the E1-only ledger constraint."""
op.execute(
"""SET LOCAL lock_timeout = '10s';
DELETE FROM evolution_approval_operations
WHERE tool_name='evolver.run_event_campaign';
ALTER TABLE evolution_approval_operations
DROP CONSTRAINT evolution_approval_operations_tool_name_check;
ALTER TABLE evolution_approval_operations
ADD CONSTRAINT evolution_approval_operations_tool_name_check
CHECK (tool_name='evolver.run_evolution');"""
)
6 changes: 3 additions & 3 deletions packages/orchestration/config/permissions.default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,8 @@ allow:
# 演化状态与候选详情只读
- "evolver.get_evolution"
- "evolver.get_candidate"
# 事件 campaign 仅在独立 sandbox 中自动迭代;不会 promote、启动或下单
# 事件 campaign 查询只读;启动 campaign 会产生 LLM 费用,必须先显式审批
- "evolver.get_event_campaign"
- "evolver.run_event_campaign"

# Swarm 批量回测(ADR-0025):只读,无下单路径
- "swarm.*"
Expand Down Expand Up @@ -93,8 +92,9 @@ ask:
- "paper.deposit_cash"
- "paper.reset_account"

# LLM 变异会产生费用;取消会改变运行状态,均需明确确认
# LLM 演化会产生费用;E2 一次审批覆盖整个五代 campaign,不逐代重复审批
- "evolver.run_evolution"
- "evolver.run_event_campaign"
- "evolver.abort_evolution"

deny:
Expand Down
19 changes: 15 additions & 4 deletions packages/orchestration/src/clients/evolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,21 @@ export class EvolverClient {
options.request,
headers,
);
return await this.http.post<EventCampaignResult>(
`/api/v1/campaigns/${created.campaign_id}/start`,
{},
);
if (created.status !== "draft") return created;

try {
return await this.http.post<EventCampaignResult>(
`/api/v1/campaigns/${created.campaign_id}/start`,
{},
);
} catch (error) {
if (!(error instanceof HttpClientError) || error.code !== "CAMPAIGN_STATE_CONFLICT") {
throw error;
}
const current = await this.getEventCampaign(created.campaign_id);
if (current.status === "draft") throw error;
return current;
}
}

async getEventCampaign(campaignId: string): Promise<EventCampaignResult> {
Expand Down
22 changes: 16 additions & 6 deletions packages/orchestration/src/hooks/with-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ type GenericTool = {
[key: string]: unknown;
};

const DURABLE_EVOLUTION_APPROVAL_TOOLS = new Set([
"evolver.run_evolution",
"evolver.run_event_campaign",
]);
const E2_CAMPAIGN_RETRY_WINDOW_MS = 2 * 60 * 1_000;

/**
* mastra ``server.middleware`` 从 Bearer JWT 解出的已认证主体(sub)写进 RequestContext
* 的 key(#91)。getSessionId 最高优先读它 → askCache 按已认证主体 scope(替代 __global__)。
Expand Down Expand Up @@ -201,14 +207,14 @@ export function withHooks<T extends GenericTool>(tool: T, opts: WithHooksOptions
if (permDecision === "ask") {
const store = opts.pendingApprovals ?? defaultPendingApprovals;
const projectedInput = projectApprovalInput(toolName, effectiveInput);
const llmSnapshot =
toolName === "evolver.run_evolution"
? getRequestContextValue<EvolutionLLMSnapshot>(ctx, USER_LLM_SNAPSHOT_KEY)
: undefined;
const durableEvolutionApproval = DURABLE_EVOLUTION_APPROVAL_TOOLS.has(toolName);
const llmSnapshot = durableEvolutionApproval
? getRequestContextValue<EvolutionLLMSnapshot>(ctx, USER_LLM_SNAPSHOT_KEY)
: undefined;
const approvalInput = llmSnapshot
? { request: projectedInput, llm_snapshot: llmSnapshot }
: projectedInput;
if (!authSub || !sessionId || (toolName === "evolver.run_evolution" && !llmSnapshot)) {
if (!authSub || !sessionId || (durableEvolutionApproval && !llmSnapshot)) {
return {
isError: true,
deniedBy: "permission-ask",
Expand All @@ -228,6 +234,10 @@ export function withHooks<T extends GenericTool>(tool: T, opts: WithHooksOptions
toolName,
approvalInput,
reuseAfterConsume: toolName === "evolver.run_evolution",
reuseOnceAfterConsumeMs:
toolName === "evolver.run_event_campaign"
? E2_CAMPAIGN_RETRY_WINDOW_MS
: undefined,
});
if (!operationId) {
const approvalViewInput = llmSnapshot
Expand All @@ -242,7 +252,7 @@ export function withHooks<T extends GenericTool>(tool: T, opts: WithHooksOptions
timeoutMs:
opts.askTimeoutMs && opts.askTimeoutMs > 0
? opts.askTimeoutMs
: toolName === "evolver.run_evolution"
: durableEvolutionApproval
? 300_000
: undefined,
});
Expand Down
2 changes: 2 additions & 0 deletions packages/orchestration/src/permissions/approval-identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export const APPROVAL_IDENTITY_FIELDS: Readonly<Record<string, readonly string[]
],
// 演化审批绑定完整计算范围;idempotencyKey 只是传输重试标识,不改变成本或行为。
"evolver.run_evolution": ["seedStrategyId", "budget", "config"],
// E2 一次审批绑定事件快照、可选来源 run 与完整 campaign 配置。
"evolver.run_event_campaign": ["eventSnapshotId", "sourceRunId", "config"],
};

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/orchestration/src/permissions/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export const DEFAULT_PERMISSIONS: PermissionConfig = {
"evolver.get_evolution",
"evolver.get_candidate",
"evolver.get_event_campaign",
"evolver.run_event_campaign",

// Swarm 批量回测(ADR-0025):只读,无下单路径
"swarm.*",
Expand Down Expand Up @@ -94,7 +93,9 @@ export const DEFAULT_PERMISSIONS: PermissionConfig = {
// reset 是破坏性操作(删全部持仓行),后端另有 running-run 409 硬守门。
"paper.deposit_cash",
"paper.reset_account",
// E2 只在 campaign 启动时审批一次;内部五代演化继续自动执行。
"evolver.run_evolution",
"evolver.run_event_campaign",
"evolver.abort_evolution",
],

Expand Down
Loading
Loading