Files
UHD_Media_Tool/packages/db/migrations/0021_agent_runtime.ts
T
rootandClaude Opus 5.5 6280d52ec3 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]>
2026-09-27 20:52:12 +08:00

66 lines
2.7 KiB
TypeScript

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;`,
);
}