feat(server): W2-D agent assembly, session API, runAgent/resolveDecision and backend e2e

- Capabilities: all 14 registered (AO: inventory.query, download.plan/submit, organize.plan/execute,
  policy.preview/apply; agent: task.inspect/retry/cancel); startup asserts count == 14.
  Registry injects server-side authorize (automation_grant by action/scope/policy version/budget,
  one-shot approval bound to plan id + payload hash + revision + expiry; model claims ignored;
  automation switch), audit_event, server idempotency keys and a capability_invocation op ledger
  (migration 0021) used for crash reconciliation. download.plan creates draft plans only;
  download.submit promotes draft -> reserved after authorization.
- Agent session API: POST/GET /agent/runs, GET /agent/runs/{id} (events by seq, messages, report),
  POST .../messages (wake), POST .../abort; automation-grants, approvals, capabilities invoke, tasks.
- runAgent task: Pi or fake provider from settings (apiKey via secrets), events persisted to
  agent_run_event then published, resume + ledger reconciliation when pendingOperations > 0,
  waits for goal-linked downloads/imports and reports from business tables (submitted != imported).
- Background triggers: decision.created -> bounded plan_only investigation (dedupe per decision);
  decision.updated(resolved) -> resolveDecision executes chosen option.
- W2 closure: all OpenAPI routes registered in contracts api.ts (+ subset test); TMDB key from
  settings secret_ref with env fallback; PUT /sites/{id}/credentials documented as alias of
  /site-accounts; completion events documented as existing status events.
- e2e (real PG + OpenWorkflow + testkit mocks): RSS->library, agent delegation with grant/deny,
  background continuation, worker kill -9 recovery (single qB add), auto investigation dedupe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-27 20:52:12 +08:00
1 parent 0dec0854df
commit 6280d52ec3
46 files changed
+5133 -111

No files matched your search

@@ -0,0 +1,65 @@
import type { Kysely } from "kysely";
import { dropTables, entityTable, execDdl, oneOf } from "../src/migration-helpers.ts";
// W2-D Agent 装配(REQ §10.3、§10.6、§10.7、§11):
// - capability_invocation:有副作用能力的操作账本。幂等键由服务端按能力 ID/版本/运行/规范化输入生成(唯一);
// succeeded 行直接返回已记录的输出,running 行(进程在调用中崩溃)按同一幂等键重跑处理器对账——
// 处理器自身必须幂等(下载提交按计划状态 + qB hash、整理按记录状态)。
// - agent_run_message:会话追加的用户消息(纠正/补充),runAgent 任务按顺序消费;
// - agent_run 增加 mode(execute | plan_only)与 dedupe_key(后台触发按根因去重)。
// biome-ignore lint/suspicious/noExplicitAny: 迁移不依赖应用表类型
export async function up(db: Kysely<any>): Promise<void> {
await execDdl(
db,
`
alter table agent_run add column mode text not null default 'execute' ${oneOf("mode", ["execute", "plan_only"])};
alter table agent_run add column dedupe_key text;
create unique index agent_run_dedupe_key on agent_run (dedupe_key) where dedupe_key is not null;
${entityTable(
"capability_invocation",
`
idempotency_key text not null,
capability_id text not null,
capability_version integer not null,
agent_run_id uuid references agent_run (id) on delete set null,
actor_id text not null,
source text not null,
status text not null default 'running' ${oneOf("status", ["running", "succeeded", "failed"])},
input jsonb not null default '{}'::jsonb,
output jsonb,
error jsonb,
grant_id uuid,
approval_id uuid,
attempts integer not null default 1,
finished_at timestamptz,
constraint capability_invocation_idempotency_key unique (idempotency_key)`,
)}
create index capability_invocation_run_idx on capability_invocation (agent_run_id, created_at) where agent_run_id is not null;
create index capability_invocation_running_idx on capability_invocation (created_at) where status = 'running';
${entityTable(
"agent_run_message",
`
run_id uuid not null references agent_run (id) on delete cascade,
text text not null,
status text not null default 'pending' ${oneOf("status", ["pending", "consumed"])},
created_by text,
consumed_at timestamptz`,
)}
create index agent_run_message_pending_idx on agent_run_message (run_id, created_at) where status = 'pending';
`,
);
}
// biome-ignore lint/suspicious/noExplicitAny: 同上
export async function down(db: Kysely<any>): Promise<void> {
await execDdl(
db,
`${dropTables(["agent_run_message", "capability_invocation"])}
drop index if exists agent_run_dedupe_key;
alter table agent_run drop column if exists dedupe_key;
alter table agent_run drop column if exists mode;`,
);
}
+44
View File
@@ -37,6 +37,7 @@ export type AgentRunStatus =
| "failed"
| "cancelled"
| "budget_exceeded";
export type AgentRunMode = "execute" | "plan_only";
export type AgentRunEventType =
| "run_started"
| "text_delta"
@@ -47,6 +48,7 @@ export type AgentRunEventType =
| "compaction"
| "run_completed"
| "run_failed";
export type AgentRunMessageStatus = "pending" | "consumed";
export type ApprovalStatus = "pending" | "approved" | "rejected" | "revoked" | "expired" | "consumed";
export type ArtifactKind = "evidence" | "plan" | "proposal" | "report" | "snapshot" | "log";
export type AssetLocationLocationKind = "library" | "download_cache" | "hardlink" | "external";
@@ -71,6 +73,7 @@ export type AssetOperationStatus = "planned" | "started" | "succeeded" | "failed
export type AssetUnitCoverageCoverage = "full" | "partial" | "segment" | "unknown";
export type AssetUnitCoverageSegment = "full" | "upper" | "middle" | "lower" | "unknown";
export type AutomationGrantStatus = "active" | "revoked" | "expired";
export type CapabilityInvocationStatus = "running" | "succeeded" | "failed";
export type ContentUnitKind = "season" | "episode" | "special" | "part";
export type ContentUnitContentType =
| "main"
@@ -305,6 +308,8 @@ export interface AgentRunTable {
created_by: string | null;
created_at: GeneratedTimestamptz;
updated_at: GeneratedTimestamptz;
mode: Generated<AgentRunMode>;
dedupe_key: string | null;
}
export interface AgentRunEventTable {
@@ -315,6 +320,17 @@ export interface AgentRunEventTable {
payload: Generated<Json>;
}
export interface AgentRunMessageTable {
id: Generated<string>;
run_id: string;
text: string;
status: Generated<AgentRunMessageStatus>;
created_by: string | null;
consumed_at: Timestamptz | null;
created_at: GeneratedTimestamptz;
updated_at: GeneratedTimestamptz;
}
export interface ApiKeyTable {
id: Generated<string>;
name: string;
@@ -444,6 +460,26 @@ export interface AutomationGrantTable {
updated_at: GeneratedTimestamptz;
}
export interface CapabilityInvocationTable {
id: Generated<string>;
idempotency_key: string;
capability_id: string;
capability_version: number;
agent_run_id: string | null;
actor_id: string;
source: string;
status: Generated<CapabilityInvocationStatus>;
input: Generated<Json>;
output: Json | null;
error: Json | null;
grant_id: string | null;
approval_id: string | null;
attempts: Generated<number>;
finished_at: Timestamptz | null;
created_at: GeneratedTimestamptz;
updated_at: GeneratedTimestamptz;
}
export interface ContentUnitTable {
id: Generated<string>;
media_entity_id: string;
@@ -1180,6 +1216,7 @@ export interface DB {
admin_user: AdminUserTable;
agent_run: AgentRunTable;
agent_run_event: AgentRunEventTable;
agent_run_message: AgentRunMessageTable;
api_key: ApiKeyTable;
approval: ApprovalTable;
artifact: ArtifactTable;
@@ -1188,6 +1225,7 @@ export interface DB {
asset_unit_coverage: AssetUnitCoverageTable;
audit_event: AuditEventTable;
automation_grant: AutomationGrantTable;
capability_invocation: CapabilityInvocationTable;
content_unit: ContentUnitTable;
decision: DecisionTable;
download_task: DownloadTaskTable;
@@ -1249,6 +1287,9 @@ export type AgentRunUpdate = Updateable<AgentRunTable>;
export type AgentRunEventRow = Selectable<AgentRunEventTable>;
export type NewAgentRunEvent = Insertable<AgentRunEventTable>;
export type AgentRunEventUpdate = Updateable<AgentRunEventTable>;
export type AgentRunMessageRow = Selectable<AgentRunMessageTable>;
export type NewAgentRunMessage = Insertable<AgentRunMessageTable>;
export type AgentRunMessageUpdate = Updateable<AgentRunMessageTable>;
export type ApiKeyRow = Selectable<ApiKeyTable>;
export type NewApiKey = Insertable<ApiKeyTable>;
export type ApiKeyUpdate = Updateable<ApiKeyTable>;
@@ -1273,6 +1314,9 @@ export type AuditEventUpdate = Updateable<AuditEventTable>;
export type AutomationGrantRow = Selectable<AutomationGrantTable>;
export type NewAutomationGrant = Insertable<AutomationGrantTable>;
export type AutomationGrantUpdate = Updateable<AutomationGrantTable>;
export type CapabilityInvocationRow = Selectable<CapabilityInvocationTable>;
export type NewCapabilityInvocation = Insertable<CapabilityInvocationTable>;
export type CapabilityInvocationUpdate = Updateable<CapabilityInvocationTable>;
export type ContentUnitRow = Selectable<ContentUnitTable>;
export type NewContentUnit = Insertable<ContentUnitTable>;
export type ContentUnitUpdate = Updateable<ContentUnitTable>;
+3
View File
@@ -75,6 +75,9 @@ const EXPECTED_TABLES = [
"identity_redirect",
"metadata_field",
"field_override",
// W2-D Agent 装配(0021)
"capability_invocation",
"agent_run_message",
// 登录门禁(0015)与 SSE 多进程总线(0016)
"admin_user",
"admin_session",