Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
chore: remove integrations that only work on a private network (#66)
Robert06220e3fee779029
diff --git a/AGENTS.md b/AGENTS.mdindex f39d296c..6cc4958b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -63,7 +63,7 @@ Preserve the platform architecture; keep deployment-specific adapters isolated.`catalogHandlers`、`issuesHandlers`、`tasksHandlers`、`runsHandlers`、`previewsHandlers`、`streamHandlers`、`runnersHandlers`、`scheduleHandlers`、`tokenHandlers`、`syncHandlers`、- `deploymentMetricsHandlers`、`assistantHandlers`、`mcpHandlers`、+ `assistantHandlers`、`mcpHandlers`、`marketHandlers`、`feedbackHandlers`…),在 `server.go` 的 `Server` 中以指针装配。2. **新领域必须新建自己的 handler struct**,不要把方法挂到现有领域 handler或 `Server` 上。diff --git a/design.md b/design.mdindex ad817990..4490fb74 100644--- a/design.md+++ b/design.md@@ -108,7 +108,7 @@| 状态色 info / success / error / warn / neutral | `#597dcc` `#338768` `#c15161` `#b7791f` `#6b6b76` | `#8aa8ee` `#34d399` `#f0899a` `#f2c46d` `#a1a1ac` || 阴影 | `--hui-panel-shadow`(面板、卡片)与 `--hui-popover-shadow`(菜单、下拉、浮层)分开使用 | 同名 |-设置区里尚未改写的旧页面(个人配置、项目配置、执行机器、角色定义、研发效能、部署耗时、业务领域、接入指南、平台管理、领域管理)在各自视图作用域内把旧基础令牌(`--text`、`--muted`、`--line`、`--panel`、`--blue`、`--v3-*` 等)映射到 `--hui-*`,只改颜色,不动尺寸。+设置区里尚未改写的旧页面(个人配置、项目配置、执行机器、角色定义、研发效能、业务领域、接入指南、平台管理、领域管理)在各自视图作用域内把旧基础令牌(`--text`、`--muted`、`--line`、`--panel`、`--blue`、`--v3-*` 等)映射到 `--hui-*`,只改颜色,不动尺寸。### 组件外观@@ -124,7 +124,7 @@### 启用视图与设置区容器-按钮、页头、输入的映射只对登记视图生效:`#issuesView`、`#approvalsView`、`#assetsView`、`#mcpView`、`#botsView`、`#knowledgeView` 以及设置区各视图(`#settingsView`、`#projectsView`、`#runnersView`、`#agentsView`、`#metricsView`、`#deploymentsView`、`#businessDomainsView`、`#guideView`、`#platformView`、`#businessDomainManagementView`),外加挂到 `<body>` 的 `#agentModal`、`#customMcpModal`、`.pw-root`、`#kbDrawer`。+按钮、页头、输入的映射只对登记视图生效:`#issuesView`、`#approvalsView`、`#assetsView`、`#mcpView`、`#botsView`、`#knowledgeView` 以及设置区各视图(`#settingsView`、`#projectsView`、`#runnersView`、`#agentsView`、`#metricsView`、`#businessDomainsView`、`#guideView`、`#platformView`、`#businessDomainManagementView`),外加挂到 `<body>` 的 `#agentModal`、`#customMcpModal`、`.pw-root`、`#kbDrawer`。设置区视图的外层内容统一居中、最大宽 1200px(`.page-view.active` 的直接子元素),页面不再各自限宽。流程设计(`#flowView`)、工作区页面、图标栏、侧栏与顶栏不受影响。diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex aac1eaa4..422684fb 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -499,7 +499,7 @@ paths:get:tags: [System]operationId: getEmployeePhoto- summary: Fetch employee avatar photo from TOF authentication service+ summary: Fetch a user avatar from the configured SSO photo serviceparameters:- name: specin: path@@ -509,7 +509,7 @@ paths:- name: usernamein: pathrequired: true- description: Employee English login name (with or without .png)+ description: User login name (with or without .png)schema: {type: string}responses:"200":@@ -525,7 +525,7 @@ paths:"404":$ref: "#/components/responses/NotFound""502":- description: TOF photo gateway error+ description: SSO photo service error/api/auth/tokens:get:tags: [System]@@ -2173,76 +2173,6 @@ paths:$ref: "#/components/schemas/OpenObject""401":$ref: "#/components/responses/Unauthorized"- /api/deployment-metrics:- get:- tags: [Analytics]- operationId: getDeploymentMetrics- summary: Query test-environment deployment duration (optional legacy integration)- description: Optional legacy CI integration that is not configured in the public edition. Uses a fixed pipeline and the signed-in user's platform credential. Loads all branches by default; branch is an optional filter. Other repositories are rejected.- parameters:- - {name: projectId, in: query, required: true, schema: {type: string}}- - {name: repositoryId, in: query, required: true, schema: {type: string}}- - {name: branch, in: query, required: false, description: Optional branch filter; omit to load all branches, schema: {type: string}}- - {name: pageSize, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 50}}- responses:- "200":- description: Normalized deployment metrics and build records- content:- application/json:- schema:- type: object- required: [projectId, repositoryId, branch, pipelineProjectId, pipelineId, queriedAt, summary, records]- properties:- projectId: {type: string}- repositoryId: {type: string}- repositoryName: {type: string}- branch: {type: string}- pipelineProjectId: {type: integer}- pipelineId: {type: integer}- pipelineUrl: {type: string, format: uri}- queriedAt: {type: string, format: date-time}- summary:- type: object- properties:- total: {type: integer}- succeeded: {type: integer}- failed: {type: integer}- running: {type: integer}- successRate: {type: number}- deployments7d: {type: integer}- average7dDurationMs: {type: integer, format: int64}- averageDurationMs: {type: integer, format: int64}- p50DurationMs: {type: integer, format: int64}- p90DurationMs: {type: integer, format: int64}- latestDurationMs: {type: integer, format: int64}- records:- type: array- items:- type: object- properties:- id: {type: string}- runNumber: {type: integer, format: int64}- status: {type: integer}- statusLabel: {type: string}- branch: {type: string}- revision: {type: string}- starter: {type: string}- triggerType: {type: string}- comment: {type: string}- startedAt: {type: string, format: date-time}- finishedAt: {type: string, format: date-time}- durationMs: {type: integer, format: int64}- url: {type: string, format: uri}- "400":- $ref: "#/components/responses/BadRequest"- "401":- $ref: "#/components/responses/Unauthorized"- "412":- description: QCI MCP or personal credential is not configured- "422":- description: The selected repository is not the configured pipeline repository- "502":- description: CodingCI query failed or returned an unsupported payload/api/runs:get:tags: [Runs]diff --git a/e2e/api/00-smoke.test.mjs b/e2e/api/00-smoke.test.mjsindex e9e83d9a..697c3fb8 100644--- a/e2e/api/00-smoke.test.mjs+++ b/e2e/api/00-smoke.test.mjs@@ -88,14 +88,8 @@ test('GET /api/knowledge/sources answers 503 with a reason when the knowledge baelse assert.ok(res.data);});-test('GET /api/deployment-metrics for a real repository', async () => {- await api('GET', '/api/deployment-metrics', undefined, { expect: 400 });- // The dashboard only supports SkillHub repositories and answers 422 for others.- for (const repo of list(await get('/api/repositories'))) {- const q = `projectId=${encodeURIComponent(repo.projectId)}&repositoryId=${encodeURIComponent(repo.id)}`;- const d = await api('GET', `/api/deployment-metrics?${q}`, undefined, { expect: [200, 422] });- assert.ok(d && typeof d === 'object');- }+test('GET /api/deployment-metrics is not served', async () => {+ await api('GET', '/api/deployment-metrics', undefined, { expect: 404 });});test('current user resolves through the token and model credentials are explicit', async () => {diff --git a/e2e/ui/01-views.spec.mjs b/e2e/ui/01-views.spec.mjsindex 8320cbbd..9cf65ac4 100644--- a/e2e/ui/01-views.spec.mjs+++ b/e2e/ui/01-views.spec.mjs@@ -6,14 +6,14 @@ import { test, expect, watchErrors } from './fixtures.mjs';// Keep in sync with viewTitles() in web/app.js; a renamed or dropped view is// a visible product change the suite should notice.const TITLES = {- collaboration: 'AI 工作台', issues: '需求列表', bots: 'Bot 管理', runs: '运行记录', metrics: '研发效能', deployments: '部署耗时',+ collaboration: 'AI 工作台', issues: '需求列表', bots: 'Bot 管理', runs: '运行记录', metrics: '研发效能',approvals: '待我确认', sops: '流程模板', flow: '流程设计', agents: '角色定义', mcp: 'MCP 管理', rules: '规则管理', skills: '技能管理',dockerfiles: 'Dockerfile', environments: '环境安装脚本', sandboxes: '沙箱管理', observability: '统计', projects: '项目配置',businessDomains: '业务领域', businessDomainManagement: '领域管理', platform: '平台管理', runners: '执行机器', settings: '个人配置',guide: '接入指南', knowledge: '知识中心',};// Only offered for some projects/hosts/roles; the app redirects otherwise.-const CONDITIONAL = ['deployments', 'businessDomainManagement', 'platform'];+const CONDITIONAL = ['businessDomainManagement', 'platform'];const ASSET_VIEWS = ['rules', 'skills', 'dockerfiles', 'environments', 'sandboxes'];const projects = [process.env.AGENTFLOW_E2E_VIEW_PROJECT || 'welcome', null];diff --git a/internal/application/operations.go b/internal/application/operations.goindex 2ebe483a..fac42217 100644--- a/internal/application/operations.go+++ b/internal/application/operations.go@@ -89,7 +89,6 @@ func PublicOperations() []Operation {{Name: "workflows_clone", Description: "Clone an SOP workflow", Method: "POST", Path: "/api/workflows/{id}/clone"},{Name: "workflow_metrics_get", Description: "Get SOP workflow operating metrics", Method: "GET", Path: "/api/workflow-metrics", ReadOnly: true},{Name: "analytics_get", Description: "Get usage and delivery analytics", Method: "GET", Path: "/api/analytics", ReadOnly: true},- {Name: "deployment_metrics_get", Description: "Query optional configured deployment duration metrics", Method: "GET", Path: "/api/deployment-metrics", ReadOnly: true},{Name: "observability_spec_get", Description: "Get the AgentFlow observability contract", Method: "GET", Path: "/api/observability/spec", ReadOnly: true},{Name: "runs_list", Description: "List lightweight Run summaries", Method: "GET", Path: "/api/runs", ReadOnly: true},{Name: "runs_control_get", Description: "Read the run mode (sop or workspace), waiting reason, allowed control actions and delivery acceptance. Node execution progress is separate from test results and user acceptance. Read this before changing a run's state.", Method: "GET", Path: "/api/runs/{id}/control", ReadOnly: true},diff --git a/internal/domain/delivery_mr_test.go b/internal/domain/delivery_mr_test.goindex 79c0b943..2ef2ab61 100644--- a/internal/domain/delivery_mr_test.go+++ b/internal/domain/delivery_mr_test.go@@ -93,19 +93,19 @@ func TestResolveRunDeliveryMRsPerRepository(t *testing.T) {func TestResolveRunDeliveryMRsAcceptsHTTPArtifactURL(t *testing.T) {run := Run{Repositories: []RepositoryContext{{- RepositoryID: "vpcdns", Name: "vpcdns_oss", GongfengProjectID: "dnspod/vpcdns/vpcdns_oss",+ RepositoryID: "demodns", Name: "dns-service", GongfengProjectID: "example/dns/dns-service",WorkBranch: "feature/story-1",}},Artifacts: []Artifact{{NodeID: "mr", Name: "mr-body",- Content: "MR: http://git.example.com/dnspod/vpcdns/vpcdns_oss/merge_requests/558",+ Content: "MR: http://git.example.com/example/dns/dns-service/merge_requests/558",}},}got := ResolveRunDeliveryMRs(run, func(RepositoryContext) (DeliveryMR, bool) { return DeliveryMR{}, false })- if len(got) != 1 || got[0].IID != 558 || got[0].RepositoryID != "vpcdns" {+ if len(got) != 1 || got[0].IID != 558 || got[0].RepositoryID != "demodns" {t.Fatalf("http artifact MR not recovered: %+v", got)}- if got[0].URL != "https://git.example.com/dnspod/vpcdns/vpcdns_oss/-/merge_requests/558" {+ if got[0].URL != "https://git.example.com/example/dns/dns-service/-/merge_requests/558" {t.Fatalf("url = %s", got[0].URL)}}diff --git a/internal/domain/mcp_test.go b/internal/domain/mcp_test.goindex 2b2f1459..6a590832 100644--- a/internal/domain/mcp_test.go+++ b/internal/domain/mcp_test.go@@ -29,7 +29,7 @@ func TestValidateMCPServer(t *testing.T) {}func TestValidateMCPServerScope(t *testing.T) {- base := MCPServerDefinition{ID: "iwiki", Name: "iWiki", Transport: "http", URL: "https://example.com/mcp"}+ base := MCPServerDefinition{ID: "wiki", Name: "Wiki", Transport: "http", URL: "https://example.com/mcp"}project := baseproject.Scope, project.ProjectID = "project", "p1"if err := ValidateMCPServer(project); err != nil {@@ -44,7 +44,7 @@ func TestValidateMCPServerScope(t *testing.T) {if err := ValidateMCPServer(personal); err == nil {t.Fatal("personal MCP without owner should be rejected")}- personal.OwnerUserID, personal.MarketID = 2, "iwiki"+ personal.OwnerUserID, personal.MarketID = 2, "wiki"if err := ValidateMCPServer(personal); err == nil {t.Fatal("personal market MCP should be rejected")}@@ -69,8 +69,8 @@ func TestParseMCPImportShapes(t *testing.T) {}func TestPublicMCPServerMasksCredentialEnvironmentOnly(t *testing.T) {- got := PublicMCPServer(MCPServerDefinition{Environment: map[string]string{"KNOT_API_TOKEN": "x", "DB_PASSWORD": "y", "PATH": "/usr/bin", "LOG_LEVEL": "debug", "GH_TOKEN": "${secret:GH}"}})- if got.Environment["KNOT_API_TOKEN"] != MaskedSecretValue || got.Environment["DB_PASSWORD"] != MaskedSecretValue {+ got := PublicMCPServer(MCPServerDefinition{Environment: map[string]string{"GATEWAY_API_TOKEN": "x", "DB_PASSWORD": "y", "PATH": "/usr/bin", "LOG_LEVEL": "debug", "GH_TOKEN": "${secret:GH}"}})+ if got.Environment["GATEWAY_API_TOKEN"] != MaskedSecretValue || got.Environment["DB_PASSWORD"] != MaskedSecretValue {t.Fatalf("credentials not masked: %v", got.Environment)}if got.Environment["PATH"] != "/usr/bin" || got.Environment["LOG_LEVEL"] != "debug" || got.Environment["GH_TOKEN"] != "${secret:GH}" {diff --git a/internal/domain/mr_test.go b/internal/domain/mr_test.goindex 24abc55f..878bac5f 100644--- a/internal/domain/mr_test.go+++ b/internal/domain/mr_test.go@@ -20,13 +20,13 @@ func TestParseGongfengMR(t *testing.T) {}func TestParseGongfengMRAcceptsHTTPAndCanonicalizes(t *testing.T) {- raw := "创建结果:http://git.example.com/dnspod/vpcdns/vpcdns_oss/merge_requests/557"+ raw := "创建结果:http://git.example.com/example/dns/dns-service/merge_requests/557"project, iid, url, ok := ParseGongfengMR(raw)- want := "https://git.example.com/dnspod/vpcdns/vpcdns_oss/-/merge_requests/557"- if !ok || project != "dnspod/vpcdns/vpcdns_oss" || iid != 557 || url != want {+ want := "https://git.example.com/example/dns/dns-service/-/merge_requests/557"+ if !ok || project != "example/dns/dns-service" || iid != 557 || url != want {t.Fatalf("got project=%q iid=%d url=%q ok=%v", project, iid, url, ok)}- if !SameGongfengMR(raw, "https://git.example.com/dnspod/vpcdns/vpcdns_oss/-/merge_requests/557") {+ if !SameGongfengMR(raw, "https://git.example.com/example/dns/dns-service/-/merge_requests/557") {t.Fatal("http and https forms of the same MR must match")}}diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.goindex 52898059..d01a506d 100644--- a/internal/engine/engine_test.go+++ b/internal/engine/engine_test.go@@ -374,15 +374,15 @@ func TestGenericMRRoleResolvesGongfengMarketAlias(t *testing.T) {}gongfeng := domain.MCPServerDefinition{ID: "mcp-61-project-alpha", Name: "Gongfeng MCP", Scope: "project", ProjectID: "alpha",- MarketID: "61", Transport: "http", URL: "https://mcpgw.knot.example.com/gongfeng",+ MarketID: "61", Transport: "http", URL: "https://mcp-gateway.example.com/gongfeng",}tapd := domain.MCPServerDefinition{ID: "mcp-70-project-alpha", Name: "TAPD MCP", Scope: "project", ProjectID: "alpha",- MarketID: "70", Transport: "http", URL: "https://mcpgw.knot.example.com/tapd",+ MarketID: "70", Transport: "http", URL: "https://mcp-gateway.example.com/tapd",}other := domain.MCPServerDefinition{ID: "mcp-61-project-beta", Name: "Gongfeng MCP", Scope: "project", ProjectID: "beta",- MarketID: "61", Transport: "http", URL: "https://mcpgw.knot.example.com/gongfeng",+ MarketID: "61", Transport: "http", URL: "https://mcp-gateway.example.com/gongfeng",}for _, server := range []domain.MCPServerDefinition{gongfeng, tapd, other} {if err := st.PutMCPServer(server); err != nil {@@ -516,8 +516,8 @@ func TestScriptNodeCanCallProjectMCP(t *testing.T) {t.Fatal(err)}if err := s.PutMCPServer(domain.MCPServerDefinition{- ID: "mcp-2214-project-dns", Name: "七彩石(Rainbow) MCP", MarketID: "2214",- Scope: "project", ProjectID: "dns", Transport: "http", URL: "https://mcpgw.knot.example.com/rainbow",+ ID: "mcp-2214-project-dns", Name: "Config Center MCP", MarketID: "2214",+ Scope: "project", ProjectID: "dns", Transport: "http", URL: "https://mcp-gateway.example.com/configcenter",Headers: map[string]string{"Authorization": "Bearer mcp_secret"},}); err != nil {t.Fatal(err)@@ -546,7 +546,7 @@ func TestScriptNodeCanCallProjectMCP(t *testing.T) {body = artifact.Content}}- if !strings.Contains(body, "2214") || !strings.Contains(body, "rainbow") {+ if !strings.Contains(body, "2214") || !strings.Contains(body, "configcenter") {t.Fatalf("mcp list artifact = %q", body)}if strings.Contains(body, "mcp_secret") || strings.Contains(strings.ToLower(body), "bearer") {@@ -568,8 +568,8 @@ func TestVerificationGateCanCallProjectMCP(t *testing.T) {t.Fatal(err)}if err := s.PutMCPServer(domain.MCPServerDefinition{- ID: "mcp-2214-project-dns", Name: "七彩石(Rainbow) MCP", MarketID: "2214",- Scope: "project", ProjectID: "dns", Transport: "http", URL: "https://mcpgw.knot.example.com/rainbow",+ ID: "mcp-2214-project-dns", Name: "Config Center MCP", MarketID: "2214",+ Scope: "project", ProjectID: "dns", Transport: "http", URL: "https://mcp-gateway.example.com/configcenter",Headers: map[string]string{"Authorization": "Bearer mcp_secret"},}); err != nil {t.Fatal(err)@@ -604,7 +604,7 @@ func TestVerificationGateCanCallProjectMCP(t *testing.T) {body = artifact.Content}}- if !strings.Contains(body, "2214") || !strings.Contains(body, "rainbow") {+ if !strings.Contains(body, "2214") || !strings.Contains(body, "configcenter") {t.Fatalf("gate mcp list artifact = %q status=%s node=%+v", body, finished.Status, finished.Nodes["prep"])}}@@ -726,7 +726,7 @@ func TestMaterializeInputsMountsCloseDeliveryArtifacts(t *testing.T) {{NodeID: "test", Attempt: 1, Name: "test-report", Path: "test-report.md", MediaType: "text/markdown", SHA256: "a", Content: "coverage 81%"},{NodeID: "test", Attempt: 1, Name: "e2e-cases", Path: "e2e-cases.md", MediaType: "text/markdown", SHA256: "b", Content: "go test ./tests/integration"},{NodeID: "mr", Attempt: 1, Name: "mr-body", Path: "mr-body.md", MediaType: "text/markdown", SHA256: "c", Content: "https://git.example.com/x/y/merge_requests/1"},- {NodeID: "verify", Attempt: 1, Name: "e2e-report", Path: "e2e-report.md", MediaType: "text/markdown", SHA256: "d", Content: "pipeline https://zhiyan.example.com/qci/1"},+ {NodeID: "verify", Attempt: 1, Name: "e2e-report", Path: "e2e-report.md", MediaType: "text/markdown", SHA256: "d", Content: "pipeline https://ci.example.com/build/1"},{NodeID: "checkers", Attempt: 1, Name: "checkers-report", Path: "checkers-report.md", MediaType: "text/markdown", SHA256: "e", Content: "all green"},}}manifest, err := materializeInputs(dir, wf, domain.WorkflowNode{ID: "close"}, run)@@ -745,7 +745,7 @@ func TestMaterializeInputsMountsCloseDeliveryArtifacts(t *testing.T) {if !strings.Contains(manifest, "verify / e2e-report") || !strings.Contains(manifest, "test / test-report") {t.Fatalf("manifest missing close delivery artifacts: %s", manifest)}- if strings.Contains(manifest, "coverage 81%") || strings.Contains(manifest, "pipeline https://zhiyan.example.com") {+ if strings.Contains(manifest, "coverage 81%") || strings.Contains(manifest, "pipeline https://ci.example.com") {t.Fatalf("prompt catalog must not inline artifact bodies: %s", manifest)}}diff --git a/internal/engine/misc_helpers_cases_test.go b/internal/engine/misc_helpers_cases_test.goindex 30e5d1f9..eb954a38 100644--- a/internal/engine/misc_helpers_cases_test.go+++ b/internal/engine/misc_helpers_cases_test.go@@ -490,7 +490,7 @@ func TestPromptObservabilityAlignAndResumeRemainingBranches(t *testing.T) {}run.Repository.PipelineURLPattern = ""run.Repository.PipelineProjectID, run.Repository.PipelineDefID = 12, 34- if prompt = applyPromptPlaceholders(nil, domain.WorkflowDefinition{}, node, nil, nil, run); !strings.Contains(prompt, "/12/") {+ if prompt = applyPromptPlaceholders(nil, domain.WorkflowDefinition{}, node, nil, nil, run); !strings.Contains(prompt, "未配置 Pipeline") {t.Fatalf("pipeline prompt=%q", prompt)}continued := domain.Run{diff --git a/internal/engine/prompt.go b/internal/engine/prompt.goindex 56b6081d..f3810cd7 100644--- a/internal/engine/prompt.go+++ b/internal/engine/prompt.go@@ -45,9 +45,6 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, nodepipelineURL := "未配置 Pipeline"if run.Repository.PipelineURLPattern != "" {pipelineURL = strings.ReplaceAll(run.Repository.PipelineURLPattern, "{build_id}", "current")- } else if run.Repository.PipelineProjectID > 0 && run.Repository.PipelineDefID > 0 {- pipelineURL = fmt.Sprintf("https://zhiyan.example.com/qci/%d/pipeline/#/pipeline/detail/%d/build/current",- run.Repository.PipelineProjectID, run.Repository.PipelineDefID)}prompt = strings.ReplaceAll(prompt, "{{pipelineUrl}}", pipelineURL)prompt = strings.ReplaceAll(prompt, "{{existingMR}}", existingMRBlurb(st, run))diff --git a/internal/httpapi/agent_tool_catalog.go b/internal/httpapi/agent_tool_catalog.goindex df31dcb6..325cf152 100644--- a/internal/httpapi/agent_tool_catalog.go+++ b/internal/httpapi/agent_tool_catalog.go@@ -81,7 +81,7 @@ func sanitizeAgentToolNamespace(id, name string) string {out = strings.ReplaceAll(out, "__", "_")}switch out {- case "", "tapd", "gongfeng", "iwiki", "agentflow":+ case "", "tapd", "gongfeng", "agentflow":return "mcp"default:return out@@ -143,12 +143,6 @@ func agentToolKindAllowlistNames(mode AgentToolMode, kind string) []string {)}return names- case "iwiki":- names := []string{"getDocument"}- if agentToolAllowsAssistantReads(mode) {- names = append(names, "getSpacePageTree", "searchDocument", "searchWeDoc", "getSpaceInfo", "getMySpaces", "aiSearchDocument", "listImages", "getComments", "glossaryTermSearch")- }- return namescase "agentflow":if mode == AgentToolClarify {return []string{"issues_get", "issues_list", "repositories_get", "projects_get"}@@ -167,7 +161,7 @@ func agentToolKindAllowlistNames(mode AgentToolMode, kind string) []string {func agentflowNoisyTool(name string) bool {switch name {- case "health_get", "capabilities_get", "openapi_get", "bootstrap_get", "observability_spec_get", "analytics_get", "analytics_skillhub_get", "deployment_metrics_get", "workflow_metrics_get":+ case "health_get", "capabilities_get", "openapi_get", "bootstrap_get", "observability_spec_get", "analytics_get", "workflow_metrics_get":return truedefault:return falsediff --git a/internal/httpapi/agent_tool_native.go b/internal/httpapi/agent_tool_native.goindex a22f9104..41c42bbd 100644--- a/internal/httpapi/agent_tool_native.go+++ b/internal/httpapi/agent_tool_native.go@@ -21,7 +21,7 @@ const (nativeAssistantUnlimitedTurns = "9007199254740991"nativeTerminalMaxRetries = 2agentToolSessionMCPServerID = "agentflow_session"- // The session gateway lists upstream TAPD/工蜂/iWiki tools before it+ // The session gateway lists upstream TAPD/工蜂 tools before it// answers tools/list, which can exceed CodeBuddy's ~2s headless MCP wait.// The tools pinned with defer_loading=false below would then be absent// from the first model request and, being non-deferred, unreachable viadiff --git a/internal/httpapi/clarify_cases_test.go b/internal/httpapi/clarify_cases_test.goindex 33b7610d..c4dcfe69 100644--- a/internal/httpapi/clarify_cases_test.go+++ b/internal/httpapi/clarify_cases_test.go@@ -189,7 +189,7 @@ func TestClarifyMCPInstructionsAndOwnership(t *testing.T) {for _, server := range []domain.MCPServerDefinition{{ID: "cva-tapd", Name: "TAPD", ProjectID: projectID, Scope: "project", MarketID: "70", Transport: "http", URL: "https://example.test/tapd"},{ID: "cva-gf", Name: "Gongfeng", ProjectID: projectID, Scope: "project", MarketID: "61", Transport: "http", URL: "https://example.test/gf"},- {ID: "cva-iwiki", Name: "iWiki", ProjectID: projectID, Scope: "project", MarketID: "58", Transport: "http", URL: "https://example.test/iwiki"},+ {ID: "cva-wiki", Name: "Wiki", ProjectID: projectID, Scope: "project", MarketID: "58", Transport: "http", URL: "https://example.test/wiki"},{ID: "cva-other", Name: "Other", ProjectID: projectID, Scope: "project", Transport: "http", URL: "https://example.test/other"},{ID: "cva-stdio", Name: "stdio", ProjectID: projectID, Scope: "project", Transport: "stdio", Command: "x"},} {@@ -198,9 +198,9 @@ func TestClarifyMCPInstructionsAndOwnership(t *testing.T) {}}h := &streamHandlers{deps: &deps{repo: st}}- tapd := domain.Issue{ID: "tapd-i", ProjectID: projectID, Source: "tapd", Description: "https://iwiki.example.com/pages/12345", ExternalRef: &domain.ExternalRef{Source: "tapd", ExternalID: "9", ExternalType: "bug", ExternalURL: "https://tapd.example.com/ws/bugtrace/bugs/view?bug_id=9"}}+ tapd := domain.Issue{ID: "tapd-i", ProjectID: projectID, Source: "tapd", Description: "https://wiki.example.com/pages/12345", ExternalRef: &domain.ExternalRef{Source: "tapd", ExternalID: "9", ExternalType: "bug", ExternalURL: "https://tapd.example.com/ws/bugtrace/bugs/view?bug_id=9"}}text := h.clarifyMCPInstructionsFor(tapd, worker, false)- if !strings.Contains(text, "bugs_get") || !strings.Contains(text, "docid=12345") || !strings.Contains(text, "其他已安装") {+ if !strings.Contains(text, "bugs_get") || strings.Contains(text, "docid=") || !strings.Contains(text, "其他已安装") {t.Fatalf("tapd instructions=%s", text)}if resumed := h.clarifyMCPInstructionsFor(tapd, worker, true); !strings.Contains(resumed, "不要再重拉") {diff --git a/internal/httpapi/clarify_mcp.go b/internal/httpapi/clarify_mcp.goindex ab7efe60..3c070ec1 100644--- a/internal/httpapi/clarify_mcp.go+++ b/internal/httpapi/clarify_mcp.go@@ -18,9 +18,6 @@ const ()var (- iwikiURLRe = regexp.MustCompile(`(?i)https?://(?:[a-z0-9.-]*iwiki[a-z0-9.-]*|\bi\.example\.com)[^\s<>"')】\]]+`)- iwikiIDRe = regexp.MustCompile(`(?i)(?:pageId|pageid|docid|docId)=([0-9A-Za-z_-]+)`)- iwikiPathRe = regexp.MustCompile(`(?i)/(?:pages?|p)/([0-9]{4,})`)tapdURLRe = regexp.MustCompile(`(?i)https?://(?:www\.)?(?:tapd\.example\.com|tapd\.cn)[^\s<>"')】\]]+`)gongfengIssueURLRe = regexp.MustCompile(`(?i)https?://git\.example\.com/[^\s<>"')】\]]+/issues/\d+`))@@ -103,8 +100,6 @@ func classifyClarifyMCP(item domain.MCPServerDefinition) string {return "tapd"case mid == "61" || mid == "gongfeng" || strings.Contains(blob, "gongfeng") || strings.Contains(blob, "工蜂"):return "gongfeng"- case mid == "58" || mid == "iwiki" || strings.Contains(blob, "iwiki"):- return "iwiki"default:return "other"}@@ -297,32 +292,6 @@ func clarifyRequestTexts(request chatClarifyRequest) []string {return texts}-func extractIWikiURLs(texts ...string) []string {- seen := map[string]bool{}- var out []string- for _, text := range texts {- for _, match := range iwikiURLRe.FindAllString(text, -1) {- url := strings.TrimRight(match, ".,;:,。;:")- if url == "" || seen[url] {- continue- }- seen[url] = true- out = append(out, url)- }- }- return out-}--func iwikiDocIDFromURL(raw string) string {- if m := iwikiIDRe.FindStringSubmatch(raw); len(m) == 2 {- return m[1]- }- if m := iwikiPathRe.FindStringSubmatch(raw); len(m) == 2 {- return m[1]- }- return ""-}-func (h *streamHandlers) clarifyMCPInstructions(issue domain.Issue, user domain.User, resumed bool, extras ...string) string {return h.clarifyMCPInstructionsFor(issue, user, resumed, extras...)}@@ -334,7 +303,7 @@ func (h *streamHandlers) clarifyMCPInstructionsFor(issue domain.Issue, user doma}servers := h.clarifyHTTPMCPs(projectID, user.ID)project, _ := h.repo.Project(projectID)- var tapd, gongfeng, iwiki []domain.MCPServerDefinition+ var tapd, gongfeng []domain.MCPServerDefinitionvar other []domain.MCPServerDefinitionfor _, item := range servers {switch classifyClarifyMCP(item) {@@ -342,8 +311,6 @@ func (h *streamHandlers) clarifyMCPInstructionsFor(issue domain.Issue, user domatapd = append(tapd, item)case "gongfeng":gongfeng = append(gongfeng, item)- case "iwiki":- iwiki = append(iwiki, item)default:other = append(other, item)}@@ -356,9 +323,6 @@ func (h *streamHandlers) clarifyMCPInstructionsFor(issue domain.Issue, user domaif len(gongfeng) > 0 {b.WriteString("代码托管 Issue 用 gongfeng__get_issue_detail、gongfeng__get_issue_notes 读取。\n")}- if len(iwiki) > 0 {- b.WriteString("文档链接用 iwiki__getDocument 读取。\n")- }if len(servers) > 0 {b.WriteString("当前项目和个人可用 HTTP MCP:\n")for _, item := range servers {@@ -383,7 +347,7 @@ func (h *streamHandlers) clarifyMCPInstructionsFor(issue domain.Issue, user domagetTool = "tasks_get"}if resumed {- fmt.Fprintf(&b, "这是 TAPD %s。对话里已有此前分析,不要再重拉原单和评论。仅当出现尚未读取的新 iWiki 链接时才 getDocument。\n", entryType)+ fmt.Fprintf(&b, "这是 TAPD %s。对话里已有此前分析,不要再重拉原单和评论。仅当出现尚未读取的新文档链接时才用对应 MCP 读取。\n", entryType)} else {fmt.Fprintf(&b, "这是 TAPD %s。先静默读取原单和评论。调用 %s:tool_name=%s,tool_args.workspace_id=%s,tool_args.id=%s(字符串),tool_args.limit=1。评论同样调用该工具,tool_name=comments_get,tool_args.workspace_id=%s,tool_args.entry_type=%s,tool_args.entry_id=%s。不要用 params,必须用 tool_args。\n",entryType, tapdTool("proxy_execute_tool"), getTool, ws, entryID, ws, entryType, entryID)@@ -403,27 +367,9 @@ func (h *streamHandlers) clarifyMCPInstructionsFor(issue domain.Issue, user domagfProject, issueIID, gfProject, issueID)}}- if issue.ID == "" && issue.ExternalRef == nil && (len(tapd) > 0 || len(gongfeng) > 0 || len(iwiki) > 0) {+ if issue.ID == "" && issue.ExternalRef == nil && (len(tapd) > 0 || len(gongfeng) > 0) {b.WriteString("这是尚未建单的需求草稿,没有原单可拉。描述或对话里出现上述工具能读取的链接时必须先读取后再出题;没有链接不要为了找原单去 list。\n")}- if len(iwiki) > 0 {- urls := extractIWikiURLs(append([]string{issue.Title, issue.Description}, extras...)...)- if resumed {- b.WriteString("仅当出现尚未读取过的新 iWiki 链接时,用 iwiki__getDocument 读取;不要顺着文档里的链接继续追。\n")- } else {- b.WriteString("若需求正文、TAPD/工蜂原单或评论里出现 iWiki 链接,必须同步读取:用 iwiki__getDocument,arguments.docid 为文档 ID(可从 URL 的 pageId/docid 或 /pages/{id} 提取)。不要只根据链接标题猜测正文。文档里再引用的 iWiki 只读与当前缺口直接相关的一篇。\n")- }- if len(urls) > 0 {- b.WriteString("当前描述中已发现 iWiki 链接:\n")- for _, url := range urls {- line := "- " + url- if id := iwikiDocIDFromURL(url); id != "" {- line += "(docid=" + id + ")"- }- b.WriteString(line + "\n")- }- }- }if len(other) > 0 {b.WriteString("其他已安装的 HTTP MCP 按工具名直接调用,仅限只读。\n")}diff --git a/internal/httpapi/clarify_mcp_test.go b/internal/httpapi/clarify_mcp_test.goindex e62cc88e..b307692d 100644--- a/internal/httpapi/clarify_mcp_test.go+++ b/internal/httpapi/clarify_mcp_test.go@@ -204,7 +204,7 @@ func TestHydrateClarifyIssueFromDraftText(t *testing.T) {}}-func TestClarifyMCPInstructionsRequireTAPDCommentsAndIWiki(t *testing.T) {+func TestClarifyMCPInstructionsRequireTAPDComments(t *testing.T) {st, err := repo.OpenTest()if err != nil {t.Fatal(err)@@ -217,21 +217,24 @@ func TestClarifyMCPInstructionsRequireTAPDCommentsAndIWiki(t *testing.T) {if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-70-project-platform", Name: "TAPD MCP", ProjectID: "platform", MarketID: "70", Scope: "project", Transport: "http", URL: "https://example.test/tapd"}); err != nil {t.Fatal(err)}- if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-58-project-platform", Name: "iWiki", ProjectID: "platform", MarketID: "58", Scope: "project", Transport: "http", URL: "https://example.test/iwiki"}); err != nil {+ if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-wiki-project-platform", Name: "Wiki", ProjectID: "platform", MarketID: "58", Scope: "project", Transport: "http", URL: "https://example.test/wiki"}); err != nil {t.Fatal(err)}h := &streamHandlers{deps: &deps{repo: st}}issue := domain.Issue{ProjectID: "platform", Source: "tapd", Title: "读评论",- Description: "方案见 https://iwiki.example.com/pages/viewpage.action?pageId=999001",+ Description: "方案见 https://wiki.example.com/pages/viewpage.action?pageId=999001",ExternalRef: &domain.ExternalRef{Source: "tapd", ExternalID: "1010000000100000555", ExternalType: "story", ExternalURL: "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100000555"},}prompt := h.clarifyMCPInstructions(issue, user, false)- for _, want := range []string{"submit_clarification", "tapd__proxy_execute_tool", "comments_get", "stories_get", "getDocument", "docid=999001"} {+ for _, want := range []string{"submit_clarification", "tapd__proxy_execute_tool", "comments_get", "stories_get", "Wiki(id=mcp-wiki-project-platform", "其他已安装的 HTTP MCP"} {if !strings.Contains(prompt, want) {t.Fatalf("prompt missing %q:\n%s", want, prompt)}}+ if strings.Contains(prompt, "getDocument") || strings.Contains(prompt, "docid=") {+ t.Fatalf("a generic wiki MCP must not get vendor-specific document instructions:\n%s", prompt)+ }if strings.Contains(prompt, "mcpCalls") {t.Fatalf("clarify instructions still mention mcpCalls:\n%s", prompt)}diff --git a/internal/httpapi/clarify_session_test.go b/internal/httpapi/clarify_session_test.goindex 32b31ac4..7b291d8c 100644--- a/internal/httpapi/clarify_session_test.go+++ b/internal/httpapi/clarify_session_test.go@@ -14,8 +14,8 @@ import (func TestMaterializeClarifyRepoCreatesRealTree(t *testing.T) {root := t.TempDir()- src := filepath.Join(root, "cache", "new_dnspod")- dest := filepath.Join(root, "ws", "new_dnspod")+ src := filepath.Join(root, "cache", "dns-console")+ dest := filepath.Join(root, "ws", "dns-console")mustWriteClarifyFile(t, filepath.Join(src, "TagService.php"), "function processMsg() {}\n")mustWriteClarifyFile(t, filepath.Join(src, ".git", "HEAD"), "ref: refs/heads/master\n")diff --git a/internal/httpapi/deployment_metrics.go b/internal/httpapi/deployment_metrics.godeleted file mode 100644index b9db7023..00000000--- a/internal/httpapi/deployment_metrics.go+++ /dev/null@@ -1,592 +0,0 @@-package httpapi--import (- "context"- "encoding/json"- "fmt"- "math"- "net/http"- "net/url"- "sort"- "strconv"- "strings"- "time"-- "agentflow/internal/domain"- "agentflow/internal/mcpclient"-- "github.com/gin-gonic/gin"-)--const (- deploymentMetricsMaxPageSize = 100- deploymentMetricsTimeout = 45 * time.Second- skillHubPipelineProjectID = 10001- skillHubDeploymentPipelineID = 10000001- skillHubGongfengProjectID = "example/team-project"-)--type deploymentMetricsHandlers struct{ *deps }--type deploymentMetricRecord struct {- ID string `json:"id"`- RunNumber int64 `json:"runNumber,omitempty"`- Status int `json:"status"`- StatusLabel string `json:"statusLabel"`- Branch string `json:"branch"`- Revision string `json:"revision,omitempty"`- Starter string `json:"starter,omitempty"`- TriggerType string `json:"triggerType,omitempty"`- Comment string `json:"comment,omitempty"`- StartedAt string `json:"startedAt,omitempty"`- FinishedAt string `json:"finishedAt,omitempty"`- DurationMs int64 `json:"durationMs"`- URL string `json:"url,omitempty"`-}--type deploymentMetricSummary struct {- Total int `json:"total"`- Succeeded int `json:"succeeded"`- Failed int `json:"failed"`- Running int `json:"running"`- SuccessRate float64 `json:"successRate"`- Deployments7d int `json:"deployments7d"`- Average7dDurationMs int64 `json:"average7dDurationMs"`- AverageDurationMs int64 `json:"averageDurationMs"`- P50DurationMs int64 `json:"p50DurationMs"`- P90DurationMs int64 `json:"p90DurationMs"`- LatestDurationMs int64 `json:"latestDurationMs"`-}--type deploymentMetricsResponse struct {- ProjectID string `json:"projectId"`- RepositoryID string `json:"repositoryId"`- RepositoryName string `json:"repositoryName"`- Branch string `json:"branch"`- PipelineProject int `json:"pipelineProjectId"`- PipelineID int `json:"pipelineId"`- PipelineURL string `json:"pipelineUrl,omitempty"`- QueriedAt string `json:"queriedAt"`- Summary deploymentMetricSummary `json:"summary"`- Records []deploymentMetricRecord `json:"records"`-}--func (h *deploymentMetricsHandlers) deploymentMetrics(c *gin.Context) {- current, ok := h.requestUser(c.Request, true)- if !ok {- c.JSON(http.StatusUnauthorized, map[string]string{"error": "请先登录后查询部署耗时"})- return- }- storedUser, ok := h.repo.User(current.ID)- if !ok {- c.JSON(http.StatusUnauthorized, map[string]string{"error": "当前用户尚未完成平台注册"})- return- }- projectID := strings.TrimSpace(c.Query("projectId"))- repositoryID := strings.TrimSpace(c.Query("repositoryId"))- branch := strings.TrimSpace(c.Query("branch"))- if projectID == "" || repositoryID == "" {- c.JSON(http.StatusBadRequest, map[string]string{"error": "projectId 和 repositoryId 必填"})- return- }- if len(branch) > 255 || strings.ContainsAny(branch, "\r\n\x00") {- c.JSON(http.StatusBadRequest, map[string]string{"error": "分支名格式不合法"})- return- }- if _, ok := h.repo.Project(projectID); !ok {- c.JSON(http.StatusNotFound, map[string]string{"error": "项目不存在"})- return- }- repository, ok := h.repo.Repository(repositoryID)- if !ok || repository.ProjectID != projectID {- c.JSON(http.StatusNotFound, map[string]string{"error": "当前项目中不存在该仓库"})- return- }- if !isSkillHubRepository(repository) {- c.JSON(http.StatusUnprocessableEntity, map[string]string{"error": "当前看板仅支持 SkillHub 仓库"})- return- }- pipelineProject := skillHubPipelineProjectID- pipelineID := skillHubDeploymentPipelineID- pageSize := positiveQueryInt(c, "pageSize", 50)- if pageSize > deploymentMetricsMaxPageSize {- pageSize = deploymentMetricsMaxPageSize- }-- server, ok := h.lookupQCIProjectMCP(projectID, current.ID)- if !ok {- c.JSON(http.StatusPreconditionFailed, map[string]string{"error": "当前项目尚未添加“智研QCI流水线” MCP,请先在 MCP 管理中添加"})- return- }- bound, err := bindAssistantMCP(server, storedUser)- if err != nil {- c.JSON(http.StatusPreconditionFailed, map[string]string{"error": err.Error()})- return- }- if bound.Headers == nil {- bound.Headers = map[string]string{}- }- bound.Headers["X-Username"] = current.LoginName- query := url.Values{}- query.Set("page_size", strconv.Itoa(pageSize))- query.Set("ordering", "-created")- if branch != "" {- query.Set("cur_branch", branch)- }- ctx, cancel := context.WithTimeout(c.Request.Context(), deploymentMetricsTimeout)- defer cancel()- client := mcpclient.New(bound.URL, bound.Headers).WithTimeout(deploymentMetricsTimeout)- records := make([]deploymentMetricRecord, 0, pageSize)- for page := 1; page <= 10; page++ {- query.Set("page", strconv.Itoa(page))- path := fmt.Sprintf("/pipeline/%d/totalresult?%s", pipelineID, query.Encode())- raw, err := client.CallToolContext(ctx, "coding_mcp", map[string]any{- "method": http.MethodGet, "path": path,- "project_id": strconv.Itoa(pipelineProject), "username": current.LoginName,- })- if err != nil {- c.JSON(http.StatusBadGateway, map[string]string{"error": "查询智研流水线失败:" + err.Error()})- return- }- batch, err := normalizeDeploymentRecords(raw, branch, repository, pipelineProject, pipelineID)- if err != nil {- c.JSON(http.StatusBadGateway, map[string]string{"error": "智研流水线返回的数据无法解析:" + err.Error()})- return- }- records = append(records, batch...)- if len(batch) < pageSize {- break- }- }- sort.SliceStable(records, func(i, j int) bool { return records[i].StartedAt > records[j].StartedAt })- response := deploymentMetricsResponse{- ProjectID: projectID, RepositoryID: repository.ID, RepositoryName: repository.Name,- Branch: branch, PipelineProject: pipelineProject, PipelineID: pipelineID,- PipelineURL: deploymentPipelineURL(repository, pipelineProject, pipelineID),- QueriedAt: time.Now().UTC().Format(time.RFC3339), Records: records,- }- response.Summary = summarizeDeploymentMetricsAt(records, time.Now().UTC())- c.JSON(http.StatusOK, response)-}--func positiveQueryInt(c *gin.Context, name string, fallback int) int {- raw := strings.TrimSpace(c.Query(name))- if raw == "" {- return fallback- }- value, err := strconv.Atoi(raw)- if err != nil || value <= 0 {- return 0- }- return value-}--func (h *deploymentMetricsHandlers) lookupQCIProjectMCP(projectID string, userID int64) (domain.MCPServerDefinition, bool) {- for _, item := range assistantOutboundMCPServers(h.repo.MCPServers(), projectID, userID) {- identity := strings.ToLower(strings.Join([]string{item.ID, item.Name, item.MarketID, item.URL}, " "))- if item.MarketID == "7897" || strings.Contains(identity, "zhiyan/qci") || strings.Contains(identity, "zhiyan-pipeline") || strings.Contains(identity, "智研qci") {- return item, true- }- }- // The SkillHub dashboard has one fixed, read-only QCI integration. Reuse the- // official market definition even when the project has not explicitly added- // it yet; personal credentials are still required and bound per call.- if item, ok := marketItem("zhiyan-pipeline"); ok {- return domain.MCPServerDefinition{- ID: "skillhub-deployment-qci", Name: item.Name, ProjectID: projectID,- MarketID: item.ID, Scope: "project", Transport: item.Transport,- URL: item.URL, AuthType: item.AuthType, TimeoutSec: 60,- }, true- }- return domain.MCPServerDefinition{}, false-}--func isSkillHubRepository(repository domain.Repository) bool {- project := strings.Trim(strings.ToLower(strings.TrimSpace(repository.GongfengProjectID)), "/")- if project == skillHubGongfengProjectID {- return true- }- if strings.EqualFold(strings.TrimSpace(repository.Name), "skillhub") {- return strings.Contains(strings.ToLower(repository.WebURL+" "+repository.CloneURL), "example/team-project")- }- return false-}--func deploymentPipelineURL(repository domain.Repository, projectID, pipelineID int) string {- if pattern := strings.TrimSpace(repository.PipelineURLPattern); pattern != "" {- return strings.ReplaceAll(pattern, "{build_id}", "current")- }- return fmt.Sprintf("https://zhiyan.example.com/qci/%d/pipeline/#/pipeline/detail/%d/build/current", projectID, pipelineID)-}--func deploymentBuildURL(repository domain.Repository, projectID, pipelineID int, buildID string) string {- if pattern := strings.TrimSpace(repository.PipelineURLPattern); pattern != "" && strings.Contains(pattern, "{build_id}") {- return strings.ReplaceAll(pattern, "{build_id}", url.PathEscape(buildID))- }- return fmt.Sprintf("https://zhiyan.example.com/qci/%d/pipeline/#/pipeline/detail/%d/build/%s", projectID, pipelineID, url.PathEscape(buildID))-}--func normalizeDeploymentRecords(raw, branch string, repository domain.Repository, pipelineProject, pipelineID int) ([]deploymentMetricRecord, error) {- rows := deploymentReadableRows(raw)- if rows == nil {- payload, err := decodeMCPJSON(raw)- if err != nil {- return nil, err- }- rows = deploymentRows(payload)- if rows == nil {- return nil, fmt.Errorf("未找到构建记录列表")- }- }- records := make([]deploymentMetricRecord, 0, len(rows))- for _, row := range rows {- recordBranch := stringField(row, "cur_branch", "curBranch", "branch", "source_branch")- if branch != "" && recordBranch != "" && recordBranch != branch {- continue- }- started := timeField(row, "start_time", "startTime", "started_at", "startedAt", "created", "created_at")- finished := timeField(row, "finish_time", "finishTime", "finished_at", "finishedAt", "updated", "updated_at")- durationMs := durationField(row, started, finished)- status := deploymentStatus(row)- id := stringField(row, "id", "totalresult_id", "totalResultId", "build_id", "buildId")- record := deploymentMetricRecord{- ID: id, RunNumber: int64(intField(row, "run_num", "runNumber")), Status: status,- StatusLabel: coalesce(stringField(row, "status_label", "statusLabel"), deploymentStatusLabel(status)), Branch: coalesce(recordBranch, branch),- Revision: stringField(row, "cur_revision", "curRevision", "revision", "commit_id"),- Starter: stringField(row, "starter", "start_user", "creator"),- TriggerType: stringField(row, "trigger_type", "triggerType"), Comment: stringField(row, "comment", "remark"),- DurationMs: durationMs,- }- if !started.IsZero() {- record.StartedAt = started.UTC().Format(time.RFC3339)- }- if !finished.IsZero() {- record.FinishedAt = finished.UTC().Format(time.RFC3339)- }- if id != "" {- record.URL = deploymentBuildURL(repository, pipelineProject, pipelineID, id)- } else {- record.URL = deploymentPipelineURL(repository, pipelineProject, pipelineID)- }- records = append(records, record)- }- sort.SliceStable(records, func(i, j int) bool { return records[i].StartedAt > records[j].StartedAt })- return records, nil-}--func deploymentReadableRows(text string) []map[string]any {- fieldNames := map[string]string{- "构建结果ID": "id", "运行序列号": "run_num", "构建状态": "status",- "触发方式": "trigger_type", "启动人": "starter", "触发分支": "cur_branch",- "Commit ID": "cur_revision", "构建备注": "comment", "构建开始时间": "start_time",- "构建结束时间": "finish_time", "构建耗时": "duration",- }- var rows []map[string]any- for _, rawLine := range strings.Split(text, "\n") {- line := strings.TrimSpace(rawLine)- dot := strings.Index(line, ". ")- if dot <= 0 {- continue- }- if _, err := strconv.Atoi(line[:dot]); err != nil {- continue- }- row := map[string]any{}- for _, field := range strings.Split(line[dot+2:], " | ") {- label, value, ok := strings.Cut(field, ": ")- if !ok {- continue- }- if key := fieldNames[strings.TrimSpace(label)]; key != "" {- row[key] = strings.TrimSpace(value)- }- }- if strings.TrimSpace(fmt.Sprint(row["id"])) != "" {- rows = append(rows, row)- }- }- return rows-}--func decodeMCPJSON(raw string) (any, error) {- text := strings.TrimSpace(raw)- if strings.HasPrefix(text, "```") {- if nl := strings.IndexByte(text, '\n'); nl >= 0 {- text = text[nl+1:]- }- text = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(text), "```"))- }- starts := []int{}- if i := strings.IndexByte(text, '{'); i >= 0 {- starts = append(starts, i)- }- if i := strings.IndexByte(text, '['); i >= 0 {- starts = append(starts, i)- }- if len(starts) == 0 {- return nil, fmt.Errorf("返回内容不是 JSON")- }- sort.Ints(starts)- for _, start := range starts {- var payload any- decoder := json.NewDecoder(strings.NewReader(text[start:]))- decoder.UseNumber()- if decoder.Decode(&payload) == nil {- return payload, nil- }- }- return nil, fmt.Errorf("JSON 格式不完整")-}--func deploymentRows(payload any) []map[string]any {- switch value := payload.(type) {- case string:- decoded, err := decodeMCPJSON(value)- if err == nil {- return deploymentRows(decoded)- }- case []any:- rows := make([]map[string]any, 0, len(value))- for _, item := range value {- if row, ok := item.(map[string]any); ok {- rows = append(rows, row)- }- }- return rows- case map[string]any:- for _, key := range []string{"results", "items", "list", "records", "data", "result"} {- if nested, ok := value[key]; ok {- if rows := deploymentRows(nested); rows != nil {- return rows- }- }- }- }- return nil-}--func mapField(row map[string]any, keys ...string) any {- for _, key := range keys {- if value, ok := row[key]; ok && value != nil {- return value- }- }- return nil-}--func stringField(row map[string]any, keys ...string) string {- value := mapField(row, keys...)- if value == nil {- return ""- }- return strings.TrimSpace(fmt.Sprint(value))-}--func intField(row map[string]any, keys ...string) int {- value := mapField(row, keys...)- switch n := value.(type) {- case json.Number:- i, _ := n.Int64()- return int(i)- case float64:- return int(n)- case int:- return n- }- i, _ := strconv.Atoi(strings.TrimSpace(fmt.Sprint(value)))- return i-}--func timeField(row map[string]any, keys ...string) time.Time {- value := strings.TrimSpace(stringField(row, keys...))- if value == "" {- return time.Time{}- }- for _, layout := range []string{time.RFC3339Nano, time.RFC3339} {- if parsed, err := time.Parse(layout, value); err == nil {- return parsed- }- }- for _, layout := range []string{"2006-01-02T15:04:05", "2006-01-02 15:04:05", "2006-01-02 15:04:05.999999"} {- if parsed, err := time.ParseInLocation(layout, value, time.Local); err == nil {- return parsed- }- }- return time.Time{}-}--func deploymentStatus(row map[string]any) int {- if status := intField(row, "status"); status != 0 {- return status- }- label := strings.ToLower(stringField(row, "status_label", "statusLabel", "status"))- switch {- case strings.Contains(label, "成功"), strings.Contains(label, "通过"), label == "succeeded", label == "success", label == "passed":- return 2- case strings.Contains(label, "测试失败"):- return 13- case strings.Contains(label, "失败"), label == "failed":- return 3- case strings.Contains(label, "超时"), label == "timeout":- return 6- case strings.Contains(label, "中止"), strings.Contains(label, "取消"), label == "cancelled", label == "aborted":- return 4- case strings.Contains(label, "运行"), strings.Contains(label, "执行中"), label == "running":- return 1- case strings.Contains(label, "阻塞"), label == "blocked":- return 7- case strings.Contains(label, "就绪"), label == "ready":- return 8- }- return 0-}--func durationField(row map[string]any, started, finished time.Time) int64 {- if !started.IsZero() && !finished.IsZero() && finished.After(started) {- return finished.Sub(started).Milliseconds()- }- if value := mapField(row, "duration_ms", "durationMs"); value != nil {- return numericMilliseconds(value, 1)- }- value := mapField(row, "duration", "elapsed", "elapsed_seconds")- if value == nil {- return 0- }- if text, ok := value.(string); ok {- text = strings.TrimSpace(text)- if parsed, err := time.ParseDuration(text); err == nil {- return parsed.Milliseconds()- }- parts := strings.Split(text, ":")- if len(parts) == 3 {- hours, e1 := strconv.ParseFloat(parts[0], 64)- minutes, e2 := strconv.ParseFloat(parts[1], 64)- seconds, e3 := strconv.ParseFloat(parts[2], 64)- if e1 == nil && e2 == nil && e3 == nil {- return int64((hours*3600 + minutes*60 + seconds) * 1000)- }- }- }- return numericMilliseconds(value, 1000)-}--func numericMilliseconds(value any, multiplier float64) int64 {- raw := strings.TrimSpace(fmt.Sprint(value))- n, err := strconv.ParseFloat(raw, 64)- if err != nil || n <= 0 {- return 0- }- return int64(math.Round(n * multiplier))-}--func deploymentStatusLabel(status int) string {- switch status {- case 0:- return "未执行"- case 1:- return "执行中"- case 2:- return "成功"- case 3:- return "失败"- case 4:- return "已中止"- case 5:- return "下发中"- case 6:- return "超时"- case 7:- return "阻塞"- case 8:- return "就绪"- case 9:- return "中止中"- case 10:- return "已忽略"- case 13:- return "测试失败"- default:- return "未知"- }-}--func summarizeDeploymentMetrics(records []deploymentMetricRecord) deploymentMetricSummary {- return summarizeDeploymentMetricsAt(records, time.Now().UTC())-}--func summarizeDeploymentMetricsAt(records []deploymentMetricRecord, now time.Time) deploymentMetricSummary {- summary := deploymentMetricSummary{Total: len(records)}- durations := make([]int64, 0, len(records))- durations7d := make([]int64, 0, len(records))- cutoff7d := now.AddDate(0, 0, -7)- for _, record := range records {- switch record.Status {- case 2:- summary.Succeeded++- case 1, 5, 7, 8, 9:- summary.Running++- case 3, 4, 6, 13:- summary.Failed++- }- if record.DurationMs > 0 && record.Status != 1 && record.Status != 5 && record.Status != 9 {- durations = append(durations, record.DurationMs)- if started, err := time.Parse(time.RFC3339, record.StartedAt); err == nil && !started.Before(cutoff7d) && !started.After(now) {- durations7d = append(durations7d, record.DurationMs)- }- }- }- finished := summary.Succeeded + summary.Failed- if finished > 0 {- summary.SuccessRate = math.Round(float64(summary.Succeeded)*1000/float64(finished)) / 10- }- summary.Deployments7d = len(durations7d)- if len(durations7d) > 0 {- var total7d int64- for _, value := range durations7d {- total7d += value- }- summary.Average7dDurationMs = total7d / int64(len(durations7d))- }- if len(durations) == 0 {- return summary- }- var total int64- for _, value := range durations {- total += value- }- summary.AverageDurationMs = total / int64(len(durations))- sorted := append([]int64(nil), durations...)- sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })- summary.P50DurationMs = percentileDuration(sorted, 0.50)- summary.P90DurationMs = percentileDuration(sorted, 0.90)- for _, record := range records {- if record.DurationMs > 0 {- summary.LatestDurationMs = record.DurationMs- break- }- }- return summary-}--func percentileDuration(sorted []int64, percentile float64) int64 {- if len(sorted) == 0 {- return 0- }- index := int(math.Ceil(percentile*float64(len(sorted)))) - 1- if index < 0 {- index = 0- }- if index >= len(sorted) {- index = len(sorted) - 1- }- return sorted[index]-}--func coalesce(values ...string) string {- for _, value := range values {- if strings.TrimSpace(value) != "" {- return value- }- }- return ""-}diff --git a/internal/httpapi/deployment_metrics_test.go b/internal/httpapi/deployment_metrics_test.godeleted file mode 100644index 14aeced9..00000000--- a/internal/httpapi/deployment_metrics_test.go+++ /dev/null@@ -1,157 +0,0 @@-package httpapi--import (- "encoding/json"- "io"- "net/http"- "net/http/httptest"- "net/url"- "path/filepath"- "strings"- "testing"- "time"-- "agentflow/internal/domain"- "agentflow/internal/engine"- "agentflow/internal/repo"- "agentflow/internal/runtime"- "agentflow/internal/tracker"-)--func TestNormalizeDeploymentRecordsAndSummary(t *testing.T) {- raw := "结果如下:\n```json\n" + `{- "data": {"results": [- {"id": 11, "run_num": 8, "status": 2, "cur_branch": "feature/board", "cur_revision": "abc123", "start_time": "2026-09-20T02:00:00Z", "finish_time": "2026-09-20T02:02:00Z"},- {"id": 10, "run_num": 7, "status_label": "失败", "cur_branch": "feature/board", "duration": 240, "created": "2026-09-19T02:00:00Z"},- {"id": 9, "status": 2, "cur_branch": "another", "duration": 1}- ]}-}` + "\n```"- records, err := normalizeDeploymentRecords(raw, "feature/board", domain.Repository{}, 5410, 3021248)- if err != nil {- t.Fatal(err)- }- if len(records) != 2 {- t.Fatalf("records=%+v", records)- }- if records[0].DurationMs != 120000 || records[1].DurationMs != 240000 {- t.Fatalf("durations=%d,%d", records[0].DurationMs, records[1].DurationMs)- }- summary := summarizeDeploymentMetricsAt(records, time.Date(2026, 9, 20, 12, 0, 0, 0, time.UTC))- if summary.Total != 2 || summary.Succeeded != 1 || summary.Failed != 1 || summary.SuccessRate != 50 {- t.Fatalf("summary=%+v", summary)- }- if summary.AverageDurationMs != 180000 || summary.P50DurationMs != 120000 || summary.P90DurationMs != 240000 {- t.Fatalf("duration summary=%+v", summary)- }- if summary.Deployments7d != 2 || summary.Average7dDurationMs != 180000 {- t.Fatalf("7-day summary=%+v", summary)- }- allRecords, err := normalizeDeploymentRecords(raw, "", domain.Repository{}, 5410, 3021248)- if err != nil {- t.Fatal(err)- }- if len(allRecords) != 3 || allRecords[2].Branch != "another" {- t.Fatalf("unfiltered records=%+v", allRecords)- }-}--func TestNormalizeDeploymentReadableRecords(t *testing.T) {- raw := `接口名称: 获取流水线最近30天构建结果列表-共 2 条记录(当前页):-1. 构建结果ID: 100000440 | 流水线ID: 10000001 | 运行序列号: 291 | 构建状态: 2 | 触发方式: TRIGGER_MANUAL | 启动人: example-admin | 触发分支: feature/board | Commit ID: 1f7666fbf02b65f4cf774b2556b4565861c9b37a | 短Commit ID: 1f7666fb | MR源分支: | MR目标分支: | 构建备注: {"start_comment":""} | 构建开始时间: 2026-09-19 03:24:37 | 构建结束时间: 2026-09-19 03:52:59 | 构建耗时: 1702 | 排队时间: 0-2. 构建结果ID: 100000441 | 流水线ID: 10000001 | 运行序列号: 292 | 构建状态: 1 | 触发方式: TRIGGER_CI | 启动人: example-dev | 触发分支: feature/running | Commit ID: abc123 | 构建备注: deploying | 构建开始时间: 2026-09-20 08:00:00 | 构建结束时间: | 构建耗时: 0 | 排队时间: 0-构建总数: 2`- records, err := normalizeDeploymentRecords(raw, "", domain.Repository{}, skillHubPipelineProjectID, skillHubDeploymentPipelineID)- if err != nil {- t.Fatal(err)- }- if len(records) != 2 {- t.Fatalf("records=%+v", records)- }- if records[0].Status != 1 || records[0].Branch != "feature/running" || records[1].DurationMs != 1702000 {- t.Fatalf("parsed records=%+v", records)- }- summary := summarizeDeploymentMetricsAt(records, time.Date(2026, 9, 20, 12, 0, 0, 0, time.UTC))- if summary.Running != 1 || summary.Deployments7d != 1 || summary.Average7dDurationMs != 1702000 {- t.Fatalf("summary=%+v", summary)- }-}--func TestDeploymentMetricsAutoLoadsAllBranches(t *testing.T) {- t.Setenv("AGENTFLOW_SESSION_SECRET", "deployment-metrics-test-secret")- st, err := repo.OpenTest()- if err != nil {- t.Fatal(err)- }- t.Cleanup(st.Close)- if err := st.PutProject(domain.Project{ID: "deploy", Name: "Deploy"}); err != nil {- t.Fatal(err)- }- if err := st.PutRepository(domain.Repository{ID: "repo-deploy", ProjectID: "deploy", Name: "skillhub", GongfengProjectID: skillHubGongfengProjectID, DefaultBranch: "master", PipelineProjectID: 5410, PipelineDefID: 3021248}); err != nil {- t.Fatal(err)- }- if err := st.PutUser(domain.User{LoginName: "deployment-user"}); err != nil {- t.Fatal(err)- }- user, _ := st.UserByLoginName("deployment-user")- var called bool- gateway := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- body, _ := io.ReadAll(r.Body)- var request struct {- ID int64 `json:"id"`- Method string `json:"method"`- Params struct {- Name string `json:"name"`- Arguments map[string]any `json:"arguments"`- } `json:"params"`- }- _ = json.Unmarshal(body, &request)- w.Header().Set("Content-Type", "application/json")- if request.Method != "tools/call" {- _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{}}`))- return- }- called = true- if request.Params.Name != "coding_mcp" || request.Params.Arguments["project_id"] != "10001" || request.Params.Arguments["username"] != "deployment-user" {- t.Errorf("unexpected call: %+v", request.Params)- }- path, _ := request.Params.Arguments["path"].(string)- parsed, parseErr := url.Parse(path)- if parseErr != nil || parsed.Query().Has("cur_branch") || !strings.Contains(parsed.Path, "/pipeline/10000001/totalresult") {- t.Errorf("unexpected path: %q (%v)", path, parseErr)- }- payload := `{"results":[{"id":77,"run_num":9,"status":2,"cur_branch":"feature/board","start_time":"2026-09-20T02:00:00Z","finish_time":"2026-09-20T02:03:00Z"}]}`- encoded, _ := json.Marshal(payload)- _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":` + string(encoded) + `}]}}`))- }))- t.Cleanup(gateway.Close)- if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "qci", Name: "智研QCI流水线", MarketID: "7897", ProjectID: "deploy", Scope: "project", Transport: "http", URL: gateway.URL}); err != nil {- t.Fatal(err)- }-- handler := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")- got := requestJSONAuthed[deploymentMetricsResponse](t, handler, user, http.MethodGet, "/api/deployment-metrics?projectId=deploy&repositoryId=repo-deploy", nil, http.StatusOK)- if !called || got.Branch != "" || len(got.Records) != 1 || got.Summary.AverageDurationMs != 180000 {- t.Fatalf("response=%+v called=%v", got, called)- }-}--func TestDeploymentMetricsRejectsNonSkillHubRepository(t *testing.T) {- st, err := repo.OpenTest()- if err != nil {- t.Fatal(err)- }- t.Cleanup(st.Close)- if err := st.PutProject(domain.Project{ID: "deploy-empty", Name: "Deploy"}); err != nil {- t.Fatal(err)- }- if err := st.PutRepository(domain.Repository{ID: "repo-empty", ProjectID: "deploy-empty", Name: "service", GongfengProjectID: "team/service"}); err != nil {- t.Fatal(err)- }- if err := st.PutUser(domain.User{LoginName: "deployment-empty-user"}); err != nil {- t.Fatal(err)- }- user, _ := st.UserByLoginName("deployment-empty-user")- handler := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")- requestJSONAuthed[map[string]string](t, handler, user, http.MethodGet, "/api/deployment-metrics?projectId=deploy-empty&repositoryId=repo-empty&branch=master", nil, http.StatusUnprocessableEntity)-}diff --git a/internal/httpapi/generic_workflows_test.go b/internal/httpapi/generic_workflows_test.goindex b387871c..a7bd5108 100644--- a/internal/httpapi/generic_workflows_test.go+++ b/internal/httpapi/generic_workflows_test.go@@ -146,7 +146,7 @@ func TestGenericTemplateCloneCreatesProjectRolesAndRemapsNodes(t *testing.T) {h, s := newGenericTemplateServer(t)gongfeng := domain.MCPServerDefinition{ID: "mcp-61-project-alpha", Name: "Gongfeng MCP", Scope: "project", ProjectID: "alpha",- MarketID: "61", Transport: "http", URL: "https://mcpgw.knot.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer tapd-token"},+ MarketID: "61", Transport: "http", URL: "https://mcp-gateway.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer tapd-token"},}if err := s.PutMCPServer(gongfeng); err != nil {t.Fatal(err)diff --git a/internal/httpapi/helpers_cases_test.go b/internal/httpapi/helpers_cases_test.goindex cf491c08..8fd482c7 100644--- a/internal/httpapi/helpers_cases_test.go+++ b/internal/httpapi/helpers_cases_test.go@@ -14,81 +14,12 @@ import ("strconv""strings""testing"- "time""agentflow/internal/domain""github.com/gin-gonic/gin")-func TestDeploymentMetricParsingBranches(t *testing.T) {- if positive := numericMilliseconds("1.25", 1000); positive != 1250 {- t.Fatalf("numeric milliseconds = %d", positive)- }- for _, bad := range []any{"bad", "-1", 0} {- if got := numericMilliseconds(bad, 1); got != 0 {- t.Fatalf("numericMilliseconds(%v) = %d", bad, got)- }- }- now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)- rows := []map[string]any{- {"id": "a/b", "run_num": json.Number("7"), "status_label": "成功", "cur_branch": "main", "start_time": now.Add(-time.Hour).Format(time.RFC3339), "finish_time": now.Format(time.RFC3339)},- {"id": "2", "runNumber": float64(8), "status": 3, "branch": "other", "duration_ms": "500"},- {"id": "3", "status": "执行中", "duration": "01:02:03"},- {"id": "4", "status": "timeout", "duration": "2.5s"},- }- raw, _ := json.Marshal(map[string]any{"data": map[string]any{"results": rows}})- repo := domain.Repository{PipelineURLPattern: "https://ci/build/{build_id}"}- records, err := normalizeDeploymentRecords("prefix\n```json\n"+string(raw)+"\n```", "", repo, 1, 2)- if err != nil || len(records) != 4 {- t.Fatalf("normalize: %v %#v", err, records)- }- if records[0].URL == "" || records[0].DurationMs == 0 {- t.Fatalf("record not normalized: %+v", records[0])- }- filtered, err := normalizeDeploymentRecords(string(raw), "main", repo, 1, 2)- if err != nil || len(filtered) != 3 {- t.Fatalf("branch filtering: %v %#v", err, filtered)- }- readable := "1. 构建结果ID: 55 | 运行序列号: 9 | 构建状态: 2 | 触发分支: main | 构建耗时: 3s\nbad line"- records, err = normalizeDeploymentRecords(readable, "", domain.Repository{}, 1, 2)- if err != nil || len(records) != 1 || records[0].ID != "55" {- t.Fatalf("readable: %v %#v", err, records)- }- for _, invalid := range []string{"plain text", "{broken"} {- if _, err := normalizeDeploymentRecords(invalid, "", repo, 1, 2); err == nil {- t.Fatalf("expected parse failure for %q", invalid)- }- }-- statusCases := map[string]int{- "成功": 2, "测试失败": 13, "失败": 3, "超时": 6, "取消": 4,- "运行中": 1, "阻塞": 7, "就绪": 8, "mystery": 0,- }- for label, want := range statusCases {- if got := deploymentStatus(map[string]any{"status_label": label}); got != want {- t.Errorf("status %q = %d, want %d", label, got, want)- }- }- for status := 0; status <= 14; status++ {- if deploymentStatusLabel(status) == "" {- t.Errorf("empty label %d", status)- }- }- summary := summarizeDeploymentMetricsAt([]deploymentMetricRecord{- {Status: 2, DurationMs: 100, StartedAt: now.Add(-time.Hour).Format(time.RFC3339)},- {Status: 3, DurationMs: 300, StartedAt: now.Add(-48 * time.Hour).Format(time.RFC3339)},- {Status: 1, DurationMs: 900, StartedAt: now.Format(time.RFC3339)},- {Status: 4, DurationMs: 500, StartedAt: now.AddDate(0, 0, -10).Format(time.RFC3339)},- }, now)- if summary.Total != 4 || summary.Succeeded != 1 || summary.Failed != 2 || summary.Running != 1 || summary.P50DurationMs != 300 || summary.P90DurationMs != 500 {- t.Fatalf("summary: %+v", summary)- }- if percentileDuration(nil, .5) != 0 || percentileDuration([]int64{10, 20}, -1) != 10 || percentileDuration([]int64{10, 20}, 2) != 20 {- t.Fatal("percentile bounds")- }-}-func TestWorkspaceFilesystemAndGitBranches(t *testing.T) {root := t.TempDir()if err := os.MkdirAll(filepath.Join(root, "src", "empty"), 0755); err != nil {diff --git a/internal/httpapi/http_matrix_cases_test.go b/internal/httpapi/http_matrix_cases_test.goindex bda3e312..f1fd0b15 100644--- a/internal/httpapi/http_matrix_cases_test.go+++ b/internal/httpapi/http_matrix_cases_test.go@@ -211,8 +211,6 @@ func TestAuthRunnerScheduleSyncValidationHTTP(t *testing.T) {{http.MethodPost, "/api/runners/tasks/missing/complete", nil, false, 401},{http.MethodGet, "/api/runners/tasks/missing/control", nil, false, 401},{http.MethodPut, "/api/runners/runtimes", map[string]any{}, true, 400},- {http.MethodGet, "/api/deployment-metrics", nil, false, 401},- {http.MethodGet, "/api/deployment-metrics", nil, true, 400},{http.MethodPost, "/api/otel/not-traces", nil, false, 404},}for i, tc := range cases {diff --git a/internal/httpapi/issues_test.go b/internal/httpapi/issues_test.goindex fee15a3e..ff8b3a68 100644--- a/internal/httpapi/issues_test.go+++ b/internal/httpapi/issues_test.go@@ -1895,10 +1895,10 @@ func TestIssuesSaveDoesNotGateSyncedTAPDRequirement(t *testing.T) {t.Fatal(err)}t.Cleanup(s.Close)- if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "dnspod-issue-fix", Name: "Issue fix", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "fix", Name: "Fix", Type: "agent"}}}); err != nil {+ if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "demodns-issue-fix", Name: "Issue fix", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "fix", Name: "Fix", Type: "agent"}}}); err != nil {t.Fatal(err)}- if err := s.PutRepository(domain.Repository{ID: "repo-new-dnspod", ProjectID: "platform", Name: "new_dnspod", GongfengProjectID: "dnspod/new_dnspod", DefaultBranch: "master"}); err != nil {+ if err := s.PutRepository(domain.Repository{ID: "repo-new-demodns", ProjectID: "platform", Name: "dns-console", GongfengProjectID: "example/dns-console", DefaultBranch: "master"}); err != nil {t.Fatal(err)}if err := s.PutIssue(domain.Issue{@@ -1919,11 +1919,11 @@ func TestIssuesSaveDoesNotGateSyncedTAPDRequirement(t *testing.T) {"title": "mq_flush_dns CMQ SDK","kind": "requirement","source": "tapd",- "workflowId": "dnspod-issue-fix",- "repositoryId": "repo-new-dnspod",- "repositoryIds": []string{"repo-new-dnspod"},+ "workflowId": "demodns-issue-fix",+ "repositoryId": "repo-new-demodns",+ "repositoryIds": []string{"repo-new-demodns"},}, http.StatusOK)- if saved.WorkflowID != "dnspod-issue-fix" || saved.RepositoryID != "repo-new-dnspod" {+ if saved.WorkflowID != "demodns-issue-fix" || saved.RepositoryID != "repo-new-demodns" {t.Fatalf("binding not saved: workflow=%q repo=%q", saved.WorkflowID, saved.RepositoryID)}if saved.Clarification.Gated || saved.Clarification.Score != 0 || saved.Clarification.Status != "" {@@ -1989,17 +1989,17 @@ func TestImportTAPDIssueBindsSelectedWorkflow(t *testing.T) {t.Fatal("import without a repository must not persist the TAPD story")}}- if err := s.PutRepository(domain.Repository{ID: "repo-import-dnspod", ProjectID: "platform", Name: "new_dnspod", GongfengProjectID: "dnspod/new_dnspod", DefaultBranch: "master"}); err != nil {+ if err := s.PutRepository(domain.Repository{ID: "repo-import-demodns", ProjectID: "platform", Name: "dns-console", GongfengProjectID: "example/dns-console", DefaultBranch: "master"}); err != nil {t.Fatal(err)}- if err := s.PutRepository(domain.Repository{ID: "repo-import-com", ProjectID: "platform", Name: "new_dnspod.com", GongfengProjectID: "dnspod/new_dnspod.com", DefaultBranch: "master"}); err != nil {+ if err := s.PutRepository(domain.Repository{ID: "repo-import-com", ProjectID: "platform", Name: "dns-console.com", GongfengProjectID: "example/dns-console.com", DefaultBranch: "master"}); err != nil {t.Fatal(err)}imported := requestJSON[domain.Issue](t, h, http.MethodPost, "/api/issues/import-tapd", map[string]any{"projectId": "platform","url": "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100001221","workflowId": wf.ID,- "repositoryIds": []string{"repo-import-dnspod"},+ "repositoryIds": []string{"repo-import-demodns"},}, http.StatusOK)if imported.WorkflowID != wf.ID {t.Fatalf("workflowId=%q want %q", imported.WorkflowID, wf.ID)@@ -2008,9 +2008,9 @@ func TestImportTAPDIssueBindsSelectedWorkflow(t *testing.T) {"projectId": "platform","url": "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100001221","workflowId": wf.ID,- "repositoryIds": []string{"repo-import-dnspod", "repo-import-com"},+ "repositoryIds": []string{"repo-import-demodns", "repo-import-com"},}, http.StatusOK)- if bound.RepositoryID != "repo-import-dnspod" {+ if bound.RepositoryID != "repo-import-demodns" {t.Fatalf("repositoryId=%q", bound.RepositoryID)}if len(bound.RepositoryIDs) != 2 || bound.RepositoryIDs[1] != "repo-import-com" {@@ -2025,7 +2025,7 @@ func TestImportTAPDIssueBindsSelectedWorkflow(t *testing.T) {"projectId": "platform","url": "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100001221","workflowId": "missing-sop",- "repositoryId": "repo-import-dnspod",+ "repositoryId": "repo-import-demodns",}, http.StatusBadRequest)}diff --git a/internal/httpapi/mcp_market_test.go b/internal/httpapi/mcp_market_test.goindex 707e6a88..15051b74 100644--- a/internal/httpapi/mcp_market_test.go+++ b/internal/httpapi/mcp_market_test.go@@ -37,9 +37,9 @@ func installTestTrackerMCPs(t *testing.T, st *repo.Store, projectID string) {}func TestMCPInstallIDSeparatesScopeAndOwner(t *testing.T) {- project := mcpInstallID("iwiki", "project", "platform")- personal := mcpInstallID("iwiki", "personal", "2")- if project == personal || project != "mcp-iwiki-project-platform" || personal != "mcp-iwiki-personal-2" {+ project := mcpInstallID("wiki", "project", "platform")+ personal := mcpInstallID("wiki", "personal", "2")+ if project == personal || project != "mcp-wiki-project-platform" || personal != "mcp-wiki-personal-2" {t.Fatalf("unexpected install ids: project=%q personal=%q", project, personal)}}@@ -63,7 +63,7 @@ func TestMCPMarketCatalogContainsOnlyPublicServices(t *testing.T) {if !ok || item.URL != "https://api.githubcopilot.com/mcp/" || item.AuthType != "github-token" {t.Fatalf("GitHub: %+v", item)}- if _, ok := marketItem("iwiki"); ok {+ if _, ok := marketItem("58"); ok {t.Fatal("enterprise catalog must not ship by default")}}@@ -91,7 +91,7 @@ func TestMCPMarketSearch(t *testing.T) {t.Fatalf("catalog meta = %+v", payload)}if len(payload.Items) == 0 {- t.Fatal("expected search hits for iwiki")+ t.Fatal("expected search hits for github")}found := falsefor _, item := range payload.Items {@@ -101,7 +101,7 @@ func TestMCPMarketSearch(t *testing.T) {}}if !found {- t.Fatalf("search iwiki missed id 58: %+v", payload.Items)+ t.Fatalf("search github missed id github: %+v", payload.Items)}all := httptest.NewRecorder()diff --git a/internal/httpapi/mcp_masking_test.go b/internal/httpapi/mcp_masking_test.goindex e73e019c..82417255 100644--- a/internal/httpapi/mcp_masking_test.go+++ b/internal/httpapi/mcp_masking_test.go@@ -22,15 +22,15 @@ func TestMCPServerCredentialsAreMaskedAndSurviveEdits(t *testing.T) {t.Cleanup(func() { s.Close() })h := New(s, engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")server := domain.MCPServerDefinition{- ID: "knot", Name: "Knot", Transport: "http", URL: "https://knot.example/mcp", TimeoutSec: 60,- Headers: map[string]string{"X-Knot-Api-Token": "knot-secret", "X-Env": "prod", "Authorization": "Bearer ${secret:KNOT}"},+ ID: "gateway", Name: "Gateway", Transport: "http", URL: "https://gateway.example/mcp", TimeoutSec: 60,+ Headers: map[string]string{"X-Gateway-Api-Token": "gateway-secret", "X-Env": "prod", "Authorization": "Bearer ${secret:GATEWAY}"},}rec := requestWithHeaders(t, h, http.MethodPut, "/api/mcp-servers", server, nil)- if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "knot-secret") {+ if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "gateway-secret") {t.Fatalf("PUT = %d %s", rec.Code, rec.Body.String())}for _, path := range []string{"/api/mcp-servers", "/api/bootstrap"} {- if body := requestWithHeaders(t, h, http.MethodGet, path, nil, nil).Body.String(); strings.Contains(body, "knot-secret") {+ if body := requestWithHeaders(t, h, http.MethodGet, path, nil, nil).Body.String(); strings.Contains(body, "gateway-secret") {t.Fatalf("GET %s leaked header: %s", path, body)}}@@ -40,11 +40,11 @@ func TestMCPServerCredentialsAreMaskedAndSurviveEdits(t *testing.T) {}var edited domain.MCPServerDefinitionfor _, item := range listed {- if item.ID == "knot" {+ if item.ID == "gateway" {edited = item}}- if edited.Headers["X-Knot-Api-Token"] != domain.MaskedSecretValue || edited.Headers["Authorization"] != "Bearer ${secret:KNOT}" {+ if edited.Headers["X-Gateway-Api-Token"] != domain.MaskedSecretValue || edited.Headers["Authorization"] != "Bearer ${secret:GATEWAY}" {t.Fatalf("listed headers = %v", edited.Headers)}edited.Description = "改了描述"@@ -52,8 +52,8 @@ func TestMCPServerCredentialsAreMaskedAndSurviveEdits(t *testing.T) {if rec := requestWithHeaders(t, h, http.MethodPut, "/api/mcp-servers", edited, nil); rec.Code != http.StatusOK {t.Fatalf("re-save = %d %s", rec.Code, rec.Body.String())}- stored, _ := s.MCPServer("knot")- want := map[string]string{"X-Knot-Api-Token": "knot-secret", "X-Env": "prod", "Authorization": "Bearer ${secret:KNOT}"}+ stored, _ := s.MCPServer("gateway")+ want := map[string]string{"X-Gateway-Api-Token": "gateway-secret", "X-Env": "prod", "Authorization": "Bearer ${secret:GATEWAY}"}if len(stored.Headers) != len(want) {t.Fatalf("stored headers = %v", stored.Headers)}@@ -62,9 +62,9 @@ func TestMCPServerCredentialsAreMaskedAndSurviveEdits(t *testing.T) {t.Fatalf("stored headers = %v", stored.Headers)}}- edited.Headers["X-Knot-Api-Token"] = "rotated"+ edited.Headers["X-Gateway-Api-Token"] = "rotated"requestWithHeaders(t, h, http.MethodPut, "/api/mcp-servers", edited, nil)- if stored, _ := s.MCPServer("knot"); stored.Headers["X-Knot-Api-Token"] != "rotated" {+ if stored, _ := s.MCPServer("gateway"); stored.Headers["X-Gateway-Api-Token"] != "rotated" {t.Fatalf("token rotation not saved: %v", stored.Headers)}}diff --git a/internal/httpapi/metrics_groups_cases_test.go b/internal/httpapi/metrics_groups_cases_test.goindex e2a0612f..8ebe418d 100644--- a/internal/httpapi/metrics_groups_cases_test.go+++ b/internal/httpapi/metrics_groups_cases_test.go@@ -1,71 +1,16 @@package httpapiimport (- "encoding/json"- "io""net/http""net/http/httptest""strings""testing"- "time""agentflow/internal/domain""github.com/gin-gonic/gin")-func TestDeploymentMetricsRemainingValidation(t *testing.T) {- f := cvBNewHTTPFixture(t)- if err := f.s.PutProject(domain.Project{ID: "cvb-deploy", Name: "Deploy"}); err != nil {- t.Fatal(err)- }- repositories := []domain.Repository{- {ID: "cvb-skillhub", ProjectID: "cvb-deploy", Name: "skillhub", GongfengProjectID: skillHubGongfengProjectID},- {ID: "cvb-other", ProjectID: "platform", Name: "skillhub", GongfengProjectID: skillHubGongfengProjectID},- {ID: "cvb-name-only", ProjectID: "cvb-deploy", Name: "SkillHub", WebURL: "https://git.example/example/team-project"},- }- for _, repository := range repositories {- if err := f.s.PutRepository(repository); err != nil {- t.Fatal(err)- }- }- cases := []struct {- path string- auth bool- want int- }{- {"/api/deployment-metrics?projectId=cvb-deploy&repositoryId=cvb-skillhub", false, http.StatusUnauthorized},- {"/api/deployment-metrics", true, http.StatusBadRequest},- {"/api/deployment-metrics?projectId=cvb-deploy&repositoryId=cvb-skillhub&branch=" + strings.Repeat("x", 256), true, http.StatusBadRequest},- {"/api/deployment-metrics?projectId=absent&repositoryId=cvb-skillhub", true, http.StatusNotFound},- {"/api/deployment-metrics?projectId=cvb-deploy&repositoryId=absent", true, http.StatusNotFound},- {"/api/deployment-metrics?projectId=cvb-deploy&repositoryId=cvb-other", true, http.StatusNotFound},- }- for _, tc := range cases {- rec := cvBRequest(t, f, http.MethodGet, tc.path, nil, tc.auth)- if rec.Code != tc.want {- t.Errorf("%s = %d, want %d: %s", tc.path, rec.Code, tc.want, rec.Body.String())- }- }-- if positiveQueryInt(cvBGinContext(t, "/?n=bad"), "n", 7) != 0 ||- positiveQueryInt(cvBGinContext(t, "/?n=-1"), "n", 7) != 0 ||- positiveQueryInt(cvBGinContext(t, "/?n=9"), "n", 7) != 9 {- t.Fatal("positiveQueryInt edge handling")- }- for _, repository := range repositories {- if got := isSkillHubRepository(repository); !got {- t.Errorf("repository should be recognized: %+v", repository)- }- }- if isSkillHubRepository(domain.Repository{Name: "SkillHub", WebURL: "https://example.test/other"}) {- t.Fatal("unrelated SkillHub name accepted")- }- if got := deploymentPipelineURL(domain.Repository{PipelineURLPattern: "https://ci/{build_id}"}, 1, 2); got != "https://ci/current" {- t.Fatalf("pipeline URL = %q", got)- }-}-func cvBGinContext(t *testing.T, target string) *gin.Context {t.Helper()rec := httptest.NewRecorder()@@ -86,94 +31,6 @@ func cvBRawRequest(t *testing.T, f cvBHTTPFixture, method, path, body string, aureturn rec}-func TestDeploymentMetricsParsingLastBranches(t *testing.T) {- if _, err := decodeMCPJSON("```"); err == nil {- t.Fatal("empty fenced response accepted")- }- if rows := deploymentRows(`{"items":[{"id":"x"}]}`); len(rows) != 1 {- t.Fatalf("string rows = %#v", rows)- }- if rows := deploymentRows([]any{"skip", map[string]any{"id": "x"}}); len(rows) != 1 {- t.Fatalf("mixed rows = %#v", rows)- }- if deploymentRows(map[string]any{"none": true}) != nil {- t.Fatal("unexpected rows")- }- if intField(map[string]any{"n": 4}, "n") != 4 || intField(map[string]any{"n": "5"}, "n") != 5 {- t.Fatal("integer conversion")- }- if timeField(map[string]any{"t": "2026-10-30 12:13:14.123456"}, "t").IsZero() {- t.Fatal("fractional local time was not parsed")- }- start := time.Date(2026, 10, 30, 1, 0, 0, 0, time.UTC)- if got := durationField(map[string]any{"elapsed": "bad"}, time.Time{}, time.Time{}); got != 0 {- t.Fatalf("bad duration = %d", got)- }- if got := durationField(map[string]any{}, start, start.Add(-time.Second)); got != 0 {- t.Fatalf("backward duration = %d", got)- }- if got := summarizeDeploymentMetrics(nil); got.Total != 0 {- t.Fatalf("empty summary = %+v", got)- }- if records, err := normalizeDeploymentRecords(`[{"status":2,"duration":1}]`, "", domain.Repository{}, 1, 2); err != nil || len(records) != 1 || records[0].URL == "" {- t.Fatalf("id-less record = %+v, %v", records, err)- }- if _, err := normalizeDeploymentRecords(`{}`, "", domain.Repository{}, 1, 2); err == nil {- t.Fatal("object without record list accepted")- }- _ = deploymentReadableRows("x. ignored\n2. no separator\n3. Unknown: value")-}--func TestDeploymentMetricsGatewayBranches(t *testing.T) {- f := cvBNewHTTPFixture(t)- if err := f.s.PutProject(domain.Project{ID: "cvb-gateway", Name: "Gateway"}); err != nil {- t.Fatal(err)- }- repository := domain.Repository{ID: "cvb-gateway-repo", ProjectID: "cvb-gateway", Name: "skillhub", GongfengProjectID: skillHubGongfengProjectID}- if err := f.s.PutRepository(repository); err != nil {- t.Fatal(err)- }- gateway := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- body, _ := io.ReadAll(r.Body)- w.Header().Set("Content-Type", "application/json")- switch {- case strings.Contains(string(body), "rpc-error"):- _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"failed"}}`))- case strings.Contains(string(body), "malformed"):- _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"not json"}]}}`))- default:- payload := `{"results":[{"id":"old","status":2,"cur_branch":"main","created":"2026-10-29T00:00:00Z","duration":1},{"id":"new","status":2,"cur_branch":"main","created":"2026-10-30T00:00:00Z","duration":2}]}`- encoded, _ := json.Marshal(payload)- _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":` + string(encoded) + `}]}}`))- }- }))- t.Cleanup(gateway.Close)- if err := f.s.PutMCPServer(domain.MCPServerDefinition{- ID: "cvb-qci", Name: "QCI", MarketID: "7897", ProjectID: "cvb-gateway",- Scope: "project", Transport: "http", URL: gateway.URL,- }); err != nil {- t.Fatal(err)- }- for _, tc := range []struct {- path string- want int- }{- {"/api/deployment-metrics?projectId=cvb-gateway&repositoryId=cvb-gateway-repo&branch=rpc-error&pageSize=0", http.StatusBadGateway},- {"/api/deployment-metrics?projectId=cvb-gateway&repositoryId=cvb-gateway-repo&branch=malformed", http.StatusBadGateway},- {"/api/deployment-metrics?projectId=cvb-gateway&repositoryId=cvb-gateway-repo&branch=main&pageSize=999", http.StatusOK},- } {- rec := cvBRequest(t, f, http.MethodGet, tc.path, nil, true)- if rec.Code != tc.want {- t.Errorf("%s = %d, want %d: %s", tc.path, rec.Code, tc.want, rec.Body.String())- }- }- handler := deploymentMetricsHandlers{deps: &deps{repo: f.s}}- _, listed := marketItem("zhiyan-pipeline")- if server, ok := handler.lookupQCIProjectMCP("unconfigured-project", f.user.ID); ok != listed || ok && server.MarketID == "" {- t.Fatalf("market fallback must follow the market listing (%v): %+v %v", listed, server, ok)- }-}-func TestRunsRemainingPureAndHTTPBranches(t *testing.T) {f := cvBNewHTTPFixture(t)for _, tc := range []struct {diff --git a/internal/httpapi/protocol_cases_test.go b/internal/httpapi/protocol_cases_test.goindex 47e6bf6c..c78d8f84 100644--- a/internal/httpapi/protocol_cases_test.go+++ b/internal/httpapi/protocol_cases_test.go@@ -113,7 +113,7 @@ func TestClarifyMCPAndTerminalValidation(t *testing.T) {}{{domain.MCPServerDefinition{MarketID: "70"}, "tapd"},{domain.MCPServerDefinition{Name: "工蜂"}, "gongfeng"},- {domain.MCPServerDefinition{ID: "iwiki-doc"}, "iwiki"},+ {domain.MCPServerDefinition{ID: "wiki-doc", MarketID: "58"}, "other"},{domain.MCPServerDefinition{Name: "other"}, "other"},} {if got := classifyClarifyMCP(tc.item); got != tc.want {@@ -124,7 +124,7 @@ func TestClarifyMCPAndTerminalValidation(t *testing.T) {if gongfengProjectPathFromClarifyURL(gf) != "group/proj" || gongfengIssueIIDFromURL(gf) != 42 {t.Fatal("gongfeng URL parsing")}- if gongfengIssueIIDFromURL("bad") != 0 || iwikiDocIDFromURL("https://iwiki.example.com/pages/12345") != "12345" {+ if gongfengIssueIIDFromURL("bad") != 0 {t.Fatal("URL fallback parsing")}issue := domain.Issue{Title: "see " + gf}@@ -132,9 +132,6 @@ func TestClarifyMCPAndTerminalValidation(t *testing.T) {if issue.Source != "gongfeng" || issue.ExternalRef == nil || issue.ExternalRef.ExternalIID != 42 {t.Fatalf("hydrated=%+v", issue)}- if urls := extractIWikiURLs("https://iwiki.example.com/p/12345.", "https://iwiki.example.com/p/12345"); len(urls) != 1 {- t.Fatalf("iwiki urls=%v", urls)- }call := assistantMCPCall{Tool: "comments_list", Arguments: map[string]any{"workspace_id": float64(3), "entry_id": 4}}wrapped := wrapClarifyTAPDCall(call)if wrapped.Tool != "proxy_execute_tool" || wrapped.Arguments["tool_name"] != "comments_get" {diff --git a/internal/httpapi/schedule_test.go b/internal/httpapi/schedule_test.goindex e07231ff..afd549f5 100644--- a/internal/httpapi/schedule_test.go+++ b/internal/httpapi/schedule_test.go@@ -507,40 +507,40 @@ func TestScheduleUIDemoServer(t *testing.T) {t.Cleanup(st.Close)now := time.Now().UTC()if err := st.PutProject(domain.Project{- ID: "dp", Key: "DP", Name: "DNSPod", Description: "本地预分诊验收", Color: "#3867f4",- WorkflowID: "dnspod-feature-dev", OwnerID: 1,+ ID: "dp", Key: "DP", Name: "DemoDNS", Description: "本地预分诊验收", Color: "#3867f4",+ WorkflowID: "demodns-feature-dev", OwnerID: 1,Members: []domain.ProjectMember{{UserID: 1, Role: "maintainer"}},CreatedAt: now, UpdatedAt: now,}); err != nil {t.Fatal(err)}for _, wf := range []domain.WorkflowDefinition{- {ID: "dnspod-issue-fix", Name: "Issue 修复", ProjectID: "dp", Status: "published", SandboxProfileID: "local", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}},- {ID: "dnspod-feature-dev", Name: "功能开发", ProjectID: "dp", Status: "published", SandboxProfileID: "local", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}},+ {ID: "demodns-issue-fix", Name: "Issue 修复", ProjectID: "dp", Status: "published", SandboxProfileID: "local", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}},+ {ID: "demodns-feature-dev", Name: "功能开发", ProjectID: "dp", Status: "published", SandboxProfileID: "local", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}},} {if err := st.PutWorkflow(wf); err != nil {t.Fatal(err)}}if err := st.PutRepository(domain.Repository{- ID: "repo-dnspod", ProjectID: "dp", Name: "dnspod", Provider: "gongfeng",- GongfengProjectID: "dnspod/dnspod", DefaultBranch: "master",+ ID: "repo-demodns", ProjectID: "dp", Name: "demodns", Provider: "gongfeng",+ GongfengProjectID: "demodns/demodns", DefaultBranch: "master",}); err != nil {t.Fatal(err)}issues := []domain.Issue{- {ID: "iss-fix-unbound", ProjectID: "dp", Title: "dnspod 解析失败:NXDOMAIN 误报", Status: "backlog", Kind: "issue", Source: "gongfeng", WorkflowID: "dnspod-issue-fix", ExternalRef: &domain.ExternalRef{Source: "gongfeng", ExternalID: "1001", ExternalIID: 1}},- {ID: "iss-fix-bound", ProjectID: "dp", Title: "dnspod 缓存刷新超时", Status: "backlog", Kind: "issue", Source: "gongfeng", WorkflowID: "dnspod-issue-fix", RepositoryID: "repo-dnspod", RepositoryIDs: []string{"repo-dnspod"}, ExternalRef: &domain.ExternalRef{Source: "gongfeng", ExternalID: "1002", ExternalIID: 2}},+ {ID: "iss-fix-unbound", ProjectID: "dp", Title: "demodns 解析失败:NXDOMAIN 误报", Status: "backlog", Kind: "issue", Source: "gongfeng", WorkflowID: "demodns-issue-fix", ExternalRef: &domain.ExternalRef{Source: "gongfeng", ExternalID: "1001", ExternalIID: 1}},+ {ID: "iss-fix-bound", ProjectID: "dp", Title: "demodns 缓存刷新超时", Status: "backlog", Kind: "issue", Source: "gongfeng", WorkflowID: "demodns-issue-fix", RepositoryID: "repo-demodns", RepositoryIDs: []string{"repo-demodns"}, ExternalRef: &domain.ExternalRef{Source: "gongfeng", ExternalID: "1002", ExternalIID: 2}},{ID: "tapd-feature", ProjectID: "dp", Title: "支持批量添加解析记录", Status: "backlog", Kind: "requirement", Source: "tapd", ExternalRef: &domain.ExternalRef{Source: "tapd", ExternalID: "1024", ExternalType: "story"}},{ID: "tapd-low", ProjectID: "dp", Title: "下周同步一下文档", Status: "backlog", Kind: "requirement", Source: "tapd", ExternalRef: &domain.ExternalRef{Source: "tapd", ExternalID: "2048", ExternalType: "story"}},- {ID: "iss-todo", ProjectID: "dp", Title: "已在 todo 不应被 backlog 扫描", Status: "todo", Kind: "issue", Source: "gongfeng", WorkflowID: "dnspod-issue-fix", ExternalRef: &domain.ExternalRef{Source: "gongfeng", ExternalID: "1003", ExternalIID: 3}},+ {ID: "iss-todo", ProjectID: "dp", Title: "已在 todo 不应被 backlog 扫描", Status: "todo", Kind: "issue", Source: "gongfeng", WorkflowID: "demodns-issue-fix", ExternalRef: &domain.ExternalRef{Source: "gongfeng", ExternalID: "1003", ExternalIID: 3}},}for _, issue := range issues {if err := st.PutIssue(issue); err != nil {t.Fatal(err)}}- prompt := `你是项目 DP(projectId: dp)的需求预分诊助手。调用 issues_list,query={"status":"backlog","limit":50},按 offset 翻页直到 hasMore=false。没有 backlog 则输出“无待处理需求”。对 source=gongfeng / kind=issue:确认 workflowId=dnspod-issue-fix,仓库缺失时结合标题与 repositories_list 判断,仅高把握用 issues_save。不要 issues_dispatch。对 source=tapd:无 TAPD MCP 时跳过处理人同步,仓库与 SOP 置信度不足则跳过。写操作只允许 issues_save,每轮最多 12 个。输出 Markdown 表格:需求编号 | 标题 | 来源 | 处理动作 | 置信度 | 说明。`+ prompt := `你是项目 DP(projectId: dp)的需求预分诊助手。调用 issues_list,query={"status":"backlog","limit":50},按 offset 翻页直到 hasMore=false。没有 backlog 则输出“无待处理需求”。对 source=gongfeng / kind=issue:确认 workflowId=demodns-issue-fix,仓库缺失时结合标题与 repositories_list 判断,仅高把握用 issues_save。不要 issues_dispatch。对 source=tapd:无 TAPD MCP 时跳过处理人同步,仓库与 SOP 置信度不足则跳过。写操作只允许 issues_save,每轮最多 12 个。输出 Markdown 表格:需求编号 | 标题 | 来源 | 处理动作 | 置信度 | 说明。`if err := st.PutScheduleJob(domain.ScheduleJob{ID: "job-triage", Name: "DP backlog 需求预分诊", ProjectID: "dp", SkipDispatch: true,AssistantPrompt: prompt, AssistantModel: "default", Enabled: true, IntervalSec: 3600,diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 9b69e129..e72adc17 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -71,21 +71,20 @@ type Server struct {projects *projectsHandlersinsights *insightsHandlersbusinessDomains *businessDomainsHandlers- catalog *catalogHandlers // catalog.go- mcp *mcpHandlers // mcp.go- market *marketHandlers // mcp_market.go- skillhub *skillhubHandlers // skillhub_market.go- issues *issuesHandlers // issues.go(依赖 tasks/stream)- tasks *tasksHandlers // tasks.go- runs *runsHandlers // runs.go- previews *previewsHandlers // run_preview.go- browser *browserHandlers // browser.go- stream *streamHandlers // stream.go- runners *runnersHandlers // runners.go- schedule *scheduleHandlers // schedule.go(align.go 并入)- tokens *tokenHandlers // auth_tokens.go- syncAPI *syncHandlers // tracker.go- deploy *deploymentMetricsHandlers // deployment_metrics.go+ catalog *catalogHandlers // catalog.go+ mcp *mcpHandlers // mcp.go+ market *marketHandlers // mcp_market.go+ skillhub *skillhubHandlers // skillhub_market.go+ issues *issuesHandlers // issues.go(依赖 tasks/stream)+ tasks *tasksHandlers // tasks.go+ runs *runsHandlers // runs.go+ previews *previewsHandlers // run_preview.go+ browser *browserHandlers // browser.go+ stream *streamHandlers // stream.go+ runners *runnersHandlers // runners.go+ schedule *scheduleHandlers // schedule.go(align.go 并入)+ tokens *tokenHandlers // auth_tokens.go+ syncAPI *syncHandlers // tracker.gonotifications *notificationHandlersbotInteractions *botInteractionHandlersbotIdentities *botIdentityHandlers@@ -163,7 +162,6 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servschedule: &scheduleHandlers{deps: d},tokens: &tokenHandlers{deps: d},syncAPI: &syncHandlers{deps: d},- deploy: &deploymentMetricsHandlers{deps: d},know: &knowledgeHandlers{deps: d, svc: knowledge.NewService(d.repo, randomID), activity: &knowledgeActivityLog{}},feedback: &feedbackHandlers{deps: d},}@@ -453,7 +451,6 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servg.DELETE("/api/insights/v1/sources/:id", api.insights.revokeSource)g.GET("/api/analytics", api.runs.analytics)g.GET("/api/observability/spec", api.observabilitySpec)- g.GET("/api/deployment-metrics", api.deploy.deploymentMetrics)g.POST("/api/otel/*path", api.otel)// --- page feedback (standalone, no project) ---diff --git a/internal/httpapi/static_routes_test.go b/internal/httpapi/static_routes_test.goindex c594c7c0..0ac7d19c 100644--- a/internal/httpapi/static_routes_test.go+++ b/internal/httpapi/static_routes_test.go@@ -38,7 +38,6 @@ func TestStaticRoutes(t *testing.T) {{"/extensions/agentflow-workspace/package.json", "json", 200},{"/app.js", "javascript", 200},{"/app/start.js", "javascript", 200},- {"/deployment-dashboard.css", "text/css", 200},{"/no-such-file.js", "", 404},{"/no/such/dir/", "", 404},} {diff --git a/internal/httpapi/tapd_import_live_test.go b/internal/httpapi/tapd_import_live_test.goindex 1abca10c..c55f7d76 100644--- a/internal/httpapi/tapd_import_live_test.go+++ b/internal/httpapi/tapd_import_live_test.go@@ -54,7 +54,7 @@ func TestLiveImportTAPDStoryWithExplicitCredentials(t *testing.T) {if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-70-project-assistant-test", Name: "TAPD MCP", MarketID: "70",Scope: "project", ProjectID: assistantAcceptanceProjectID, Transport: "http",- URL: "https://mcpgw.knot.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer " + token}, TimeoutSec: 60,+ URL: "https://mcp-gateway.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer " + token}, TimeoutSec: 60,}); err != nil {t.Fatal(err)}@@ -121,7 +121,7 @@ func TestDisposableStudioForBrowserIT(t *testing.T) {if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-70-project-assistant-test", Name: "TAPD MCP", MarketID: "70",Scope: "project", ProjectID: assistantAcceptanceProjectID, Transport: "http",- URL: "https://mcpgw.knot.example.com/tapd/", Headers: headers, TimeoutSec: 60,+ URL: "https://mcp-gateway.example.com/tapd/", Headers: headers, TimeoutSec: 60,}); err != nil {t.Fatal(err)}@@ -175,7 +175,7 @@ func TestMySQLImportTAPDAndSanitizeClarifyOptions(t *testing.T) {if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-70-project-" + projectID, Name: "TAPD MCP", MarketID: "70",Scope: "project", ProjectID: projectID, Transport: "http",- URL: "https://mcpgw.knot.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer " + token}, TimeoutSec: 60,+ URL: "https://mcp-gateway.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer " + token}, TimeoutSec: 60,}); err != nil {t.Fatal(err)}@@ -273,7 +273,7 @@ func TestSeedLocalClarifyPreview(t *testing.T) {}user, _ = st.UserByLoginName("example-maintainer")if err := st.PutProject(domain.Project{- ID: "dp", Key: "DP", Name: "DNSPod", Color: "#536dfe", OwnerID: user.ID,+ ID: "dp", Key: "DP", Name: "DemoDNS", Color: "#536dfe", OwnerID: user.ID,Members: []domain.ProjectMember{{UserID: user.ID, Role: "maintainer"}},}); err != nil {t.Fatal(err)@@ -281,7 +281,7 @@ func TestSeedLocalClarifyPreview(t *testing.T) {if err := st.PutMCPServer(domain.MCPServerDefinition{ID: "mcp-70-project-dp", Name: "TAPD MCP", MarketID: "70",Scope: "project", ProjectID: "dp", Transport: "http",- URL: "https://mcpgw.knot.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer " + token}, TimeoutSec: 60,+ URL: "https://mcp-gateway.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer " + token}, TimeoutSec: 60,}); err != nil {t.Fatal(err)}diff --git a/internal/repo/mr_delivery_memory_test.go b/internal/repo/mr_delivery_memory_test.goindex 7c91fde8..46c0279c 100644--- a/internal/repo/mr_delivery_memory_test.go+++ b/internal/repo/mr_delivery_memory_test.go@@ -461,12 +461,12 @@ func TestReconcileDeliveryMRStatesRecoversHTTPArtifactLink(t *testing.T) {ID: "run-http", Status: "succeeded", UpdatedAt: time.Now().UTC(),ExecutionContext: domain.TelemetryContext{IssueID: issue.ID},Repositories: []domain.RepositoryContext{{- RepositoryID: "vpcdns", Name: "vpcdns_oss", GongfengProjectID: "dnspod/vpcdns/vpcdns_oss",+ RepositoryID: "demodns", Name: "dns-service", GongfengProjectID: "example/dns/dns-service",WorkBranch: "feature/story-1",}},Artifacts: []domain.Artifact{{NodeID: "mr", Name: "mr-body",- Content: "http://git.example.com/dnspod/vpcdns/vpcdns_oss/merge_requests/558",+ Content: "http://git.example.com/example/dns/dns-service/merge_requests/558",}},}if err := s.PutRun(run); err != nil {@@ -476,7 +476,7 @@ func TestReconcileDeliveryMRStatesRecoversHTTPArtifactLink(t *testing.T) {t.Fatal(err)}got, _ := s.Issue(issue.ID)- want := "https://git.example.com/dnspod/vpcdns/vpcdns_oss/-/merge_requests/558"+ want := "https://git.example.com/example/dns/dns-service/-/merge_requests/558"if len(got.DeliveryMRs) != 1 || got.DeliveryMRURL != want || got.DeliveryMRs[0].IID != 558 {t.Fatalf("locked issue did not recover http MR: %+v", got)}diff --git a/internal/repo/opentest.go b/internal/repo/opentest.goindex 4e2e3958..eef63a3c 100644--- a/internal/repo/opentest.go+++ b/internal/repo/opentest.go@@ -112,8 +112,8 @@ func seedTestDefaults(s *Store) error {}if err := s.PutSyncConfig(domain.SyncConfig{GongfengProjectID: "example/team-project",- GongfengMCPURL: "https://mcpgw.knot.example.com/gongfeng",- TAPDMCPURL: "https://mcpgw.knot.example.com/tapd/",+ GongfengMCPURL: "https://mcp-gateway.example.com/gongfeng",+ TAPDMCPURL: "https://mcp-gateway.example.com/tapd/",AutoSyncEnabled: false,AutoSyncIntervalSec: 300,}); err != nil {diff --git a/internal/runtime/materialize.go b/internal/runtime/materialize.goindex 9e5bfd43..45c989b9 100644--- a/internal/runtime/materialize.go+++ b/internal/runtime/materialize.go@@ -431,9 +431,6 @@ func mcpAliases(m domain.MCPServerDefinition) []string {}key := strings.ToLower(m.ID + " " + m.URL)var out []string- if m.ID == "zhiyan-pipeline" || strings.Contains(key, "zhiyan") || strings.Contains(key, "/qci") {- out = append(out, "coding-mcp")- }if m.ID == "gongfeng-delivery" || strings.Contains(key, "gongfeng") {out = append(out, "gongfeng")}@@ -508,7 +505,7 @@ func headerLookup(headers map[string]string, name string) (string, bool) {func mcpUsageHint(servers []domain.MCPServerDefinition) string {var ids []string- hasQCI, hasGongfeng := false, false+ hasGongfeng := falsefor _, m := range servers {if strings.TrimSpace(m.ID) != "" {ids = append(ids, m.ID)@@ -517,9 +514,6 @@ func mcpUsageHint(servers []domain.MCPServerDefinition) string {continue}key := strings.ToLower(m.ID + " " + m.URL)- if m.ID == "coding-mcp" || m.ID == "zhiyan-pipeline" || strings.Contains(key, "zhiyan") || strings.Contains(key, "/qci") {- hasQCI = true- }if m.ID == "gongfeng" || m.ID == "gongfeng-delivery" || strings.Contains(key, "gongfeng") {hasGongfeng = true}@@ -531,8 +525,8 @@ func mcpUsageHint(servers []domain.MCPServerDefinition) string {b.WriteString("## MCP 怎么用\n\n")b.WriteString("本节点的平台 MCP 配置已按 Agent allowlist 严格注入:")b.WriteString(strings.Join(ids, "、"))- b.WriteString("。别名:zhiyan-pipeline=coding-mcp,gongfeng-delivery=gongfeng。\n")- b.WriteString("这些 MCP 已写入 `--mcp-config .agentflow/config/<agent>/mcp.json`,会以原生工具出现(名称常为 mcp__<server>__*)。直接调原生工具。HTTP MCP 禁止用 curl 打网关,禁止 Bash mcporter:JSON body 容易丢,QueryErrorLog 会变成 taskId=0,报 query old totalresult 0 failed。\n")+ b.WriteString("。别名:gongfeng-delivery=gongfeng。\n")+ b.WriteString("这些 MCP 已写入 `--mcp-config .agentflow/config/<agent>/mcp.json`,会以原生工具出现(名称常为 mcp__<server>__*)。直接调原生工具。HTTP MCP 禁止用 curl 打网关,禁止 Bash mcporter:JSON body 容易丢,参数会被静默截断。\n")if hasGongfeng {b.WriteString("\n### 工蜂:看 MR / Checkers\n")b.WriteString("真值是 commit status,不是审查报告是否 SUCCESS。\n")@@ -540,15 +534,6 @@ func mcpUsageHint(servers []domain.MCPServerDefinition) string {b.WriteString("2. 原生 `get_commit_combined_status`(sha=当前 HEAD)。这是 Checkers 列表。轮询最多 20 轮、间隔 90s,直到应等项终态。\n")b.WriteString("3. 失败项再 `search_merge_request_notes` 翻页对齐建议;`get_review_intelligent_result` 只表示审查意见,**不等于** MR审查 pipeline 绿。\n")b.WriteString("4. 创建 MR 用 `create_merge_request`;更新已有本轮 MR 才 `update_merge_request`;讨论区回评用 `create_merge_request_note`。\n")- }- if hasQCI {- b.WriteString("\n### 智研 QCI:看流水线失败原因\n")- b.WriteString("从 check 的 target_url 抽出 pipeline_id 和 build_id。近 30 天构建用原生 **coding_mcp**:\n")- b.WriteString("`GET /pipeline/{pipeline_id}/totalresult/{build_id}`\n")- b.WriteString("**禁止** `/pipeline/{id}/oldtotalresult`(冷库,会 0 条,不是「MCP 没数据」)。\n")- b.WriteString("从 totalresult 取失败 task 的真实 taskId(数字,禁止 0)。拉错误日志只能用原生 **coding_skill**(不要 coding_mcp,那条路径 404):\n")- b.WriteString("`POST /QueryErrorLog` body=`{\"pipelineId\":...,\"buildId\":...,\"taskId\":<上一步的id>}` 三个字段都必填。\n")- b.WriteString("若返回 `query old totalresult 0 failed`:MCP 是通的,是 ID 丢了。用 totalresult 里的数字重试。\n")b.WriteString("自动代码审查类检查失败若是 401 / no permission 等鉴权错误且没有代码审查结论,记 SKIP_INFRA,不要当成业务缺陷打回。\n")}return b.String()diff --git a/internal/runtime/materialize_skill_files_test.go b/internal/runtime/materialize_skill_files_test.goindex 0f42b5db..d29c34e7 100644--- a/internal/runtime/materialize_skill_files_test.go+++ b/internal/runtime/materialize_skill_files_test.go@@ -85,7 +85,7 @@ func TestMaterializeUploadedSkillMdGetsFrontmatterWhenMissing(t *testing.T) {ID: "sop", Name: "SOP", Description: "Issue 修复 SOP", Content: "payload should not win",FileRefs: []domain.SkillFileRef{{Path: "SKILL.md", Size: 12, Mode: 0o644}},}},- SkillFiles: map[string]map[string][]byte{"sop": {"SKILL.md": []byte("# DNSPod Issue 修复\n")}},+ SkillFiles: map[string]map[string][]byte{"sop": {"SKILL.md": []byte("# DemoDNS Issue 修复\n")}},}agent := domain.AgentDefinition{ID: "tester", Name: "Tester"}if _, err := materialize(workspace, "invoke-sop", domain.ExecutorDefinition{Kind: "codex"}, agent, assets); err != nil {@@ -96,7 +96,7 @@ func TestMaterializeUploadedSkillMdGetsFrontmatterWhenMissing(t *testing.T) {t.Fatal(err)}text := string(content)- if !strings.HasPrefix(strings.TrimSpace(text), "---") || !strings.Contains(text, "name: sop") || !strings.Contains(text, "# DNSPod Issue 修复") {+ if !strings.HasPrefix(strings.TrimSpace(text), "---") || !strings.Contains(text, "name: sop") || !strings.Contains(text, "# DemoDNS Issue 修复") {t.Fatalf("missing frontmatter on uploaded SKILL.md: %q", text)}}@@ -106,17 +106,17 @@ func TestMaterializeSelectedSkillsListsInvocationNameAndRoot(t *testing.T) {assets := domain.AgentAssetBundle{Skills: []domain.SkillDefinition{{ID: "unit-test-gen", Name: "单元测试生成", Description: "单元测试生成", Content: "unused"},- {ID: "dnspod-issue-fix", Name: "Issue 修复", Description: "SOP overview", Content: "# SOP\n"},+ {ID: "demodns-issue-fix", Name: "Issue 修复", Description: "SOP overview", Content: "# SOP\n"},},SkillFiles: map[string]map[string][]byte{"unit-test-gen": {"SKILL.md": []byte("---\nname: unit-test\ndescription: 单测治理总线(迁移增强版)\n---\n\n# Unit Test\n")},},}- agent := domain.AgentDefinition{ID: "dnspod-unit-test-engineer", Name: "DNSPod 单元测试工程师", Instructions: "写增量单测。"}+ agent := domain.AgentDefinition{ID: "demodns-unit-test-engineer", Name: "DemoDNS 单元测试工程师", Instructions: "写增量单测。"}if _, err := materialize(workspace, "invoke-skills", domain.ExecutorDefinition{Kind: "codebuddy"}, agent, assets); err != nil {t.Fatal(err)}- raw, err := os.ReadFile(filepath.Join(workspace, ".agentflow", "dnspod-unit-test-engineer", "agent-system.md"))+ raw, err := os.ReadFile(filepath.Join(workspace, ".agentflow", "demodns-unit-test-engineer", "agent-system.md"))if err != nil {t.Fatal(err)}@@ -126,9 +126,9 @@ func TestMaterializeSelectedSkillsListsInvocationNameAndRoot(t *testing.T) {"Otherwise read SKILL.md, then follow it using the skill root","name: `unit-test-gen` (id: unit-test-gen)","description: 单测治理总线(迁移增强版)",- "root: `.agentflow/dnspod-unit-test-engineer/skills/unit-test-gen`",- "name: `dnspod-issue-fix` (id: dnspod-issue-fix)",- "root: `.agentflow/dnspod-unit-test-engineer/skills/dnspod-issue-fix`",+ "root: `.agentflow/demodns-unit-test-engineer/skills/unit-test-gen`",+ "name: `demodns-issue-fix` (id: demodns-issue-fix)",+ "root: `.agentflow/demodns-unit-test-engineer/skills/demodns-issue-fix`",} {if !strings.Contains(text, needle) {t.Fatalf("agent-system.md missing %q:\n%s", needle, text)diff --git a/internal/runtime/mcp_call_test.go b/internal/runtime/mcp_call_test.goindex 09396b0f..cb072d49 100644--- a/internal/runtime/mcp_call_test.go+++ b/internal/runtime/mcp_call_test.go@@ -24,16 +24,16 @@ func TestMain(m *testing.M) {func TestMCPCallAliasesMatchURLAndInstallID(t *testing.T) {server := mcpCallServer{ID: "mcp-2214-project-dns",- Name: "七彩石(Rainbow) MCP",+ Name: "Config Center MCP",MarketID: "2214",- URL: "https://mcpgw.knot.example.com/rainbow",+ URL: "https://mcp-gateway.example.com/configcenter",Aliases: mcpCallAliases(domain.MCPServerDefinition{- ID: "mcp-2214-project-dns", Name: "七彩石(Rainbow) MCP", MarketID: "2214", URL: "https://mcpgw.knot.example.com/rainbow",+ ID: "mcp-2214-project-dns", Name: "Config Center MCP", MarketID: "2214", URL: "https://mcp-gateway.example.com/configcenter",}),}- got, err := matchMCPCallServer([]mcpCallServer{server}, "rainbow")+ got, err := matchMCPCallServer([]mcpCallServer{server}, "configcenter")if err != nil || got.ID != server.ID {- t.Fatalf("rainbow = %+v err=%v aliases=%v", got, err, server.Aliases)+ t.Fatalf("configcenter = %+v err=%v aliases=%v", got, err, server.Aliases)}got, err = matchMCPCallServer([]mcpCallServer{server}, "2214")if err != nil || got.ID != server.ID {@@ -71,7 +71,7 @@ func TestMCPCallCLIInvokesBoundHTTPServer(t *testing.T) {workspace := t.TempDir()sb := &localSandbox{workspace: workspace}assets := domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{{- ID: "mcp-2214-project-dns", Name: "七彩石(Rainbow) MCP", MarketID: "2214", Transport: "http",+ ID: "mcp-2214-project-dns", Name: "Config Center MCP", MarketID: "2214", Transport: "http",URL: gateway.URL, Headers: map[string]string{"Authorization": "Bearer mcp-token"},}}}env, err := ScriptMCPEnvironment(sb, workspace, assets.MCPServers)@@ -81,7 +81,7 @@ func TestMCPCallCLIInvokesBoundHTTPServer(t *testing.T) {for key, value := range env {t.Setenv(key, value)}- stdout, stderr, code := captureMCPCall(t, []string{"call", "2214", "get_config", `{"group":"dnspod_intl.dnspod_api"}`})+ stdout, stderr, code := captureMCPCall(t, []string{"call", "2214", "get_config", `{"group":"demodns_intl.demodns_api"}`})if code != 0 {t.Fatalf("exit %d stderr=%q stdout=%q", code, stderr, stdout)}diff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.goindex 1aa8f42a..d9f3a10c 100644--- a/internal/runtime/runtime_test.go+++ b/internal/runtime/runtime_test.go@@ -98,7 +98,7 @@ func TestMaterializeExpandsMCPBearerSecret(t *testing.T) {_, err := materialize(dir, "secret-ok", domain.ExecutorDefinition{Kind: "codebuddy"}, domain.AgentDefinition{ID: "checker", Name: "Checker"}, domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{{ID: "gongfeng-delivery", Name: "工蜂", Transport: "http",- URL: "https://mcpgw.knot.example.com/gongfeng",+ URL: "https://mcp-gateway.example.com/gongfeng",Headers: map[string]string{"Authorization": "Bearer ${secret:AGENTFLOW_MCP_TOKEN}"},}},})@@ -124,7 +124,7 @@ func TestMaterializeFailsWhenMCPSecretMissing(t *testing.T) {_, err := materialize(dir, "secret-missing", domain.ExecutorDefinition{Kind: "codebuddy"}, domain.AgentDefinition{ID: "checker", Name: "Checker"}, domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{{ID: "gongfeng-delivery", Name: "工蜂", Transport: "http",- URL: "https://mcpgw.knot.example.com/gongfeng",+ URL: "https://mcp-gateway.example.com/gongfeng",Headers: map[string]string{"Authorization": "Bearer ${secret:AGENTFLOW_MCP_TOKEN}"},}},})@@ -142,7 +142,7 @@ func TestMaterializeUsesPlainMCPHeaders(t *testing.T) {_, err := materialize(dir, "plain-headers", domain.ExecutorDefinition{Kind: "codebuddy"}, domain.AgentDefinition{ID: "checker", Name: "Checker"}, domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{{ID: "gongfeng-delivery", Name: "工蜂", Transport: "http",- URL: "https://mcpgw.knot.example.com/gongfeng",+ URL: "https://mcp-gateway.example.com/gongfeng",Headers: map[string]string{"Authorization": "Bearer tai_plain_in_mcp"},}},})@@ -309,7 +309,7 @@ func TestPrepareDockerfileBuildContextWritesRecipeAndFiles(t *testing.T) {func TestCachedDockerImageNameIgnoresCatalogMetadata(t *testing.T) {a := domain.DockerfileDefinition{- ID: "dnspod-php-backend",+ ID: "demodns-php-backend",Name: "PHP",Content: "FROM node:22-bookworm-slim\n",Files: map[string]string{"conf/php.ini": "memory_limit=1G\n", "conf/www.conf": "user=nobody\n"},@@ -1949,8 +1949,8 @@ func TestMaterializeInjectsHTTPMCPAliases(t *testing.T) {t.Setenv("AGENTFLOW_MCP_USERNAME", "example-admin")assets := domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{- {ID: "zhiyan-pipeline", Name: "智研", Transport: "http", URL: "https://mcpgw.knot.example.com/zhiyan/qci", Headers: map[string]string{"Authorization": "Bearer test-token"}},- {ID: "gongfeng-delivery", Name: "工蜂", Transport: "http", URL: "https://mcpgw.knot.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer test-token"}},+ {ID: "ci-pipeline", Name: "CI", Transport: "http", URL: "https://mcp.example.com/ci", Headers: map[string]string{"Authorization": "Bearer test-token"}},+ {ID: "gongfeng-delivery", Name: "工蜂", Transport: "http", URL: "https://mcp.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer test-token"}},},}_, err := materialize(dir, "invoke-1", domain.ExecutorDefinition{Kind: "codebuddy"}, domain.AgentDefinition{ID: "checker", Name: "Checker"}, assets)@@ -1962,18 +1962,23 @@ func TestMaterializeInjectsHTTPMCPAliases(t *testing.T) {t.Fatal(err)}text := string(raw)- for _, needle := range []string{`"zhiyan-pipeline"`, `"coding-mcp"`, `"gongfeng-delivery"`, `"gongfeng"`, `"X-Username": "example-admin"`, "mcpgw.knot.example.com/zhiyan/qci"} {+ for _, needle := range []string{`"ci-pipeline"`, `"gongfeng-delivery"`, `"gongfeng"`, `"X-Username": "example-admin"`, "mcp.example.com/ci"} {if !strings.Contains(text, needle) {t.Fatalf("mcp.json missing %s:\n%s", needle, text)}}+ if strings.Contains(text, `"coding-mcp"`) {+ t.Fatalf("a generic HTTP MCP must not get a vendor alias:\n%s", text)+ }sys, err := os.ReadFile(filepath.Join(dir, ".agentflow", "checker", "agent-system.md"))if err != nil {t.Fatal(err)}hint := string(sys)- if !strings.Contains(hint, "totalresult") || !strings.Contains(hint, "oldtotalresult") || !strings.Contains(hint, "QueryErrorLog") || !strings.Contains(hint, "taskId") || !strings.Contains(hint, "get_commit_combined_status") || !strings.Contains(hint, "coding_skill") {- t.Fatalf("system prompt missing QCI/MR API rules:\n%s", hint)+ for _, want := range []string{"ci-pipeline", "get_commit_combined_status", "SKIP_INFRA", "别名:gongfeng-delivery=gongfeng"} {+ if !strings.Contains(hint, want) {+ t.Fatalf("system prompt missing MCP rule %q:\n%s", want, hint)+ }}}@@ -2092,7 +2097,7 @@ func TestCodeBuddyDropsToolsAllowlistWhenHTTPMCPPresent(t *testing.T) {}assets := domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{- {ID: "gongfeng-delivery", Name: "工蜂", Transport: "http", URL: "https://mcpgw.knot.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer test-token"}},+ {ID: "gongfeng-delivery", Name: "工蜂", Transport: "http", URL: "https://mcp-gateway.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer test-token"}},},}if _, err := NewExecutorRunner().Run(context.Background(), sb, "invoke-mcp", ex, domain.AgentDefinition{ID: "closer", Name: "Closer"}, assets, "probe", InvocationOptions{}, nil); err != nil {diff --git a/internal/runtime/skill_md_test.go b/internal/runtime/skill_md_test.goindex bdeb4806..0289ea2c 100644--- a/internal/runtime/skill_md_test.go+++ b/internal/runtime/skill_md_test.go@@ -27,14 +27,14 @@ func TestEnsureSkillFrontmatterFillsMissingDescription(t *testing.T) {}func TestEnsureSkillFrontmatterAddsNameAndDescription(t *testing.T) {- got := string(ensureSkillFrontmatter([]byte("# DNSPod Issue 修复\n"), "dnspod-issue-fix", "openclaw-universal SMALL"))- if !strings.HasPrefix(got, "---\nname: dnspod-issue-fix\n") {+ got := string(ensureSkillFrontmatter([]byte("# DemoDNS Issue 修复\n"), "demodns-issue-fix", "openclaw-universal SMALL"))+ if !strings.HasPrefix(got, "---\nname: demodns-issue-fix\n") {t.Fatalf("missing name frontmatter: %q", got)}if !strings.Contains(got, `description: "openclaw-universal SMALL"`) && !strings.Contains(got, "description: openclaw-universal SMALL") {t.Fatalf("missing description: %q", got)}- if !strings.Contains(got, "# DNSPod Issue 修复") {+ if !strings.Contains(got, "# DemoDNS Issue 修复") {t.Fatalf("body was dropped: %q", got)}}diff --git a/internal/tracker/catalog_test.go b/internal/tracker/catalog_test.goindex b0203292..bad322f2 100644--- a/internal/tracker/catalog_test.go+++ b/internal/tracker/catalog_test.go@@ -38,13 +38,13 @@ func (f projectAuthFixture) MCPServers() []domain.MCPServerDefinition { return ffunc TestBindTrackerMCPPrefersCatalogHeadersOverEnvToken(t *testing.T) {cfg := domain.SyncConfig{- GongfengMCPURL: "https://mcpgw.knot.example.com/gongfeng",- TAPDMCPURL: "https://mcpgw.knot.example.com/tapd/",+ GongfengMCPURL: "https://mcp-gateway.example.com/gongfeng",+ TAPDMCPURL: "https://mcp-gateway.example.com/tapd/",}servers := []domain.MCPServerDefinition{{ID: "gongfeng-delivery",Transport: "http",- URL: "https://mcpgw.knot.example.com/gongfeng",+ URL: "https://mcp-gateway.example.com/gongfeng",Headers: map[string]string{"Authorization": "Bearer catalog-pat"},}}gf := bindTrackerMCP("gongfeng", cfg, servers, "expired-env-token", "Bearer expired-oauth")@@ -67,10 +67,10 @@ func TestBindTrackerMCPPrefersCatalogHeadersOverEnvToken(t *testing.T) {}func TestBindTrackerMCPUsesDedicatedTAPDCatalog(t *testing.T) {- cfg := domain.SyncConfig{TAPDMCPURL: "https://mcpgw.knot.example.com/tapd/"}+ cfg := domain.SyncConfig{TAPDMCPURL: "https://mcp-gateway.example.com/tapd/"}servers := []domain.MCPServerDefinition{- {ID: "gongfeng-delivery", Transport: "http", URL: "https://mcpgw.knot.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer gf"}},- {ID: "tapd-delivery", Transport: "http", URL: "https://mcpgw.knot.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer tapd"}},+ {ID: "gongfeng-delivery", Transport: "http", URL: "https://mcp-gateway.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer gf"}},+ {ID: "tapd-delivery", Transport: "http", URL: "https://mcp-gateway.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer tapd"}},}got := bindTrackerMCP("tapd", cfg, servers, "env", "")if got.Source != "catalog:tapd-delivery" || got.Headers["Authorization"] != "Bearer tapd" {@@ -79,7 +79,7 @@ func TestBindTrackerMCPUsesDedicatedTAPDCatalog(t *testing.T) {}func TestBindTrackerMCPFallsBackWhenCatalogMissing(t *testing.T) {- cfg := domain.SyncConfig{GongfengMCPURL: "https://mcpgw.knot.example.com/gongfeng"}+ cfg := domain.SyncConfig{GongfengMCPURL: "https://mcp-gateway.example.com/gongfeng"}got := bindTrackerMCP("gongfeng", cfg, nil, "env-token", "")if got.Source != "env:AGENTFLOW_MCP_TOKEN" {t.Fatalf("source=%q", got.Source)diff --git a/internal/tracker/tapd_bug_sync_test.go b/internal/tracker/tapd_bug_sync_test.goindex 7a787cfe..e47146e7 100644--- a/internal/tracker/tapd_bug_sync_test.go+++ b/internal/tracker/tapd_bug_sync_test.go@@ -76,7 +76,7 @@ func TestTapdBugStatusToStatus(t *testing.T) {func TestUpsertTAPDBug(t *testing.T) {svc := NewService()- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS"}}}issue, err := svc.upsertTAPDBug(store, "dp", "10000000", tapdStory{ID: "1010000000100002109", Name: "国际站dnssec调用digns服务失败",Description: "## 问题描述\n连接异常", Status: "new", Priority: "low",diff --git a/internal/tracker/tapd_import_test.go b/internal/tracker/tapd_import_test.goindex 57a284f8..bf32c55c 100644--- a/internal/tracker/tapd_import_test.go+++ b/internal/tracker/tapd_import_test.go@@ -18,7 +18,7 @@ func TestImportTAPDStoryFromDetailURL(t *testing.T) {svc := NewService()svc.Configure(domain.SyncConfig{TAPDMCPURL: gateway.URL})- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS"}}}issue, err := svc.ImportTAPDStory(store, "dp", "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100000555", 0)if err != nil {t.Fatal(err)@@ -232,7 +232,7 @@ func TestImportTAPDStoryScoresCompleteDescription(t *testing.T) {defer gateway.Close()svc := NewService()svc.Configure(domain.SyncConfig{TAPDMCPURL: gateway.URL})- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS"}}}issue, err := svc.ImportTAPDStory(store, "dp", "https://tapd.example.com/tapd_fe/10000000/story/detail/1002", 0)if err != nil {t.Fatal(err)@@ -250,7 +250,7 @@ func TestSyncTAPDStoryDoesNotScoreOrGate(t *testing.T) {defer gateway.Close()svc := NewService()svc.Configure(domain.SyncConfig{TAPDMCPURL: gateway.URL})- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS"}}}issue, err := svc.upsertTAPDStory(store, "dp", "10000000", tapdStory{ID: "3001", Name: "【国内站】mq_flush_dns命令CMQ SDK连接异常", Status: "open"}, 0, false)if err != nil {t.Fatal(err)diff --git a/internal/tracker/tapd_resync_test.go b/internal/tracker/tapd_resync_test.goindex 76e18c90..ff1b2757 100644--- a/internal/tracker/tapd_resync_test.go+++ b/internal/tracker/tapd_resync_test.go@@ -14,7 +14,7 @@ func TestResyncTAPDIssueRefreshesStoryContent(t *testing.T) {svc := NewService()svc.Configure(domain.SyncConfig{TAPDMCPURL: gateway.URL})- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod", TAPDWorkspaceID: "10000000"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS", TAPDWorkspaceID: "10000000"}}}seed, err := svc.upsertTAPDStory(store, "dp", "10000000", tapdStory{ID: "1001", Name: "旧标题", Description: "旧正文", Status: "planned",@@ -63,7 +63,7 @@ func TestResyncTAPDIssueRefreshesBugContent(t *testing.T) {svc := NewService()svc.Configure(domain.SyncConfig{TAPDMCPURL: gateway.URL})- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod", TAPDWorkspaceID: "10000000"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS", TAPDWorkspaceID: "10000000"}}}seed, err := svc.upsertTAPDBug(store, "dp", "10000000", tapdStory{ID: "2001", Name: "缺陷B旧标题", Description: "缺陷旧正文", Status: "new",@@ -88,7 +88,7 @@ func TestResyncTAPDIssueRefreshesBugContent(t *testing.T) {func TestResyncTAPDIssueRejectsNonTAPDSource(t *testing.T) {svc := NewService()- store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DNSPod"}}}+ store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp", Name: "DemoDNS"}}}if _, err := svc.ResyncTAPDIssue(store, domain.Issue{ID: "local-1", ProjectID: "dp", Source: "local"}); err == nil {t.Fatal("expected error for non-tapd issue")}diff --git a/local/.claude/skills/agent-observability/SKILL.md b/local/.claude/skills/agent-observability/SKILL.mdindex 8bff9f0c..5f980a68 100644--- a/local/.claude/skills/agent-observability/SKILL.md+++ b/local/.claude/skills/agent-observability/SKILL.md@@ -1,6 +1,6 @@---name: agent-observability-description: Add or maintain CodeBuddy hook observability for projects that need local metrics for tool latency, transcript token usage, session cost, and multi-agent trace attribution. Use when wiring hook-based telemetry, debugging missing usage events, and validating AgentLens state.+description: Add or maintain CodeBuddy hook observability for projects that need local metrics for tool latency, transcript token usage, session cost, and multi-agent trace attribution. Use when wiring hook-based telemetry, and debugging missing usage events.---## Workflow@@ -8,7 +8,7 @@ description: Add or maintain CodeBuddy hook observability for projects that need1. Merge `templates/settings-hook.json` into the user or project `settings.json`.2. Keep hook entries command-only and keep timeouts around 5 to 10 seconds.3. Run a normal CodeBuddy session and inspect `logs/metrics.ndjson`.-4. Inspect `logs/.state.json` when usage replay, offsets, or AgentLens turn state look wrong.+4. Inspect `logs/.state.json` when usage replay or offsets look wrong.5. Keep the runtime generic and verify output from `metrics.ndjson` and `.state.json`.## Read Next@@ -20,8 +20,7 @@ description: Add or maintain CodeBuddy hook observability for projects that need- `scripts/main.py`: hook entrypoint for `session-start`, `user-prompt-submit`, `pre`, `post`, and `stop`- `scripts/run_hook.sh`: stable shell wrapper for CodeBuddy hook commands- `scripts/core/collector.py`: transcript parsing, pre/post pairing, and session usage recording-- `scripts/core/agentlens.py`: AgentLens trace emission and agent or step grouping-- `scripts/core/state.py`: persisted hook state, offsets, and AgentLens sidecar state+- `scripts/core/state.py`: persisted hook state, offsets, and pending tool events- `scripts/core/devflow.py`: optional devflow-awareness — detects a `multi-agents-devflow-*` team, reads `workflow-state.json`, and emits `stage_transition` events. No-ops entirely on non-devflow projects.- `templates/settings-hook.json`: hook wiring templatediff --git a/local/.claude/skills/agent-observability/references/quickstart.md b/local/.claude/skills/agent-observability/references/quickstart.mdindex 4a667772..06d1b139 100644--- a/local/.claude/skills/agent-observability/references/quickstart.md+++ b/local/.claude/skills/agent-observability/references/quickstart.md@@ -129,7 +129,6 @@ PY- 没有日志:检查 hook 命令路径。- `ms` 为空:通常是 pre/post 未配对。- 没有 `usage`:`transcript_path` 缺失、tail 无 usage,或增量已去重。-- AgentLens 未启用:检查 `.state.json` 的 `_agentlens.enabled` / `last_error`。### 已知问题(未修复)diff --git a/local/.claude/skills/agent-observability/references/schema-v2.md b/local/.claude/skills/agent-observability/references/schema-v2.mdindex 43b84e1c..0bade267 100644--- a/local/.claude/skills/agent-observability/references/schema-v2.md+++ b/local/.claude/skills/agent-observability/references/schema-v2.md@@ -32,7 +32,7 @@ devflow 项目完全不受影响:| event | 实际顶层字段 | 说明 ||---|---|---|| `start` | `event`, `sid`, `agent`, `ts` | 会话开始 |-| `user_prompt_submit` | `event`, `sid`, `agent`, `turn_id`, `prompt_len`, `ts` | 新 turn 边界;AgentLens 侧按 `1 Trace = 1 Turn` 生成 trace |+| `user_prompt_submit` | `event`, `sid`, `agent`, `turn_id`, `prompt_len`, `ts` | 新 turn 边界;之后没有自带 `turn_id` 的事件归入该 turn || `tool` | `event`, `sid`, `agent`, `tool`, `ms`, `transcript_path`, `turn_id`, `ts`, `skill`, `rule`, `cwd`, `call_id`, `message_id`, `tool_details`, `task_slug`?, `stage`?, `pt_id`? | 工具调用与耗时 || `usage` | `event`, `sid`, `agent`, `tool`, `tokens`, `model`, `transcript_path`, `source_offset`, `turn_id`, `message_id`, `ts`, `task_slug`?, `stage`? | transcript 增量 token / 模型 / 消息归属 || `stop` | `event`, `sid`, `agent`, `tokens`, `model`, `transcript_path`, `source_offset`, `turn_id`, `message_id`, `ts`, `task_slug`?, `stage`? | 会话尾部 flush |@@ -254,18 +254,6 @@ devflow 项目完全不受影响:}```-### AgentLens sidecar--`.state.json[sid]._agentlens` 只作为内部状态使用,核心字段:--- `enabled`: AgentLens 上报是否可用-- `last_error`: 最近一次降级原因-- `current_turn.carrier.traceparent`: 当前 turn 的 trace context-- `current_turn.subagent_spans`: 同一 turn 下的子 agent span carrier-- `current_turn.agent_spans`: 同一 turn 下按 agent 聚合的 span carrier 与累计统计-- `current_turn.step_spans`: `(agent, message_id)` 级 step span registry-- `turn_history`: 已结束 turn 的摘要-### Hook 接入参考 `templates/settings-hook.json`,必须启用:diff --git a/local/.claude/skills/agent-observability/scripts/build_dashboard_data.py b/local/.claude/skills/agent-observability/scripts/build_dashboard_data.pyindex 4c639f1a..ec5f234b 100644--- a/local/.claude/skills/agent-observability/scripts/build_dashboard_data.py+++ b/local/.claude/skills/agent-observability/scripts/build_dashboard_data.py@@ -126,9 +126,8 @@ def build_daily_and_sessions(events: list[dict[str, Any]]) -> tuple[list[dict[stby_day: dict[str, dict[str, Any]] = {}by_sid: dict[str, dict[str, Any]] = {}by_sid_turn: dict[tuple[str, str], dict[str, Any]] = {}- # AgentLens(写 state.current_turn 的那套 tracing)默认关闭时,tool/usage 事件- # 自身的 turn_id 永远是 None——但 user_prompt_submit 事件不依赖 AgentLens,- # 始终携带真实 turn_id(见 emitter.build_prompt_submit_event)。按 ts 排序后,+ # tool/usage 事件自身不带 turn_id,只有 user_prompt_submit 事件+ # 携带真实 turn_id(见 emitter.build_prompt_submit_event)。按 ts 排序后,# 把它当作 turn 边界,让后续没有自带 turn_id 的 tool/usage 事件归入"当前 sid# 最近一次打开的 turn",而不是全部塌缩进同一个 "?" 占位桶。current_turn_by_sid: dict[str, str] = {}diff --git a/local/.claude/skills/agent-observability/scripts/core/__init__.py b/local/.claude/skills/agent-observability/scripts/core/__init__.pyindex 1d6ad5e9..a45607b6 100644--- a/local/.claude/skills/agent-observability/scripts/core/__init__.py+++ b/local/.claude/skills/agent-observability/scripts/core/__init__.py@@ -4,5 +4,4 @@- 采集与 transcript 解析- 状态读写与去重- skill/rule 扫描-- AgentLens trace 镜像"""diff --git a/local/.claude/skills/agent-observability/scripts/core/agentlens/__init__.py b/local/.claude/skills/agent-observability/scripts/core/agentlens/__init__.pydeleted file mode 100644index 2fea21d6..00000000--- a/local/.claude/skills/agent-observability/scripts/core/agentlens/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""可选的 AgentLens sink,用于实时镜像 trace。"""-from .runtime import emit_post_step, emit_session_start, emit_session_stop, emit_turn_start--__all__ = [- "emit_post_step",- "emit_session_start",- "emit_session_stop",- "emit_turn_start",-]diff --git a/local/.claude/skills/agent-observability/scripts/core/agentlens/bootstrap.py b/local/.claude/skills/agent-observability/scripts/core/agentlens/bootstrap.pydeleted file mode 100644index d6fc970e..00000000--- a/local/.claude/skills/agent-observability/scripts/core/agentlens/bootstrap.py+++ /dev/null@@ -1,229 +0,0 @@-from __future__ import annotations-"""AgentLens 启动辅助层。--这一层负责“读入与初始化”:-- 解析项目配置与环境变量-- 延迟加载可选的 zhiyan 运行时-- 缓存初始化结果,避免重复 init-- 处理调试落盘与失败状态写回-"""--import getpass-import json-import os-from dataclasses import dataclass-from pathlib import Path-from typing import Any--from .. import state as st--DEFAULT_APP_NAME = "skillhub.codebuddy-hooks"-DEFAULT_BUSINESS_SCENARIO = "codebuddy-hook"--_RUNTIME: dict[str, Any] | None = None-_INIT_SIGNATURE: tuple[str, str, str] | None = None---@dataclass(frozen=True)-class AgentLensConfig:- """从环境变量与 env 文件归一化得到的 AgentLens 配置。"""- endpoint: str | None- api_key: str | None- app_name: str- business_scenario: str- user: str-- @property- def enabled(self) -> bool:- return bool(self.endpoint and self.api_key)---def project_root(cwd: str | None = None) -> Path:- """解析用于查找 `.env` 的项目根目录。"""- if cwd:- return Path(cwd).expanduser().resolve()- env_cwd = str(os.environ.get("CODEBUDDY_PROJECT_DIR") or "").strip()- if env_cwd:- return Path(env_cwd).expanduser().resolve()- return Path.cwd().resolve()---def read_env_file(path: Path) -> dict[str, str]:- """以轻量方式解析 shell 风格的 env 文件,不做 source。"""- values: dict[str, str] = {}- if not path.is_file():- return values- try:- lines = path.read_text("utf-8").splitlines()- except Exception:- return values-- for raw_line in lines:- line = raw_line.strip()- if not line or line.startswith("#"):- continue- if line.startswith("export "):- line = line[7:].strip()- if "=" not in line:- continue- key, value = line.split("=", 1)- key = key.strip()- value = value.strip()- if not key:- continue- if value and value[0] == value[-1] and value[0] in {"'", '"'}:- value = value[1:-1]- values[key] = value- return values---def load_config(project_root_path: Path) -> AgentLensConfig:- """按优先级加载配置:进程环境变量 > `.env.local` > `.env`。"""- env_file = read_env_file(project_root_path / ".env")- env_local_file = read_env_file(project_root_path / ".env.local")-- def _value(name: str, default: str | None = None) -> str | None:- env_value = os.environ.get(name)- if env_value is not None and str(env_value).strip():- return str(env_value).strip()- if name in env_local_file and str(env_local_file[name]).strip():- return str(env_local_file[name]).strip()- if name in env_file and str(env_file[name]).strip():- return str(env_file[name]).strip()- return default-- user = _value("ZHIYANLLM_USER")- if not user:- user = (- str(os.environ.get("USER") or "").strip()- or str(os.environ.get("USERNAME") or "").strip()- or getpass.getuser()- )-- return AgentLensConfig(- endpoint=_value("ZHIYANLLM_API_ENDPOINT"),- api_key=_value("ZHIYANLLM_API_KEY"),- app_name=_value("ZHIYANLLM_APP_NAME", DEFAULT_APP_NAME) or DEFAULT_APP_NAME,- business_scenario=_value("ZHIYANLLM_BUSINESS_SCENARIO", DEFAULT_BUSINESS_SCENARIO)- or DEFAULT_BUSINESS_SCENARIO,- user=user or "unknown",- )---def load_runtime() -> dict[str, Any] | None:- """延迟导入可选的 zhiyan 运行时组件。-- 即使本地没有安装 AgentLens 依赖,hook 主链路也必须继续工作,- 所以这里返回 ``None``,而不是把导入异常抛出去。- """- global _RUNTIME- if _RUNTIME is not None:- return _RUNTIME- try:- from zhiyanllm import Zhiyanllm- from zhiyanllm.opentelemetry.instrumentation.semconv_ai import (- SpanAttributes as ZhiyanSpanAttributes,- ZhiyanllmSpanKindValues,- )- from zhiyanllm.tracing.context_manager import get_tracer- from zhiyanllm.tracing.manual import track_llm_call, track_task_server_call- from zhiyanllm.tracing.tracing import TracerWrapper- from opentelemetry.context import attach as otel_attach, detach as otel_detach- except Exception:- _RUNTIME = None- return None-- _RUNTIME = {- "Zhiyanllm": Zhiyanllm,- "track_llm_call": track_llm_call,- "track_task_server_call": track_task_server_call,- "TracerWrapper": TracerWrapper,- "get_tracer": get_tracer,- "ZhiyanSpanAttributes": ZhiyanSpanAttributes,- "ZhiyanllmSpanKindValues": ZhiyanllmSpanKindValues,- "otel_attach": otel_attach,- "otel_detach": otel_detach,- }- return _RUNTIME---def ensure_initialized(config: AgentLensConfig) -> dict[str, Any] | None:- """仅当有效配置签名发生变化时才重新初始化 zhiyan。"""- global _INIT_SIGNATURE- if not config.enabled:- return None- runtime = load_runtime()- if runtime is None:- return None- signature = (str(config.endpoint), str(config.api_key), str(config.app_name))- if _INIT_SIGNATURE == signature:- return runtime- runtime["Zhiyanllm"].init(- app_name=str(config.app_name),- api_endpoint=str(config.endpoint),- api_key=str(config.api_key),- disable_batch=True,- )- _INIT_SIGNATURE = signature- return runtime---def project_root_from_state_path(state_path: Path) -> Path:- """尽力从 `logs/.state.json` 反推出项目根目录。"""- try:- current = state_path.resolve().parent- for parent in [current, *current.parents]:- if parent.name == ".codebuddy":- return parent.parent- return state_path.resolve().parents[4]- except Exception:- return Path.cwd().resolve()---def debug_enabled(state_path: Path) -> bool:- """判断是否要把 span 调试信息镜像写入 `agentlens-push-debug.ndjson`。"""- root = project_root_from_state_path(state_path)- env_file = read_env_file(root / ".env")- env_local_file = read_env_file(root / ".env.local")- raw = (- os.environ.get("AGENTLENS_PUSH_DEBUG")- or env_local_file.get("AGENTLENS_PUSH_DEBUG")- or env_file.get("AGENTLENS_PUSH_DEBUG")- or ""- )- return str(raw).strip().lower() in {"1", "true", "yes", "on"}---def debug_write_span(- state_path: Path | None,- sid: str | None,- payload: dict[str, Any],- *,- sanitizer,-) -> None:- """在开启 AgentLens 调试模式时追加写入清洗后的调试记录。"""- if state_path is None or not sid:- return- try:- if not debug_enabled(state_path):- return- debug_path = state_path.parent / "agentlens-push-debug.ndjson"- record = {"sid": sid, **sanitizer(payload)}- with debug_path.open("a", encoding="utf-8") as fp:- fp.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")- except Exception:- return---def set_failure(state_path: Path, sid: str, message: str) -> None:- """记录最近一次 AgentLens 失败,但不打断 hook 主流程。"""- st.update_agentlens_session(- state_path,- sid,- {"enabled": False, "last_error": str(message)},- )---def get_session_context(state_path: Path, sid: str) -> dict[str, Any]:- """从共享状态里读取 AgentLens sidecar 的 session payload。"""- return st.load_agentlens_session(state_path, sid)diff --git a/local/.claude/skills/agent-observability/scripts/core/agentlens/normalize.py b/local/.claude/skills/agent-observability/scripts/core/agentlens/normalize.pydeleted file mode 100644index 2b730f06..00000000--- a/local/.claude/skills/agent-observability/scripts/core/agentlens/normalize.py+++ /dev/null@@ -1,323 +0,0 @@-from __future__ import annotations-"""AgentLens 负载清洗层。--这一层负责“清洗与整形”:-- 在发送或调试前把任意 payload 转成安全的 JSON 结构-- 把本地 token 结构归一化成类似 OpenAI 的 usage 结构-- 从 transcript 中重建轻量的 message / tool-call 上下文-"""--import json-import os-from pathlib import Path-from typing import Any--from .. import state as st-from .bootstrap import AgentLensConfig---def sanitize_payload(value: Any) -> Any:- """把任意 Python 值转换成适合调试/打点的 JSON 安全结构。"""- try:- return json.loads(json.dumps(value, ensure_ascii=False, default=str))- except Exception:- return str(value)---def association_properties(config: AgentLensConfig, sid: str, state_path: Path | None = None) -> dict[str, str]:- """构造 trace 级关联属性,并允许按 turn 覆盖业务场景。"""- scenario = config.business_scenario- if state_path:- try:- session_ctx = st.load_agentlens_session(state_path, sid)- turn_scenario = session_ctx.get("_turn_business_scenario")- if isinstance(turn_scenario, str) and turn_scenario.strip():- scenario = turn_scenario.strip()- except Exception:- pass- return {- "session_id": sid,- "business_scenario": scenario,- "user": config.user,- }---def to_openai_usage(tokens: dict[str, Any] | None) -> dict[str, int]:- """把本地 token 结构转换成 zhiyan 期望的 usage 形状。"""- if not isinstance(tokens, dict):- return {}-- def _int(v: Any) -> int:- try:- return int(v or 0)- except Exception:- return 0-- prompt = _int(tokens.get("input"))- completion = _int(tokens.get("output"))- if prompt <= 0 and completion <= 0:- return {}- return {"prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": prompt + completion}---def infer_vendor(model: str | None) -> str:- """根据模型名推断一个粗粒度的 provider/vendor 标签。"""- text = str(model or "").strip().lower()- if not text:- return "unknown"- if "gpt" in text or "openai" in text:- return "openai"- if "claude" in text or "anthropic" in text:- return "anthropic"- if "gemini" in text or "google" in text:- return "google"- if text.startswith("hy") or "hunyuan" in text:- return "tencent"- return text.split("/", 1)[0].split("-", 1)[0] or "unknown"---def extract_message_text(content: Any) -> str:- """把嵌套的 transcript message 内容压平成纯文本。"""- if content is None:- return ""- if isinstance(content, str):- return content- if isinstance(content, list):- parts: list[str] = []- for item in content:- if isinstance(item, dict):- txt = item.get("text")- if isinstance(txt, str):- parts.append(txt)- elif item.get("type") == "tool_use":- parts.append(f"[tool_use {item.get('name', '')}]")- elif item.get("type") == "tool_result":- parts.append(extract_message_text(item.get("content")))- else:- parts.append(str(item))- return "\n".join(p for p in parts if p)- if isinstance(content, dict):- return extract_message_text(content.get("text") or content.get("content"))- return str(content)---def find_message_id_in_record(obj: Any) -> str | None:- """在 transcript 记录里递归查找稳定的 message 标识。"""- message_id_keys = ("messageId", "responseId", "requestId")- if isinstance(obj, dict):- provider = obj.get("providerData")- if isinstance(provider, dict):- for key in message_id_keys:- value = provider.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- extra = obj.get("extra")- if isinstance(extra, dict):- for key in message_id_keys:- value = extra.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- for key in message_id_keys:- value = obj.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- for value in obj.values():- found = find_message_id_in_record(value)- if found:- return found- elif isinstance(obj, list):- for value in obj:- found = find_message_id_in_record(value)- if found:- return found- return None---def collect_tool_calls_for_message(transcript_path: str, message_id: str) -> list[dict[str, Any]]:- """为指定 assistant message 重建它挂载的 tool-call 摘要。"""- if not transcript_path or not message_id or not os.path.isfile(transcript_path):- return []- try:- with open(transcript_path, "rb") as fp:- blob = fp.read()- except Exception:- return []-- tool_calls: list[dict[str, Any]] = []- for raw_line in blob.splitlines(keepends=True):- if not raw_line.lstrip().startswith(b"{"):- continue- try:- rec = json.loads(raw_line.decode("utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(rec, dict):- continue- if str(rec.get("type") or "").strip().lower() != "function_call":- continue- rec_mid = find_message_id_in_record(rec)- if rec_mid != message_id:- continue- call_id = str(rec.get("callId") or "").strip()- name = str(rec.get("name") or "").strip()- arguments = rec.get("arguments")- entry: dict[str, Any] = {"id": call_id, "name": name}- if arguments is not None:- entry["arguments"] = arguments if isinstance(arguments, str) else json.dumps(arguments, ensure_ascii=False)- tool_calls.append(entry)- return tool_calls---def find_tool_usage_event(tool_event: dict[str, Any], usage_events: list[dict[str, Any]]) -> dict[str, Any] | None:- """从 usage 列表里挑出最可能属于当前 tool 事件的那一条。"""- tool_name = str(tool_event.get("tool") or "")- transcript_path = str(tool_event.get("transcript_path") or "")- agent = str(tool_event.get("agent") or "main")- for usage_event in usage_events:- if not isinstance(usage_event, dict):- continue- if str(usage_event.get("agent") or "main") != agent:- continue- if transcript_path and str(usage_event.get("transcript_path") or "") != transcript_path:- continue- if tool_name and str(usage_event.get("tool") or "") not in {tool_name, "model_request"}:- continue- if str(usage_event.get("message_id") or "").strip():- return usage_event- for usage_event in usage_events:- if not isinstance(usage_event, dict):- continue- if str(usage_event.get("agent") or "main") != agent:- continue- if transcript_path and str(usage_event.get("transcript_path") or "") != transcript_path:- continue- return usage_event- return None---def build_llm_io_from_transcript(- *,- transcript_path: str,- source_offset: int,- tokens: dict[str, Any] | None,- model: str | None,- start_offset: int = 0,- current_message_id: str | None = None,-) -> tuple[dict[str, Any], dict[str, Any], str]:- """从 transcript 历史中构造紧凑版的 LLM 输入/输出负载。"""- input_data: dict[str, Any] = {"model": str(model or "unknown"), "messages": []}- output_data: dict[str, Any] = {"choices": [], "usage": to_openai_usage(tokens)}- if not transcript_path or not os.path.isfile(transcript_path):- return input_data, output_data, ""- try:- with open(transcript_path, "rb") as fp:- fp.seek(0)- blob = fp.read(source_offset) if source_offset else fp.read()- except Exception:- return input_data, output_data, ""-- messages: list[dict[str, Any]] = []- system_prompts: list[str] = []- cursor = 0- last_asst_text: str | None = None-- def _truncate(text: str, limit: int = 4000) -> str:- if len(text) <= limit:- return text- return text[:limit] + "...(truncated)"-- for raw_line in blob.splitlines(keepends=True):- cursor += len(raw_line)- if not raw_line.lstrip().startswith(b"{"):- continue- try:- rec = json.loads(raw_line.decode("utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(rec, dict):- continue-- rec_type = str(rec.get("type") or "").strip().lower()- is_incremental = cursor > start_offset-- # 重建 prompt 上下文时要跳过“当前正在发出的 assistant message”,- # 否则同一段回复会同时出现在 input 和 output 两边。- if current_message_id and is_incremental:- rec_mid = find_message_id_in_record(rec)- if rec_mid == current_message_id:- if rec_type == "message" and rec.get("role") == "assistant":- text = extract_message_text(rec.get("content"))- if text:- last_asst_text = text- continue-- if rec_type == "message":- role = rec.get("role")- text = extract_message_text(rec.get("content"))- if not text:- continue- if role == "system":- system_prompts.append(text)- elif is_incremental:- if role == "user":- messages.append({"role": "user", "content": _truncate(text, 8000)})- last_asst_text = None- elif role == "assistant":- messages.append({"role": "assistant", "content": _truncate(text, 4000)})- last_asst_text = text- elif is_incremental:- # 把 function call / result 记录转换成 Chat Completions 风格的- # assistant/tool message,方便 tracing UI 按对话链路展示。- if rec_type == "function_call":- name = str(rec.get("name") or "").strip()- call_id = str(rec.get("callId") or "").strip()- arguments = rec.get("arguments", "")- if isinstance(arguments, dict):- arguments = json.dumps(arguments, ensure_ascii=False)- tool_call: dict[str, Any] = {"type": "function", "function": {"name": name}}- if name and arguments:- tool_call["function"]["arguments"] = _truncate(str(arguments), 2000)- if call_id:- tool_call["id"] = call_id- if (- messages- and messages[-1].get("role") == "assistant"- and "tool_calls" not in messages[-1]- and messages[-1].get("content")- ):- messages[-1]["tool_calls"] = [tool_call]- else:- msg: dict[str, Any] = {"role": "assistant", "content": ""}- msg["tool_calls"] = [tool_call]- messages.append(msg)- elif rec_type == "function_call_result":- call_id = str(rec.get("callId") or "").strip()- provider = rec.get("providerData", {})- result_content = ""- if isinstance(provider, dict):- tool_result = provider.get("toolResult", {})- if isinstance(tool_result, dict):- result_content = extract_message_text(tool_result.get("content"))- if not result_content:- output = rec.get("output")- result_content = str(output.get("text", "")) if isinstance(output, dict) else ""- tool_msg: dict[str, Any] = {"role": "tool", "content": _truncate(result_content, 2000)}- if call_id:- tool_msg["tool_call_id"] = call_id- messages.append(tool_msg)-- final_messages: list[dict[str, Any]] = []- for prompt in system_prompts[-2:]:- if prompt:- final_messages.append({"role": "system", "content": _truncate(prompt, 2000)})- final_messages.extend(messages)- input_data["messages"] = final_messages-- if last_asst_text is not None:- output_data["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": last_asst_text[:8000]},- }]-- return input_data, output_data, ""diff --git a/local/.claude/skills/agent-observability/scripts/core/agentlens/runtime.py b/local/.claude/skills/agent-observability/scripts/core/agentlens/runtime.pydeleted file mode 100644index 575f5077..00000000--- a/local/.claude/skills/agent-observability/scripts/core/agentlens/runtime.py+++ /dev/null@@ -1,764 +0,0 @@-"""AgentLens 运行时编排层。--这一层保留对外暴露的 4 个入口:-- `emit_session_start`-- `emit_turn_start`-- `emit_post_step`-- `emit_session_stop`--它本身不负责底层清洗或 carrier 生成,而是把调用编排到-`bootstrap / normalize / tracing` 三层上。-"""-from __future__ import annotations--from pathlib import Path-from typing import Any--try:- from opentelemetry import trace as _otel_trace-except Exception: # pragma: no cover - 可选依赖缺失时优雅降级- _otel_trace = None--from .. import state as st-from .bootstrap import (- debug_write_span as _debug_write_span,- ensure_initialized as _ensure_initialized,- get_session_context as _get_session_context,- load_config,- project_root as _project_root,- set_failure as _set_failure,-)-from .normalize import (- association_properties as _association_properties,- build_llm_io_from_transcript as _build_llm_io_from_transcript,- find_tool_usage_event as _find_tool_usage_event,- infer_vendor as _infer_vendor,- sanitize_payload as _sanitize_payload,- to_openai_usage as _to_openai_usage,-)-from .tracing import (- annotate as _annotate,- emit_assistant_span as _emit_assistant_span,- emit_tool_span as _emit_tool_span,- generate_subagent_carrier as _generate_subagent_carrier,- generate_turn_carrier as _generate_turn_carrier,- resolve_agent_carrier as _resolve_agent_carrier,- resolve_step_carrier as _resolve_step_carrier,- set_agent_aggregate_on_span as _set_agent_aggregate_on_span,- span_context_ids as _span_context_ids,- traceparent_parts as _traceparent_parts,-)---def emit_session_start(- *,- state_path: Path,- sid: str,- cwd: str,- agent: str = "main",-) -> None:- """初始化 v2 版本的 `_agentlens` session payload。-- 在 turn-centric 模型下,这里**不再**生成 trace_id。- 它只负责记录 session 级元数据(如 `enabled`、`session_id`、`app_name`),- 并清理上一次运行遗留的 carrier / error 状态。- 真正的新 trace 会在第一次 `UserPromptSubmit` 时由 `emit_turn_start` 打开。- """- _ = agent- config = load_config(_project_root(cwd))- # 注意:这里不要清空 current_turn / turn_history。- # 同一个 sid 下 SessionStart 可能多次触发(例如 subagent 启动、IDE 刷新、- # workspace 切换)。如果这里清空,会把进行中的 turn 擦掉,后续 PostToolUse- # 会全部看到 no_active_turn,最终把这一轮观测链路打断。- base_updates: dict[str, Any] = {- "session_id": sid,- "app_name": config.app_name,- }- if not config.enabled:- base_updates["enabled"] = False- st.update_agentlens_session(- state_path,- sid,- base_updates,- clear_keys=["carrier", "last_error"],- )- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return- base_updates["enabled"] = True- st.update_agentlens_session(- state_path,- sid,- base_updates,- clear_keys=["carrier", "last_error"],- )- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_turn_start(- *,- state_path: Path,- sid: str,- cwd: str,- turn_id: str,- prompt_meta: dict[str, Any] | None = None,- business_scenario: str | None = None,-) -> None:- """打开一个新的 turn,生成新的 trace_id 并写入 `_agentlens.current_turn`。-- 这是当前实现里**唯一**允许生成新 trace_id 的地方。- `emit_post_step` / `emit_session_stop` 都不会重新造 carrier;- 找不到时只会优雅降级,不会私自开新链路。- """- _ = prompt_meta- config = load_config(_project_root(cwd))- if not config.enabled:- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return- # 先把 per-turn business scenario 写进 state,- # 这样 `_generate_turn_carrier -> _association_properties`- # 才能在生成 trace 时把这次 turn 的业务场景烘焙进去。- if business_scenario:- st.update_agentlens_session(- state_path,- sid,- {"enabled": True, "session_id": sid, "app_name": config.app_name, "_turn_business_scenario": business_scenario},- clear_keys=["last_error"],- )- else:- st.update_agentlens_session(- state_path,- sid,- {"enabled": True, "session_id": sid, "app_name": config.app_name},- clear_keys=["last_error", "_turn_business_scenario"],- )- carrier = _generate_turn_carrier(runtime, config=config, sid=sid, turn_id=turn_id, state_path=state_path)- st.begin_turn(state_path, sid, turn_id, carrier)- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_post_step(- *,- state_path: Path,- sid: str,- tool_event: dict[str, Any] | None,- usage_events: list[dict[str, Any]],-) -> None:- """发出扁平化的 LLM span,只保留最小 TASK 包装层来传播 carrier 上下文。-- 面向 turn 的 v2 约束:- - 活跃的 ``current_turn.carrier`` 是唯一的 trace 上下文来源。- - 如果不存在 ``current_turn``(例如 UserPromptSubmit hook 还没触发),- 这里只会记录 ``last_error`` 并返回,不会私自生成新的 trace_id。- - subagent(``active_agent != "main"``)会拿到当前 turn 下的- ``invoke_agent`` 子 span,后续 chat span 都挂到这个子 span 下,- 以保持因果链路连续。- """- if not isinstance(tool_event, dict) and not usage_events:- return-- cwd_hint = ""- if isinstance(tool_event, dict):- cwd_hint = str(tool_event.get("cwd") or "")- config = load_config(_project_root(cwd_hint))- if not config.enabled:- return-- session_ctx = _get_session_context(state_path, sid)- # 快路径:尊重 SessionStart 阶段已经写入的 enabled 标记。- if session_ctx.get("enabled") is False:- return-- current_turn = session_ctx.get("current_turn")- if not isinstance(current_turn, dict):- _set_failure(state_path, sid, "no_active_turn")- return- parent_carrier = current_turn.get("carrier")- if not isinstance(parent_carrier, dict) or not parent_carrier.get("traceparent"):- _set_failure(state_path, sid, "no_active_turn_carrier")- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return-- tool_name = str((tool_event or {}).get("tool") or "unknown_tool")- active_agent = str((tool_event or {}).get("agent") or "main")- transcript_path = str((tool_event or {}).get("transcript_path") or "")- skills = (tool_event or {}).get("skill") or []- rules = (tool_event or {}).get("rule") or []-- # 解析这次事件真正要用的 carrier。- # main agent 直接使用 turn 根 carrier;subagent 则使用按角色拆分的- # 子 span carrier,并在当前 turn 下做幂等注册。- carrier = dict(parent_carrier)- if active_agent and active_agent != "main":- existing = None- subs = current_turn.get("subagent_spans")- if isinstance(subs, dict):- rec = subs.get(active_agent)- if isinstance(rec, dict) and isinstance(rec.get("carrier"), dict):- existing = rec["carrier"]- if isinstance(existing, dict) and existing.get("traceparent"):- carrier = dict(existing)- else:- # 原子化的 get-or-create:只有确认 subagent span 不存在时,- # 才会在写锁内部调用 carrier_factory。- # 这样可以避免并发 hook 进程之间的 TOCTOU 竞争,产生孤儿- # invoke_agent.TASK span。- def _factory() -> dict[str, str]:- return _generate_subagent_carrier(- runtime, parent_carrier=parent_carrier, role=active_agent- )-- registered = st.upsert_subagent_span_atomic(- state_path, sid, active_agent, carrier_factory=_factory- )- if isinstance(registered, dict) and registered.get("traceparent"):- carrier = dict(registered)- runtime["Zhiyanllm"].set_association_properties(_association_properties(config, sid, state_path))- # 静默挂载 carrier 上下文(不额外创建 TASK span),让内部 span- # 继承正确的 trace_id / parent_id。- _ctx = runtime["TracerWrapper"].extract_context(carrier)- _token = runtime["otel_attach"](_ctx)- try:- preferred_tool_message_id = str((tool_event or {}).get("message_id") or "").strip() or None- _assistant_emitted_mids: set[str] = set()- pre_bumped_steps: set[tuple[str, str]] = set()- committed_steps: set[tuple[str, str]] = set()-- if isinstance(tool_event, dict):- if preferred_tool_message_id and st.get_step_span_carrier(- state_path, sid, active_agent, preferred_tool_message_id- ) is None:- pre_bumped_steps.add((active_agent, preferred_tool_message_id))- for usage_event in usage_events:- event_agent = str(usage_event.get("agent") or active_agent or "main")- event_message_id = str(usage_event.get("message_id") or "").strip() or None- if event_message_id:- step_key = (event_agent, event_message_id)- if (- step_key not in pre_bumped_steps- and st.get_step_span_carrier(state_path, sid, event_agent, event_message_id) is None- ):- pre_bumped_steps.add(step_key)- if not usage_events and isinstance(tool_event, dict):- tool_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=active_agent,- )- if preferred_tool_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=tool_parent_carrier,- agent=active_agent,- message_id=preferred_tool_message_id,- transcript_path=transcript_path,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- tool_parent_carrier = dict(step_carrier)- _emit_tool_span(- runtime,- carrier=tool_parent_carrier,- tool_name=tool_name,- active_agent=active_agent,- skills=skills,- rules=rules,- duration_ms=tool_event.get("ms") if isinstance(tool_event.get("ms"), (int, float)) else None,- tool_details=tool_event.get("tool_details") if isinstance(tool_event.get("tool_details"), dict) else None,- message_id=preferred_tool_message_id,- step_grouping="message_id" if preferred_tool_message_id else "fallback",- state_path=state_path,- sid=sid,- )- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- tool_event=tool_event,- )- if (- preferred_tool_message_id- and (active_agent, preferred_tool_message_id) in pre_bumped_steps- and (active_agent, preferred_tool_message_id) not in committed_steps- ):- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- step_created=True,- )- committed_steps.add((active_agent, preferred_tool_message_id))- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- return-- matched_usage = _find_tool_usage_event(tool_event, usage_events) if isinstance(tool_event, dict) else None- tool_message_id = preferred_tool_message_id or str((matched_usage or {}).get("message_id") or "").strip() or None- if isinstance(tool_event, dict):- # 先构造 assistant 预览,再打开 agent/step 父 span。- # 这样即便 transcript 重建失败,也不会留下空的分组 TASK。- _assistant_preview_content: str | None = None- _assistant_preview_transcript = transcript_path- _assistant_preview_model = ""- if tool_message_id:- for _ue in usage_events:- if str(_ue.get("message_id") or "").strip() != tool_message_id:- continue- _ue_transcript = str(_ue.get("transcript_path") or transcript_path)- _ue_offset = int(_ue.get("source_offset") or 0)- _, _llm_out_pre, _ = _build_llm_io_from_transcript(- transcript_path=_ue_transcript,- source_offset=_ue_offset,- tokens=_ue.get("tokens"),- model=str(_ue.get("model") or ""),- )- _pre_content = ""- if _llm_out_pre.get("choices"):- _pre_msg = _llm_out_pre["choices"][0].get("message") or {}- _pre_content = str(_pre_msg.get("content") or "")- if _pre_content and _pre_content.strip():- _assistant_preview_content = _pre_content- _assistant_preview_transcript = _ue_transcript- _assistant_preview_model = str(_ue.get("model") or "")- break-- tool_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=active_agent,- )- if tool_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=tool_parent_carrier,- agent=active_agent,- message_id=tool_message_id,- transcript_path=transcript_path,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- tool_parent_carrier = dict(step_carrier)- if _assistant_preview_content and tool_message_id:- _emit_assistant_span(- runtime,- carrier=tool_parent_carrier,- agent=active_agent,- message_id=tool_message_id,- assistant_text=_assistant_preview_content,- model=_assistant_preview_model,- transcript_path=_assistant_preview_transcript,- state_path=state_path,- sid=sid,- )- _assistant_emitted_mids.add(tool_message_id)-- _emit_tool_span(- runtime,- carrier=tool_parent_carrier,- tool_name=tool_name,- active_agent=active_agent,- skills=skills,- rules=rules,- duration_ms=tool_event.get("ms") if isinstance(tool_event.get("ms"), (int, float)) else None,- tool_details=tool_event.get("tool_details") if isinstance(tool_event.get("tool_details"), dict) else None,- message_id=tool_message_id,- step_grouping="message_id" if tool_message_id else "fallback",- state_path=state_path,- sid=sid,- )- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- tool_event=tool_event,- )- if tool_message_id and (active_agent, tool_message_id) in pre_bumped_steps:- step_key = (active_agent, tool_message_id)- if step_key not in committed_steps:- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- step_created=True,- )- committed_steps.add(step_key)-- _prev_llm_offsets: dict[str, int] = {}- for usage_event in usage_events:- model = str(usage_event.get("model") or "")- ev_transcript = str(usage_event.get("transcript_path") or transcript_path)- ev_offset = int(usage_event.get("source_offset") or 0)- raw_tokens = usage_event.get("tokens") or {}- event_message_id = str(usage_event.get("message_id") or "").strip() or None- event_agent = str(usage_event.get("agent") or active_agent or "main")- start_offset = _prev_llm_offsets.get(ev_transcript) or st.get_last_llm_offset(- st.load_state(state_path), sid, ev_transcript- )- llm_input, llm_output, _turn_title = _build_llm_io_from_transcript(- transcript_path=ev_transcript,- source_offset=ev_offset,- start_offset=int(start_offset or 0),- current_message_id=event_message_id,- tokens=raw_tokens,- model=model or None,- )- _prev_llm_offsets[ev_transcript] = ev_offset- # 原子写回 state,供跨进程增量跟踪复用- def _update_llm_offset(state: dict[str, Any], _ev=ev_transcript, _off=ev_offset) -> None:- st.set_last_llm_offset(state, sid, _off, _ev)- st.update_state_locked(state_path, _update_llm_offset)- # --- 把 skill/rule/agent 作为独立消息标签注入 input_data ---- _meta_messages: list[dict[str, str]] = []- _ev_agent = str(usage_event.get("agent") or active_agent)- if _ev_agent and _ev_agent != "main":- _meta_messages.append({"role": "agent", "content": _ev_agent})- if skills:- _meta_messages.append({"role": "skill", "content": ", ".join(skills)})- if rules:- _meta_messages.append({"role": "rule", "content": ", ".join(rules)})- if _meta_messages:- llm_input.setdefault("messages", [])- for msg in reversed(_meta_messages):- llm_input["messages"].insert(0, msg)- # --- 构造 usage ---- llm_output["usage"] = _to_openai_usage(raw_tokens)- # --- 只附带成本细节来构造 output 内容 ---- _cost_info = {- "input_tokens": raw_tokens.get("input"),- "output_tokens": raw_tokens.get("output"),- "cache_read": raw_tokens.get("cache_read"),- "cache_creation": raw_tokens.get("cache_creation"),- "total_tokens": raw_tokens.get("total"),- "cost_usd": usage_event.get("cost_usd"),- }- _cost_info = {k: v for k, v in _cost_info.items() if v is not None}- _existing_content = ""- if llm_output.get("choices"):- _msg = llm_output["choices"][0].get("message") or {}- _existing_content = str(_msg.get("content") or "")- _output_content = _existing_content- if _cost_info:- _cost_line = " | ".join(f"{k}: {v}" for k, v in _cost_info.items())- _output_content = f"[{_cost_line}]\n{_existing_content}" if _existing_content else f"[{_cost_line}]"- llm_output["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": _output_content},- }]- event_parent_carrier = carrier- if event_message_id:- event_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=event_agent,- )- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- transcript_path=ev_transcript,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- event_parent_carrier = dict(step_carrier)- ev_ctx = runtime["TracerWrapper"].extract_context(event_parent_carrier)- ev_token = runtime["otel_attach"](ev_ctx)- # 先累计聚合值,再发 LLM span,这样 span 上带的是最新累计属性。- st.bump_agent_aggregate(- state_path,- sid,- event_agent,- usage_event=usage_event,- )- _current_agg = st.get_subagent_aggregate(state_path, sid, event_agent)- try:- with runtime["track_llm_call"](_infer_vendor(model), "model_request") as llm_span:- # track_llm_call 已经设置了 gen_ai.span.kind/system/operation.name。- # 下方 _annotate 会通过 handle_llm_response 设置 gen_ai.usage.*。- # LLMSpan 包装层没有 set_attribute,所以这里改用原生 span 写 ID。- _native_span = _otel_trace.get_current_span()- _set_agent_aggregate_on_span(_native_span, _current_agg)- span_ids = _span_context_ids(_native_span)- parent_parts = _traceparent_parts(event_parent_carrier)- _debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "llm",- "span_name": "model_request",- "model": model,- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- "agent": event_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": ev_transcript,- "source_offset": ev_offset,- },- sanitizer=_sanitize_payload,- )- _annotate(- runtime,- span=llm_span,- input_data=llm_input,- output_data=llm_output,- tags={- "cost_usd": str(usage_event.get("cost_usd") or "-"),- "input_tokens": str(raw_tokens.get("input", "-")),- "output_tokens": str(raw_tokens.get("output", "-")),- "cache_read": str(raw_tokens.get("cache_read", "-")),- "cache_creation": str(raw_tokens.get("cache_creation", "-")),- "total_tokens": str(raw_tokens.get("total", "-")),- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- },- )- finally:- runtime["otel_detach"](ev_token)- if event_message_id and (event_agent, event_message_id) in pre_bumped_steps:- step_key = (event_agent, event_message_id)- if step_key not in committed_steps:- st.bump_agent_aggregate(- state_path,- sid,- event_agent,- step_created=True,- )- committed_steps.add(step_key)- if _existing_content and _existing_content.strip() and event_message_id not in _assistant_emitted_mids:- _emit_assistant_span(- runtime,- carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- assistant_text=_existing_content,- model=model,- transcript_path=ev_transcript,- state_path=state_path,- sid=sid,- )- finally:- runtime["otel_detach"](_token)- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_session_stop(- *,- state_path: Path,- sid: str,- cwd: str,- active_agent: str,- transcript_path: str,- stop_events: list[dict[str, Any]],-) -> None:- """在 session stop 阶段发出扁平化 LLM span,只保留最小 TASK 包装层传播上下文。"""- config = load_config(_project_root(cwd))- if not config.enabled:- return-- session_ctx = _get_session_context(state_path, sid)- if session_ctx.get("enabled") is False:- return-- current_turn = session_ctx.get("current_turn")- if not isinstance(current_turn, dict):- _set_failure(state_path, sid, "no_active_turn")- return- carrier = current_turn.get("carrier")- if not isinstance(carrier, dict) or not carrier.get("traceparent"):- _set_failure(state_path, sid, "no_active_turn_carrier")- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return-- runtime["Zhiyanllm"].set_association_properties(_association_properties(config, sid, state_path))- if not stop_events:- return- # 静默挂载 carrier 上下文(不额外创建 TASK span)。- _ctx = runtime["TracerWrapper"].extract_context(carrier)- _token = runtime["otel_attach"](_ctx)- try:- _prev_stop_offsets: dict[str, int] = {}- for stop_event in stop_events:- model = str(stop_event.get("model") or "")- ev_transcript = str(stop_event.get("transcript_path") or transcript_path)- ev_offset = int(stop_event.get("source_offset") or 0)- raw_tokens = stop_event.get("tokens") or {}- event_message_id = str(stop_event.get("message_id") or "").strip() or None- event_agent = str(stop_event.get("agent") or active_agent or "main")- start_offset = _prev_stop_offsets.get(ev_transcript) or st.get_last_llm_offset(- st.load_state(state_path), sid, ev_transcript- )- llm_input, llm_output, _turn_title = _build_llm_io_from_transcript(- transcript_path=ev_transcript,- source_offset=ev_offset,- start_offset=int(start_offset or 0),- current_message_id=event_message_id,- tokens=raw_tokens,- model=model or None,- )- _prev_stop_offsets[ev_transcript] = ev_offset- # 原子写回 state,供跨进程增量跟踪复用- def _update_llm_offset_stop(state: dict[str, Any], _ev=ev_transcript, _off=ev_offset) -> None:- st.set_last_llm_offset(state, sid, _off, _ev)- st.update_state_locked(state_path, _update_llm_offset_stop)- # --- 把 agent 作为独立消息标签注入 input_data ---- _ev_agent = str(stop_event.get("agent") or active_agent)- if _ev_agent and _ev_agent != "main":- llm_input.setdefault("messages", []).insert(0, {"role": "agent", "content": _ev_agent})- # --- 构造 usage ---- llm_output["usage"] = _to_openai_usage(raw_tokens)- # --- 构造带上下文和成本细节的 output 内容 ---- _cost_info = {- "input_tokens": raw_tokens.get("input"),- "output_tokens": raw_tokens.get("output"),- "cache_read": raw_tokens.get("cache_read"),- "cache_creation": raw_tokens.get("cache_creation"),- "total_tokens": raw_tokens.get("total"),- "cost_usd": stop_event.get("cost_usd"),- "cost_session_usd": stop_event.get("cost_session_usd"),- }- _cost_info = {k: v for k, v in _cost_info.items() if v is not None}- _existing_content = ""- if llm_output.get("choices"):- _msg = llm_output["choices"][0].get("message") or {}- _existing_content = str(_msg.get("content") or "")- _output_content = _existing_content- if _cost_info:- _cost_line = " | ".join(f"{k}: {v}" for k, v in _cost_info.items())- _output_content = f"[{_cost_line}]\n{_existing_content}" if _existing_content else f"[{_cost_line}]"- llm_output["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": _output_content},- }]- event_parent_carrier = carrier- # 先解析 agent carrier,让 step 挂在 agent 的 react_agent span 下,- # 而不是直接挂在 turn 根 span 下。- if event_agent and event_agent != "main":- agent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=event_agent,- )- if isinstance(agent_carrier, dict) and agent_carrier.get("traceparent"):- event_parent_carrier = dict(agent_carrier)- if event_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- transcript_path=ev_transcript,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- event_parent_carrier = dict(step_carrier)- ev_ctx = runtime["TracerWrapper"].extract_context(event_parent_carrier)- ev_token = runtime["otel_attach"](ev_ctx)- # 这里不要再 bump,emit_post_step 已经累计过这条 usage_event。- # SessionStop 会为同一次调用补发一个重复的 LLM span,再累加就会双算。- # 因此这里只读取当前聚合值。- _current_agg = st.get_subagent_aggregate(state_path, sid, event_agent)- try:- with runtime["track_llm_call"](_infer_vendor(model), "model_request") as llm_span:- # track_llm_call 已经设置了 gen_ai.span.kind/system/operation.name。- # 下方 _annotate 会通过 handle_llm_response 设置 gen_ai.usage.*。- # LLMSpan 包装层没有 set_attribute,所以这里改用原生 span 写 ID。- _native_span = _otel_trace.get_current_span()- _set_agent_aggregate_on_span(_native_span, _current_agg)- span_ids = _span_context_ids(_native_span)- parent_parts = _traceparent_parts(event_parent_carrier)- _debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "llm",- "span_name": "model_request",- "model": model,- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- "agent": event_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": ev_transcript,- "source_offset": ev_offset,- },- sanitizer=_sanitize_payload,- )- _annotate(- runtime,- span=llm_span,- input_data=llm_input,- output_data=llm_output,- tags={- "cost_usd": str(stop_event.get("cost_usd") or "-"),- "cost_session_usd": str(stop_event.get("cost_session_usd") or "-"),- "input_tokens": str(raw_tokens.get("input", "-")),- "output_tokens": str(raw_tokens.get("output", "-")),- "cache_read": str(raw_tokens.get("cache_read", "-")),- "cache_creation": str(raw_tokens.get("cache_creation", "-")),- "total_tokens": str(raw_tokens.get("total", "-")),- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- },- )- finally:- runtime["otel_detach"](ev_token)- if _existing_content and _existing_content.strip():- _emit_assistant_span(- runtime,- carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- assistant_text=_existing_content,- model=model,- transcript_path=ev_transcript,- state_path=state_path,- sid=sid,- )- finally:- runtime["otel_detach"](_token)- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- except Exception as exc:- _set_failure(state_path, sid, str(exc))diff --git a/local/.claude/skills/agent-observability/scripts/core/agentlens/tracing.py b/local/.claude/skills/agent-observability/scripts/core/agentlens/tracing.pydeleted file mode 100644index afb678ad..00000000--- a/local/.claude/skills/agent-observability/scripts/core/agentlens/tracing.py+++ /dev/null@@ -1,504 +0,0 @@-from __future__ import annotations-"""AgentLens trace 拓扑层。--这一层负责“trace 结构本身”:-- 创建或派生 carrier-- 生成 agent / step / assistant / tool span-- 把后续聚合需要的 span 元数据写回 state-"""--import json-import secrets-from pathlib import Path-from typing import Any--from .. import state as st-from .bootstrap import AgentLensConfig, debug_write_span-from .normalize import association_properties, collect_tool_calls_for_message, sanitize_payload---def annotate(runtime: dict[str, Any], *, span: Any | None = None, input_data: Any = None, output_data: Any = None, tags: dict[str, Any] | None = None) -> None:- """在调用 zhiyan annotate 前,先统一清洗 payload。"""- _ = span- runtime["Zhiyanllm"].annotate(- input_data=sanitize_payload(input_data),- output_data=sanitize_payload(output_data),- tags=sanitize_payload(tags) if tags else None,- )---def traceparent_parts(carrier: dict[str, str] | None) -> dict[str, str]:- """把 W3C `traceparent` 拆成调试日志里常用的几个字段。"""- traceparent = str((carrier or {}).get("traceparent") or "").strip()- parts = traceparent.split("-")- if len(parts) >= 4:- return {- "traceparent": traceparent,- "trace_id": parts[1],- "span_id": parts[2],- "flags": parts[3],- }- return {"traceparent": traceparent}---def span_context_ids(span: Any) -> dict[str, str]:- """从 OTel span 对象中提取十六进制的 trace/span id。"""- try:- ctx = span.get_span_context()- return {- "trace_id": f"{int(ctx.trace_id):032x}",- "span_id": f"{int(ctx.span_id):016x}",- }- except Exception:- return {}---def ensure_traceparent(carrier: dict[str, str]) -> None:- """当上游没有成功注入时,补一个最小可用的 `traceparent`。"""- if str(carrier.get("traceparent") or "").strip():- return- trace_id = secrets.token_hex(16)- parent_id = secrets.token_hex(8)- carrier["traceparent"] = f"00-{trace_id}-{parent_id}-01"---def carrier_from_span(parent_carrier: dict[str, str], span: Any) -> dict[str, str]:- """基于父 carrier 和当前 span 生成一个仍在同一 trace 上的子 carrier。"""- try:- span_ctx = span.get_span_context()- trace_id = f"{int(span_ctx.trace_id):032x}"- span_id = f"{int(span_ctx.span_id):016x}"- except Exception:- return {}- parent_tp = str((parent_carrier or {}).get("traceparent") or "").strip()- flags = "01"- if parent_tp:- parts = parent_tp.split("-")- if len(parts) >= 4 and parts[3]:- flags = parts[3]- child_carrier: dict[str, str] = dict(parent_carrier or {})- child_carrier["traceparent"] = f"00-{trace_id}-{span_id}-{flags}"- return child_carrier---def carrier_from_task_span(parent_carrier: dict[str, str], task_span: Any) -> dict[str, str]:- """兼容包装过的 task span 和原始 OTel span 两种形态。"""- span = getattr(task_span, "_span", None)- if span is None and hasattr(task_span, "get_span_context"):- span = task_span- if span is None:- return {}- return carrier_from_span(parent_carrier, span)---def zhiyan_attr(runtime: dict[str, Any], name: str, fallback: str) -> str:- """防御式读取 zhiyan 语义约定常量。"""- return str(getattr(runtime.get("ZhiyanSpanAttributes"), name, fallback))---def generate_turn_carrier(- runtime: dict[str, Any],- *,- config: AgentLensConfig,- sid: str,- turn_id: str,- state_path: Path | None = None,-) -> dict[str, str]:- """为一个用户 turn 生成根 carrier。"""- from opentelemetry import trace-- carrier: dict[str, str] = {}- span = trace.get_tracer(__name__).start_span(f"turn.{sid}.{turn_id}")- try:- runtime["Zhiyanllm"].set_association_properties(association_properties(config, sid, state_path))- runtime["Zhiyanllm"].inject_context(carrier)- finally:- span.end()- ensure_traceparent(carrier)- return carrier---def generate_subagent_carrier(runtime: dict[str, Any], *, parent_carrier: dict[str, str], role: str) -> dict[str, str]:- """在当前 turn 下面创建 `invoke_agent` 子 carrier。"""- try:- with runtime["track_task_server_call"]("invoke_agent", carrier=parent_carrier) as task_span:- annotate(runtime, input_data={"agent": role}, output_data={"result": "dispatched"}, tags={"agent": role})- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def generate_step_carrier(- runtime: dict[str, Any],- *,- parent_carrier: dict[str, str],- agent: str,- message_id: str,- transcript_path: str,-) -> dict[str, str]:- """创建用于归并同一条 message 工作的 synthetic step span。"""- try:- with runtime["track_task_server_call"]("react_step", carrier=parent_carrier) as task_span:- annotate(- runtime,- input_data={"agent": agent, "message_id": message_id},- output_data={"result": "grouped"},- tags={"message_id": message_id, "agent": agent, "transcript_path": transcript_path or ""},- )- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def generate_agent_carrier(runtime: dict[str, Any], *, parent_carrier: dict[str, str], agent: str) -> dict[str, str]:- """在当前 turn 下创建稳定的 per-agent 聚合 span。"""- try:- with runtime["track_task_server_call"]("react_agent", carrier=parent_carrier) as task_span:- span = getattr(task_span, "_span", None)- if span is not None and hasattr(span, "set_attribute"):- span.set_attribute("agent.name", agent)- annotate(runtime, input_data={"agent": agent}, output_data={"agent": agent}, tags={"agent": agent})- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def resolve_agent_carrier(- *,- state_path: Path,- sid: str,- runtime: dict[str, Any],- parent_carrier: dict[str, str],- agent: str,-) -> dict[str, str]:- """从共享状态里获取或创建持久化的 agent 聚合 carrier。"""- normalized_agent = str(agent or "main").strip() or "main"- existing = st.get_agent_span_carrier(state_path, sid, normalized_agent)- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)-- def _factory() -> dict[str, str]:- return generate_agent_carrier(runtime, parent_carrier=parent_carrier, agent=normalized_agent)-- effective_carrier = st.upsert_agent_span_atomic(state_path, sid, normalized_agent, carrier_factory=_factory)- if not isinstance(effective_carrier, dict) or not effective_carrier.get("traceparent"):- return dict(parent_carrier)- agent_parts = traceparent_parts(effective_carrier)- parent_parts = traceparent_parts(parent_carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "agent",- "span_name": "react_agent",- "agent": normalized_agent,- "trace_id": agent_parts.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": agent_parts.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- return dict(effective_carrier)---def resolve_step_carrier(- *,- state_path: Path,- sid: str,- runtime: dict[str, Any],- parent_carrier: dict[str, str],- agent: str,- message_id: str | None,- transcript_path: str,-) -> dict[str, str] | None:- """获取或创建按 message 分组使用的 step carrier。"""- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return None- existing = st.get_step_span_carrier(state_path, sid, agent, normalized_message_id)- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)-- def _factory() -> dict[str, str]:- return generate_step_carrier(- runtime,- parent_carrier=parent_carrier,- agent=agent,- message_id=normalized_message_id,- transcript_path=transcript_path,- )-- effective_carrier = st.upsert_step_span_atomic(- state_path,- sid,- agent,- normalized_message_id,- carrier_factory=_factory,- transcript_path=transcript_path,- )- if not isinstance(effective_carrier, dict) or not effective_carrier.get("traceparent"):- return None- step_parts = traceparent_parts(effective_carrier)- parent_parts = traceparent_parts(parent_carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "step",- "span_name": "react_step",- "message_id": normalized_message_id,- "agent": agent,- "trace_id": step_parts.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": step_parts.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": transcript_path or "",- },- sanitizer=sanitize_payload,- )- return dict(effective_carrier)---def set_agent_aggregate_on_span(span: Any, aggregate: dict[str, Any] | None) -> None:- """把 agent 的累计指标投影成当前 span 的属性。"""- if span is None or not hasattr(span, "set_attribute") or not isinstance(aggregate, dict):- return- tokens = aggregate.get("tokens") or {}- if isinstance(tokens, dict):- for key in ("input", "output", "cache_read", "cache_creation", "total"):- if key in tokens:- span.set_attribute(f"agent.cumulative_tokens.{key}", int(tokens.get(key) or 0))- for key in ("cost_usd", "tool_duration_ms", "llm_call_count", "tool_call_count", "step_count", "event_count"):- if key in aggregate:- try:- span.set_attribute(f"agent.cumulative.{key}", int(aggregate.get(key) or 0))- except (TypeError, ValueError):- span.set_attribute(f"agent.cumulative.{key}", str(aggregate.get(key)))---def emit_assistant_span(- runtime: dict[str, Any],- *,- carrier: dict[str, str],- agent: str,- message_id: str | None,- assistant_text: str,- model: str | None = None,- transcript_path: str | None = None,- state_path: Path | None = None,- sid: str | None = None,-) -> None:- """发出一个轻量 assistant span,并按需补上 tool calls。"""- if not assistant_text or not assistant_text.strip():- return- tool_calls: list[dict[str, Any]] = []- if message_id and transcript_path:- tool_calls = collect_tool_calls_for_message(transcript_path, message_id)- output_data: dict[str, Any] = {"role": "assistant", "content": assistant_text[:8000]}- if tool_calls:- output_data["tool_calls"] = tool_calls- ctx = runtime["TracerWrapper"].extract_context(carrier)- token = runtime["otel_attach"](ctx)- try:- with runtime["get_tracer"]() as tracer:- with tracer.start_as_current_span(name="assistant_message") as span:- span.set_attribute(runtime["ZhiyanSpanAttributes"].LLM_SPAN_KIND, runtime["ZhiyanllmSpanKindValues"].LLM.value)- span_ids = span_context_ids(span)- parent_parts = traceparent_parts(carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "assistant",- "span_name": "assistant_message",- "message_id": str(message_id or ""),- "agent": agent,- "model": str(model or ""),- "tool_call_count": len(tool_calls),- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- annotate(- runtime,- input_data={"agent": agent, "message_id": message_id or "", "model": model or ""},- output_data=output_data,- tags={"message_id": str(message_id or ""), "agent": agent},- )- finally:- runtime["otel_detach"](token)---def emit_tool_span(- runtime: dict[str, Any],- *,- carrier: dict[str, str],- tool_name: str,- active_agent: str,- skills: list[str],- rules: list[str],- duration_ms: int | None = None,- tool_details: dict[str, Any] | None = None,- message_id: str | None = None,- step_grouping: str = "fallback",- state_path: Path | None = None,- sid: str | None = None,-) -> None:- """发出 tool span,并以受控大小挂载 tool payload。"""- def _truncate(value: Any, limit: int = 1200) -> Any:- text = value if isinstance(value, str) else None- if text is None:- return value- if len(text) <= limit:- return text- return text[:limit] + "...(truncated)"-- def _maybe_parse_json_text(value: Any) -> Any:- if not isinstance(value, str):- return value- text = value.strip()- if not text or text[0] not in "{[":- return value- try:- return json.loads(text)- except Exception:- return value-- def _parse_bash_result_content(value: Any) -> dict[str, Any] | None:- if not isinstance(value, str) or "Command:" not in value:- return None- normalized_value = value.replace("\\n", "\n")- markers = [- ("Command:", "command"),- ("Stdout:", "stdout"),- ("Stderr:", "stderr"),- ("Exit Code:", "exit_code"),- ("Signal:", "signal"),- ]- parsed: dict[str, Any] = {}- for idx, (marker, key) in enumerate(markers):- start = normalized_value.find(marker)- if start < 0:- continue- start += len(marker)- end = len(normalized_value)- for next_marker, _ in markers[idx + 1:]:- pos = normalized_value.find(next_marker, start)- if pos >= 0:- end = min(end, pos)- segment = normalized_value[start:end].strip()- if not segment:- continue- parsed[key] = _truncate(segment, 1200 if key in {"command", "stdout", "stderr"} else 200)- return parsed or None-- tool_input: dict[str, Any] = {"tool": tool_name, "agent": active_agent}- if skills:- tool_input["skill"] = ", ".join(skills)- if rules:- tool_input["rule"] = ", ".join(rules)- if message_id:- tool_input["message_id"] = message_id- details = dict(tool_details or {})- call_id = str(details.get("call_id") or "").strip() or None- if call_id:- tool_input["call_id"] = call_id- arguments_display_text = details.get("arguments_display_text")- if arguments_display_text:- tool_input["arguments_display_text"] = _truncate(arguments_display_text, 600)- arguments = details.get("arguments")- if arguments:- parsed_arguments = _maybe_parse_json_text(arguments)- tool_input["arguments"] = _truncate(parsed_arguments, 1200)- if isinstance(parsed_arguments, dict):- if parsed_arguments.get("command"):- tool_input["command"] = _truncate(parsed_arguments.get("command"), 1200)- if parsed_arguments.get("description"):- tool_input["description"] = _truncate(parsed_arguments.get("description"), 400)-- tool_output: dict[str, Any] = {"result": "executed"}- result_content = details.get("result_content")- if result_content is not None:- structured_result = _parse_bash_result_content(result_content)- if structured_result:- tool_output["result"] = structured_result- else:- tool_output["result_content"] = _truncate(result_content, 1600)- output_text = details.get("output_text")- if output_text:- tool_output["output_text"] = _truncate(output_text, 1600)- raw_response = details.get("raw_response")- if isinstance(raw_response, dict):- tool_output["raw_response"] = {- "exitCode": raw_response.get("exitCode"),- "signal": raw_response.get("signal"),- "interrupted": raw_response.get("interrupted"),- "sandboxDenied": raw_response.get("sandboxDenied"),- "tool_error_code": raw_response.get("tool_error_code"),- }-- ctx = runtime["TracerWrapper"].extract_context(carrier)- token = runtime["otel_attach"](ctx)- try:- with runtime["get_tracer"]() as tracer:- with tracer.start_as_current_span(name=f"{tool_name}.TOOL") as span:- span_kind_value = runtime["ZhiyanllmSpanKindValues"].TOOL.value- span.set_attribute(zhiyan_attr(runtime, "LLM_SPAN_KIND", "gen_ai.span.kind"), span_kind_value)- span.set_attribute("gen_ai.span.kind", span_kind_value)- span.set_attribute(zhiyan_attr(runtime, "TOOL_NAME", "tool.name"), tool_name)- if isinstance(tool_details, dict):- desc = tool_details.get("description") or tool_details.get("tool_description")- if isinstance(desc, str) and desc.strip():- span.set_attribute(zhiyan_attr(runtime, "TOOL_DESCRIPTION", "tool.description"), desc.strip())- tool_params = tool_input.get("arguments")- if tool_params is not None:- if not isinstance(tool_params, str):- tool_params = json.dumps(tool_params, ensure_ascii=False, default=str)- span.set_attribute(zhiyan_attr(runtime, "TOOL_PARAMETERS", "tool.parameters"), tool_params)- if duration_ms is not None:- span.set_attribute("tool.duration_ms", int(duration_ms))- span_ids = span_context_ids(span)- parent_parts = traceparent_parts(carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "tool",- "span_name": f"{tool_name}.TOOL",- "tool": tool_name,- "message_id": str(message_id or ""),- "call_id": call_id or "",- "step_grouping": step_grouping,- "agent": active_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- annotate(- runtime,- input_data=tool_input,- output_data=tool_output,- tags={"step_grouping": step_grouping, "message_id": str(message_id or "")},- )- finally:- runtime["otel_detach"](token)diff --git a/local/.claude/skills/agent-observability/scripts/core/cls_sink.py b/local/.claude/skills/agent-observability/scripts/core/cls_sink.pyindex e2c72391..0b5ce0f6 100644--- a/local/.claude/skills/agent-observability/scripts/core/cls_sink.py+++ b/local/.claude/skills/agent-observability/scripts/core/cls_sink.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from .agentlens import bootstrap+from . import envfile@@ -278,9 +278,9 @@ def _int_value(def load_config(cwd: str | None = None) -> CLSConfig:- project_root = bootstrap.project_root(cwd)- env_file = bootstrap.read_env_file(project_root / ".env")- env_local = bootstrap.read_env_file(project_root / ".env.local")+ project_root = envfile.project_root(cwd)+ env_file = envfile.read_env_file(project_root / ".env")+ env_local = envfile.read_env_file(project_root / ".env.local")return CLSConfig(enabled=_enabled_flag(env_local=env_local, env_file=env_file),endpoint=_value(diff --git a/local/.claude/skills/agent-observability/scripts/core/collector.py b/local/.claude/skills/agent-observability/scripts/core/collector.pyindex cfd681b2..1986ae51 100644--- a/local/.claude/skills/agent-observability/scripts/core/collector.py+++ b/local/.claude/skills/agent-observability/scripts/core/collector.py@@ -811,7 +811,7 @@ def find_fallback_usage_event(tool_event: dict[str, Any],usage_events: list[dict[str, Any]],) -> dict[str, Any] | None:- """当找不到直接匹配的 tool usage 时,为 AgentLens 选一条兜底 usage。"""+ """当找不到直接匹配的 tool usage 时,选一条兜底 usage 补齐 message_id。"""tool_name = str(tool_event.get("tool") or "").strip()transcript_path = str(tool_event.get("transcript_path") or "").strip()agent = str(tool_event.get("agent") or "main").strip() or "main"diff --git a/local/.claude/skills/agent-observability/scripts/core/emitter.py b/local/.claude/skills/agent-observability/scripts/core/emitter.pyindex a41dfc05..cbbe295d 100644--- a/local/.claude/skills/agent-observability/scripts/core/emitter.py+++ b/local/.claude/skills/agent-observability/scripts/core/emitter.py@@ -260,7 +260,7 @@ def build_prompt_submit_event() -> dict[str, Any]:"""构造 `user_prompt_submit` 事件,作为 turn 边界标记。- 这条记录会落到 metrics.ndjson,方便下游把 turn 和 AgentLens trace 对上。+ 这条记录会落到 metrics.ndjson,下游据此划分 turn。"""record: dict[str, Any] = {"event": "user_prompt_submit",diff --git a/local/.claude/skills/agent-observability/scripts/core/envfile.py b/local/.claude/skills/agent-observability/scripts/core/envfile.pynew file mode 100644index 00000000..a7acf86e--- /dev/null+++ b/local/.claude/skills/agent-observability/scripts/core/envfile.py@@ -0,0 +1,44 @@+from __future__ import annotations+"""项目 `.env` / `.env.local` 的轻量读取辅助。"""++import os+from pathlib import Path+++def project_root(cwd: str | None = None) -> Path:+ """解析用于查找 `.env` 的项目根目录。"""+ if cwd:+ return Path(cwd).expanduser().resolve()+ env_cwd = str(os.environ.get("CODEBUDDY_PROJECT_DIR") or "").strip()+ if env_cwd:+ return Path(env_cwd).expanduser().resolve()+ return Path.cwd().resolve()+++def read_env_file(path: Path) -> dict[str, str]:+ """以轻量方式解析 shell 风格的 env 文件,不做 source。"""+ values: dict[str, str] = {}+ if not path.is_file():+ return values+ try:+ lines = path.read_text("utf-8").splitlines()+ except Exception:+ return values++ for raw_line in lines:+ line = raw_line.strip()+ if not line or line.startswith("#"):+ continue+ if line.startswith("export "):+ line = line[7:].strip()+ if "=" not in line:+ continue+ key, value = line.split("=", 1)+ key = key.strip()+ value = value.strip()+ if not key:+ continue+ if value and value[0] == value[-1] and value[0] in {"'", '"'}:+ value = value[1:-1]+ values[key] = value+ return valuesdiff --git a/local/.claude/skills/agent-observability/scripts/core/runtime.py b/local/.claude/skills/agent-observability/scripts/core/runtime.pyindex 9c647bc0..a37a02a4 100644--- a/local/.claude/skills/agent-observability/scripts/core/runtime.py+++ b/local/.claude/skills/agent-observability/scripts/core/runtime.py@@ -4,18 +4,17 @@ from __future__ import annotations这一层负责把外部 hook phase 分发到内部能力:- session-start / user-prompt-submit / pre / post / stop- 组装统一运行时路径-- 串联 collector / emitter / agentlens,并承担 transcript 运行时编排+- 串联 collector / emitter,并承担 transcript 运行时编排"""import os-import reimport timeimport tracebackfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from . import agent_identity, agentlens, collector, devflow, emitter, scanner, state as st+from . import agent_identity, collector, devflow, emitter, scanner, state as st@dataclass(frozen=True)@@ -111,44 +110,8 @@ def prompt_text_length(data: dict[str, Any]) -> int | None:return None-def extract_prompt_text(data: dict[str, Any]) -> str:- """从 hook payload 中提取可读的 prompt 文本。"""- for key in ("prompt", "user_prompt", "message", "text"):- val = data.get(key)- if isinstance(val, str) and val.strip():- return val.strip()- if isinstance(val, list):- parts = []- for item in val:- if isinstance(item, dict):- txt = item.get("text")- if isinstance(txt, str):- parts.append(txt)- elif isinstance(item, str):- parts.append(item)- if parts:- return "\n".join(parts).strip()- return ""---def derive_business_scenario(prompt_text: str) -> str | None:- """从 prompt 文本中派生一个简短业务场景标识。"""- if not prompt_text:- return None-- m = re.search(r"标题[::]\s*(.+?)(?:\s*描述[::]|\s*$)", prompt_text, re.DOTALL)- if m:- title = m.group(1).strip()[:60]- else:- title = prompt_text[:50].strip()-- sanitized = re.sub(r"[^\w\u4e00-\u9fff\-]", "-", title)- sanitized = re.sub(r"-{2,}", "-", sanitized).strip("-")- return sanitized if sanitized else None--def handle_session_start(data: dict[str, Any]) -> None:- """处理 SessionStart:预热 inventory,写 start 事件,初始化 AgentLens。"""+ """处理 SessionStart:预热 inventory,写 start 事件。"""current_sid = session_id_of(data)if not current_sid:return@@ -157,33 +120,21 @@ def handle_session_start(data: dict[str, Any]) -> None:skills_meta, rules_meta = scanner.scan_skills_and_rules(cwd_value)collector.cache_inventory(paths.state_path, current_sid, skills_meta, rules_meta)emitter.emit(paths.log_path, emitter.build_start_event(sid=current_sid, agent="main"))- agentlens.emit_session_start(state_path=paths.state_path, sid=current_sid, cwd=cwd_value, agent="main")def handle_user_prompt_submit(data: dict[str, Any]) -> None:- """处理 UserPromptSubmit:建立 turn 边界,并打开 AgentLens turn。"""+ """处理 UserPromptSubmit:建立 turn 边界。"""current_sid = session_id_of(data)if not current_sid:returnpaths = build_runtime_paths()- cwd_value = cwd(data)turn_id = derive_turn_id(data)prompt_len = prompt_text_length(data)- prompt_text = extract_prompt_text(data)- business_scenario = derive_business_scenario(prompt_text)emitter.emit(paths.log_path,emitter.build_prompt_submit_event(sid=current_sid, turn_id=turn_id, agent="main", prompt_len=prompt_len),)- agentlens.emit_turn_start(- state_path=paths.state_path,- sid=current_sid,- cwd=cwd_value,- turn_id=turn_id,- prompt_meta={"prompt_len": prompt_len} if prompt_len is not None else None,- business_scenario=business_scenario,- )def handle_pre(data: dict[str, Any]) -> None:@@ -223,7 +174,7 @@ def handle_post(data: dict[str, Any]) -> None:tool_name = str(data.get("tool_name") or "")transcript_path = collector.transcript_path(data)- turn_id = current_turn_id(paths.state_path, current_sid)+ turn_id = Noneevent_ts = time.time()tool_call_id = collector.extract_tool_call_id(data)dv_ctx = resolve_devflow(paths.state_path, current_sid, cwd_value, paths.log_path)@@ -297,21 +248,9 @@ def handle_post(data: dict[str, Any]) -> None:if duplicate_tool_context:if not usage_events:return- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=None,- usage_events=usage_events,- )returnif str(tool_event.get("message_id") or "").strip():emitter.emit(paths.log_path, tool_event)- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=tool_event,- usage_events=usage_events,- )returnfallback_usage = collector.find_fallback_usage_event(tool_event, usage_events)@@ -319,19 +258,13 @@ def handle_post(data: dict[str, Any]) -> None:if fallback_usage_mid:tool_event["message_id"] = fallback_usage_midemitter.emit(paths.log_path, tool_event)- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=tool_event,- usage_events=usage_events,- )returnst.append_pending_tool_emit(paths.state_path, current_sid, tool_event)def handle_stop(data: dict[str, Any]) -> None:- """处理 Stop:补发 transcript 事件、汇总 session 成本并关闭 AgentLens。"""+ """处理 Stop:补发 transcript 事件、汇总 session 成本。"""current_sid = session_id_of(data)if not current_sid:return@@ -344,11 +277,11 @@ def handle_stop(data: dict[str, Any]) -> None:data=data,)transcript_path = collector.transcript_path(data)- turn_id = current_turn_id(paths.state_path, current_sid)+ turn_id = Nonedv_ctx = resolve_devflow(paths.state_path, current_sid, cwd_value, paths.log_path)task_slug = str(dv_ctx.get("task_slug") or "").strip() if dv_ctx else Nonestage = str(dv_ctx.get("current_stage") or "").strip() if dv_ctx else None- stop_events = emit_transcript_events(+ emit_transcript_events(state_path=paths.state_path,log_path=paths.log_path,sid=current_sid,@@ -369,14 +302,6 @@ def handle_stop(data: dict[str, Any]) -> None:sid=current_sid,force_emit_fallback=True,)- agentlens.emit_session_stop(- state_path=paths.state_path,- sid=current_sid,- cwd=cwd_value,- active_agent=active_agent,- transcript_path=transcript_path,- stop_events=stop_events,- )def resolve_devflow(state_path: Path, sid: str, cwd_value: str, log_path: Path) -> dict[str, Any] | None:@@ -410,19 +335,6 @@ def resolve_devflow(state_path: Path, sid: str, cwd_value: str, log_path: Path)return dv_ctx-def current_turn_id(state_path: Path, sid: str) -> str | None:- """从 state 中读取当前 session 激活中的 turn id。"""- try:- turn = st.get_current_turn(state_path, sid)- except Exception:- turn = None- if isinstance(turn, dict):- raw = turn.get("turn_id")- if isinstance(raw, str) and raw.strip():- return raw.strip()- return None--def flush_pending_tool_events(*,state_path: Path,@@ -471,21 +383,9 @@ def flush_pending_tool_events(if isinstance(tool_details, dict) and tool_details:tool_event["tool_details"] = dict(tool_details)emitter.emit(log_path, tool_event)- agentlens.emit_post_step(- state_path=state_path,- sid=sid,- tool_event=tool_event,- usage_events=[],- )continueif force_emit_fallback:emitter.emit(log_path, tool_event)- agentlens.emit_post_step(- state_path=state_path,- sid=sid,- tool_event=tool_event,- usage_events=[],- )continueremaining.append(tool_event)diff --git a/local/.claude/skills/agent-observability/scripts/core/state.py b/local/.claude/skills/agent-observability/scripts/core/state.pyindex 5e7d33e9..4e192bd0 100644--- a/local/.claude/skills/agent-observability/scripts/core/state.py+++ b/local/.claude/skills/agent-observability/scripts/core/state.py@@ -4,7 +4,6 @@- session 级 skill/rule 使用统计- 当前 agent、派发关系与历史- transcript offset、去重 claim、pending emits-- AgentLens sidecar 状态"""from __future__ import annotations@@ -174,612 +173,6 @@ def set_devflow_state(state: dict[str, Any], sid: str, updates: dict[str, Any])dv.update(updates)-def get_agentlens_session(state: dict[str, Any], sid: str) -> dict[str, Any]:- """返回某个 session 的 AgentLens sidecar payload。"""- sess = ensure_session(state, sid)- payload = sess.setdefault("_agentlens", {})- if not isinstance(payload, dict):- payload = {}- sess["_agentlens"] = payload- return payload---AGENTLENS_SCHEMA_VERSION = 2-_TURN_HISTORY_MAX = 5---def _migrate_agentlens_v1_to_v2(payload: dict[str, Any], sess: dict[str, Any] | None) -> dict[str, Any]:- """把 v1 版 ``_agentlens`` payload 转成以 turn 为中心的 v2 布局。-- v1 布局(pre-turn):- {"carrier": {...}, "enabled": bool, "session_id": "...", "app_name": "..."}- v2 布局(turn-centric):- {- "version": 2,- "session_id": "...",- "enabled": bool,- "app_name": "...",- "current_turn": {"turn_id": "legacy", "started_at": ..., "carrier": {...}, "subagent_spans": {}, "agent_spans": {}, "step_spans": {}},- "turn_history": [],- }-- 幂等约束:如果已经带有 ``version``,就原样返回。- """- if not isinstance(payload, dict):- return {"version": AGENTLENS_SCHEMA_VERSION, "enabled": False, "current_turn": None, "turn_history": []}- if payload.get("version") == AGENTLENS_SCHEMA_VERSION:- payload.setdefault("current_turn", None)- payload.setdefault("turn_history", [])- current = payload.get("current_turn")- if isinstance(current, dict):- current.setdefault("subagent_spans", {})- current.setdefault("agent_spans", {})- current.setdefault("step_spans", {})- return payload-- migrated: dict[str, Any] = {- "version": AGENTLENS_SCHEMA_VERSION,- "session_id": payload.get("session_id"),- "enabled": bool(payload.get("enabled", False)),- }- if "app_name" in payload:- migrated["app_name"] = payload.get("app_name")- if "last_error" in payload:- migrated["last_error"] = payload.get("last_error")-- legacy_carrier = payload.get("carrier")- if isinstance(legacy_carrier, dict) and legacy_carrier:- started_at = None- if isinstance(sess, dict):- try:- started_at = float(sess.get("started_at") or 0) or None- except Exception:- started_at = None- migrated["current_turn"] = {- "turn_id": "legacy",- "started_at": started_at or time.time(),- "carrier": dict(legacy_carrier),- "subagent_spans": {},- "agent_spans": {},- "step_spans": {},- }- else:- migrated["current_turn"] = None- migrated["turn_history"] = []- return migrated---def load_agentlens_session(state_path: Path, sid: str) -> dict[str, Any]:- """加载某个 session 已持久化的 AgentLens sidecar payload。-- 这里使用共享读锁,避免并发 ``update_agentlens_session`` 写入时读到撕裂数据。- 返回值会透明地把 v1 payload 迁移成 v2 副本;真正落盘迁移会在下一次写入时完成。- """- with state_read_lock(state_path):- state = load_state(state_path)- sess = state.get(sid)- if not isinstance(sess, dict):- return {}- payload = sess.get("_agentlens")- if not isinstance(payload, dict):- return {}- # 先给调用方返回迁移后的副本,真正持久化迁移留到后续写入时完成。- return _migrate_agentlens_v1_to_v2(dict(payload), sess)---def update_agentlens_session(- state_path: Path,- sid: str,- updates: dict[str, Any],- *,- clear_keys: list[str] | None = None,-) -> dict[str, Any]:- """原子地持久化某个 session 的 AgentLens sidecar 字段。-- 在合并 updates 之前会先做 v1→v2 迁移,这样磁盘上的 payload 会随着写入自然收敛到 v2。- """-- def _update(state: dict[str, Any]) -> dict[str, Any]:- sess = ensure_session(state, sid)- payload = get_agentlens_session(state, sid)- # 如果仍是 v1,就原地迁移。- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), sess)- payload.clear()- payload.update(migrated)- for key in clear_keys or []:- payload.pop(key, None)- for key, value in updates.items():- if value is None:- payload.pop(key, None)- else:- payload[key] = value- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(payload)-- return update_state_locked(state_path, _update)---def begin_turn(- state_path: Path,- sid: str,- turn_id: str,- carrier: dict[str, str],- *,- started_at: float | None = None,- max_history: int = _TURN_HISTORY_MAX,-) -> dict[str, Any]:- """在独占锁下打开一个新的 turn。-- 语义:- - 如果存在 ``current_turn``,先把它归档进有上限的 ``turn_history``。- - 为新 turn 重置 ``subagent_spans`` / ``agent_spans`` / ``step_spans``。- - 对相同 ``turn_id`` 保持幂等:重复调用直接返回已有 ``current_turn``,- 不重新生成 trace_id。-- 返回最终生成的 ``current_turn`` 字典。- """- ts = float(started_at if started_at is not None else time.time())-- def _update(state: dict[str, Any]) -> dict[str, Any]:- sess = ensure_session(state, sid)- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), sess)- payload.clear()- payload.update(migrated)-- current = payload.get("current_turn")- # 幂等:如果同一个 turn_id 还在处理中,就原样返回。- if isinstance(current, dict) and str(current.get("turn_id") or "") == str(turn_id):- return dict(current)-- # 归档上一个 turn。- if isinstance(current, dict) and current.get("turn_id"):- history = payload.setdefault("turn_history", [])- if not isinstance(history, list):- history = []- payload["turn_history"] = history- archived = {- "turn_id": current.get("turn_id"),- "started_at": current.get("started_at"),- "ended_at": ts,- "carrier_traceparent": (current.get("carrier") or {}).get("traceparent"),- }- history.append(archived)- if len(history) > max_history:- del history[: len(history) - max_history]-- new_turn = {- "turn_id": str(turn_id),- "started_at": ts,- "carrier": dict(carrier or {}),- "subagent_spans": {},- "agent_spans": {},- "step_spans": {},- }- payload["current_turn"] = new_turn- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_turn)-- return update_state_locked(state_path, _update)---def upsert_subagent_span(- state_path: Path,- sid: str,- role: str,- carrier: dict[str, str],-) -> dict[str, str]:- """在当前 turn 下登记 subagent 的 ``invoke_agent`` 子 span carrier。-- 对 `(turn, role)` 维度保持幂等:如果活跃 turn 下已经记录了该角色的 carrier,- 就直接返回已有值,不再重复创建。- """- now = time.time()-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- # 没有活跃 turn,无法登记 subagent span。- return {}- subs = current.setdefault("subagent_spans", {})- if not isinstance(subs, dict):- subs = {}- current["subagent_spans"] = subs- existing = subs.get(role)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- subs[role] = {"carrier": dict(carrier or {}), "opened_at": now}- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(carrier or {})-- return update_state_locked(state_path, _update)---def upsert_subagent_span_atomic(- state_path: Path,- sid: str,- role: str,- *,- carrier_factory: Any,-) -> dict[str, str]:- """在写锁内原子地获取或创建 subagent 的 ``invoke_agent`` carrier。-- `carrier_factory` 是一个无参可调用对象,用来生成 carrier 字典。- 只有在 span 还不存在时才会被调用,从而避免这样的 TOCTOU 竞争:- ``_generate_subagent_carrier`` 先产生了不可逆的 zhiyanllm ``invoke_agent`` span,- 随后另一个 hook 进程已经写入同一角色,导致本次创建变成孤儿。- """- now = time.time()-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- subs = current.setdefault("subagent_spans", {})- if not isinstance(subs, dict):- subs = {}- current["subagent_spans"] = subs- existing = subs.get(role)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- subs[role] = {"carrier": dict(new_carrier), "opened_at": now}- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def get_current_turn(state_path: Path, sid: str) -> dict[str, Any] | None:- """返回当前活跃的 turn 字典;如果没有打开 turn,就返回 None。"""- payload = load_agentlens_session(state_path, sid)- current = payload.get("current_turn")- return current if isinstance(current, dict) else None---def get_subagent_span_carrier(state_path: Path, sid: str, role: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 subagent span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- subs = turn.get("subagent_spans")- if not isinstance(subs, dict):- return None- rec = subs.get(role)- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None---def _empty_agent_aggregate() -> dict[str, Any]:- """创建一份空的 agent 聚合指标骨架。"""- return {- "tokens": {- "input": 0,- "output": 0,- "cache_read": 0,- "cache_creation": 0,- "total": 0,- },- "event_count": 0,- "cost_usd": 0.0,- "tool_duration_ms": 0,- "llm_call_count": 0,- "tool_call_count": 0,- "step_count": 0,- }---def _normalize_agent(agent: str | None) -> str:- """把 agent 名归一化,空值统一落到 ``main``。"""- return str(agent or "main").strip() or "main"---def _ensure_turn_agent_spans(current: dict[str, Any]) -> dict[str, Any]:- """确保当前 turn 下存在 `agent_spans` 容器。"""- agent_spans = current.setdefault("agent_spans", {})- if not isinstance(agent_spans, dict):- agent_spans = {}- current["agent_spans"] = agent_spans- return agent_spans---def _ensure_agent_span_rec(current: dict[str, Any], agent: str) -> dict[str, Any]:- """确保指定 agent 在当前 turn 下有一条完整聚合记录。"""- agent_spans = _ensure_turn_agent_spans(current)- rec = agent_spans.get(agent)- if not isinstance(rec, dict):- rec = {}- agent_spans[agent] = rec- carrier = rec.get("carrier")- if not isinstance(carrier, dict):- rec["carrier"] = {}- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- rec["aggregate"] = _empty_agent_aggregate()- return rec---def get_agent_span_carrier(state_path: Path, sid: str, agent: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 agent 分组 span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- agent_spans = turn.get("agent_spans")- if not isinstance(agent_spans, dict):- return None- rec = agent_spans.get(_normalize_agent(agent))- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None---def upsert_agent_span_atomic(- state_path: Path,- sid: str,- agent: str,- *,- carrier_factory: Any,-) -> dict[str, str]:- """原子地获取或创建 agent 分组 span carrier。"""- now = time.time()- normalized_agent = _normalize_agent(agent)-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(- dict(payload),- state.get(sid) if isinstance(state.get(sid), dict) else None,- )- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- rec = _ensure_agent_span_rec(current, normalized_agent)- existing = rec.get("carrier")- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- rec["carrier"] = dict(new_carrier)- rec.setdefault("opened_at", now)- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def bump_agent_aggregate(- state_path: Path,- sid: str,- agent: str,- *,- usage_event: dict[str, Any] | None = None,- tool_event: dict[str, Any] | None = None,- step_created: bool = False,-) -> dict[str, Any]:- """增加活跃 turn 下按 agent 聚合的统计指标。"""- normalized_agent = _normalize_agent(agent)-- def _int(value: Any) -> int:- try:- return int(value or 0)- except Exception:- return 0-- def _float(value: Any) -> float:- try:- return float(value or 0)- except Exception:- return 0.0-- def _update(state: dict[str, Any]) -> dict[str, Any]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(- dict(payload),- state.get(sid) if isinstance(state.get(sid), dict) else None,- )- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- rec = _ensure_agent_span_rec(current, normalized_agent)- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- aggregate = _empty_agent_aggregate()- rec["aggregate"] = aggregate- tokens = aggregate.setdefault("tokens", {})- if not isinstance(tokens, dict):- tokens = {}- aggregate["tokens"] = tokens-- if step_created:- aggregate["step_count"] = _int(aggregate.get("step_count")) + 1-- if isinstance(tool_event, dict):- aggregate["tool_call_count"] = _int(aggregate.get("tool_call_count")) + 1- ms = tool_event.get("ms")- if ms is not None:- aggregate["tool_duration_ms"] = _int(aggregate.get("tool_duration_ms")) + _int(ms)-- if isinstance(usage_event, dict):- raw_tokens = usage_event.get("tokens")- if isinstance(raw_tokens, dict):- # 聚合 agent 摘要里需要暴露的字段。- for key in ("input", "output", "cache_read", "cache_creation"):- tokens[key] = _int(tokens.get(key)) + _int(raw_tokens.get(key))- # total = input + output,其中 input 已经包含 cache_read。- tokens["total"] = _int(tokens.get("input")) + _int(tokens.get("output"))- aggregate["llm_call_count"] = _int(aggregate.get("llm_call_count")) + 1- aggregate["event_count"] = _int(aggregate.get("event_count")) + 1- aggregate["cost_usd"] = round(_float(aggregate.get("cost_usd")) + _float(usage_event.get("cost_usd")), 10)-- payload["version"] = AGENTLENS_SCHEMA_VERSION- return json.loads(json.dumps(aggregate, ensure_ascii=False))-- return update_state_locked(state_path, _update)---def get_subagent_aggregate(state_path: Path, sid: str, role: str) -> dict[str, Any] | None:- """返回活跃 turn 下当前 agent 的聚合摘要。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- agent_spans = turn.get("agent_spans")- if not isinstance(agent_spans, dict):- return None- rec = agent_spans.get(_normalize_agent(role))- if not isinstance(rec, dict):- return None- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- return None- return json.loads(json.dumps(aggregate, ensure_ascii=False))---def _step_span_key(agent: str, message_id: str) -> str:- """为 step span 生成按 agent 与 message_id 唯一定位的 key。"""- return f"{agent}|{message_id}"---def upsert_step_span(- state_path: Path,- sid: str,- agent: str,- message_id: str,- carrier: dict[str, str],- *,- transcript_path: str | None = None,-) -> dict[str, str]:- """在当前 turn 下登记一个 step span carrier,并对 `(turn, agent, message_id)` 保持幂等。"""- now = time.time()- normalized_agent = str(agent or "main").strip() or "main"- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return {}-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- steps = current.setdefault("step_spans", {})- if not isinstance(steps, dict):- steps = {}- current["step_spans"] = steps- key = _step_span_key(normalized_agent, normalized_message_id)- existing = steps.get(key)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- steps[key] = {- "carrier": dict(carrier or {}),- "opened_at": now,- "agent": normalized_agent,- "message_id": normalized_message_id,- "transcript_path": transcript_path or "",- }- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(carrier or {})-- return update_state_locked(state_path, _update)---def upsert_step_span_atomic(- state_path: Path,- sid: str,- agent: str,- message_id: str,- *,- carrier_factory: Any,- transcript_path: str | None = None,-) -> dict[str, str]:- """在写锁内原子地获取或创建一个 step span carrier。-- `carrier_factory` 是一个无参可调用对象,用来生成 carrier 字典。- 只有在 span 还不存在时才会被调用,从而避免这样的 TOCTOU 竞争:- ``_generate_step_carrier`` 已经先产生了不可逆的 zhiyanllm span,- 但随后另一个 hook 进程已经写入同一 step,导致本次创建失去归属。- """- now = time.time()- normalized_agent = str(agent or "main").strip() or "main"- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return {}-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- steps = current.setdefault("step_spans", {})- if not isinstance(steps, dict):- steps = {}- current["step_spans"] = steps- key = _step_span_key(normalized_agent, normalized_message_id)- existing = steps.get(key)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- steps[key] = {- "carrier": dict(new_carrier),- "opened_at": now,- "agent": normalized_agent,- "message_id": normalized_message_id,- "transcript_path": transcript_path or "",- }- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def get_step_span_carrier(state_path: Path, sid: str, agent: str, message_id: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 step span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- steps = turn.get("step_spans")- if not isinstance(steps, dict):- return None- key = _step_span_key(str(agent or "main").strip() or "main", str(message_id or "").strip())- rec = steps.get(key)- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None--def get_latest_session_id(state: dict[str, Any]) -> str | None:"""返回 state 中最近启动的 session id。"""latest_sid: str | None = None@@ -1061,38 +454,6 @@ def get_last_cumulative_usage(return {}-def get_last_llm_offset(- state: dict,- sid: str,- transcript_path: str | None = None,-) -> int:- """获取最近一次处理到的 LLM source_offset,用于增量构建 I/O。"""- sess = state.get(sid)- if not isinstance(sess, dict):- return 0- scope = _get_transcript_scope(sess, transcript_path)- if isinstance(scope, dict):- v = scope.get("last_llm_offset")- if isinstance(v, (int, float)):- return int(v)- return 0---def set_last_llm_offset(- state: dict,- sid: str,- offset: int,- transcript_path: str | None = None,-) -> None:- """持久化某个 transcript 最近处理到的 LLM source_offset。"""- sess = state.get(sid)- if not isinstance(sess, dict):- return- scope = _get_transcript_scope(sess, transcript_path, create=True)- if isinstance(scope, dict):- scope["last_llm_offset"] = int(offset or 0)--def set_last_cumulative_usage(state: dict,sid: str,diff --git a/local/.claude/skills/agent-observability/scripts/run_hook.sh b/local/.claude/skills/agent-observability/scripts/run_hook.shindex d476810f..e73e814a 100644--- a/local/.claude/skills/agent-observability/scripts/run_hook.sh+++ b/local/.claude/skills/agent-observability/scripts/run_hook.sh@@ -2,15 +2,6 @@set -euPROJECT_DIR="${CODEBUDDY_PROJECT_DIR:-$(cd "$(dirname "$0")"/../../../.. && pwd -P)}"-PYTHON_BIN="$PROJECT_DIR/.venv/bin/python"MAIN_PY="$PROJECT_DIR/.codebuddy/skills/agent-observability/scripts/main.py"-# 只有当 .venv 里可用 zhiyanllm 时才优先使用该解释器;-# 否则回退到已安装 zhiyanllm 的系统 python3。-if [ -x "$PYTHON_BIN" ]; then- if "$PYTHON_BIN" -c "import zhiyanllm" 2>/dev/null; then- exec "$PYTHON_BIN" "$MAIN_PY" "$@"- fi-fi-exec python3 "$MAIN_PY" "$@"diff --git a/local/.claude/skills/agent-observability/tests/test_build_dashboard_data.py b/local/.claude/skills/agent-observability/tests/test_build_dashboard_data.pyindex 6ee93f75..00127338 100644--- a/local/.claude/skills/agent-observability/tests/test_build_dashboard_data.py+++ b/local/.claude/skills/agent-observability/tests/test_build_dashboard_data.py@@ -285,8 +285,7 @@ class TopSlowTests(unittest.TestCase):class BuildDailyAndSessionsTurnAttributionTests(unittest.TestCase):- """真实场景复现过:AgentLens(写 state.current_turn 的那套 tracing)关闭时,- tool/usage 事件自己的 turn_id 永远是 None,只有 user_prompt_submit 事件带真实+ """真实场景复现过:tool/usage 事件自己的 turn_id 永远是 None,只有 user_prompt_submit 事件带真实turn_id。修复前所有没有 turn_id 的事件会被塌缩进同一个 "?" 占位桶,看起来像"整个会话只有 1 个 turn",哪怕实际发了好几轮 prompt。"""diff --git a/local/.claude/skills/agent-observability/tests/test_collector.py b/local/.claude/skills/agent-observability/tests/test_collector.pyindex 05547f06..b70f127d 100644--- a/local/.claude/skills/agent-observability/tests/test_collector.py+++ b/local/.claude/skills/agent-observability/tests/test_collector.py@@ -12,7 +12,7 @@ SCRIPTS = ROOT / "scripts"if str(SCRIPTS) not in sys.path:sys.path.insert(0, str(SCRIPTS))-from core import agent_identity, agentlens, collector, emitter, runtime, state as st # type: ignore+from core import agent_identity, collector, emitter, runtime, state as st # type: ignoreclass CollectorTests(unittest.TestCase):@@ -550,24 +550,16 @@ class CollectorTests(unittest.TestCase):encoding="utf-8",)- emitted_calls: list[dict[str, object]] = []- original_emit_post_step = agentlens.emit_post_step- try:- agentlens.emit_post_step = lambda **kwargs: emitted_calls.append(kwargs)- runtime.flush_pending_tool_events(- state_path=state_path,- log_path=log_path,- sid=sid,- )- finally:- agentlens.emit_post_step = original_emit_post_step+ runtime.flush_pending_tool_events(+ state_path=state_path,+ log_path=log_path,+ sid=sid,+ )self.assertEqual(st.get_pending_tool_emits(state_path, sid), [])lines = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()]self.assertEqual(len(lines), 1)self.assertEqual(lines[0]["message_id"], "msg-later")- self.assertEqual(len(emitted_calls), 1)- self.assertEqual(emitted_calls[0]["tool_event"]["message_id"], "msg-later")def test_related_transcript_paths_include_subagents(self):with tempfile.TemporaryDirectory() as td:@@ -683,33 +675,6 @@ class CollectorTests(unittest.TestCase):self.assertEqual(skills_usage.get("pdf", {}).get("count"), 1)self.assertEqual(rules_usage.get("security", {}).get("count"), 1)- def test_step_span_registry_is_idempotent(self):- with tempfile.TemporaryDirectory() as td:- state_path = Path(td) / ".state.json"- sid = "s-step"- carrier = {"traceparent": "00-" + ("1" * 32) + "-" + ("2" * 16) + "-01"}- st.begin_turn(state_path, sid, "turn-1", carrier)-- first = st.upsert_step_span(- state_path,- sid,- "main",- "msg-001",- {"traceparent": "00-" + ("1" * 32) + "-" + ("3" * 16) + "-01"},- transcript_path="/tmp/demo.jsonl",- )- second = st.upsert_step_span(- state_path,- sid,- "main",- "msg-001",- {"traceparent": "00-" + ("1" * 32) + "-" + ("4" * 16) + "-01"},- transcript_path="/tmp/demo.jsonl",- )-- self.assertEqual(first, second)- self.assertEqual(st.get_step_span_carrier(state_path, sid, "main", "msg-001"), first)-if __name__ == "__main__":unittest.main()diff --git a/local/.claude/skills/agent-observability/tests/test_runtime_flow.py b/local/.claude/skills/agent-observability/tests/test_runtime_flow.pyindex 7bd143ba..2931ffed 100644--- a/local/.claude/skills/agent-observability/tests/test_runtime_flow.py+++ b/local/.claude/skills/agent-observability/tests/test_runtime_flow.py@@ -49,15 +49,13 @@ class RuntimeFlowTests(unittest.TestCase):mock.patch.object(runtime.collector, "cache_inventory"), \mock.patch.object(runtime.collector, "record_tool_usage", return_value=([], [])), \mock.patch.object(runtime.agent_identity, "resolve_active_agent_for_event", return_value=("main", None)), \- mock.patch.object(runtime, "current_turn_id", return_value="turn-1"), \mock.patch.object(runtime.collector, "extract_tool_call_id", return_value=None), \mock.patch.object(runtime, "flush_pending_tool_events"), \mock.patch.object(runtime.collector, "find_current_tool_context", return_value=None), \mock.patch.object(runtime.collector, "related_transcript_paths", return_value=["/tmp/demo.jsonl"]), \mock.patch.object(runtime, "emit_transcript_events", return_value=[]), \mock.patch.object(runtime.collector, "find_fallback_usage_event", return_value=None), \- mock.patch.object(runtime.st, "append_pending_tool_emit"), \- mock.patch.object(runtime.agentlens, "emit_post_step"):+ mock.patch.object(runtime.st, "append_pending_tool_emit"):mock_paths.return_value = runtime.RuntimePaths(base_dir=Path(td),state_path=Path(td) / ".state.json",diff --git a/local/.codebuddy/skills/agent-observability/SKILL.md b/local/.codebuddy/skills/agent-observability/SKILL.mdindex 8bff9f0c..5f980a68 100644--- a/local/.codebuddy/skills/agent-observability/SKILL.md+++ b/local/.codebuddy/skills/agent-observability/SKILL.md@@ -1,6 +1,6 @@---name: agent-observability-description: Add or maintain CodeBuddy hook observability for projects that need local metrics for tool latency, transcript token usage, session cost, and multi-agent trace attribution. Use when wiring hook-based telemetry, debugging missing usage events, and validating AgentLens state.+description: Add or maintain CodeBuddy hook observability for projects that need local metrics for tool latency, transcript token usage, session cost, and multi-agent trace attribution. Use when wiring hook-based telemetry, and debugging missing usage events.---## Workflow@@ -8,7 +8,7 @@ description: Add or maintain CodeBuddy hook observability for projects that need1. Merge `templates/settings-hook.json` into the user or project `settings.json`.2. Keep hook entries command-only and keep timeouts around 5 to 10 seconds.3. Run a normal CodeBuddy session and inspect `logs/metrics.ndjson`.-4. Inspect `logs/.state.json` when usage replay, offsets, or AgentLens turn state look wrong.+4. Inspect `logs/.state.json` when usage replay or offsets look wrong.5. Keep the runtime generic and verify output from `metrics.ndjson` and `.state.json`.## Read Next@@ -20,8 +20,7 @@ description: Add or maintain CodeBuddy hook observability for projects that need- `scripts/main.py`: hook entrypoint for `session-start`, `user-prompt-submit`, `pre`, `post`, and `stop`- `scripts/run_hook.sh`: stable shell wrapper for CodeBuddy hook commands- `scripts/core/collector.py`: transcript parsing, pre/post pairing, and session usage recording-- `scripts/core/agentlens.py`: AgentLens trace emission and agent or step grouping-- `scripts/core/state.py`: persisted hook state, offsets, and AgentLens sidecar state+- `scripts/core/state.py`: persisted hook state, offsets, and pending tool events- `scripts/core/devflow.py`: optional devflow-awareness — detects a `multi-agents-devflow-*` team, reads `workflow-state.json`, and emits `stage_transition` events. No-ops entirely on non-devflow projects.- `templates/settings-hook.json`: hook wiring templatediff --git a/local/.codebuddy/skills/agent-observability/references/quickstart.md b/local/.codebuddy/skills/agent-observability/references/quickstart.mdindex 72ea7bfb..e5c08232 100644--- a/local/.codebuddy/skills/agent-observability/references/quickstart.md+++ b/local/.codebuddy/skills/agent-observability/references/quickstart.md@@ -129,7 +129,6 @@ PY- 没有日志:检查 hook 命令路径。- `ms` 为空:通常是 pre/post 未配对。- 没有 `usage`:`transcript_path` 缺失、tail 无 usage,或增量已去重。-- AgentLens 未启用:检查 `.state.json` 的 `_agentlens.enabled` / `last_error`。### 已知问题(未修复)diff --git a/local/.codebuddy/skills/agent-observability/references/schema-v2.md b/local/.codebuddy/skills/agent-observability/references/schema-v2.mdindex 98179404..ef9c0287 100644--- a/local/.codebuddy/skills/agent-observability/references/schema-v2.md+++ b/local/.codebuddy/skills/agent-observability/references/schema-v2.md@@ -32,7 +32,7 @@ devflow 项目完全不受影响:| event | 实际顶层字段 | 说明 ||---|---|---|| `start` | `event`, `sid`, `agent`, `ts` | 会话开始 |-| `user_prompt_submit` | `event`, `sid`, `agent`, `turn_id`, `prompt_len`, `ts` | 新 turn 边界;AgentLens 侧按 `1 Trace = 1 Turn` 生成 trace |+| `user_prompt_submit` | `event`, `sid`, `agent`, `turn_id`, `prompt_len`, `ts` | 新 turn 边界;之后没有自带 `turn_id` 的事件归入该 turn || `tool` | `event`, `sid`, `agent`, `tool`, `ms`, `transcript_path`, `turn_id`, `ts`, `skill`, `rule`, `cwd`, `call_id`, `message_id`, `tool_details`, `task_slug`?, `stage`?, `pt_id`? | 工具调用与耗时 || `usage` | `event`, `sid`, `agent`, `tool`, `tokens`, `model`, `transcript_path`, `source_offset`, `turn_id`, `message_id`, `ts`, `task_slug`?, `stage`? | transcript 增量 token / 模型 / 消息归属 || `stop` | `event`, `sid`, `agent`, `tokens`, `model`, `transcript_path`, `source_offset`, `turn_id`, `message_id`, `ts`, `task_slug`?, `stage`? | 会话尾部 flush |@@ -254,18 +254,6 @@ devflow 项目完全不受影响:}```-### AgentLens sidecar--`.state.json[sid]._agentlens` 只作为内部状态使用,核心字段:--- `enabled`: AgentLens 上报是否可用-- `last_error`: 最近一次降级原因-- `current_turn.carrier.traceparent`: 当前 turn 的 trace context-- `current_turn.subagent_spans`: 同一 turn 下的子 agent span carrier-- `current_turn.agent_spans`: 同一 turn 下按 agent 聚合的 span carrier 与累计统计-- `current_turn.step_spans`: `(agent, message_id)` 级 step span registry-- `turn_history`: 已结束 turn 的摘要-### Hook 接入参考 `templates/settings-hook.json`,必须启用:diff --git a/local/.codebuddy/skills/agent-observability/scripts/build_dashboard_data.py b/local/.codebuddy/skills/agent-observability/scripts/build_dashboard_data.pyindex 4c639f1a..ec5f234b 100644--- a/local/.codebuddy/skills/agent-observability/scripts/build_dashboard_data.py+++ b/local/.codebuddy/skills/agent-observability/scripts/build_dashboard_data.py@@ -126,9 +126,8 @@ def build_daily_and_sessions(events: list[dict[str, Any]]) -> tuple[list[dict[stby_day: dict[str, dict[str, Any]] = {}by_sid: dict[str, dict[str, Any]] = {}by_sid_turn: dict[tuple[str, str], dict[str, Any]] = {}- # AgentLens(写 state.current_turn 的那套 tracing)默认关闭时,tool/usage 事件- # 自身的 turn_id 永远是 None——但 user_prompt_submit 事件不依赖 AgentLens,- # 始终携带真实 turn_id(见 emitter.build_prompt_submit_event)。按 ts 排序后,+ # tool/usage 事件自身不带 turn_id,只有 user_prompt_submit 事件+ # 携带真实 turn_id(见 emitter.build_prompt_submit_event)。按 ts 排序后,# 把它当作 turn 边界,让后续没有自带 turn_id 的 tool/usage 事件归入"当前 sid# 最近一次打开的 turn",而不是全部塌缩进同一个 "?" 占位桶。current_turn_by_sid: dict[str, str] = {}diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/__init__.py b/local/.codebuddy/skills/agent-observability/scripts/core/__init__.pyindex 1d6ad5e9..a45607b6 100644--- a/local/.codebuddy/skills/agent-observability/scripts/core/__init__.py+++ b/local/.codebuddy/skills/agent-observability/scripts/core/__init__.py@@ -4,5 +4,4 @@- 采集与 transcript 解析- 状态读写与去重- skill/rule 扫描-- AgentLens trace 镜像"""diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/__init__.py b/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/__init__.pydeleted file mode 100644index 2fea21d6..00000000--- a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""可选的 AgentLens sink,用于实时镜像 trace。"""-from .runtime import emit_post_step, emit_session_start, emit_session_stop, emit_turn_start--__all__ = [- "emit_post_step",- "emit_session_start",- "emit_session_stop",- "emit_turn_start",-]diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/bootstrap.py b/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/bootstrap.pydeleted file mode 100644index d6fc970e..00000000--- a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/bootstrap.py+++ /dev/null@@ -1,229 +0,0 @@-from __future__ import annotations-"""AgentLens 启动辅助层。--这一层负责“读入与初始化”:-- 解析项目配置与环境变量-- 延迟加载可选的 zhiyan 运行时-- 缓存初始化结果,避免重复 init-- 处理调试落盘与失败状态写回-"""--import getpass-import json-import os-from dataclasses import dataclass-from pathlib import Path-from typing import Any--from .. import state as st--DEFAULT_APP_NAME = "skillhub.codebuddy-hooks"-DEFAULT_BUSINESS_SCENARIO = "codebuddy-hook"--_RUNTIME: dict[str, Any] | None = None-_INIT_SIGNATURE: tuple[str, str, str] | None = None---@dataclass(frozen=True)-class AgentLensConfig:- """从环境变量与 env 文件归一化得到的 AgentLens 配置。"""- endpoint: str | None- api_key: str | None- app_name: str- business_scenario: str- user: str-- @property- def enabled(self) -> bool:- return bool(self.endpoint and self.api_key)---def project_root(cwd: str | None = None) -> Path:- """解析用于查找 `.env` 的项目根目录。"""- if cwd:- return Path(cwd).expanduser().resolve()- env_cwd = str(os.environ.get("CODEBUDDY_PROJECT_DIR") or "").strip()- if env_cwd:- return Path(env_cwd).expanduser().resolve()- return Path.cwd().resolve()---def read_env_file(path: Path) -> dict[str, str]:- """以轻量方式解析 shell 风格的 env 文件,不做 source。"""- values: dict[str, str] = {}- if not path.is_file():- return values- try:- lines = path.read_text("utf-8").splitlines()- except Exception:- return values-- for raw_line in lines:- line = raw_line.strip()- if not line or line.startswith("#"):- continue- if line.startswith("export "):- line = line[7:].strip()- if "=" not in line:- continue- key, value = line.split("=", 1)- key = key.strip()- value = value.strip()- if not key:- continue- if value and value[0] == value[-1] and value[0] in {"'", '"'}:- value = value[1:-1]- values[key] = value- return values---def load_config(project_root_path: Path) -> AgentLensConfig:- """按优先级加载配置:进程环境变量 > `.env.local` > `.env`。"""- env_file = read_env_file(project_root_path / ".env")- env_local_file = read_env_file(project_root_path / ".env.local")-- def _value(name: str, default: str | None = None) -> str | None:- env_value = os.environ.get(name)- if env_value is not None and str(env_value).strip():- return str(env_value).strip()- if name in env_local_file and str(env_local_file[name]).strip():- return str(env_local_file[name]).strip()- if name in env_file and str(env_file[name]).strip():- return str(env_file[name]).strip()- return default-- user = _value("ZHIYANLLM_USER")- if not user:- user = (- str(os.environ.get("USER") or "").strip()- or str(os.environ.get("USERNAME") or "").strip()- or getpass.getuser()- )-- return AgentLensConfig(- endpoint=_value("ZHIYANLLM_API_ENDPOINT"),- api_key=_value("ZHIYANLLM_API_KEY"),- app_name=_value("ZHIYANLLM_APP_NAME", DEFAULT_APP_NAME) or DEFAULT_APP_NAME,- business_scenario=_value("ZHIYANLLM_BUSINESS_SCENARIO", DEFAULT_BUSINESS_SCENARIO)- or DEFAULT_BUSINESS_SCENARIO,- user=user or "unknown",- )---def load_runtime() -> dict[str, Any] | None:- """延迟导入可选的 zhiyan 运行时组件。-- 即使本地没有安装 AgentLens 依赖,hook 主链路也必须继续工作,- 所以这里返回 ``None``,而不是把导入异常抛出去。- """- global _RUNTIME- if _RUNTIME is not None:- return _RUNTIME- try:- from zhiyanllm import Zhiyanllm- from zhiyanllm.opentelemetry.instrumentation.semconv_ai import (- SpanAttributes as ZhiyanSpanAttributes,- ZhiyanllmSpanKindValues,- )- from zhiyanllm.tracing.context_manager import get_tracer- from zhiyanllm.tracing.manual import track_llm_call, track_task_server_call- from zhiyanllm.tracing.tracing import TracerWrapper- from opentelemetry.context import attach as otel_attach, detach as otel_detach- except Exception:- _RUNTIME = None- return None-- _RUNTIME = {- "Zhiyanllm": Zhiyanllm,- "track_llm_call": track_llm_call,- "track_task_server_call": track_task_server_call,- "TracerWrapper": TracerWrapper,- "get_tracer": get_tracer,- "ZhiyanSpanAttributes": ZhiyanSpanAttributes,- "ZhiyanllmSpanKindValues": ZhiyanllmSpanKindValues,- "otel_attach": otel_attach,- "otel_detach": otel_detach,- }- return _RUNTIME---def ensure_initialized(config: AgentLensConfig) -> dict[str, Any] | None:- """仅当有效配置签名发生变化时才重新初始化 zhiyan。"""- global _INIT_SIGNATURE- if not config.enabled:- return None- runtime = load_runtime()- if runtime is None:- return None- signature = (str(config.endpoint), str(config.api_key), str(config.app_name))- if _INIT_SIGNATURE == signature:- return runtime- runtime["Zhiyanllm"].init(- app_name=str(config.app_name),- api_endpoint=str(config.endpoint),- api_key=str(config.api_key),- disable_batch=True,- )- _INIT_SIGNATURE = signature- return runtime---def project_root_from_state_path(state_path: Path) -> Path:- """尽力从 `logs/.state.json` 反推出项目根目录。"""- try:- current = state_path.resolve().parent- for parent in [current, *current.parents]:- if parent.name == ".codebuddy":- return parent.parent- return state_path.resolve().parents[4]- except Exception:- return Path.cwd().resolve()---def debug_enabled(state_path: Path) -> bool:- """判断是否要把 span 调试信息镜像写入 `agentlens-push-debug.ndjson`。"""- root = project_root_from_state_path(state_path)- env_file = read_env_file(root / ".env")- env_local_file = read_env_file(root / ".env.local")- raw = (- os.environ.get("AGENTLENS_PUSH_DEBUG")- or env_local_file.get("AGENTLENS_PUSH_DEBUG")- or env_file.get("AGENTLENS_PUSH_DEBUG")- or ""- )- return str(raw).strip().lower() in {"1", "true", "yes", "on"}---def debug_write_span(- state_path: Path | None,- sid: str | None,- payload: dict[str, Any],- *,- sanitizer,-) -> None:- """在开启 AgentLens 调试模式时追加写入清洗后的调试记录。"""- if state_path is None or not sid:- return- try:- if not debug_enabled(state_path):- return- debug_path = state_path.parent / "agentlens-push-debug.ndjson"- record = {"sid": sid, **sanitizer(payload)}- with debug_path.open("a", encoding="utf-8") as fp:- fp.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")- except Exception:- return---def set_failure(state_path: Path, sid: str, message: str) -> None:- """记录最近一次 AgentLens 失败,但不打断 hook 主流程。"""- st.update_agentlens_session(- state_path,- sid,- {"enabled": False, "last_error": str(message)},- )---def get_session_context(state_path: Path, sid: str) -> dict[str, Any]:- """从共享状态里读取 AgentLens sidecar 的 session payload。"""- return st.load_agentlens_session(state_path, sid)diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/normalize.py b/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/normalize.pydeleted file mode 100644index 2b730f06..00000000--- a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/normalize.py+++ /dev/null@@ -1,323 +0,0 @@-from __future__ import annotations-"""AgentLens 负载清洗层。--这一层负责“清洗与整形”:-- 在发送或调试前把任意 payload 转成安全的 JSON 结构-- 把本地 token 结构归一化成类似 OpenAI 的 usage 结构-- 从 transcript 中重建轻量的 message / tool-call 上下文-"""--import json-import os-from pathlib import Path-from typing import Any--from .. import state as st-from .bootstrap import AgentLensConfig---def sanitize_payload(value: Any) -> Any:- """把任意 Python 值转换成适合调试/打点的 JSON 安全结构。"""- try:- return json.loads(json.dumps(value, ensure_ascii=False, default=str))- except Exception:- return str(value)---def association_properties(config: AgentLensConfig, sid: str, state_path: Path | None = None) -> dict[str, str]:- """构造 trace 级关联属性,并允许按 turn 覆盖业务场景。"""- scenario = config.business_scenario- if state_path:- try:- session_ctx = st.load_agentlens_session(state_path, sid)- turn_scenario = session_ctx.get("_turn_business_scenario")- if isinstance(turn_scenario, str) and turn_scenario.strip():- scenario = turn_scenario.strip()- except Exception:- pass- return {- "session_id": sid,- "business_scenario": scenario,- "user": config.user,- }---def to_openai_usage(tokens: dict[str, Any] | None) -> dict[str, int]:- """把本地 token 结构转换成 zhiyan 期望的 usage 形状。"""- if not isinstance(tokens, dict):- return {}-- def _int(v: Any) -> int:- try:- return int(v or 0)- except Exception:- return 0-- prompt = _int(tokens.get("input"))- completion = _int(tokens.get("output"))- if prompt <= 0 and completion <= 0:- return {}- return {"prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": prompt + completion}---def infer_vendor(model: str | None) -> str:- """根据模型名推断一个粗粒度的 provider/vendor 标签。"""- text = str(model or "").strip().lower()- if not text:- return "unknown"- if "gpt" in text or "openai" in text:- return "openai"- if "claude" in text or "anthropic" in text:- return "anthropic"- if "gemini" in text or "google" in text:- return "google"- if text.startswith("hy") or "hunyuan" in text:- return "tencent"- return text.split("/", 1)[0].split("-", 1)[0] or "unknown"---def extract_message_text(content: Any) -> str:- """把嵌套的 transcript message 内容压平成纯文本。"""- if content is None:- return ""- if isinstance(content, str):- return content- if isinstance(content, list):- parts: list[str] = []- for item in content:- if isinstance(item, dict):- txt = item.get("text")- if isinstance(txt, str):- parts.append(txt)- elif item.get("type") == "tool_use":- parts.append(f"[tool_use {item.get('name', '')}]")- elif item.get("type") == "tool_result":- parts.append(extract_message_text(item.get("content")))- else:- parts.append(str(item))- return "\n".join(p for p in parts if p)- if isinstance(content, dict):- return extract_message_text(content.get("text") or content.get("content"))- return str(content)---def find_message_id_in_record(obj: Any) -> str | None:- """在 transcript 记录里递归查找稳定的 message 标识。"""- message_id_keys = ("messageId", "responseId", "requestId")- if isinstance(obj, dict):- provider = obj.get("providerData")- if isinstance(provider, dict):- for key in message_id_keys:- value = provider.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- extra = obj.get("extra")- if isinstance(extra, dict):- for key in message_id_keys:- value = extra.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- for key in message_id_keys:- value = obj.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- for value in obj.values():- found = find_message_id_in_record(value)- if found:- return found- elif isinstance(obj, list):- for value in obj:- found = find_message_id_in_record(value)- if found:- return found- return None---def collect_tool_calls_for_message(transcript_path: str, message_id: str) -> list[dict[str, Any]]:- """为指定 assistant message 重建它挂载的 tool-call 摘要。"""- if not transcript_path or not message_id or not os.path.isfile(transcript_path):- return []- try:- with open(transcript_path, "rb") as fp:- blob = fp.read()- except Exception:- return []-- tool_calls: list[dict[str, Any]] = []- for raw_line in blob.splitlines(keepends=True):- if not raw_line.lstrip().startswith(b"{"):- continue- try:- rec = json.loads(raw_line.decode("utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(rec, dict):- continue- if str(rec.get("type") or "").strip().lower() != "function_call":- continue- rec_mid = find_message_id_in_record(rec)- if rec_mid != message_id:- continue- call_id = str(rec.get("callId") or "").strip()- name = str(rec.get("name") or "").strip()- arguments = rec.get("arguments")- entry: dict[str, Any] = {"id": call_id, "name": name}- if arguments is not None:- entry["arguments"] = arguments if isinstance(arguments, str) else json.dumps(arguments, ensure_ascii=False)- tool_calls.append(entry)- return tool_calls---def find_tool_usage_event(tool_event: dict[str, Any], usage_events: list[dict[str, Any]]) -> dict[str, Any] | None:- """从 usage 列表里挑出最可能属于当前 tool 事件的那一条。"""- tool_name = str(tool_event.get("tool") or "")- transcript_path = str(tool_event.get("transcript_path") or "")- agent = str(tool_event.get("agent") or "main")- for usage_event in usage_events:- if not isinstance(usage_event, dict):- continue- if str(usage_event.get("agent") or "main") != agent:- continue- if transcript_path and str(usage_event.get("transcript_path") or "") != transcript_path:- continue- if tool_name and str(usage_event.get("tool") or "") not in {tool_name, "model_request"}:- continue- if str(usage_event.get("message_id") or "").strip():- return usage_event- for usage_event in usage_events:- if not isinstance(usage_event, dict):- continue- if str(usage_event.get("agent") or "main") != agent:- continue- if transcript_path and str(usage_event.get("transcript_path") or "") != transcript_path:- continue- return usage_event- return None---def build_llm_io_from_transcript(- *,- transcript_path: str,- source_offset: int,- tokens: dict[str, Any] | None,- model: str | None,- start_offset: int = 0,- current_message_id: str | None = None,-) -> tuple[dict[str, Any], dict[str, Any], str]:- """从 transcript 历史中构造紧凑版的 LLM 输入/输出负载。"""- input_data: dict[str, Any] = {"model": str(model or "unknown"), "messages": []}- output_data: dict[str, Any] = {"choices": [], "usage": to_openai_usage(tokens)}- if not transcript_path or not os.path.isfile(transcript_path):- return input_data, output_data, ""- try:- with open(transcript_path, "rb") as fp:- fp.seek(0)- blob = fp.read(source_offset) if source_offset else fp.read()- except Exception:- return input_data, output_data, ""-- messages: list[dict[str, Any]] = []- system_prompts: list[str] = []- cursor = 0- last_asst_text: str | None = None-- def _truncate(text: str, limit: int = 4000) -> str:- if len(text) <= limit:- return text- return text[:limit] + "...(truncated)"-- for raw_line in blob.splitlines(keepends=True):- cursor += len(raw_line)- if not raw_line.lstrip().startswith(b"{"):- continue- try:- rec = json.loads(raw_line.decode("utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(rec, dict):- continue-- rec_type = str(rec.get("type") or "").strip().lower()- is_incremental = cursor > start_offset-- # 重建 prompt 上下文时要跳过“当前正在发出的 assistant message”,- # 否则同一段回复会同时出现在 input 和 output 两边。- if current_message_id and is_incremental:- rec_mid = find_message_id_in_record(rec)- if rec_mid == current_message_id:- if rec_type == "message" and rec.get("role") == "assistant":- text = extract_message_text(rec.get("content"))- if text:- last_asst_text = text- continue-- if rec_type == "message":- role = rec.get("role")- text = extract_message_text(rec.get("content"))- if not text:- continue- if role == "system":- system_prompts.append(text)- elif is_incremental:- if role == "user":- messages.append({"role": "user", "content": _truncate(text, 8000)})- last_asst_text = None- elif role == "assistant":- messages.append({"role": "assistant", "content": _truncate(text, 4000)})- last_asst_text = text- elif is_incremental:- # 把 function call / result 记录转换成 Chat Completions 风格的- # assistant/tool message,方便 tracing UI 按对话链路展示。- if rec_type == "function_call":- name = str(rec.get("name") or "").strip()- call_id = str(rec.get("callId") or "").strip()- arguments = rec.get("arguments", "")- if isinstance(arguments, dict):- arguments = json.dumps(arguments, ensure_ascii=False)- tool_call: dict[str, Any] = {"type": "function", "function": {"name": name}}- if name and arguments:- tool_call["function"]["arguments"] = _truncate(str(arguments), 2000)- if call_id:- tool_call["id"] = call_id- if (- messages- and messages[-1].get("role") == "assistant"- and "tool_calls" not in messages[-1]- and messages[-1].get("content")- ):- messages[-1]["tool_calls"] = [tool_call]- else:- msg: dict[str, Any] = {"role": "assistant", "content": ""}- msg["tool_calls"] = [tool_call]- messages.append(msg)- elif rec_type == "function_call_result":- call_id = str(rec.get("callId") or "").strip()- provider = rec.get("providerData", {})- result_content = ""- if isinstance(provider, dict):- tool_result = provider.get("toolResult", {})- if isinstance(tool_result, dict):- result_content = extract_message_text(tool_result.get("content"))- if not result_content:- output = rec.get("output")- result_content = str(output.get("text", "")) if isinstance(output, dict) else ""- tool_msg: dict[str, Any] = {"role": "tool", "content": _truncate(result_content, 2000)}- if call_id:- tool_msg["tool_call_id"] = call_id- messages.append(tool_msg)-- final_messages: list[dict[str, Any]] = []- for prompt in system_prompts[-2:]:- if prompt:- final_messages.append({"role": "system", "content": _truncate(prompt, 2000)})- final_messages.extend(messages)- input_data["messages"] = final_messages-- if last_asst_text is not None:- output_data["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": last_asst_text[:8000]},- }]-- return input_data, output_data, ""diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/runtime.py b/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/runtime.pydeleted file mode 100644index 575f5077..00000000--- a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/runtime.py+++ /dev/null@@ -1,764 +0,0 @@-"""AgentLens 运行时编排层。--这一层保留对外暴露的 4 个入口:-- `emit_session_start`-- `emit_turn_start`-- `emit_post_step`-- `emit_session_stop`--它本身不负责底层清洗或 carrier 生成,而是把调用编排到-`bootstrap / normalize / tracing` 三层上。-"""-from __future__ import annotations--from pathlib import Path-from typing import Any--try:- from opentelemetry import trace as _otel_trace-except Exception: # pragma: no cover - 可选依赖缺失时优雅降级- _otel_trace = None--from .. import state as st-from .bootstrap import (- debug_write_span as _debug_write_span,- ensure_initialized as _ensure_initialized,- get_session_context as _get_session_context,- load_config,- project_root as _project_root,- set_failure as _set_failure,-)-from .normalize import (- association_properties as _association_properties,- build_llm_io_from_transcript as _build_llm_io_from_transcript,- find_tool_usage_event as _find_tool_usage_event,- infer_vendor as _infer_vendor,- sanitize_payload as _sanitize_payload,- to_openai_usage as _to_openai_usage,-)-from .tracing import (- annotate as _annotate,- emit_assistant_span as _emit_assistant_span,- emit_tool_span as _emit_tool_span,- generate_subagent_carrier as _generate_subagent_carrier,- generate_turn_carrier as _generate_turn_carrier,- resolve_agent_carrier as _resolve_agent_carrier,- resolve_step_carrier as _resolve_step_carrier,- set_agent_aggregate_on_span as _set_agent_aggregate_on_span,- span_context_ids as _span_context_ids,- traceparent_parts as _traceparent_parts,-)---def emit_session_start(- *,- state_path: Path,- sid: str,- cwd: str,- agent: str = "main",-) -> None:- """初始化 v2 版本的 `_agentlens` session payload。-- 在 turn-centric 模型下,这里**不再**生成 trace_id。- 它只负责记录 session 级元数据(如 `enabled`、`session_id`、`app_name`),- 并清理上一次运行遗留的 carrier / error 状态。- 真正的新 trace 会在第一次 `UserPromptSubmit` 时由 `emit_turn_start` 打开。- """- _ = agent- config = load_config(_project_root(cwd))- # 注意:这里不要清空 current_turn / turn_history。- # 同一个 sid 下 SessionStart 可能多次触发(例如 subagent 启动、IDE 刷新、- # workspace 切换)。如果这里清空,会把进行中的 turn 擦掉,后续 PostToolUse- # 会全部看到 no_active_turn,最终把这一轮观测链路打断。- base_updates: dict[str, Any] = {- "session_id": sid,- "app_name": config.app_name,- }- if not config.enabled:- base_updates["enabled"] = False- st.update_agentlens_session(- state_path,- sid,- base_updates,- clear_keys=["carrier", "last_error"],- )- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return- base_updates["enabled"] = True- st.update_agentlens_session(- state_path,- sid,- base_updates,- clear_keys=["carrier", "last_error"],- )- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_turn_start(- *,- state_path: Path,- sid: str,- cwd: str,- turn_id: str,- prompt_meta: dict[str, Any] | None = None,- business_scenario: str | None = None,-) -> None:- """打开一个新的 turn,生成新的 trace_id 并写入 `_agentlens.current_turn`。-- 这是当前实现里**唯一**允许生成新 trace_id 的地方。- `emit_post_step` / `emit_session_stop` 都不会重新造 carrier;- 找不到时只会优雅降级,不会私自开新链路。- """- _ = prompt_meta- config = load_config(_project_root(cwd))- if not config.enabled:- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return- # 先把 per-turn business scenario 写进 state,- # 这样 `_generate_turn_carrier -> _association_properties`- # 才能在生成 trace 时把这次 turn 的业务场景烘焙进去。- if business_scenario:- st.update_agentlens_session(- state_path,- sid,- {"enabled": True, "session_id": sid, "app_name": config.app_name, "_turn_business_scenario": business_scenario},- clear_keys=["last_error"],- )- else:- st.update_agentlens_session(- state_path,- sid,- {"enabled": True, "session_id": sid, "app_name": config.app_name},- clear_keys=["last_error", "_turn_business_scenario"],- )- carrier = _generate_turn_carrier(runtime, config=config, sid=sid, turn_id=turn_id, state_path=state_path)- st.begin_turn(state_path, sid, turn_id, carrier)- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_post_step(- *,- state_path: Path,- sid: str,- tool_event: dict[str, Any] | None,- usage_events: list[dict[str, Any]],-) -> None:- """发出扁平化的 LLM span,只保留最小 TASK 包装层来传播 carrier 上下文。-- 面向 turn 的 v2 约束:- - 活跃的 ``current_turn.carrier`` 是唯一的 trace 上下文来源。- - 如果不存在 ``current_turn``(例如 UserPromptSubmit hook 还没触发),- 这里只会记录 ``last_error`` 并返回,不会私自生成新的 trace_id。- - subagent(``active_agent != "main"``)会拿到当前 turn 下的- ``invoke_agent`` 子 span,后续 chat span 都挂到这个子 span 下,- 以保持因果链路连续。- """- if not isinstance(tool_event, dict) and not usage_events:- return-- cwd_hint = ""- if isinstance(tool_event, dict):- cwd_hint = str(tool_event.get("cwd") or "")- config = load_config(_project_root(cwd_hint))- if not config.enabled:- return-- session_ctx = _get_session_context(state_path, sid)- # 快路径:尊重 SessionStart 阶段已经写入的 enabled 标记。- if session_ctx.get("enabled") is False:- return-- current_turn = session_ctx.get("current_turn")- if not isinstance(current_turn, dict):- _set_failure(state_path, sid, "no_active_turn")- return- parent_carrier = current_turn.get("carrier")- if not isinstance(parent_carrier, dict) or not parent_carrier.get("traceparent"):- _set_failure(state_path, sid, "no_active_turn_carrier")- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return-- tool_name = str((tool_event or {}).get("tool") or "unknown_tool")- active_agent = str((tool_event or {}).get("agent") or "main")- transcript_path = str((tool_event or {}).get("transcript_path") or "")- skills = (tool_event or {}).get("skill") or []- rules = (tool_event or {}).get("rule") or []-- # 解析这次事件真正要用的 carrier。- # main agent 直接使用 turn 根 carrier;subagent 则使用按角色拆分的- # 子 span carrier,并在当前 turn 下做幂等注册。- carrier = dict(parent_carrier)- if active_agent and active_agent != "main":- existing = None- subs = current_turn.get("subagent_spans")- if isinstance(subs, dict):- rec = subs.get(active_agent)- if isinstance(rec, dict) and isinstance(rec.get("carrier"), dict):- existing = rec["carrier"]- if isinstance(existing, dict) and existing.get("traceparent"):- carrier = dict(existing)- else:- # 原子化的 get-or-create:只有确认 subagent span 不存在时,- # 才会在写锁内部调用 carrier_factory。- # 这样可以避免并发 hook 进程之间的 TOCTOU 竞争,产生孤儿- # invoke_agent.TASK span。- def _factory() -> dict[str, str]:- return _generate_subagent_carrier(- runtime, parent_carrier=parent_carrier, role=active_agent- )-- registered = st.upsert_subagent_span_atomic(- state_path, sid, active_agent, carrier_factory=_factory- )- if isinstance(registered, dict) and registered.get("traceparent"):- carrier = dict(registered)- runtime["Zhiyanllm"].set_association_properties(_association_properties(config, sid, state_path))- # 静默挂载 carrier 上下文(不额外创建 TASK span),让内部 span- # 继承正确的 trace_id / parent_id。- _ctx = runtime["TracerWrapper"].extract_context(carrier)- _token = runtime["otel_attach"](_ctx)- try:- preferred_tool_message_id = str((tool_event or {}).get("message_id") or "").strip() or None- _assistant_emitted_mids: set[str] = set()- pre_bumped_steps: set[tuple[str, str]] = set()- committed_steps: set[tuple[str, str]] = set()-- if isinstance(tool_event, dict):- if preferred_tool_message_id and st.get_step_span_carrier(- state_path, sid, active_agent, preferred_tool_message_id- ) is None:- pre_bumped_steps.add((active_agent, preferred_tool_message_id))- for usage_event in usage_events:- event_agent = str(usage_event.get("agent") or active_agent or "main")- event_message_id = str(usage_event.get("message_id") or "").strip() or None- if event_message_id:- step_key = (event_agent, event_message_id)- if (- step_key not in pre_bumped_steps- and st.get_step_span_carrier(state_path, sid, event_agent, event_message_id) is None- ):- pre_bumped_steps.add(step_key)- if not usage_events and isinstance(tool_event, dict):- tool_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=active_agent,- )- if preferred_tool_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=tool_parent_carrier,- agent=active_agent,- message_id=preferred_tool_message_id,- transcript_path=transcript_path,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- tool_parent_carrier = dict(step_carrier)- _emit_tool_span(- runtime,- carrier=tool_parent_carrier,- tool_name=tool_name,- active_agent=active_agent,- skills=skills,- rules=rules,- duration_ms=tool_event.get("ms") if isinstance(tool_event.get("ms"), (int, float)) else None,- tool_details=tool_event.get("tool_details") if isinstance(tool_event.get("tool_details"), dict) else None,- message_id=preferred_tool_message_id,- step_grouping="message_id" if preferred_tool_message_id else "fallback",- state_path=state_path,- sid=sid,- )- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- tool_event=tool_event,- )- if (- preferred_tool_message_id- and (active_agent, preferred_tool_message_id) in pre_bumped_steps- and (active_agent, preferred_tool_message_id) not in committed_steps- ):- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- step_created=True,- )- committed_steps.add((active_agent, preferred_tool_message_id))- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- return-- matched_usage = _find_tool_usage_event(tool_event, usage_events) if isinstance(tool_event, dict) else None- tool_message_id = preferred_tool_message_id or str((matched_usage or {}).get("message_id") or "").strip() or None- if isinstance(tool_event, dict):- # 先构造 assistant 预览,再打开 agent/step 父 span。- # 这样即便 transcript 重建失败,也不会留下空的分组 TASK。- _assistant_preview_content: str | None = None- _assistant_preview_transcript = transcript_path- _assistant_preview_model = ""- if tool_message_id:- for _ue in usage_events:- if str(_ue.get("message_id") or "").strip() != tool_message_id:- continue- _ue_transcript = str(_ue.get("transcript_path") or transcript_path)- _ue_offset = int(_ue.get("source_offset") or 0)- _, _llm_out_pre, _ = _build_llm_io_from_transcript(- transcript_path=_ue_transcript,- source_offset=_ue_offset,- tokens=_ue.get("tokens"),- model=str(_ue.get("model") or ""),- )- _pre_content = ""- if _llm_out_pre.get("choices"):- _pre_msg = _llm_out_pre["choices"][0].get("message") or {}- _pre_content = str(_pre_msg.get("content") or "")- if _pre_content and _pre_content.strip():- _assistant_preview_content = _pre_content- _assistant_preview_transcript = _ue_transcript- _assistant_preview_model = str(_ue.get("model") or "")- break-- tool_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=active_agent,- )- if tool_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=tool_parent_carrier,- agent=active_agent,- message_id=tool_message_id,- transcript_path=transcript_path,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- tool_parent_carrier = dict(step_carrier)- if _assistant_preview_content and tool_message_id:- _emit_assistant_span(- runtime,- carrier=tool_parent_carrier,- agent=active_agent,- message_id=tool_message_id,- assistant_text=_assistant_preview_content,- model=_assistant_preview_model,- transcript_path=_assistant_preview_transcript,- state_path=state_path,- sid=sid,- )- _assistant_emitted_mids.add(tool_message_id)-- _emit_tool_span(- runtime,- carrier=tool_parent_carrier,- tool_name=tool_name,- active_agent=active_agent,- skills=skills,- rules=rules,- duration_ms=tool_event.get("ms") if isinstance(tool_event.get("ms"), (int, float)) else None,- tool_details=tool_event.get("tool_details") if isinstance(tool_event.get("tool_details"), dict) else None,- message_id=tool_message_id,- step_grouping="message_id" if tool_message_id else "fallback",- state_path=state_path,- sid=sid,- )- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- tool_event=tool_event,- )- if tool_message_id and (active_agent, tool_message_id) in pre_bumped_steps:- step_key = (active_agent, tool_message_id)- if step_key not in committed_steps:- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- step_created=True,- )- committed_steps.add(step_key)-- _prev_llm_offsets: dict[str, int] = {}- for usage_event in usage_events:- model = str(usage_event.get("model") or "")- ev_transcript = str(usage_event.get("transcript_path") or transcript_path)- ev_offset = int(usage_event.get("source_offset") or 0)- raw_tokens = usage_event.get("tokens") or {}- event_message_id = str(usage_event.get("message_id") or "").strip() or None- event_agent = str(usage_event.get("agent") or active_agent or "main")- start_offset = _prev_llm_offsets.get(ev_transcript) or st.get_last_llm_offset(- st.load_state(state_path), sid, ev_transcript- )- llm_input, llm_output, _turn_title = _build_llm_io_from_transcript(- transcript_path=ev_transcript,- source_offset=ev_offset,- start_offset=int(start_offset or 0),- current_message_id=event_message_id,- tokens=raw_tokens,- model=model or None,- )- _prev_llm_offsets[ev_transcript] = ev_offset- # 原子写回 state,供跨进程增量跟踪复用- def _update_llm_offset(state: dict[str, Any], _ev=ev_transcript, _off=ev_offset) -> None:- st.set_last_llm_offset(state, sid, _off, _ev)- st.update_state_locked(state_path, _update_llm_offset)- # --- 把 skill/rule/agent 作为独立消息标签注入 input_data ---- _meta_messages: list[dict[str, str]] = []- _ev_agent = str(usage_event.get("agent") or active_agent)- if _ev_agent and _ev_agent != "main":- _meta_messages.append({"role": "agent", "content": _ev_agent})- if skills:- _meta_messages.append({"role": "skill", "content": ", ".join(skills)})- if rules:- _meta_messages.append({"role": "rule", "content": ", ".join(rules)})- if _meta_messages:- llm_input.setdefault("messages", [])- for msg in reversed(_meta_messages):- llm_input["messages"].insert(0, msg)- # --- 构造 usage ---- llm_output["usage"] = _to_openai_usage(raw_tokens)- # --- 只附带成本细节来构造 output 内容 ---- _cost_info = {- "input_tokens": raw_tokens.get("input"),- "output_tokens": raw_tokens.get("output"),- "cache_read": raw_tokens.get("cache_read"),- "cache_creation": raw_tokens.get("cache_creation"),- "total_tokens": raw_tokens.get("total"),- "cost_usd": usage_event.get("cost_usd"),- }- _cost_info = {k: v for k, v in _cost_info.items() if v is not None}- _existing_content = ""- if llm_output.get("choices"):- _msg = llm_output["choices"][0].get("message") or {}- _existing_content = str(_msg.get("content") or "")- _output_content = _existing_content- if _cost_info:- _cost_line = " | ".join(f"{k}: {v}" for k, v in _cost_info.items())- _output_content = f"[{_cost_line}]\n{_existing_content}" if _existing_content else f"[{_cost_line}]"- llm_output["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": _output_content},- }]- event_parent_carrier = carrier- if event_message_id:- event_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=event_agent,- )- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- transcript_path=ev_transcript,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- event_parent_carrier = dict(step_carrier)- ev_ctx = runtime["TracerWrapper"].extract_context(event_parent_carrier)- ev_token = runtime["otel_attach"](ev_ctx)- # 先累计聚合值,再发 LLM span,这样 span 上带的是最新累计属性。- st.bump_agent_aggregate(- state_path,- sid,- event_agent,- usage_event=usage_event,- )- _current_agg = st.get_subagent_aggregate(state_path, sid, event_agent)- try:- with runtime["track_llm_call"](_infer_vendor(model), "model_request") as llm_span:- # track_llm_call 已经设置了 gen_ai.span.kind/system/operation.name。- # 下方 _annotate 会通过 handle_llm_response 设置 gen_ai.usage.*。- # LLMSpan 包装层没有 set_attribute,所以这里改用原生 span 写 ID。- _native_span = _otel_trace.get_current_span()- _set_agent_aggregate_on_span(_native_span, _current_agg)- span_ids = _span_context_ids(_native_span)- parent_parts = _traceparent_parts(event_parent_carrier)- _debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "llm",- "span_name": "model_request",- "model": model,- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- "agent": event_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": ev_transcript,- "source_offset": ev_offset,- },- sanitizer=_sanitize_payload,- )- _annotate(- runtime,- span=llm_span,- input_data=llm_input,- output_data=llm_output,- tags={- "cost_usd": str(usage_event.get("cost_usd") or "-"),- "input_tokens": str(raw_tokens.get("input", "-")),- "output_tokens": str(raw_tokens.get("output", "-")),- "cache_read": str(raw_tokens.get("cache_read", "-")),- "cache_creation": str(raw_tokens.get("cache_creation", "-")),- "total_tokens": str(raw_tokens.get("total", "-")),- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- },- )- finally:- runtime["otel_detach"](ev_token)- if event_message_id and (event_agent, event_message_id) in pre_bumped_steps:- step_key = (event_agent, event_message_id)- if step_key not in committed_steps:- st.bump_agent_aggregate(- state_path,- sid,- event_agent,- step_created=True,- )- committed_steps.add(step_key)- if _existing_content and _existing_content.strip() and event_message_id not in _assistant_emitted_mids:- _emit_assistant_span(- runtime,- carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- assistant_text=_existing_content,- model=model,- transcript_path=ev_transcript,- state_path=state_path,- sid=sid,- )- finally:- runtime["otel_detach"](_token)- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_session_stop(- *,- state_path: Path,- sid: str,- cwd: str,- active_agent: str,- transcript_path: str,- stop_events: list[dict[str, Any]],-) -> None:- """在 session stop 阶段发出扁平化 LLM span,只保留最小 TASK 包装层传播上下文。"""- config = load_config(_project_root(cwd))- if not config.enabled:- return-- session_ctx = _get_session_context(state_path, sid)- if session_ctx.get("enabled") is False:- return-- current_turn = session_ctx.get("current_turn")- if not isinstance(current_turn, dict):- _set_failure(state_path, sid, "no_active_turn")- return- carrier = current_turn.get("carrier")- if not isinstance(carrier, dict) or not carrier.get("traceparent"):- _set_failure(state_path, sid, "no_active_turn_carrier")- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return-- runtime["Zhiyanllm"].set_association_properties(_association_properties(config, sid, state_path))- if not stop_events:- return- # 静默挂载 carrier 上下文(不额外创建 TASK span)。- _ctx = runtime["TracerWrapper"].extract_context(carrier)- _token = runtime["otel_attach"](_ctx)- try:- _prev_stop_offsets: dict[str, int] = {}- for stop_event in stop_events:- model = str(stop_event.get("model") or "")- ev_transcript = str(stop_event.get("transcript_path") or transcript_path)- ev_offset = int(stop_event.get("source_offset") or 0)- raw_tokens = stop_event.get("tokens") or {}- event_message_id = str(stop_event.get("message_id") or "").strip() or None- event_agent = str(stop_event.get("agent") or active_agent or "main")- start_offset = _prev_stop_offsets.get(ev_transcript) or st.get_last_llm_offset(- st.load_state(state_path), sid, ev_transcript- )- llm_input, llm_output, _turn_title = _build_llm_io_from_transcript(- transcript_path=ev_transcript,- source_offset=ev_offset,- start_offset=int(start_offset or 0),- current_message_id=event_message_id,- tokens=raw_tokens,- model=model or None,- )- _prev_stop_offsets[ev_transcript] = ev_offset- # 原子写回 state,供跨进程增量跟踪复用- def _update_llm_offset_stop(state: dict[str, Any], _ev=ev_transcript, _off=ev_offset) -> None:- st.set_last_llm_offset(state, sid, _off, _ev)- st.update_state_locked(state_path, _update_llm_offset_stop)- # --- 把 agent 作为独立消息标签注入 input_data ---- _ev_agent = str(stop_event.get("agent") or active_agent)- if _ev_agent and _ev_agent != "main":- llm_input.setdefault("messages", []).insert(0, {"role": "agent", "content": _ev_agent})- # --- 构造 usage ---- llm_output["usage"] = _to_openai_usage(raw_tokens)- # --- 构造带上下文和成本细节的 output 内容 ---- _cost_info = {- "input_tokens": raw_tokens.get("input"),- "output_tokens": raw_tokens.get("output"),- "cache_read": raw_tokens.get("cache_read"),- "cache_creation": raw_tokens.get("cache_creation"),- "total_tokens": raw_tokens.get("total"),- "cost_usd": stop_event.get("cost_usd"),- "cost_session_usd": stop_event.get("cost_session_usd"),- }- _cost_info = {k: v for k, v in _cost_info.items() if v is not None}- _existing_content = ""- if llm_output.get("choices"):- _msg = llm_output["choices"][0].get("message") or {}- _existing_content = str(_msg.get("content") or "")- _output_content = _existing_content- if _cost_info:- _cost_line = " | ".join(f"{k}: {v}" for k, v in _cost_info.items())- _output_content = f"[{_cost_line}]\n{_existing_content}" if _existing_content else f"[{_cost_line}]"- llm_output["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": _output_content},- }]- event_parent_carrier = carrier- # 先解析 agent carrier,让 step 挂在 agent 的 react_agent span 下,- # 而不是直接挂在 turn 根 span 下。- if event_agent and event_agent != "main":- agent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=event_agent,- )- if isinstance(agent_carrier, dict) and agent_carrier.get("traceparent"):- event_parent_carrier = dict(agent_carrier)- if event_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- transcript_path=ev_transcript,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- event_parent_carrier = dict(step_carrier)- ev_ctx = runtime["TracerWrapper"].extract_context(event_parent_carrier)- ev_token = runtime["otel_attach"](ev_ctx)- # 这里不要再 bump,emit_post_step 已经累计过这条 usage_event。- # SessionStop 会为同一次调用补发一个重复的 LLM span,再累加就会双算。- # 因此这里只读取当前聚合值。- _current_agg = st.get_subagent_aggregate(state_path, sid, event_agent)- try:- with runtime["track_llm_call"](_infer_vendor(model), "model_request") as llm_span:- # track_llm_call 已经设置了 gen_ai.span.kind/system/operation.name。- # 下方 _annotate 会通过 handle_llm_response 设置 gen_ai.usage.*。- # LLMSpan 包装层没有 set_attribute,所以这里改用原生 span 写 ID。- _native_span = _otel_trace.get_current_span()- _set_agent_aggregate_on_span(_native_span, _current_agg)- span_ids = _span_context_ids(_native_span)- parent_parts = _traceparent_parts(event_parent_carrier)- _debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "llm",- "span_name": "model_request",- "model": model,- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- "agent": event_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": ev_transcript,- "source_offset": ev_offset,- },- sanitizer=_sanitize_payload,- )- _annotate(- runtime,- span=llm_span,- input_data=llm_input,- output_data=llm_output,- tags={- "cost_usd": str(stop_event.get("cost_usd") or "-"),- "cost_session_usd": str(stop_event.get("cost_session_usd") or "-"),- "input_tokens": str(raw_tokens.get("input", "-")),- "output_tokens": str(raw_tokens.get("output", "-")),- "cache_read": str(raw_tokens.get("cache_read", "-")),- "cache_creation": str(raw_tokens.get("cache_creation", "-")),- "total_tokens": str(raw_tokens.get("total", "-")),- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- },- )- finally:- runtime["otel_detach"](ev_token)- if _existing_content and _existing_content.strip():- _emit_assistant_span(- runtime,- carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- assistant_text=_existing_content,- model=model,- transcript_path=ev_transcript,- state_path=state_path,- sid=sid,- )- finally:- runtime["otel_detach"](_token)- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- except Exception as exc:- _set_failure(state_path, sid, str(exc))diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/tracing.py b/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/tracing.pydeleted file mode 100644index afb678ad..00000000--- a/local/.codebuddy/skills/agent-observability/scripts/core/agentlens/tracing.py+++ /dev/null@@ -1,504 +0,0 @@-from __future__ import annotations-"""AgentLens trace 拓扑层。--这一层负责“trace 结构本身”:-- 创建或派生 carrier-- 生成 agent / step / assistant / tool span-- 把后续聚合需要的 span 元数据写回 state-"""--import json-import secrets-from pathlib import Path-from typing import Any--from .. import state as st-from .bootstrap import AgentLensConfig, debug_write_span-from .normalize import association_properties, collect_tool_calls_for_message, sanitize_payload---def annotate(runtime: dict[str, Any], *, span: Any | None = None, input_data: Any = None, output_data: Any = None, tags: dict[str, Any] | None = None) -> None:- """在调用 zhiyan annotate 前,先统一清洗 payload。"""- _ = span- runtime["Zhiyanllm"].annotate(- input_data=sanitize_payload(input_data),- output_data=sanitize_payload(output_data),- tags=sanitize_payload(tags) if tags else None,- )---def traceparent_parts(carrier: dict[str, str] | None) -> dict[str, str]:- """把 W3C `traceparent` 拆成调试日志里常用的几个字段。"""- traceparent = str((carrier or {}).get("traceparent") or "").strip()- parts = traceparent.split("-")- if len(parts) >= 4:- return {- "traceparent": traceparent,- "trace_id": parts[1],- "span_id": parts[2],- "flags": parts[3],- }- return {"traceparent": traceparent}---def span_context_ids(span: Any) -> dict[str, str]:- """从 OTel span 对象中提取十六进制的 trace/span id。"""- try:- ctx = span.get_span_context()- return {- "trace_id": f"{int(ctx.trace_id):032x}",- "span_id": f"{int(ctx.span_id):016x}",- }- except Exception:- return {}---def ensure_traceparent(carrier: dict[str, str]) -> None:- """当上游没有成功注入时,补一个最小可用的 `traceparent`。"""- if str(carrier.get("traceparent") or "").strip():- return- trace_id = secrets.token_hex(16)- parent_id = secrets.token_hex(8)- carrier["traceparent"] = f"00-{trace_id}-{parent_id}-01"---def carrier_from_span(parent_carrier: dict[str, str], span: Any) -> dict[str, str]:- """基于父 carrier 和当前 span 生成一个仍在同一 trace 上的子 carrier。"""- try:- span_ctx = span.get_span_context()- trace_id = f"{int(span_ctx.trace_id):032x}"- span_id = f"{int(span_ctx.span_id):016x}"- except Exception:- return {}- parent_tp = str((parent_carrier or {}).get("traceparent") or "").strip()- flags = "01"- if parent_tp:- parts = parent_tp.split("-")- if len(parts) >= 4 and parts[3]:- flags = parts[3]- child_carrier: dict[str, str] = dict(parent_carrier or {})- child_carrier["traceparent"] = f"00-{trace_id}-{span_id}-{flags}"- return child_carrier---def carrier_from_task_span(parent_carrier: dict[str, str], task_span: Any) -> dict[str, str]:- """兼容包装过的 task span 和原始 OTel span 两种形态。"""- span = getattr(task_span, "_span", None)- if span is None and hasattr(task_span, "get_span_context"):- span = task_span- if span is None:- return {}- return carrier_from_span(parent_carrier, span)---def zhiyan_attr(runtime: dict[str, Any], name: str, fallback: str) -> str:- """防御式读取 zhiyan 语义约定常量。"""- return str(getattr(runtime.get("ZhiyanSpanAttributes"), name, fallback))---def generate_turn_carrier(- runtime: dict[str, Any],- *,- config: AgentLensConfig,- sid: str,- turn_id: str,- state_path: Path | None = None,-) -> dict[str, str]:- """为一个用户 turn 生成根 carrier。"""- from opentelemetry import trace-- carrier: dict[str, str] = {}- span = trace.get_tracer(__name__).start_span(f"turn.{sid}.{turn_id}")- try:- runtime["Zhiyanllm"].set_association_properties(association_properties(config, sid, state_path))- runtime["Zhiyanllm"].inject_context(carrier)- finally:- span.end()- ensure_traceparent(carrier)- return carrier---def generate_subagent_carrier(runtime: dict[str, Any], *, parent_carrier: dict[str, str], role: str) -> dict[str, str]:- """在当前 turn 下面创建 `invoke_agent` 子 carrier。"""- try:- with runtime["track_task_server_call"]("invoke_agent", carrier=parent_carrier) as task_span:- annotate(runtime, input_data={"agent": role}, output_data={"result": "dispatched"}, tags={"agent": role})- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def generate_step_carrier(- runtime: dict[str, Any],- *,- parent_carrier: dict[str, str],- agent: str,- message_id: str,- transcript_path: str,-) -> dict[str, str]:- """创建用于归并同一条 message 工作的 synthetic step span。"""- try:- with runtime["track_task_server_call"]("react_step", carrier=parent_carrier) as task_span:- annotate(- runtime,- input_data={"agent": agent, "message_id": message_id},- output_data={"result": "grouped"},- tags={"message_id": message_id, "agent": agent, "transcript_path": transcript_path or ""},- )- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def generate_agent_carrier(runtime: dict[str, Any], *, parent_carrier: dict[str, str], agent: str) -> dict[str, str]:- """在当前 turn 下创建稳定的 per-agent 聚合 span。"""- try:- with runtime["track_task_server_call"]("react_agent", carrier=parent_carrier) as task_span:- span = getattr(task_span, "_span", None)- if span is not None and hasattr(span, "set_attribute"):- span.set_attribute("agent.name", agent)- annotate(runtime, input_data={"agent": agent}, output_data={"agent": agent}, tags={"agent": agent})- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def resolve_agent_carrier(- *,- state_path: Path,- sid: str,- runtime: dict[str, Any],- parent_carrier: dict[str, str],- agent: str,-) -> dict[str, str]:- """从共享状态里获取或创建持久化的 agent 聚合 carrier。"""- normalized_agent = str(agent or "main").strip() or "main"- existing = st.get_agent_span_carrier(state_path, sid, normalized_agent)- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)-- def _factory() -> dict[str, str]:- return generate_agent_carrier(runtime, parent_carrier=parent_carrier, agent=normalized_agent)-- effective_carrier = st.upsert_agent_span_atomic(state_path, sid, normalized_agent, carrier_factory=_factory)- if not isinstance(effective_carrier, dict) or not effective_carrier.get("traceparent"):- return dict(parent_carrier)- agent_parts = traceparent_parts(effective_carrier)- parent_parts = traceparent_parts(parent_carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "agent",- "span_name": "react_agent",- "agent": normalized_agent,- "trace_id": agent_parts.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": agent_parts.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- return dict(effective_carrier)---def resolve_step_carrier(- *,- state_path: Path,- sid: str,- runtime: dict[str, Any],- parent_carrier: dict[str, str],- agent: str,- message_id: str | None,- transcript_path: str,-) -> dict[str, str] | None:- """获取或创建按 message 分组使用的 step carrier。"""- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return None- existing = st.get_step_span_carrier(state_path, sid, agent, normalized_message_id)- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)-- def _factory() -> dict[str, str]:- return generate_step_carrier(- runtime,- parent_carrier=parent_carrier,- agent=agent,- message_id=normalized_message_id,- transcript_path=transcript_path,- )-- effective_carrier = st.upsert_step_span_atomic(- state_path,- sid,- agent,- normalized_message_id,- carrier_factory=_factory,- transcript_path=transcript_path,- )- if not isinstance(effective_carrier, dict) or not effective_carrier.get("traceparent"):- return None- step_parts = traceparent_parts(effective_carrier)- parent_parts = traceparent_parts(parent_carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "step",- "span_name": "react_step",- "message_id": normalized_message_id,- "agent": agent,- "trace_id": step_parts.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": step_parts.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": transcript_path or "",- },- sanitizer=sanitize_payload,- )- return dict(effective_carrier)---def set_agent_aggregate_on_span(span: Any, aggregate: dict[str, Any] | None) -> None:- """把 agent 的累计指标投影成当前 span 的属性。"""- if span is None or not hasattr(span, "set_attribute") or not isinstance(aggregate, dict):- return- tokens = aggregate.get("tokens") or {}- if isinstance(tokens, dict):- for key in ("input", "output", "cache_read", "cache_creation", "total"):- if key in tokens:- span.set_attribute(f"agent.cumulative_tokens.{key}", int(tokens.get(key) or 0))- for key in ("cost_usd", "tool_duration_ms", "llm_call_count", "tool_call_count", "step_count", "event_count"):- if key in aggregate:- try:- span.set_attribute(f"agent.cumulative.{key}", int(aggregate.get(key) or 0))- except (TypeError, ValueError):- span.set_attribute(f"agent.cumulative.{key}", str(aggregate.get(key)))---def emit_assistant_span(- runtime: dict[str, Any],- *,- carrier: dict[str, str],- agent: str,- message_id: str | None,- assistant_text: str,- model: str | None = None,- transcript_path: str | None = None,- state_path: Path | None = None,- sid: str | None = None,-) -> None:- """发出一个轻量 assistant span,并按需补上 tool calls。"""- if not assistant_text or not assistant_text.strip():- return- tool_calls: list[dict[str, Any]] = []- if message_id and transcript_path:- tool_calls = collect_tool_calls_for_message(transcript_path, message_id)- output_data: dict[str, Any] = {"role": "assistant", "content": assistant_text[:8000]}- if tool_calls:- output_data["tool_calls"] = tool_calls- ctx = runtime["TracerWrapper"].extract_context(carrier)- token = runtime["otel_attach"](ctx)- try:- with runtime["get_tracer"]() as tracer:- with tracer.start_as_current_span(name="assistant_message") as span:- span.set_attribute(runtime["ZhiyanSpanAttributes"].LLM_SPAN_KIND, runtime["ZhiyanllmSpanKindValues"].LLM.value)- span_ids = span_context_ids(span)- parent_parts = traceparent_parts(carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "assistant",- "span_name": "assistant_message",- "message_id": str(message_id or ""),- "agent": agent,- "model": str(model or ""),- "tool_call_count": len(tool_calls),- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- annotate(- runtime,- input_data={"agent": agent, "message_id": message_id or "", "model": model or ""},- output_data=output_data,- tags={"message_id": str(message_id or ""), "agent": agent},- )- finally:- runtime["otel_detach"](token)---def emit_tool_span(- runtime: dict[str, Any],- *,- carrier: dict[str, str],- tool_name: str,- active_agent: str,- skills: list[str],- rules: list[str],- duration_ms: int | None = None,- tool_details: dict[str, Any] | None = None,- message_id: str | None = None,- step_grouping: str = "fallback",- state_path: Path | None = None,- sid: str | None = None,-) -> None:- """发出 tool span,并以受控大小挂载 tool payload。"""- def _truncate(value: Any, limit: int = 1200) -> Any:- text = value if isinstance(value, str) else None- if text is None:- return value- if len(text) <= limit:- return text- return text[:limit] + "...(truncated)"-- def _maybe_parse_json_text(value: Any) -> Any:- if not isinstance(value, str):- return value- text = value.strip()- if not text or text[0] not in "{[":- return value- try:- return json.loads(text)- except Exception:- return value-- def _parse_bash_result_content(value: Any) -> dict[str, Any] | None:- if not isinstance(value, str) or "Command:" not in value:- return None- normalized_value = value.replace("\\n", "\n")- markers = [- ("Command:", "command"),- ("Stdout:", "stdout"),- ("Stderr:", "stderr"),- ("Exit Code:", "exit_code"),- ("Signal:", "signal"),- ]- parsed: dict[str, Any] = {}- for idx, (marker, key) in enumerate(markers):- start = normalized_value.find(marker)- if start < 0:- continue- start += len(marker)- end = len(normalized_value)- for next_marker, _ in markers[idx + 1:]:- pos = normalized_value.find(next_marker, start)- if pos >= 0:- end = min(end, pos)- segment = normalized_value[start:end].strip()- if not segment:- continue- parsed[key] = _truncate(segment, 1200 if key in {"command", "stdout", "stderr"} else 200)- return parsed or None-- tool_input: dict[str, Any] = {"tool": tool_name, "agent": active_agent}- if skills:- tool_input["skill"] = ", ".join(skills)- if rules:- tool_input["rule"] = ", ".join(rules)- if message_id:- tool_input["message_id"] = message_id- details = dict(tool_details or {})- call_id = str(details.get("call_id") or "").strip() or None- if call_id:- tool_input["call_id"] = call_id- arguments_display_text = details.get("arguments_display_text")- if arguments_display_text:- tool_input["arguments_display_text"] = _truncate(arguments_display_text, 600)- arguments = details.get("arguments")- if arguments:- parsed_arguments = _maybe_parse_json_text(arguments)- tool_input["arguments"] = _truncate(parsed_arguments, 1200)- if isinstance(parsed_arguments, dict):- if parsed_arguments.get("command"):- tool_input["command"] = _truncate(parsed_arguments.get("command"), 1200)- if parsed_arguments.get("description"):- tool_input["description"] = _truncate(parsed_arguments.get("description"), 400)-- tool_output: dict[str, Any] = {"result": "executed"}- result_content = details.get("result_content")- if result_content is not None:- structured_result = _parse_bash_result_content(result_content)- if structured_result:- tool_output["result"] = structured_result- else:- tool_output["result_content"] = _truncate(result_content, 1600)- output_text = details.get("output_text")- if output_text:- tool_output["output_text"] = _truncate(output_text, 1600)- raw_response = details.get("raw_response")- if isinstance(raw_response, dict):- tool_output["raw_response"] = {- "exitCode": raw_response.get("exitCode"),- "signal": raw_response.get("signal"),- "interrupted": raw_response.get("interrupted"),- "sandboxDenied": raw_response.get("sandboxDenied"),- "tool_error_code": raw_response.get("tool_error_code"),- }-- ctx = runtime["TracerWrapper"].extract_context(carrier)- token = runtime["otel_attach"](ctx)- try:- with runtime["get_tracer"]() as tracer:- with tracer.start_as_current_span(name=f"{tool_name}.TOOL") as span:- span_kind_value = runtime["ZhiyanllmSpanKindValues"].TOOL.value- span.set_attribute(zhiyan_attr(runtime, "LLM_SPAN_KIND", "gen_ai.span.kind"), span_kind_value)- span.set_attribute("gen_ai.span.kind", span_kind_value)- span.set_attribute(zhiyan_attr(runtime, "TOOL_NAME", "tool.name"), tool_name)- if isinstance(tool_details, dict):- desc = tool_details.get("description") or tool_details.get("tool_description")- if isinstance(desc, str) and desc.strip():- span.set_attribute(zhiyan_attr(runtime, "TOOL_DESCRIPTION", "tool.description"), desc.strip())- tool_params = tool_input.get("arguments")- if tool_params is not None:- if not isinstance(tool_params, str):- tool_params = json.dumps(tool_params, ensure_ascii=False, default=str)- span.set_attribute(zhiyan_attr(runtime, "TOOL_PARAMETERS", "tool.parameters"), tool_params)- if duration_ms is not None:- span.set_attribute("tool.duration_ms", int(duration_ms))- span_ids = span_context_ids(span)- parent_parts = traceparent_parts(carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "tool",- "span_name": f"{tool_name}.TOOL",- "tool": tool_name,- "message_id": str(message_id or ""),- "call_id": call_id or "",- "step_grouping": step_grouping,- "agent": active_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- annotate(- runtime,- input_data=tool_input,- output_data=tool_output,- tags={"step_grouping": step_grouping, "message_id": str(message_id or "")},- )- finally:- runtime["otel_detach"](token)diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/cls_sink.py b/local/.codebuddy/skills/agent-observability/scripts/core/cls_sink.pyindex e2c72391..0b5ce0f6 100644--- a/local/.codebuddy/skills/agent-observability/scripts/core/cls_sink.py+++ b/local/.codebuddy/skills/agent-observability/scripts/core/cls_sink.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from .agentlens import bootstrap+from . import envfile@@ -278,9 +278,9 @@ def _int_value(def load_config(cwd: str | None = None) -> CLSConfig:- project_root = bootstrap.project_root(cwd)- env_file = bootstrap.read_env_file(project_root / ".env")- env_local = bootstrap.read_env_file(project_root / ".env.local")+ project_root = envfile.project_root(cwd)+ env_file = envfile.read_env_file(project_root / ".env")+ env_local = envfile.read_env_file(project_root / ".env.local")return CLSConfig(enabled=_enabled_flag(env_local=env_local, env_file=env_file),endpoint=_value(diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/collector.py b/local/.codebuddy/skills/agent-observability/scripts/core/collector.pyindex cfd681b2..1986ae51 100644--- a/local/.codebuddy/skills/agent-observability/scripts/core/collector.py+++ b/local/.codebuddy/skills/agent-observability/scripts/core/collector.py@@ -811,7 +811,7 @@ def find_fallback_usage_event(tool_event: dict[str, Any],usage_events: list[dict[str, Any]],) -> dict[str, Any] | None:- """当找不到直接匹配的 tool usage 时,为 AgentLens 选一条兜底 usage。"""+ """当找不到直接匹配的 tool usage 时,选一条兜底 usage 补齐 message_id。"""tool_name = str(tool_event.get("tool") or "").strip()transcript_path = str(tool_event.get("transcript_path") or "").strip()agent = str(tool_event.get("agent") or "main").strip() or "main"diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/emitter.py b/local/.codebuddy/skills/agent-observability/scripts/core/emitter.pyindex a41dfc05..cbbe295d 100644--- a/local/.codebuddy/skills/agent-observability/scripts/core/emitter.py+++ b/local/.codebuddy/skills/agent-observability/scripts/core/emitter.py@@ -260,7 +260,7 @@ def build_prompt_submit_event() -> dict[str, Any]:"""构造 `user_prompt_submit` 事件,作为 turn 边界标记。- 这条记录会落到 metrics.ndjson,方便下游把 turn 和 AgentLens trace 对上。+ 这条记录会落到 metrics.ndjson,下游据此划分 turn。"""record: dict[str, Any] = {"event": "user_prompt_submit",diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/envfile.py b/local/.codebuddy/skills/agent-observability/scripts/core/envfile.pynew file mode 100644index 00000000..a7acf86e--- /dev/null+++ b/local/.codebuddy/skills/agent-observability/scripts/core/envfile.py@@ -0,0 +1,44 @@+from __future__ import annotations+"""项目 `.env` / `.env.local` 的轻量读取辅助。"""++import os+from pathlib import Path+++def project_root(cwd: str | None = None) -> Path:+ """解析用于查找 `.env` 的项目根目录。"""+ if cwd:+ return Path(cwd).expanduser().resolve()+ env_cwd = str(os.environ.get("CODEBUDDY_PROJECT_DIR") or "").strip()+ if env_cwd:+ return Path(env_cwd).expanduser().resolve()+ return Path.cwd().resolve()+++def read_env_file(path: Path) -> dict[str, str]:+ """以轻量方式解析 shell 风格的 env 文件,不做 source。"""+ values: dict[str, str] = {}+ if not path.is_file():+ return values+ try:+ lines = path.read_text("utf-8").splitlines()+ except Exception:+ return values++ for raw_line in lines:+ line = raw_line.strip()+ if not line or line.startswith("#"):+ continue+ if line.startswith("export "):+ line = line[7:].strip()+ if "=" not in line:+ continue+ key, value = line.split("=", 1)+ key = key.strip()+ value = value.strip()+ if not key:+ continue+ if value and value[0] == value[-1] and value[0] in {"'", '"'}:+ value = value[1:-1]+ values[key] = value+ return valuesdiff --git a/local/.codebuddy/skills/agent-observability/scripts/core/runtime.py b/local/.codebuddy/skills/agent-observability/scripts/core/runtime.pyindex 9c647bc0..a37a02a4 100644--- a/local/.codebuddy/skills/agent-observability/scripts/core/runtime.py+++ b/local/.codebuddy/skills/agent-observability/scripts/core/runtime.py@@ -4,18 +4,17 @@ from __future__ import annotations这一层负责把外部 hook phase 分发到内部能力:- session-start / user-prompt-submit / pre / post / stop- 组装统一运行时路径-- 串联 collector / emitter / agentlens,并承担 transcript 运行时编排+- 串联 collector / emitter,并承担 transcript 运行时编排"""import os-import reimport timeimport tracebackfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from . import agent_identity, agentlens, collector, devflow, emitter, scanner, state as st+from . import agent_identity, collector, devflow, emitter, scanner, state as st@dataclass(frozen=True)@@ -111,44 +110,8 @@ def prompt_text_length(data: dict[str, Any]) -> int | None:return None-def extract_prompt_text(data: dict[str, Any]) -> str:- """从 hook payload 中提取可读的 prompt 文本。"""- for key in ("prompt", "user_prompt", "message", "text"):- val = data.get(key)- if isinstance(val, str) and val.strip():- return val.strip()- if isinstance(val, list):- parts = []- for item in val:- if isinstance(item, dict):- txt = item.get("text")- if isinstance(txt, str):- parts.append(txt)- elif isinstance(item, str):- parts.append(item)- if parts:- return "\n".join(parts).strip()- return ""---def derive_business_scenario(prompt_text: str) -> str | None:- """从 prompt 文本中派生一个简短业务场景标识。"""- if not prompt_text:- return None-- m = re.search(r"标题[::]\s*(.+?)(?:\s*描述[::]|\s*$)", prompt_text, re.DOTALL)- if m:- title = m.group(1).strip()[:60]- else:- title = prompt_text[:50].strip()-- sanitized = re.sub(r"[^\w\u4e00-\u9fff\-]", "-", title)- sanitized = re.sub(r"-{2,}", "-", sanitized).strip("-")- return sanitized if sanitized else None--def handle_session_start(data: dict[str, Any]) -> None:- """处理 SessionStart:预热 inventory,写 start 事件,初始化 AgentLens。"""+ """处理 SessionStart:预热 inventory,写 start 事件。"""current_sid = session_id_of(data)if not current_sid:return@@ -157,33 +120,21 @@ def handle_session_start(data: dict[str, Any]) -> None:skills_meta, rules_meta = scanner.scan_skills_and_rules(cwd_value)collector.cache_inventory(paths.state_path, current_sid, skills_meta, rules_meta)emitter.emit(paths.log_path, emitter.build_start_event(sid=current_sid, agent="main"))- agentlens.emit_session_start(state_path=paths.state_path, sid=current_sid, cwd=cwd_value, agent="main")def handle_user_prompt_submit(data: dict[str, Any]) -> None:- """处理 UserPromptSubmit:建立 turn 边界,并打开 AgentLens turn。"""+ """处理 UserPromptSubmit:建立 turn 边界。"""current_sid = session_id_of(data)if not current_sid:returnpaths = build_runtime_paths()- cwd_value = cwd(data)turn_id = derive_turn_id(data)prompt_len = prompt_text_length(data)- prompt_text = extract_prompt_text(data)- business_scenario = derive_business_scenario(prompt_text)emitter.emit(paths.log_path,emitter.build_prompt_submit_event(sid=current_sid, turn_id=turn_id, agent="main", prompt_len=prompt_len),)- agentlens.emit_turn_start(- state_path=paths.state_path,- sid=current_sid,- cwd=cwd_value,- turn_id=turn_id,- prompt_meta={"prompt_len": prompt_len} if prompt_len is not None else None,- business_scenario=business_scenario,- )def handle_pre(data: dict[str, Any]) -> None:@@ -223,7 +174,7 @@ def handle_post(data: dict[str, Any]) -> None:tool_name = str(data.get("tool_name") or "")transcript_path = collector.transcript_path(data)- turn_id = current_turn_id(paths.state_path, current_sid)+ turn_id = Noneevent_ts = time.time()tool_call_id = collector.extract_tool_call_id(data)dv_ctx = resolve_devflow(paths.state_path, current_sid, cwd_value, paths.log_path)@@ -297,21 +248,9 @@ def handle_post(data: dict[str, Any]) -> None:if duplicate_tool_context:if not usage_events:return- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=None,- usage_events=usage_events,- )returnif str(tool_event.get("message_id") or "").strip():emitter.emit(paths.log_path, tool_event)- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=tool_event,- usage_events=usage_events,- )returnfallback_usage = collector.find_fallback_usage_event(tool_event, usage_events)@@ -319,19 +258,13 @@ def handle_post(data: dict[str, Any]) -> None:if fallback_usage_mid:tool_event["message_id"] = fallback_usage_midemitter.emit(paths.log_path, tool_event)- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=tool_event,- usage_events=usage_events,- )returnst.append_pending_tool_emit(paths.state_path, current_sid, tool_event)def handle_stop(data: dict[str, Any]) -> None:- """处理 Stop:补发 transcript 事件、汇总 session 成本并关闭 AgentLens。"""+ """处理 Stop:补发 transcript 事件、汇总 session 成本。"""current_sid = session_id_of(data)if not current_sid:return@@ -344,11 +277,11 @@ def handle_stop(data: dict[str, Any]) -> None:data=data,)transcript_path = collector.transcript_path(data)- turn_id = current_turn_id(paths.state_path, current_sid)+ turn_id = Nonedv_ctx = resolve_devflow(paths.state_path, current_sid, cwd_value, paths.log_path)task_slug = str(dv_ctx.get("task_slug") or "").strip() if dv_ctx else Nonestage = str(dv_ctx.get("current_stage") or "").strip() if dv_ctx else None- stop_events = emit_transcript_events(+ emit_transcript_events(state_path=paths.state_path,log_path=paths.log_path,sid=current_sid,@@ -369,14 +302,6 @@ def handle_stop(data: dict[str, Any]) -> None:sid=current_sid,force_emit_fallback=True,)- agentlens.emit_session_stop(- state_path=paths.state_path,- sid=current_sid,- cwd=cwd_value,- active_agent=active_agent,- transcript_path=transcript_path,- stop_events=stop_events,- )def resolve_devflow(state_path: Path, sid: str, cwd_value: str, log_path: Path) -> dict[str, Any] | None:@@ -410,19 +335,6 @@ def resolve_devflow(state_path: Path, sid: str, cwd_value: str, log_path: Path)return dv_ctx-def current_turn_id(state_path: Path, sid: str) -> str | None:- """从 state 中读取当前 session 激活中的 turn id。"""- try:- turn = st.get_current_turn(state_path, sid)- except Exception:- turn = None- if isinstance(turn, dict):- raw = turn.get("turn_id")- if isinstance(raw, str) and raw.strip():- return raw.strip()- return None--def flush_pending_tool_events(*,state_path: Path,@@ -471,21 +383,9 @@ def flush_pending_tool_events(if isinstance(tool_details, dict) and tool_details:tool_event["tool_details"] = dict(tool_details)emitter.emit(log_path, tool_event)- agentlens.emit_post_step(- state_path=state_path,- sid=sid,- tool_event=tool_event,- usage_events=[],- )continueif force_emit_fallback:emitter.emit(log_path, tool_event)- agentlens.emit_post_step(- state_path=state_path,- sid=sid,- tool_event=tool_event,- usage_events=[],- )continueremaining.append(tool_event)diff --git a/local/.codebuddy/skills/agent-observability/scripts/core/state.py b/local/.codebuddy/skills/agent-observability/scripts/core/state.pyindex 5e7d33e9..4e192bd0 100644--- a/local/.codebuddy/skills/agent-observability/scripts/core/state.py+++ b/local/.codebuddy/skills/agent-observability/scripts/core/state.py@@ -4,7 +4,6 @@- session 级 skill/rule 使用统计- 当前 agent、派发关系与历史- transcript offset、去重 claim、pending emits-- AgentLens sidecar 状态"""from __future__ import annotations@@ -174,612 +173,6 @@ def set_devflow_state(state: dict[str, Any], sid: str, updates: dict[str, Any])dv.update(updates)-def get_agentlens_session(state: dict[str, Any], sid: str) -> dict[str, Any]:- """返回某个 session 的 AgentLens sidecar payload。"""- sess = ensure_session(state, sid)- payload = sess.setdefault("_agentlens", {})- if not isinstance(payload, dict):- payload = {}- sess["_agentlens"] = payload- return payload---AGENTLENS_SCHEMA_VERSION = 2-_TURN_HISTORY_MAX = 5---def _migrate_agentlens_v1_to_v2(payload: dict[str, Any], sess: dict[str, Any] | None) -> dict[str, Any]:- """把 v1 版 ``_agentlens`` payload 转成以 turn 为中心的 v2 布局。-- v1 布局(pre-turn):- {"carrier": {...}, "enabled": bool, "session_id": "...", "app_name": "..."}- v2 布局(turn-centric):- {- "version": 2,- "session_id": "...",- "enabled": bool,- "app_name": "...",- "current_turn": {"turn_id": "legacy", "started_at": ..., "carrier": {...}, "subagent_spans": {}, "agent_spans": {}, "step_spans": {}},- "turn_history": [],- }-- 幂等约束:如果已经带有 ``version``,就原样返回。- """- if not isinstance(payload, dict):- return {"version": AGENTLENS_SCHEMA_VERSION, "enabled": False, "current_turn": None, "turn_history": []}- if payload.get("version") == AGENTLENS_SCHEMA_VERSION:- payload.setdefault("current_turn", None)- payload.setdefault("turn_history", [])- current = payload.get("current_turn")- if isinstance(current, dict):- current.setdefault("subagent_spans", {})- current.setdefault("agent_spans", {})- current.setdefault("step_spans", {})- return payload-- migrated: dict[str, Any] = {- "version": AGENTLENS_SCHEMA_VERSION,- "session_id": payload.get("session_id"),- "enabled": bool(payload.get("enabled", False)),- }- if "app_name" in payload:- migrated["app_name"] = payload.get("app_name")- if "last_error" in payload:- migrated["last_error"] = payload.get("last_error")-- legacy_carrier = payload.get("carrier")- if isinstance(legacy_carrier, dict) and legacy_carrier:- started_at = None- if isinstance(sess, dict):- try:- started_at = float(sess.get("started_at") or 0) or None- except Exception:- started_at = None- migrated["current_turn"] = {- "turn_id": "legacy",- "started_at": started_at or time.time(),- "carrier": dict(legacy_carrier),- "subagent_spans": {},- "agent_spans": {},- "step_spans": {},- }- else:- migrated["current_turn"] = None- migrated["turn_history"] = []- return migrated---def load_agentlens_session(state_path: Path, sid: str) -> dict[str, Any]:- """加载某个 session 已持久化的 AgentLens sidecar payload。-- 这里使用共享读锁,避免并发 ``update_agentlens_session`` 写入时读到撕裂数据。- 返回值会透明地把 v1 payload 迁移成 v2 副本;真正落盘迁移会在下一次写入时完成。- """- with state_read_lock(state_path):- state = load_state(state_path)- sess = state.get(sid)- if not isinstance(sess, dict):- return {}- payload = sess.get("_agentlens")- if not isinstance(payload, dict):- return {}- # 先给调用方返回迁移后的副本,真正持久化迁移留到后续写入时完成。- return _migrate_agentlens_v1_to_v2(dict(payload), sess)---def update_agentlens_session(- state_path: Path,- sid: str,- updates: dict[str, Any],- *,- clear_keys: list[str] | None = None,-) -> dict[str, Any]:- """原子地持久化某个 session 的 AgentLens sidecar 字段。-- 在合并 updates 之前会先做 v1→v2 迁移,这样磁盘上的 payload 会随着写入自然收敛到 v2。- """-- def _update(state: dict[str, Any]) -> dict[str, Any]:- sess = ensure_session(state, sid)- payload = get_agentlens_session(state, sid)- # 如果仍是 v1,就原地迁移。- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), sess)- payload.clear()- payload.update(migrated)- for key in clear_keys or []:- payload.pop(key, None)- for key, value in updates.items():- if value is None:- payload.pop(key, None)- else:- payload[key] = value- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(payload)-- return update_state_locked(state_path, _update)---def begin_turn(- state_path: Path,- sid: str,- turn_id: str,- carrier: dict[str, str],- *,- started_at: float | None = None,- max_history: int = _TURN_HISTORY_MAX,-) -> dict[str, Any]:- """在独占锁下打开一个新的 turn。-- 语义:- - 如果存在 ``current_turn``,先把它归档进有上限的 ``turn_history``。- - 为新 turn 重置 ``subagent_spans`` / ``agent_spans`` / ``step_spans``。- - 对相同 ``turn_id`` 保持幂等:重复调用直接返回已有 ``current_turn``,- 不重新生成 trace_id。-- 返回最终生成的 ``current_turn`` 字典。- """- ts = float(started_at if started_at is not None else time.time())-- def _update(state: dict[str, Any]) -> dict[str, Any]:- sess = ensure_session(state, sid)- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), sess)- payload.clear()- payload.update(migrated)-- current = payload.get("current_turn")- # 幂等:如果同一个 turn_id 还在处理中,就原样返回。- if isinstance(current, dict) and str(current.get("turn_id") or "") == str(turn_id):- return dict(current)-- # 归档上一个 turn。- if isinstance(current, dict) and current.get("turn_id"):- history = payload.setdefault("turn_history", [])- if not isinstance(history, list):- history = []- payload["turn_history"] = history- archived = {- "turn_id": current.get("turn_id"),- "started_at": current.get("started_at"),- "ended_at": ts,- "carrier_traceparent": (current.get("carrier") or {}).get("traceparent"),- }- history.append(archived)- if len(history) > max_history:- del history[: len(history) - max_history]-- new_turn = {- "turn_id": str(turn_id),- "started_at": ts,- "carrier": dict(carrier or {}),- "subagent_spans": {},- "agent_spans": {},- "step_spans": {},- }- payload["current_turn"] = new_turn- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_turn)-- return update_state_locked(state_path, _update)---def upsert_subagent_span(- state_path: Path,- sid: str,- role: str,- carrier: dict[str, str],-) -> dict[str, str]:- """在当前 turn 下登记 subagent 的 ``invoke_agent`` 子 span carrier。-- 对 `(turn, role)` 维度保持幂等:如果活跃 turn 下已经记录了该角色的 carrier,- 就直接返回已有值,不再重复创建。- """- now = time.time()-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- # 没有活跃 turn,无法登记 subagent span。- return {}- subs = current.setdefault("subagent_spans", {})- if not isinstance(subs, dict):- subs = {}- current["subagent_spans"] = subs- existing = subs.get(role)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- subs[role] = {"carrier": dict(carrier or {}), "opened_at": now}- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(carrier or {})-- return update_state_locked(state_path, _update)---def upsert_subagent_span_atomic(- state_path: Path,- sid: str,- role: str,- *,- carrier_factory: Any,-) -> dict[str, str]:- """在写锁内原子地获取或创建 subagent 的 ``invoke_agent`` carrier。-- `carrier_factory` 是一个无参可调用对象,用来生成 carrier 字典。- 只有在 span 还不存在时才会被调用,从而避免这样的 TOCTOU 竞争:- ``_generate_subagent_carrier`` 先产生了不可逆的 zhiyanllm ``invoke_agent`` span,- 随后另一个 hook 进程已经写入同一角色,导致本次创建变成孤儿。- """- now = time.time()-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- subs = current.setdefault("subagent_spans", {})- if not isinstance(subs, dict):- subs = {}- current["subagent_spans"] = subs- existing = subs.get(role)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- subs[role] = {"carrier": dict(new_carrier), "opened_at": now}- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def get_current_turn(state_path: Path, sid: str) -> dict[str, Any] | None:- """返回当前活跃的 turn 字典;如果没有打开 turn,就返回 None。"""- payload = load_agentlens_session(state_path, sid)- current = payload.get("current_turn")- return current if isinstance(current, dict) else None---def get_subagent_span_carrier(state_path: Path, sid: str, role: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 subagent span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- subs = turn.get("subagent_spans")- if not isinstance(subs, dict):- return None- rec = subs.get(role)- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None---def _empty_agent_aggregate() -> dict[str, Any]:- """创建一份空的 agent 聚合指标骨架。"""- return {- "tokens": {- "input": 0,- "output": 0,- "cache_read": 0,- "cache_creation": 0,- "total": 0,- },- "event_count": 0,- "cost_usd": 0.0,- "tool_duration_ms": 0,- "llm_call_count": 0,- "tool_call_count": 0,- "step_count": 0,- }---def _normalize_agent(agent: str | None) -> str:- """把 agent 名归一化,空值统一落到 ``main``。"""- return str(agent or "main").strip() or "main"---def _ensure_turn_agent_spans(current: dict[str, Any]) -> dict[str, Any]:- """确保当前 turn 下存在 `agent_spans` 容器。"""- agent_spans = current.setdefault("agent_spans", {})- if not isinstance(agent_spans, dict):- agent_spans = {}- current["agent_spans"] = agent_spans- return agent_spans---def _ensure_agent_span_rec(current: dict[str, Any], agent: str) -> dict[str, Any]:- """确保指定 agent 在当前 turn 下有一条完整聚合记录。"""- agent_spans = _ensure_turn_agent_spans(current)- rec = agent_spans.get(agent)- if not isinstance(rec, dict):- rec = {}- agent_spans[agent] = rec- carrier = rec.get("carrier")- if not isinstance(carrier, dict):- rec["carrier"] = {}- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- rec["aggregate"] = _empty_agent_aggregate()- return rec---def get_agent_span_carrier(state_path: Path, sid: str, agent: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 agent 分组 span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- agent_spans = turn.get("agent_spans")- if not isinstance(agent_spans, dict):- return None- rec = agent_spans.get(_normalize_agent(agent))- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None---def upsert_agent_span_atomic(- state_path: Path,- sid: str,- agent: str,- *,- carrier_factory: Any,-) -> dict[str, str]:- """原子地获取或创建 agent 分组 span carrier。"""- now = time.time()- normalized_agent = _normalize_agent(agent)-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(- dict(payload),- state.get(sid) if isinstance(state.get(sid), dict) else None,- )- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- rec = _ensure_agent_span_rec(current, normalized_agent)- existing = rec.get("carrier")- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- rec["carrier"] = dict(new_carrier)- rec.setdefault("opened_at", now)- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def bump_agent_aggregate(- state_path: Path,- sid: str,- agent: str,- *,- usage_event: dict[str, Any] | None = None,- tool_event: dict[str, Any] | None = None,- step_created: bool = False,-) -> dict[str, Any]:- """增加活跃 turn 下按 agent 聚合的统计指标。"""- normalized_agent = _normalize_agent(agent)-- def _int(value: Any) -> int:- try:- return int(value or 0)- except Exception:- return 0-- def _float(value: Any) -> float:- try:- return float(value or 0)- except Exception:- return 0.0-- def _update(state: dict[str, Any]) -> dict[str, Any]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(- dict(payload),- state.get(sid) if isinstance(state.get(sid), dict) else None,- )- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- rec = _ensure_agent_span_rec(current, normalized_agent)- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- aggregate = _empty_agent_aggregate()- rec["aggregate"] = aggregate- tokens = aggregate.setdefault("tokens", {})- if not isinstance(tokens, dict):- tokens = {}- aggregate["tokens"] = tokens-- if step_created:- aggregate["step_count"] = _int(aggregate.get("step_count")) + 1-- if isinstance(tool_event, dict):- aggregate["tool_call_count"] = _int(aggregate.get("tool_call_count")) + 1- ms = tool_event.get("ms")- if ms is not None:- aggregate["tool_duration_ms"] = _int(aggregate.get("tool_duration_ms")) + _int(ms)-- if isinstance(usage_event, dict):- raw_tokens = usage_event.get("tokens")- if isinstance(raw_tokens, dict):- # 聚合 agent 摘要里需要暴露的字段。- for key in ("input", "output", "cache_read", "cache_creation"):- tokens[key] = _int(tokens.get(key)) + _int(raw_tokens.get(key))- # total = input + output,其中 input 已经包含 cache_read。- tokens["total"] = _int(tokens.get("input")) + _int(tokens.get("output"))- aggregate["llm_call_count"] = _int(aggregate.get("llm_call_count")) + 1- aggregate["event_count"] = _int(aggregate.get("event_count")) + 1- aggregate["cost_usd"] = round(_float(aggregate.get("cost_usd")) + _float(usage_event.get("cost_usd")), 10)-- payload["version"] = AGENTLENS_SCHEMA_VERSION- return json.loads(json.dumps(aggregate, ensure_ascii=False))-- return update_state_locked(state_path, _update)---def get_subagent_aggregate(state_path: Path, sid: str, role: str) -> dict[str, Any] | None:- """返回活跃 turn 下当前 agent 的聚合摘要。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- agent_spans = turn.get("agent_spans")- if not isinstance(agent_spans, dict):- return None- rec = agent_spans.get(_normalize_agent(role))- if not isinstance(rec, dict):- return None- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- return None- return json.loads(json.dumps(aggregate, ensure_ascii=False))---def _step_span_key(agent: str, message_id: str) -> str:- """为 step span 生成按 agent 与 message_id 唯一定位的 key。"""- return f"{agent}|{message_id}"---def upsert_step_span(- state_path: Path,- sid: str,- agent: str,- message_id: str,- carrier: dict[str, str],- *,- transcript_path: str | None = None,-) -> dict[str, str]:- """在当前 turn 下登记一个 step span carrier,并对 `(turn, agent, message_id)` 保持幂等。"""- now = time.time()- normalized_agent = str(agent or "main").strip() or "main"- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return {}-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- steps = current.setdefault("step_spans", {})- if not isinstance(steps, dict):- steps = {}- current["step_spans"] = steps- key = _step_span_key(normalized_agent, normalized_message_id)- existing = steps.get(key)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- steps[key] = {- "carrier": dict(carrier or {}),- "opened_at": now,- "agent": normalized_agent,- "message_id": normalized_message_id,- "transcript_path": transcript_path or "",- }- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(carrier or {})-- return update_state_locked(state_path, _update)---def upsert_step_span_atomic(- state_path: Path,- sid: str,- agent: str,- message_id: str,- *,- carrier_factory: Any,- transcript_path: str | None = None,-) -> dict[str, str]:- """在写锁内原子地获取或创建一个 step span carrier。-- `carrier_factory` 是一个无参可调用对象,用来生成 carrier 字典。- 只有在 span 还不存在时才会被调用,从而避免这样的 TOCTOU 竞争:- ``_generate_step_carrier`` 已经先产生了不可逆的 zhiyanllm span,- 但随后另一个 hook 进程已经写入同一 step,导致本次创建失去归属。- """- now = time.time()- normalized_agent = str(agent or "main").strip() or "main"- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return {}-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- steps = current.setdefault("step_spans", {})- if not isinstance(steps, dict):- steps = {}- current["step_spans"] = steps- key = _step_span_key(normalized_agent, normalized_message_id)- existing = steps.get(key)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- steps[key] = {- "carrier": dict(new_carrier),- "opened_at": now,- "agent": normalized_agent,- "message_id": normalized_message_id,- "transcript_path": transcript_path or "",- }- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def get_step_span_carrier(state_path: Path, sid: str, agent: str, message_id: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 step span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- steps = turn.get("step_spans")- if not isinstance(steps, dict):- return None- key = _step_span_key(str(agent or "main").strip() or "main", str(message_id or "").strip())- rec = steps.get(key)- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None--def get_latest_session_id(state: dict[str, Any]) -> str | None:"""返回 state 中最近启动的 session id。"""latest_sid: str | None = None@@ -1061,38 +454,6 @@ def get_last_cumulative_usage(return {}-def get_last_llm_offset(- state: dict,- sid: str,- transcript_path: str | None = None,-) -> int:- """获取最近一次处理到的 LLM source_offset,用于增量构建 I/O。"""- sess = state.get(sid)- if not isinstance(sess, dict):- return 0- scope = _get_transcript_scope(sess, transcript_path)- if isinstance(scope, dict):- v = scope.get("last_llm_offset")- if isinstance(v, (int, float)):- return int(v)- return 0---def set_last_llm_offset(- state: dict,- sid: str,- offset: int,- transcript_path: str | None = None,-) -> None:- """持久化某个 transcript 最近处理到的 LLM source_offset。"""- sess = state.get(sid)- if not isinstance(sess, dict):- return- scope = _get_transcript_scope(sess, transcript_path, create=True)- if isinstance(scope, dict):- scope["last_llm_offset"] = int(offset or 0)--def set_last_cumulative_usage(state: dict,sid: str,diff --git a/local/.codebuddy/skills/agent-observability/scripts/run_hook.sh b/local/.codebuddy/skills/agent-observability/scripts/run_hook.shindex d476810f..e73e814a 100755--- a/local/.codebuddy/skills/agent-observability/scripts/run_hook.sh+++ b/local/.codebuddy/skills/agent-observability/scripts/run_hook.sh@@ -2,15 +2,6 @@set -euPROJECT_DIR="${CODEBUDDY_PROJECT_DIR:-$(cd "$(dirname "$0")"/../../../.. && pwd -P)}"-PYTHON_BIN="$PROJECT_DIR/.venv/bin/python"MAIN_PY="$PROJECT_DIR/.codebuddy/skills/agent-observability/scripts/main.py"-# 只有当 .venv 里可用 zhiyanllm 时才优先使用该解释器;-# 否则回退到已安装 zhiyanllm 的系统 python3。-if [ -x "$PYTHON_BIN" ]; then- if "$PYTHON_BIN" -c "import zhiyanllm" 2>/dev/null; then- exec "$PYTHON_BIN" "$MAIN_PY" "$@"- fi-fi-exec python3 "$MAIN_PY" "$@"diff --git a/local/.codebuddy/skills/agent-observability/tests/test_build_dashboard_data.py b/local/.codebuddy/skills/agent-observability/tests/test_build_dashboard_data.pyindex 6ee93f75..00127338 100644--- a/local/.codebuddy/skills/agent-observability/tests/test_build_dashboard_data.py+++ b/local/.codebuddy/skills/agent-observability/tests/test_build_dashboard_data.py@@ -285,8 +285,7 @@ class TopSlowTests(unittest.TestCase):class BuildDailyAndSessionsTurnAttributionTests(unittest.TestCase):- """真实场景复现过:AgentLens(写 state.current_turn 的那套 tracing)关闭时,- tool/usage 事件自己的 turn_id 永远是 None,只有 user_prompt_submit 事件带真实+ """真实场景复现过:tool/usage 事件自己的 turn_id 永远是 None,只有 user_prompt_submit 事件带真实turn_id。修复前所有没有 turn_id 的事件会被塌缩进同一个 "?" 占位桶,看起来像"整个会话只有 1 个 turn",哪怕实际发了好几轮 prompt。"""diff --git a/local/.codebuddy/skills/agent-observability/tests/test_collector.py b/local/.codebuddy/skills/agent-observability/tests/test_collector.pyindex 05547f06..b70f127d 100644--- a/local/.codebuddy/skills/agent-observability/tests/test_collector.py+++ b/local/.codebuddy/skills/agent-observability/tests/test_collector.py@@ -12,7 +12,7 @@ SCRIPTS = ROOT / "scripts"if str(SCRIPTS) not in sys.path:sys.path.insert(0, str(SCRIPTS))-from core import agent_identity, agentlens, collector, emitter, runtime, state as st # type: ignore+from core import agent_identity, collector, emitter, runtime, state as st # type: ignoreclass CollectorTests(unittest.TestCase):@@ -550,24 +550,16 @@ class CollectorTests(unittest.TestCase):encoding="utf-8",)- emitted_calls: list[dict[str, object]] = []- original_emit_post_step = agentlens.emit_post_step- try:- agentlens.emit_post_step = lambda **kwargs: emitted_calls.append(kwargs)- runtime.flush_pending_tool_events(- state_path=state_path,- log_path=log_path,- sid=sid,- )- finally:- agentlens.emit_post_step = original_emit_post_step+ runtime.flush_pending_tool_events(+ state_path=state_path,+ log_path=log_path,+ sid=sid,+ )self.assertEqual(st.get_pending_tool_emits(state_path, sid), [])lines = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()]self.assertEqual(len(lines), 1)self.assertEqual(lines[0]["message_id"], "msg-later")- self.assertEqual(len(emitted_calls), 1)- self.assertEqual(emitted_calls[0]["tool_event"]["message_id"], "msg-later")def test_related_transcript_paths_include_subagents(self):with tempfile.TemporaryDirectory() as td:@@ -683,33 +675,6 @@ class CollectorTests(unittest.TestCase):self.assertEqual(skills_usage.get("pdf", {}).get("count"), 1)self.assertEqual(rules_usage.get("security", {}).get("count"), 1)- def test_step_span_registry_is_idempotent(self):- with tempfile.TemporaryDirectory() as td:- state_path = Path(td) / ".state.json"- sid = "s-step"- carrier = {"traceparent": "00-" + ("1" * 32) + "-" + ("2" * 16) + "-01"}- st.begin_turn(state_path, sid, "turn-1", carrier)-- first = st.upsert_step_span(- state_path,- sid,- "main",- "msg-001",- {"traceparent": "00-" + ("1" * 32) + "-" + ("3" * 16) + "-01"},- transcript_path="/tmp/demo.jsonl",- )- second = st.upsert_step_span(- state_path,- sid,- "main",- "msg-001",- {"traceparent": "00-" + ("1" * 32) + "-" + ("4" * 16) + "-01"},- transcript_path="/tmp/demo.jsonl",- )-- self.assertEqual(first, second)- self.assertEqual(st.get_step_span_carrier(state_path, sid, "main", "msg-001"), first)-if __name__ == "__main__":unittest.main()diff --git a/local/.codebuddy/skills/agent-observability/tests/test_runtime_flow.py b/local/.codebuddy/skills/agent-observability/tests/test_runtime_flow.pyindex 7bd143ba..2931ffed 100644--- a/local/.codebuddy/skills/agent-observability/tests/test_runtime_flow.py+++ b/local/.codebuddy/skills/agent-observability/tests/test_runtime_flow.py@@ -49,15 +49,13 @@ class RuntimeFlowTests(unittest.TestCase):mock.patch.object(runtime.collector, "cache_inventory"), \mock.patch.object(runtime.collector, "record_tool_usage", return_value=([], [])), \mock.patch.object(runtime.agent_identity, "resolve_active_agent_for_event", return_value=("main", None)), \- mock.patch.object(runtime, "current_turn_id", return_value="turn-1"), \mock.patch.object(runtime.collector, "extract_tool_call_id", return_value=None), \mock.patch.object(runtime, "flush_pending_tool_events"), \mock.patch.object(runtime.collector, "find_current_tool_context", return_value=None), \mock.patch.object(runtime.collector, "related_transcript_paths", return_value=["/tmp/demo.jsonl"]), \mock.patch.object(runtime, "emit_transcript_events", return_value=[]), \mock.patch.object(runtime.collector, "find_fallback_usage_event", return_value=None), \- mock.patch.object(runtime.st, "append_pending_tool_emit"), \- mock.patch.object(runtime.agentlens, "emit_post_step"):+ mock.patch.object(runtime.st, "append_pending_tool_emit"):mock_paths.return_value = runtime.RuntimePaths(base_dir=Path(td),state_path=Path(td) / ".state.json",diff --git a/local/.cursor/skills/agent-observability/SKILL.md b/local/.cursor/skills/agent-observability/SKILL.mdindex 8bff9f0c..5f980a68 100644--- a/local/.cursor/skills/agent-observability/SKILL.md+++ b/local/.cursor/skills/agent-observability/SKILL.md@@ -1,6 +1,6 @@---name: agent-observability-description: Add or maintain CodeBuddy hook observability for projects that need local metrics for tool latency, transcript token usage, session cost, and multi-agent trace attribution. Use when wiring hook-based telemetry, debugging missing usage events, and validating AgentLens state.+description: Add or maintain CodeBuddy hook observability for projects that need local metrics for tool latency, transcript token usage, session cost, and multi-agent trace attribution. Use when wiring hook-based telemetry, and debugging missing usage events.---## Workflow@@ -8,7 +8,7 @@ description: Add or maintain CodeBuddy hook observability for projects that need1. Merge `templates/settings-hook.json` into the user or project `settings.json`.2. Keep hook entries command-only and keep timeouts around 5 to 10 seconds.3. Run a normal CodeBuddy session and inspect `logs/metrics.ndjson`.-4. Inspect `logs/.state.json` when usage replay, offsets, or AgentLens turn state look wrong.+4. Inspect `logs/.state.json` when usage replay or offsets look wrong.5. Keep the runtime generic and verify output from `metrics.ndjson` and `.state.json`.## Read Next@@ -20,8 +20,7 @@ description: Add or maintain CodeBuddy hook observability for projects that need- `scripts/main.py`: hook entrypoint for `session-start`, `user-prompt-submit`, `pre`, `post`, and `stop`- `scripts/run_hook.sh`: stable shell wrapper for CodeBuddy hook commands- `scripts/core/collector.py`: transcript parsing, pre/post pairing, and session usage recording-- `scripts/core/agentlens.py`: AgentLens trace emission and agent or step grouping-- `scripts/core/state.py`: persisted hook state, offsets, and AgentLens sidecar state+- `scripts/core/state.py`: persisted hook state, offsets, and pending tool events- `scripts/core/devflow.py`: optional devflow-awareness — detects a `multi-agents-devflow-*` team, reads `workflow-state.json`, and emits `stage_transition` events. No-ops entirely on non-devflow projects.- `templates/settings-hook.json`: hook wiring templatediff --git a/local/.cursor/skills/agent-observability/references/quickstart.md b/local/.cursor/skills/agent-observability/references/quickstart.mdindex 7a30ef68..de2fae37 100644--- a/local/.cursor/skills/agent-observability/references/quickstart.md+++ b/local/.cursor/skills/agent-observability/references/quickstart.md@@ -129,7 +129,6 @@ PY- 没有日志:检查 hook 命令路径。- `ms` 为空:通常是 pre/post 未配对。- 没有 `usage`:`transcript_path` 缺失、tail 无 usage,或增量已去重。-- AgentLens 未启用:检查 `.state.json` 的 `_agentlens.enabled` / `last_error`。### 已知问题(未修复)diff --git a/local/.cursor/skills/agent-observability/references/schema-v2.md b/local/.cursor/skills/agent-observability/references/schema-v2.mdindex a04d4d09..034b50c7 100644--- a/local/.cursor/skills/agent-observability/references/schema-v2.md+++ b/local/.cursor/skills/agent-observability/references/schema-v2.md@@ -32,7 +32,7 @@ devflow 项目完全不受影响:| event | 实际顶层字段 | 说明 ||---|---|---|| `start` | `event`, `sid`, `agent`, `ts` | 会话开始 |-| `user_prompt_submit` | `event`, `sid`, `agent`, `turn_id`, `prompt_len`, `ts` | 新 turn 边界;AgentLens 侧按 `1 Trace = 1 Turn` 生成 trace |+| `user_prompt_submit` | `event`, `sid`, `agent`, `turn_id`, `prompt_len`, `ts` | 新 turn 边界;之后没有自带 `turn_id` 的事件归入该 turn || `tool` | `event`, `sid`, `agent`, `tool`, `ms`, `transcript_path`, `turn_id`, `ts`, `skill`, `rule`, `cwd`, `call_id`, `message_id`, `tool_details`, `task_slug`?, `stage`?, `pt_id`? | 工具调用与耗时 || `usage` | `event`, `sid`, `agent`, `tool`, `tokens`, `model`, `transcript_path`, `source_offset`, `turn_id`, `message_id`, `ts`, `task_slug`?, `stage`? | transcript 增量 token / 模型 / 消息归属 || `stop` | `event`, `sid`, `agent`, `tokens`, `model`, `transcript_path`, `source_offset`, `turn_id`, `message_id`, `ts`, `task_slug`?, `stage`? | 会话尾部 flush |@@ -254,18 +254,6 @@ devflow 项目完全不受影响:}```-### AgentLens sidecar--`.state.json[sid]._agentlens` 只作为内部状态使用,核心字段:--- `enabled`: AgentLens 上报是否可用-- `last_error`: 最近一次降级原因-- `current_turn.carrier.traceparent`: 当前 turn 的 trace context-- `current_turn.subagent_spans`: 同一 turn 下的子 agent span carrier-- `current_turn.agent_spans`: 同一 turn 下按 agent 聚合的 span carrier 与累计统计-- `current_turn.step_spans`: `(agent, message_id)` 级 step span registry-- `turn_history`: 已结束 turn 的摘要-### Hook 接入参考 `templates/settings-hook.json`,必须启用:diff --git a/local/.cursor/skills/agent-observability/scripts/build_dashboard_data.py b/local/.cursor/skills/agent-observability/scripts/build_dashboard_data.pyindex 4c639f1a..ec5f234b 100644--- a/local/.cursor/skills/agent-observability/scripts/build_dashboard_data.py+++ b/local/.cursor/skills/agent-observability/scripts/build_dashboard_data.py@@ -126,9 +126,8 @@ def build_daily_and_sessions(events: list[dict[str, Any]]) -> tuple[list[dict[stby_day: dict[str, dict[str, Any]] = {}by_sid: dict[str, dict[str, Any]] = {}by_sid_turn: dict[tuple[str, str], dict[str, Any]] = {}- # AgentLens(写 state.current_turn 的那套 tracing)默认关闭时,tool/usage 事件- # 自身的 turn_id 永远是 None——但 user_prompt_submit 事件不依赖 AgentLens,- # 始终携带真实 turn_id(见 emitter.build_prompt_submit_event)。按 ts 排序后,+ # tool/usage 事件自身不带 turn_id,只有 user_prompt_submit 事件+ # 携带真实 turn_id(见 emitter.build_prompt_submit_event)。按 ts 排序后,# 把它当作 turn 边界,让后续没有自带 turn_id 的 tool/usage 事件归入"当前 sid# 最近一次打开的 turn",而不是全部塌缩进同一个 "?" 占位桶。current_turn_by_sid: dict[str, str] = {}diff --git a/local/.cursor/skills/agent-observability/scripts/core/__init__.py b/local/.cursor/skills/agent-observability/scripts/core/__init__.pyindex 1d6ad5e9..a45607b6 100644--- a/local/.cursor/skills/agent-observability/scripts/core/__init__.py+++ b/local/.cursor/skills/agent-observability/scripts/core/__init__.py@@ -4,5 +4,4 @@- 采集与 transcript 解析- 状态读写与去重- skill/rule 扫描-- AgentLens trace 镜像"""diff --git a/local/.cursor/skills/agent-observability/scripts/core/agentlens/__init__.py b/local/.cursor/skills/agent-observability/scripts/core/agentlens/__init__.pydeleted file mode 100644index 2fea21d6..00000000--- a/local/.cursor/skills/agent-observability/scripts/core/agentlens/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""可选的 AgentLens sink,用于实时镜像 trace。"""-from .runtime import emit_post_step, emit_session_start, emit_session_stop, emit_turn_start--__all__ = [- "emit_post_step",- "emit_session_start",- "emit_session_stop",- "emit_turn_start",-]diff --git a/local/.cursor/skills/agent-observability/scripts/core/agentlens/bootstrap.py b/local/.cursor/skills/agent-observability/scripts/core/agentlens/bootstrap.pydeleted file mode 100644index d6fc970e..00000000--- a/local/.cursor/skills/agent-observability/scripts/core/agentlens/bootstrap.py+++ /dev/null@@ -1,229 +0,0 @@-from __future__ import annotations-"""AgentLens 启动辅助层。--这一层负责“读入与初始化”:-- 解析项目配置与环境变量-- 延迟加载可选的 zhiyan 运行时-- 缓存初始化结果,避免重复 init-- 处理调试落盘与失败状态写回-"""--import getpass-import json-import os-from dataclasses import dataclass-from pathlib import Path-from typing import Any--from .. import state as st--DEFAULT_APP_NAME = "skillhub.codebuddy-hooks"-DEFAULT_BUSINESS_SCENARIO = "codebuddy-hook"--_RUNTIME: dict[str, Any] | None = None-_INIT_SIGNATURE: tuple[str, str, str] | None = None---@dataclass(frozen=True)-class AgentLensConfig:- """从环境变量与 env 文件归一化得到的 AgentLens 配置。"""- endpoint: str | None- api_key: str | None- app_name: str- business_scenario: str- user: str-- @property- def enabled(self) -> bool:- return bool(self.endpoint and self.api_key)---def project_root(cwd: str | None = None) -> Path:- """解析用于查找 `.env` 的项目根目录。"""- if cwd:- return Path(cwd).expanduser().resolve()- env_cwd = str(os.environ.get("CODEBUDDY_PROJECT_DIR") or "").strip()- if env_cwd:- return Path(env_cwd).expanduser().resolve()- return Path.cwd().resolve()---def read_env_file(path: Path) -> dict[str, str]:- """以轻量方式解析 shell 风格的 env 文件,不做 source。"""- values: dict[str, str] = {}- if not path.is_file():- return values- try:- lines = path.read_text("utf-8").splitlines()- except Exception:- return values-- for raw_line in lines:- line = raw_line.strip()- if not line or line.startswith("#"):- continue- if line.startswith("export "):- line = line[7:].strip()- if "=" not in line:- continue- key, value = line.split("=", 1)- key = key.strip()- value = value.strip()- if not key:- continue- if value and value[0] == value[-1] and value[0] in {"'", '"'}:- value = value[1:-1]- values[key] = value- return values---def load_config(project_root_path: Path) -> AgentLensConfig:- """按优先级加载配置:进程环境变量 > `.env.local` > `.env`。"""- env_file = read_env_file(project_root_path / ".env")- env_local_file = read_env_file(project_root_path / ".env.local")-- def _value(name: str, default: str | None = None) -> str | None:- env_value = os.environ.get(name)- if env_value is not None and str(env_value).strip():- return str(env_value).strip()- if name in env_local_file and str(env_local_file[name]).strip():- return str(env_local_file[name]).strip()- if name in env_file and str(env_file[name]).strip():- return str(env_file[name]).strip()- return default-- user = _value("ZHIYANLLM_USER")- if not user:- user = (- str(os.environ.get("USER") or "").strip()- or str(os.environ.get("USERNAME") or "").strip()- or getpass.getuser()- )-- return AgentLensConfig(- endpoint=_value("ZHIYANLLM_API_ENDPOINT"),- api_key=_value("ZHIYANLLM_API_KEY"),- app_name=_value("ZHIYANLLM_APP_NAME", DEFAULT_APP_NAME) or DEFAULT_APP_NAME,- business_scenario=_value("ZHIYANLLM_BUSINESS_SCENARIO", DEFAULT_BUSINESS_SCENARIO)- or DEFAULT_BUSINESS_SCENARIO,- user=user or "unknown",- )---def load_runtime() -> dict[str, Any] | None:- """延迟导入可选的 zhiyan 运行时组件。-- 即使本地没有安装 AgentLens 依赖,hook 主链路也必须继续工作,- 所以这里返回 ``None``,而不是把导入异常抛出去。- """- global _RUNTIME- if _RUNTIME is not None:- return _RUNTIME- try:- from zhiyanllm import Zhiyanllm- from zhiyanllm.opentelemetry.instrumentation.semconv_ai import (- SpanAttributes as ZhiyanSpanAttributes,- ZhiyanllmSpanKindValues,- )- from zhiyanllm.tracing.context_manager import get_tracer- from zhiyanllm.tracing.manual import track_llm_call, track_task_server_call- from zhiyanllm.tracing.tracing import TracerWrapper- from opentelemetry.context import attach as otel_attach, detach as otel_detach- except Exception:- _RUNTIME = None- return None-- _RUNTIME = {- "Zhiyanllm": Zhiyanllm,- "track_llm_call": track_llm_call,- "track_task_server_call": track_task_server_call,- "TracerWrapper": TracerWrapper,- "get_tracer": get_tracer,- "ZhiyanSpanAttributes": ZhiyanSpanAttributes,- "ZhiyanllmSpanKindValues": ZhiyanllmSpanKindValues,- "otel_attach": otel_attach,- "otel_detach": otel_detach,- }- return _RUNTIME---def ensure_initialized(config: AgentLensConfig) -> dict[str, Any] | None:- """仅当有效配置签名发生变化时才重新初始化 zhiyan。"""- global _INIT_SIGNATURE- if not config.enabled:- return None- runtime = load_runtime()- if runtime is None:- return None- signature = (str(config.endpoint), str(config.api_key), str(config.app_name))- if _INIT_SIGNATURE == signature:- return runtime- runtime["Zhiyanllm"].init(- app_name=str(config.app_name),- api_endpoint=str(config.endpoint),- api_key=str(config.api_key),- disable_batch=True,- )- _INIT_SIGNATURE = signature- return runtime---def project_root_from_state_path(state_path: Path) -> Path:- """尽力从 `logs/.state.json` 反推出项目根目录。"""- try:- current = state_path.resolve().parent- for parent in [current, *current.parents]:- if parent.name == ".codebuddy":- return parent.parent- return state_path.resolve().parents[4]- except Exception:- return Path.cwd().resolve()---def debug_enabled(state_path: Path) -> bool:- """判断是否要把 span 调试信息镜像写入 `agentlens-push-debug.ndjson`。"""- root = project_root_from_state_path(state_path)- env_file = read_env_file(root / ".env")- env_local_file = read_env_file(root / ".env.local")- raw = (- os.environ.get("AGENTLENS_PUSH_DEBUG")- or env_local_file.get("AGENTLENS_PUSH_DEBUG")- or env_file.get("AGENTLENS_PUSH_DEBUG")- or ""- )- return str(raw).strip().lower() in {"1", "true", "yes", "on"}---def debug_write_span(- state_path: Path | None,- sid: str | None,- payload: dict[str, Any],- *,- sanitizer,-) -> None:- """在开启 AgentLens 调试模式时追加写入清洗后的调试记录。"""- if state_path is None or not sid:- return- try:- if not debug_enabled(state_path):- return- debug_path = state_path.parent / "agentlens-push-debug.ndjson"- record = {"sid": sid, **sanitizer(payload)}- with debug_path.open("a", encoding="utf-8") as fp:- fp.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")- except Exception:- return---def set_failure(state_path: Path, sid: str, message: str) -> None:- """记录最近一次 AgentLens 失败,但不打断 hook 主流程。"""- st.update_agentlens_session(- state_path,- sid,- {"enabled": False, "last_error": str(message)},- )---def get_session_context(state_path: Path, sid: str) -> dict[str, Any]:- """从共享状态里读取 AgentLens sidecar 的 session payload。"""- return st.load_agentlens_session(state_path, sid)diff --git a/local/.cursor/skills/agent-observability/scripts/core/agentlens/normalize.py b/local/.cursor/skills/agent-observability/scripts/core/agentlens/normalize.pydeleted file mode 100644index 2b730f06..00000000--- a/local/.cursor/skills/agent-observability/scripts/core/agentlens/normalize.py+++ /dev/null@@ -1,323 +0,0 @@-from __future__ import annotations-"""AgentLens 负载清洗层。--这一层负责“清洗与整形”:-- 在发送或调试前把任意 payload 转成安全的 JSON 结构-- 把本地 token 结构归一化成类似 OpenAI 的 usage 结构-- 从 transcript 中重建轻量的 message / tool-call 上下文-"""--import json-import os-from pathlib import Path-from typing import Any--from .. import state as st-from .bootstrap import AgentLensConfig---def sanitize_payload(value: Any) -> Any:- """把任意 Python 值转换成适合调试/打点的 JSON 安全结构。"""- try:- return json.loads(json.dumps(value, ensure_ascii=False, default=str))- except Exception:- return str(value)---def association_properties(config: AgentLensConfig, sid: str, state_path: Path | None = None) -> dict[str, str]:- """构造 trace 级关联属性,并允许按 turn 覆盖业务场景。"""- scenario = config.business_scenario- if state_path:- try:- session_ctx = st.load_agentlens_session(state_path, sid)- turn_scenario = session_ctx.get("_turn_business_scenario")- if isinstance(turn_scenario, str) and turn_scenario.strip():- scenario = turn_scenario.strip()- except Exception:- pass- return {- "session_id": sid,- "business_scenario": scenario,- "user": config.user,- }---def to_openai_usage(tokens: dict[str, Any] | None) -> dict[str, int]:- """把本地 token 结构转换成 zhiyan 期望的 usage 形状。"""- if not isinstance(tokens, dict):- return {}-- def _int(v: Any) -> int:- try:- return int(v or 0)- except Exception:- return 0-- prompt = _int(tokens.get("input"))- completion = _int(tokens.get("output"))- if prompt <= 0 and completion <= 0:- return {}- return {"prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": prompt + completion}---def infer_vendor(model: str | None) -> str:- """根据模型名推断一个粗粒度的 provider/vendor 标签。"""- text = str(model or "").strip().lower()- if not text:- return "unknown"- if "gpt" in text or "openai" in text:- return "openai"- if "claude" in text or "anthropic" in text:- return "anthropic"- if "gemini" in text or "google" in text:- return "google"- if text.startswith("hy") or "hunyuan" in text:- return "tencent"- return text.split("/", 1)[0].split("-", 1)[0] or "unknown"---def extract_message_text(content: Any) -> str:- """把嵌套的 transcript message 内容压平成纯文本。"""- if content is None:- return ""- if isinstance(content, str):- return content- if isinstance(content, list):- parts: list[str] = []- for item in content:- if isinstance(item, dict):- txt = item.get("text")- if isinstance(txt, str):- parts.append(txt)- elif item.get("type") == "tool_use":- parts.append(f"[tool_use {item.get('name', '')}]")- elif item.get("type") == "tool_result":- parts.append(extract_message_text(item.get("content")))- else:- parts.append(str(item))- return "\n".join(p for p in parts if p)- if isinstance(content, dict):- return extract_message_text(content.get("text") or content.get("content"))- return str(content)---def find_message_id_in_record(obj: Any) -> str | None:- """在 transcript 记录里递归查找稳定的 message 标识。"""- message_id_keys = ("messageId", "responseId", "requestId")- if isinstance(obj, dict):- provider = obj.get("providerData")- if isinstance(provider, dict):- for key in message_id_keys:- value = provider.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- extra = obj.get("extra")- if isinstance(extra, dict):- for key in message_id_keys:- value = extra.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- for key in message_id_keys:- value = obj.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- for value in obj.values():- found = find_message_id_in_record(value)- if found:- return found- elif isinstance(obj, list):- for value in obj:- found = find_message_id_in_record(value)- if found:- return found- return None---def collect_tool_calls_for_message(transcript_path: str, message_id: str) -> list[dict[str, Any]]:- """为指定 assistant message 重建它挂载的 tool-call 摘要。"""- if not transcript_path or not message_id or not os.path.isfile(transcript_path):- return []- try:- with open(transcript_path, "rb") as fp:- blob = fp.read()- except Exception:- return []-- tool_calls: list[dict[str, Any]] = []- for raw_line in blob.splitlines(keepends=True):- if not raw_line.lstrip().startswith(b"{"):- continue- try:- rec = json.loads(raw_line.decode("utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(rec, dict):- continue- if str(rec.get("type") or "").strip().lower() != "function_call":- continue- rec_mid = find_message_id_in_record(rec)- if rec_mid != message_id:- continue- call_id = str(rec.get("callId") or "").strip()- name = str(rec.get("name") or "").strip()- arguments = rec.get("arguments")- entry: dict[str, Any] = {"id": call_id, "name": name}- if arguments is not None:- entry["arguments"] = arguments if isinstance(arguments, str) else json.dumps(arguments, ensure_ascii=False)- tool_calls.append(entry)- return tool_calls---def find_tool_usage_event(tool_event: dict[str, Any], usage_events: list[dict[str, Any]]) -> dict[str, Any] | None:- """从 usage 列表里挑出最可能属于当前 tool 事件的那一条。"""- tool_name = str(tool_event.get("tool") or "")- transcript_path = str(tool_event.get("transcript_path") or "")- agent = str(tool_event.get("agent") or "main")- for usage_event in usage_events:- if not isinstance(usage_event, dict):- continue- if str(usage_event.get("agent") or "main") != agent:- continue- if transcript_path and str(usage_event.get("transcript_path") or "") != transcript_path:- continue- if tool_name and str(usage_event.get("tool") or "") not in {tool_name, "model_request"}:- continue- if str(usage_event.get("message_id") or "").strip():- return usage_event- for usage_event in usage_events:- if not isinstance(usage_event, dict):- continue- if str(usage_event.get("agent") or "main") != agent:- continue- if transcript_path and str(usage_event.get("transcript_path") or "") != transcript_path:- continue- return usage_event- return None---def build_llm_io_from_transcript(- *,- transcript_path: str,- source_offset: int,- tokens: dict[str, Any] | None,- model: str | None,- start_offset: int = 0,- current_message_id: str | None = None,-) -> tuple[dict[str, Any], dict[str, Any], str]:- """从 transcript 历史中构造紧凑版的 LLM 输入/输出负载。"""- input_data: dict[str, Any] = {"model": str(model or "unknown"), "messages": []}- output_data: dict[str, Any] = {"choices": [], "usage": to_openai_usage(tokens)}- if not transcript_path or not os.path.isfile(transcript_path):- return input_data, output_data, ""- try:- with open(transcript_path, "rb") as fp:- fp.seek(0)- blob = fp.read(source_offset) if source_offset else fp.read()- except Exception:- return input_data, output_data, ""-- messages: list[dict[str, Any]] = []- system_prompts: list[str] = []- cursor = 0- last_asst_text: str | None = None-- def _truncate(text: str, limit: int = 4000) -> str:- if len(text) <= limit:- return text- return text[:limit] + "...(truncated)"-- for raw_line in blob.splitlines(keepends=True):- cursor += len(raw_line)- if not raw_line.lstrip().startswith(b"{"):- continue- try:- rec = json.loads(raw_line.decode("utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(rec, dict):- continue-- rec_type = str(rec.get("type") or "").strip().lower()- is_incremental = cursor > start_offset-- # 重建 prompt 上下文时要跳过“当前正在发出的 assistant message”,- # 否则同一段回复会同时出现在 input 和 output 两边。- if current_message_id and is_incremental:- rec_mid = find_message_id_in_record(rec)- if rec_mid == current_message_id:- if rec_type == "message" and rec.get("role") == "assistant":- text = extract_message_text(rec.get("content"))- if text:- last_asst_text = text- continue-- if rec_type == "message":- role = rec.get("role")- text = extract_message_text(rec.get("content"))- if not text:- continue- if role == "system":- system_prompts.append(text)- elif is_incremental:- if role == "user":- messages.append({"role": "user", "content": _truncate(text, 8000)})- last_asst_text = None- elif role == "assistant":- messages.append({"role": "assistant", "content": _truncate(text, 4000)})- last_asst_text = text- elif is_incremental:- # 把 function call / result 记录转换成 Chat Completions 风格的- # assistant/tool message,方便 tracing UI 按对话链路展示。- if rec_type == "function_call":- name = str(rec.get("name") or "").strip()- call_id = str(rec.get("callId") or "").strip()- arguments = rec.get("arguments", "")- if isinstance(arguments, dict):- arguments = json.dumps(arguments, ensure_ascii=False)- tool_call: dict[str, Any] = {"type": "function", "function": {"name": name}}- if name and arguments:- tool_call["function"]["arguments"] = _truncate(str(arguments), 2000)- if call_id:- tool_call["id"] = call_id- if (- messages- and messages[-1].get("role") == "assistant"- and "tool_calls" not in messages[-1]- and messages[-1].get("content")- ):- messages[-1]["tool_calls"] = [tool_call]- else:- msg: dict[str, Any] = {"role": "assistant", "content": ""}- msg["tool_calls"] = [tool_call]- messages.append(msg)- elif rec_type == "function_call_result":- call_id = str(rec.get("callId") or "").strip()- provider = rec.get("providerData", {})- result_content = ""- if isinstance(provider, dict):- tool_result = provider.get("toolResult", {})- if isinstance(tool_result, dict):- result_content = extract_message_text(tool_result.get("content"))- if not result_content:- output = rec.get("output")- result_content = str(output.get("text", "")) if isinstance(output, dict) else ""- tool_msg: dict[str, Any] = {"role": "tool", "content": _truncate(result_content, 2000)}- if call_id:- tool_msg["tool_call_id"] = call_id- messages.append(tool_msg)-- final_messages: list[dict[str, Any]] = []- for prompt in system_prompts[-2:]:- if prompt:- final_messages.append({"role": "system", "content": _truncate(prompt, 2000)})- final_messages.extend(messages)- input_data["messages"] = final_messages-- if last_asst_text is not None:- output_data["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": last_asst_text[:8000]},- }]-- return input_data, output_data, ""diff --git a/local/.cursor/skills/agent-observability/scripts/core/agentlens/runtime.py b/local/.cursor/skills/agent-observability/scripts/core/agentlens/runtime.pydeleted file mode 100644index 575f5077..00000000--- a/local/.cursor/skills/agent-observability/scripts/core/agentlens/runtime.py+++ /dev/null@@ -1,764 +0,0 @@-"""AgentLens 运行时编排层。--这一层保留对外暴露的 4 个入口:-- `emit_session_start`-- `emit_turn_start`-- `emit_post_step`-- `emit_session_stop`--它本身不负责底层清洗或 carrier 生成,而是把调用编排到-`bootstrap / normalize / tracing` 三层上。-"""-from __future__ import annotations--from pathlib import Path-from typing import Any--try:- from opentelemetry import trace as _otel_trace-except Exception: # pragma: no cover - 可选依赖缺失时优雅降级- _otel_trace = None--from .. import state as st-from .bootstrap import (- debug_write_span as _debug_write_span,- ensure_initialized as _ensure_initialized,- get_session_context as _get_session_context,- load_config,- project_root as _project_root,- set_failure as _set_failure,-)-from .normalize import (- association_properties as _association_properties,- build_llm_io_from_transcript as _build_llm_io_from_transcript,- find_tool_usage_event as _find_tool_usage_event,- infer_vendor as _infer_vendor,- sanitize_payload as _sanitize_payload,- to_openai_usage as _to_openai_usage,-)-from .tracing import (- annotate as _annotate,- emit_assistant_span as _emit_assistant_span,- emit_tool_span as _emit_tool_span,- generate_subagent_carrier as _generate_subagent_carrier,- generate_turn_carrier as _generate_turn_carrier,- resolve_agent_carrier as _resolve_agent_carrier,- resolve_step_carrier as _resolve_step_carrier,- set_agent_aggregate_on_span as _set_agent_aggregate_on_span,- span_context_ids as _span_context_ids,- traceparent_parts as _traceparent_parts,-)---def emit_session_start(- *,- state_path: Path,- sid: str,- cwd: str,- agent: str = "main",-) -> None:- """初始化 v2 版本的 `_agentlens` session payload。-- 在 turn-centric 模型下,这里**不再**生成 trace_id。- 它只负责记录 session 级元数据(如 `enabled`、`session_id`、`app_name`),- 并清理上一次运行遗留的 carrier / error 状态。- 真正的新 trace 会在第一次 `UserPromptSubmit` 时由 `emit_turn_start` 打开。- """- _ = agent- config = load_config(_project_root(cwd))- # 注意:这里不要清空 current_turn / turn_history。- # 同一个 sid 下 SessionStart 可能多次触发(例如 subagent 启动、IDE 刷新、- # workspace 切换)。如果这里清空,会把进行中的 turn 擦掉,后续 PostToolUse- # 会全部看到 no_active_turn,最终把这一轮观测链路打断。- base_updates: dict[str, Any] = {- "session_id": sid,- "app_name": config.app_name,- }- if not config.enabled:- base_updates["enabled"] = False- st.update_agentlens_session(- state_path,- sid,- base_updates,- clear_keys=["carrier", "last_error"],- )- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return- base_updates["enabled"] = True- st.update_agentlens_session(- state_path,- sid,- base_updates,- clear_keys=["carrier", "last_error"],- )- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_turn_start(- *,- state_path: Path,- sid: str,- cwd: str,- turn_id: str,- prompt_meta: dict[str, Any] | None = None,- business_scenario: str | None = None,-) -> None:- """打开一个新的 turn,生成新的 trace_id 并写入 `_agentlens.current_turn`。-- 这是当前实现里**唯一**允许生成新 trace_id 的地方。- `emit_post_step` / `emit_session_stop` 都不会重新造 carrier;- 找不到时只会优雅降级,不会私自开新链路。- """- _ = prompt_meta- config = load_config(_project_root(cwd))- if not config.enabled:- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return- # 先把 per-turn business scenario 写进 state,- # 这样 `_generate_turn_carrier -> _association_properties`- # 才能在生成 trace 时把这次 turn 的业务场景烘焙进去。- if business_scenario:- st.update_agentlens_session(- state_path,- sid,- {"enabled": True, "session_id": sid, "app_name": config.app_name, "_turn_business_scenario": business_scenario},- clear_keys=["last_error"],- )- else:- st.update_agentlens_session(- state_path,- sid,- {"enabled": True, "session_id": sid, "app_name": config.app_name},- clear_keys=["last_error", "_turn_business_scenario"],- )- carrier = _generate_turn_carrier(runtime, config=config, sid=sid, turn_id=turn_id, state_path=state_path)- st.begin_turn(state_path, sid, turn_id, carrier)- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_post_step(- *,- state_path: Path,- sid: str,- tool_event: dict[str, Any] | None,- usage_events: list[dict[str, Any]],-) -> None:- """发出扁平化的 LLM span,只保留最小 TASK 包装层来传播 carrier 上下文。-- 面向 turn 的 v2 约束:- - 活跃的 ``current_turn.carrier`` 是唯一的 trace 上下文来源。- - 如果不存在 ``current_turn``(例如 UserPromptSubmit hook 还没触发),- 这里只会记录 ``last_error`` 并返回,不会私自生成新的 trace_id。- - subagent(``active_agent != "main"``)会拿到当前 turn 下的- ``invoke_agent`` 子 span,后续 chat span 都挂到这个子 span 下,- 以保持因果链路连续。- """- if not isinstance(tool_event, dict) and not usage_events:- return-- cwd_hint = ""- if isinstance(tool_event, dict):- cwd_hint = str(tool_event.get("cwd") or "")- config = load_config(_project_root(cwd_hint))- if not config.enabled:- return-- session_ctx = _get_session_context(state_path, sid)- # 快路径:尊重 SessionStart 阶段已经写入的 enabled 标记。- if session_ctx.get("enabled") is False:- return-- current_turn = session_ctx.get("current_turn")- if not isinstance(current_turn, dict):- _set_failure(state_path, sid, "no_active_turn")- return- parent_carrier = current_turn.get("carrier")- if not isinstance(parent_carrier, dict) or not parent_carrier.get("traceparent"):- _set_failure(state_path, sid, "no_active_turn_carrier")- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return-- tool_name = str((tool_event or {}).get("tool") or "unknown_tool")- active_agent = str((tool_event or {}).get("agent") or "main")- transcript_path = str((tool_event or {}).get("transcript_path") or "")- skills = (tool_event or {}).get("skill") or []- rules = (tool_event or {}).get("rule") or []-- # 解析这次事件真正要用的 carrier。- # main agent 直接使用 turn 根 carrier;subagent 则使用按角色拆分的- # 子 span carrier,并在当前 turn 下做幂等注册。- carrier = dict(parent_carrier)- if active_agent and active_agent != "main":- existing = None- subs = current_turn.get("subagent_spans")- if isinstance(subs, dict):- rec = subs.get(active_agent)- if isinstance(rec, dict) and isinstance(rec.get("carrier"), dict):- existing = rec["carrier"]- if isinstance(existing, dict) and existing.get("traceparent"):- carrier = dict(existing)- else:- # 原子化的 get-or-create:只有确认 subagent span 不存在时,- # 才会在写锁内部调用 carrier_factory。- # 这样可以避免并发 hook 进程之间的 TOCTOU 竞争,产生孤儿- # invoke_agent.TASK span。- def _factory() -> dict[str, str]:- return _generate_subagent_carrier(- runtime, parent_carrier=parent_carrier, role=active_agent- )-- registered = st.upsert_subagent_span_atomic(- state_path, sid, active_agent, carrier_factory=_factory- )- if isinstance(registered, dict) and registered.get("traceparent"):- carrier = dict(registered)- runtime["Zhiyanllm"].set_association_properties(_association_properties(config, sid, state_path))- # 静默挂载 carrier 上下文(不额外创建 TASK span),让内部 span- # 继承正确的 trace_id / parent_id。- _ctx = runtime["TracerWrapper"].extract_context(carrier)- _token = runtime["otel_attach"](_ctx)- try:- preferred_tool_message_id = str((tool_event or {}).get("message_id") or "").strip() or None- _assistant_emitted_mids: set[str] = set()- pre_bumped_steps: set[tuple[str, str]] = set()- committed_steps: set[tuple[str, str]] = set()-- if isinstance(tool_event, dict):- if preferred_tool_message_id and st.get_step_span_carrier(- state_path, sid, active_agent, preferred_tool_message_id- ) is None:- pre_bumped_steps.add((active_agent, preferred_tool_message_id))- for usage_event in usage_events:- event_agent = str(usage_event.get("agent") or active_agent or "main")- event_message_id = str(usage_event.get("message_id") or "").strip() or None- if event_message_id:- step_key = (event_agent, event_message_id)- if (- step_key not in pre_bumped_steps- and st.get_step_span_carrier(state_path, sid, event_agent, event_message_id) is None- ):- pre_bumped_steps.add(step_key)- if not usage_events and isinstance(tool_event, dict):- tool_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=active_agent,- )- if preferred_tool_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=tool_parent_carrier,- agent=active_agent,- message_id=preferred_tool_message_id,- transcript_path=transcript_path,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- tool_parent_carrier = dict(step_carrier)- _emit_tool_span(- runtime,- carrier=tool_parent_carrier,- tool_name=tool_name,- active_agent=active_agent,- skills=skills,- rules=rules,- duration_ms=tool_event.get("ms") if isinstance(tool_event.get("ms"), (int, float)) else None,- tool_details=tool_event.get("tool_details") if isinstance(tool_event.get("tool_details"), dict) else None,- message_id=preferred_tool_message_id,- step_grouping="message_id" if preferred_tool_message_id else "fallback",- state_path=state_path,- sid=sid,- )- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- tool_event=tool_event,- )- if (- preferred_tool_message_id- and (active_agent, preferred_tool_message_id) in pre_bumped_steps- and (active_agent, preferred_tool_message_id) not in committed_steps- ):- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- step_created=True,- )- committed_steps.add((active_agent, preferred_tool_message_id))- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- return-- matched_usage = _find_tool_usage_event(tool_event, usage_events) if isinstance(tool_event, dict) else None- tool_message_id = preferred_tool_message_id or str((matched_usage or {}).get("message_id") or "").strip() or None- if isinstance(tool_event, dict):- # 先构造 assistant 预览,再打开 agent/step 父 span。- # 这样即便 transcript 重建失败,也不会留下空的分组 TASK。- _assistant_preview_content: str | None = None- _assistant_preview_transcript = transcript_path- _assistant_preview_model = ""- if tool_message_id:- for _ue in usage_events:- if str(_ue.get("message_id") or "").strip() != tool_message_id:- continue- _ue_transcript = str(_ue.get("transcript_path") or transcript_path)- _ue_offset = int(_ue.get("source_offset") or 0)- _, _llm_out_pre, _ = _build_llm_io_from_transcript(- transcript_path=_ue_transcript,- source_offset=_ue_offset,- tokens=_ue.get("tokens"),- model=str(_ue.get("model") or ""),- )- _pre_content = ""- if _llm_out_pre.get("choices"):- _pre_msg = _llm_out_pre["choices"][0].get("message") or {}- _pre_content = str(_pre_msg.get("content") or "")- if _pre_content and _pre_content.strip():- _assistant_preview_content = _pre_content- _assistant_preview_transcript = _ue_transcript- _assistant_preview_model = str(_ue.get("model") or "")- break-- tool_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=active_agent,- )- if tool_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=tool_parent_carrier,- agent=active_agent,- message_id=tool_message_id,- transcript_path=transcript_path,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- tool_parent_carrier = dict(step_carrier)- if _assistant_preview_content and tool_message_id:- _emit_assistant_span(- runtime,- carrier=tool_parent_carrier,- agent=active_agent,- message_id=tool_message_id,- assistant_text=_assistant_preview_content,- model=_assistant_preview_model,- transcript_path=_assistant_preview_transcript,- state_path=state_path,- sid=sid,- )- _assistant_emitted_mids.add(tool_message_id)-- _emit_tool_span(- runtime,- carrier=tool_parent_carrier,- tool_name=tool_name,- active_agent=active_agent,- skills=skills,- rules=rules,- duration_ms=tool_event.get("ms") if isinstance(tool_event.get("ms"), (int, float)) else None,- tool_details=tool_event.get("tool_details") if isinstance(tool_event.get("tool_details"), dict) else None,- message_id=tool_message_id,- step_grouping="message_id" if tool_message_id else "fallback",- state_path=state_path,- sid=sid,- )- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- tool_event=tool_event,- )- if tool_message_id and (active_agent, tool_message_id) in pre_bumped_steps:- step_key = (active_agent, tool_message_id)- if step_key not in committed_steps:- st.bump_agent_aggregate(- state_path,- sid,- active_agent,- step_created=True,- )- committed_steps.add(step_key)-- _prev_llm_offsets: dict[str, int] = {}- for usage_event in usage_events:- model = str(usage_event.get("model") or "")- ev_transcript = str(usage_event.get("transcript_path") or transcript_path)- ev_offset = int(usage_event.get("source_offset") or 0)- raw_tokens = usage_event.get("tokens") or {}- event_message_id = str(usage_event.get("message_id") or "").strip() or None- event_agent = str(usage_event.get("agent") or active_agent or "main")- start_offset = _prev_llm_offsets.get(ev_transcript) or st.get_last_llm_offset(- st.load_state(state_path), sid, ev_transcript- )- llm_input, llm_output, _turn_title = _build_llm_io_from_transcript(- transcript_path=ev_transcript,- source_offset=ev_offset,- start_offset=int(start_offset or 0),- current_message_id=event_message_id,- tokens=raw_tokens,- model=model or None,- )- _prev_llm_offsets[ev_transcript] = ev_offset- # 原子写回 state,供跨进程增量跟踪复用- def _update_llm_offset(state: dict[str, Any], _ev=ev_transcript, _off=ev_offset) -> None:- st.set_last_llm_offset(state, sid, _off, _ev)- st.update_state_locked(state_path, _update_llm_offset)- # --- 把 skill/rule/agent 作为独立消息标签注入 input_data ---- _meta_messages: list[dict[str, str]] = []- _ev_agent = str(usage_event.get("agent") or active_agent)- if _ev_agent and _ev_agent != "main":- _meta_messages.append({"role": "agent", "content": _ev_agent})- if skills:- _meta_messages.append({"role": "skill", "content": ", ".join(skills)})- if rules:- _meta_messages.append({"role": "rule", "content": ", ".join(rules)})- if _meta_messages:- llm_input.setdefault("messages", [])- for msg in reversed(_meta_messages):- llm_input["messages"].insert(0, msg)- # --- 构造 usage ---- llm_output["usage"] = _to_openai_usage(raw_tokens)- # --- 只附带成本细节来构造 output 内容 ---- _cost_info = {- "input_tokens": raw_tokens.get("input"),- "output_tokens": raw_tokens.get("output"),- "cache_read": raw_tokens.get("cache_read"),- "cache_creation": raw_tokens.get("cache_creation"),- "total_tokens": raw_tokens.get("total"),- "cost_usd": usage_event.get("cost_usd"),- }- _cost_info = {k: v for k, v in _cost_info.items() if v is not None}- _existing_content = ""- if llm_output.get("choices"):- _msg = llm_output["choices"][0].get("message") or {}- _existing_content = str(_msg.get("content") or "")- _output_content = _existing_content- if _cost_info:- _cost_line = " | ".join(f"{k}: {v}" for k, v in _cost_info.items())- _output_content = f"[{_cost_line}]\n{_existing_content}" if _existing_content else f"[{_cost_line}]"- llm_output["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": _output_content},- }]- event_parent_carrier = carrier- if event_message_id:- event_parent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=event_agent,- )- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- transcript_path=ev_transcript,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- event_parent_carrier = dict(step_carrier)- ev_ctx = runtime["TracerWrapper"].extract_context(event_parent_carrier)- ev_token = runtime["otel_attach"](ev_ctx)- # 先累计聚合值,再发 LLM span,这样 span 上带的是最新累计属性。- st.bump_agent_aggregate(- state_path,- sid,- event_agent,- usage_event=usage_event,- )- _current_agg = st.get_subagent_aggregate(state_path, sid, event_agent)- try:- with runtime["track_llm_call"](_infer_vendor(model), "model_request") as llm_span:- # track_llm_call 已经设置了 gen_ai.span.kind/system/operation.name。- # 下方 _annotate 会通过 handle_llm_response 设置 gen_ai.usage.*。- # LLMSpan 包装层没有 set_attribute,所以这里改用原生 span 写 ID。- _native_span = _otel_trace.get_current_span()- _set_agent_aggregate_on_span(_native_span, _current_agg)- span_ids = _span_context_ids(_native_span)- parent_parts = _traceparent_parts(event_parent_carrier)- _debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "llm",- "span_name": "model_request",- "model": model,- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- "agent": event_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": ev_transcript,- "source_offset": ev_offset,- },- sanitizer=_sanitize_payload,- )- _annotate(- runtime,- span=llm_span,- input_data=llm_input,- output_data=llm_output,- tags={- "cost_usd": str(usage_event.get("cost_usd") or "-"),- "input_tokens": str(raw_tokens.get("input", "-")),- "output_tokens": str(raw_tokens.get("output", "-")),- "cache_read": str(raw_tokens.get("cache_read", "-")),- "cache_creation": str(raw_tokens.get("cache_creation", "-")),- "total_tokens": str(raw_tokens.get("total", "-")),- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- },- )- finally:- runtime["otel_detach"](ev_token)- if event_message_id and (event_agent, event_message_id) in pre_bumped_steps:- step_key = (event_agent, event_message_id)- if step_key not in committed_steps:- st.bump_agent_aggregate(- state_path,- sid,- event_agent,- step_created=True,- )- committed_steps.add(step_key)- if _existing_content and _existing_content.strip() and event_message_id not in _assistant_emitted_mids:- _emit_assistant_span(- runtime,- carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- assistant_text=_existing_content,- model=model,- transcript_path=ev_transcript,- state_path=state_path,- sid=sid,- )- finally:- runtime["otel_detach"](_token)- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- except Exception as exc:- _set_failure(state_path, sid, str(exc))---def emit_session_stop(- *,- state_path: Path,- sid: str,- cwd: str,- active_agent: str,- transcript_path: str,- stop_events: list[dict[str, Any]],-) -> None:- """在 session stop 阶段发出扁平化 LLM span,只保留最小 TASK 包装层传播上下文。"""- config = load_config(_project_root(cwd))- if not config.enabled:- return-- session_ctx = _get_session_context(state_path, sid)- if session_ctx.get("enabled") is False:- return-- current_turn = session_ctx.get("current_turn")- if not isinstance(current_turn, dict):- _set_failure(state_path, sid, "no_active_turn")- return- carrier = current_turn.get("carrier")- if not isinstance(carrier, dict) or not carrier.get("traceparent"):- _set_failure(state_path, sid, "no_active_turn_carrier")- return-- try:- runtime = _ensure_initialized(config)- if runtime is None:- _set_failure(state_path, sid, "zhiyanllm runtime unavailable")- return-- runtime["Zhiyanllm"].set_association_properties(_association_properties(config, sid, state_path))- if not stop_events:- return- # 静默挂载 carrier 上下文(不额外创建 TASK span)。- _ctx = runtime["TracerWrapper"].extract_context(carrier)- _token = runtime["otel_attach"](_ctx)- try:- _prev_stop_offsets: dict[str, int] = {}- for stop_event in stop_events:- model = str(stop_event.get("model") or "")- ev_transcript = str(stop_event.get("transcript_path") or transcript_path)- ev_offset = int(stop_event.get("source_offset") or 0)- raw_tokens = stop_event.get("tokens") or {}- event_message_id = str(stop_event.get("message_id") or "").strip() or None- event_agent = str(stop_event.get("agent") or active_agent or "main")- start_offset = _prev_stop_offsets.get(ev_transcript) or st.get_last_llm_offset(- st.load_state(state_path), sid, ev_transcript- )- llm_input, llm_output, _turn_title = _build_llm_io_from_transcript(- transcript_path=ev_transcript,- source_offset=ev_offset,- start_offset=int(start_offset or 0),- current_message_id=event_message_id,- tokens=raw_tokens,- model=model or None,- )- _prev_stop_offsets[ev_transcript] = ev_offset- # 原子写回 state,供跨进程增量跟踪复用- def _update_llm_offset_stop(state: dict[str, Any], _ev=ev_transcript, _off=ev_offset) -> None:- st.set_last_llm_offset(state, sid, _off, _ev)- st.update_state_locked(state_path, _update_llm_offset_stop)- # --- 把 agent 作为独立消息标签注入 input_data ---- _ev_agent = str(stop_event.get("agent") or active_agent)- if _ev_agent and _ev_agent != "main":- llm_input.setdefault("messages", []).insert(0, {"role": "agent", "content": _ev_agent})- # --- 构造 usage ---- llm_output["usage"] = _to_openai_usage(raw_tokens)- # --- 构造带上下文和成本细节的 output 内容 ---- _cost_info = {- "input_tokens": raw_tokens.get("input"),- "output_tokens": raw_tokens.get("output"),- "cache_read": raw_tokens.get("cache_read"),- "cache_creation": raw_tokens.get("cache_creation"),- "total_tokens": raw_tokens.get("total"),- "cost_usd": stop_event.get("cost_usd"),- "cost_session_usd": stop_event.get("cost_session_usd"),- }- _cost_info = {k: v for k, v in _cost_info.items() if v is not None}- _existing_content = ""- if llm_output.get("choices"):- _msg = llm_output["choices"][0].get("message") or {}- _existing_content = str(_msg.get("content") or "")- _output_content = _existing_content- if _cost_info:- _cost_line = " | ".join(f"{k}: {v}" for k, v in _cost_info.items())- _output_content = f"[{_cost_line}]\n{_existing_content}" if _existing_content else f"[{_cost_line}]"- llm_output["choices"] = [{- "index": 0,- "finish_reason": "stop",- "message": {"role": "assistant", "content": _output_content},- }]- event_parent_carrier = carrier- # 先解析 agent carrier,让 step 挂在 agent 的 react_agent span 下,- # 而不是直接挂在 turn 根 span 下。- if event_agent and event_agent != "main":- agent_carrier = _resolve_agent_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=carrier,- agent=event_agent,- )- if isinstance(agent_carrier, dict) and agent_carrier.get("traceparent"):- event_parent_carrier = dict(agent_carrier)- if event_message_id:- step_carrier = _resolve_step_carrier(- state_path=state_path,- sid=sid,- runtime=runtime,- parent_carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- transcript_path=ev_transcript,- )- if isinstance(step_carrier, dict) and step_carrier.get("traceparent"):- event_parent_carrier = dict(step_carrier)- ev_ctx = runtime["TracerWrapper"].extract_context(event_parent_carrier)- ev_token = runtime["otel_attach"](ev_ctx)- # 这里不要再 bump,emit_post_step 已经累计过这条 usage_event。- # SessionStop 会为同一次调用补发一个重复的 LLM span,再累加就会双算。- # 因此这里只读取当前聚合值。- _current_agg = st.get_subagent_aggregate(state_path, sid, event_agent)- try:- with runtime["track_llm_call"](_infer_vendor(model), "model_request") as llm_span:- # track_llm_call 已经设置了 gen_ai.span.kind/system/operation.name。- # 下方 _annotate 会通过 handle_llm_response 设置 gen_ai.usage.*。- # LLMSpan 包装层没有 set_attribute,所以这里改用原生 span 写 ID。- _native_span = _otel_trace.get_current_span()- _set_agent_aggregate_on_span(_native_span, _current_agg)- span_ids = _span_context_ids(_native_span)- parent_parts = _traceparent_parts(event_parent_carrier)- _debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "llm",- "span_name": "model_request",- "model": model,- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- "agent": event_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": ev_transcript,- "source_offset": ev_offset,- },- sanitizer=_sanitize_payload,- )- _annotate(- runtime,- span=llm_span,- input_data=llm_input,- output_data=llm_output,- tags={- "cost_usd": str(stop_event.get("cost_usd") or "-"),- "cost_session_usd": str(stop_event.get("cost_session_usd") or "-"),- "input_tokens": str(raw_tokens.get("input", "-")),- "output_tokens": str(raw_tokens.get("output", "-")),- "cache_read": str(raw_tokens.get("cache_read", "-")),- "cache_creation": str(raw_tokens.get("cache_creation", "-")),- "total_tokens": str(raw_tokens.get("total", "-")),- "message_id": str(event_message_id or ""),- "step_grouping": "message_id" if event_message_id else "fallback",- },- )- finally:- runtime["otel_detach"](ev_token)- if _existing_content and _existing_content.strip():- _emit_assistant_span(- runtime,- carrier=event_parent_carrier,- agent=event_agent,- message_id=event_message_id,- assistant_text=_existing_content,- model=model,- transcript_path=ev_transcript,- state_path=state_path,- sid=sid,- )- finally:- runtime["otel_detach"](_token)- st.update_agentlens_session(state_path, sid, {"enabled": True}, clear_keys=["last_error"])- except Exception as exc:- _set_failure(state_path, sid, str(exc))diff --git a/local/.cursor/skills/agent-observability/scripts/core/agentlens/tracing.py b/local/.cursor/skills/agent-observability/scripts/core/agentlens/tracing.pydeleted file mode 100644index afb678ad..00000000--- a/local/.cursor/skills/agent-observability/scripts/core/agentlens/tracing.py+++ /dev/null@@ -1,504 +0,0 @@-from __future__ import annotations-"""AgentLens trace 拓扑层。--这一层负责“trace 结构本身”:-- 创建或派生 carrier-- 生成 agent / step / assistant / tool span-- 把后续聚合需要的 span 元数据写回 state-"""--import json-import secrets-from pathlib import Path-from typing import Any--from .. import state as st-from .bootstrap import AgentLensConfig, debug_write_span-from .normalize import association_properties, collect_tool_calls_for_message, sanitize_payload---def annotate(runtime: dict[str, Any], *, span: Any | None = None, input_data: Any = None, output_data: Any = None, tags: dict[str, Any] | None = None) -> None:- """在调用 zhiyan annotate 前,先统一清洗 payload。"""- _ = span- runtime["Zhiyanllm"].annotate(- input_data=sanitize_payload(input_data),- output_data=sanitize_payload(output_data),- tags=sanitize_payload(tags) if tags else None,- )---def traceparent_parts(carrier: dict[str, str] | None) -> dict[str, str]:- """把 W3C `traceparent` 拆成调试日志里常用的几个字段。"""- traceparent = str((carrier or {}).get("traceparent") or "").strip()- parts = traceparent.split("-")- if len(parts) >= 4:- return {- "traceparent": traceparent,- "trace_id": parts[1],- "span_id": parts[2],- "flags": parts[3],- }- return {"traceparent": traceparent}---def span_context_ids(span: Any) -> dict[str, str]:- """从 OTel span 对象中提取十六进制的 trace/span id。"""- try:- ctx = span.get_span_context()- return {- "trace_id": f"{int(ctx.trace_id):032x}",- "span_id": f"{int(ctx.span_id):016x}",- }- except Exception:- return {}---def ensure_traceparent(carrier: dict[str, str]) -> None:- """当上游没有成功注入时,补一个最小可用的 `traceparent`。"""- if str(carrier.get("traceparent") or "").strip():- return- trace_id = secrets.token_hex(16)- parent_id = secrets.token_hex(8)- carrier["traceparent"] = f"00-{trace_id}-{parent_id}-01"---def carrier_from_span(parent_carrier: dict[str, str], span: Any) -> dict[str, str]:- """基于父 carrier 和当前 span 生成一个仍在同一 trace 上的子 carrier。"""- try:- span_ctx = span.get_span_context()- trace_id = f"{int(span_ctx.trace_id):032x}"- span_id = f"{int(span_ctx.span_id):016x}"- except Exception:- return {}- parent_tp = str((parent_carrier or {}).get("traceparent") or "").strip()- flags = "01"- if parent_tp:- parts = parent_tp.split("-")- if len(parts) >= 4 and parts[3]:- flags = parts[3]- child_carrier: dict[str, str] = dict(parent_carrier or {})- child_carrier["traceparent"] = f"00-{trace_id}-{span_id}-{flags}"- return child_carrier---def carrier_from_task_span(parent_carrier: dict[str, str], task_span: Any) -> dict[str, str]:- """兼容包装过的 task span 和原始 OTel span 两种形态。"""- span = getattr(task_span, "_span", None)- if span is None and hasattr(task_span, "get_span_context"):- span = task_span- if span is None:- return {}- return carrier_from_span(parent_carrier, span)---def zhiyan_attr(runtime: dict[str, Any], name: str, fallback: str) -> str:- """防御式读取 zhiyan 语义约定常量。"""- return str(getattr(runtime.get("ZhiyanSpanAttributes"), name, fallback))---def generate_turn_carrier(- runtime: dict[str, Any],- *,- config: AgentLensConfig,- sid: str,- turn_id: str,- state_path: Path | None = None,-) -> dict[str, str]:- """为一个用户 turn 生成根 carrier。"""- from opentelemetry import trace-- carrier: dict[str, str] = {}- span = trace.get_tracer(__name__).start_span(f"turn.{sid}.{turn_id}")- try:- runtime["Zhiyanllm"].set_association_properties(association_properties(config, sid, state_path))- runtime["Zhiyanllm"].inject_context(carrier)- finally:- span.end()- ensure_traceparent(carrier)- return carrier---def generate_subagent_carrier(runtime: dict[str, Any], *, parent_carrier: dict[str, str], role: str) -> dict[str, str]:- """在当前 turn 下面创建 `invoke_agent` 子 carrier。"""- try:- with runtime["track_task_server_call"]("invoke_agent", carrier=parent_carrier) as task_span:- annotate(runtime, input_data={"agent": role}, output_data={"result": "dispatched"}, tags={"agent": role})- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def generate_step_carrier(- runtime: dict[str, Any],- *,- parent_carrier: dict[str, str],- agent: str,- message_id: str,- transcript_path: str,-) -> dict[str, str]:- """创建用于归并同一条 message 工作的 synthetic step span。"""- try:- with runtime["track_task_server_call"]("react_step", carrier=parent_carrier) as task_span:- annotate(- runtime,- input_data={"agent": agent, "message_id": message_id},- output_data={"result": "grouped"},- tags={"message_id": message_id, "agent": agent, "transcript_path": transcript_path or ""},- )- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def generate_agent_carrier(runtime: dict[str, Any], *, parent_carrier: dict[str, str], agent: str) -> dict[str, str]:- """在当前 turn 下创建稳定的 per-agent 聚合 span。"""- try:- with runtime["track_task_server_call"]("react_agent", carrier=parent_carrier) as task_span:- span = getattr(task_span, "_span", None)- if span is not None and hasattr(span, "set_attribute"):- span.set_attribute("agent.name", agent)- annotate(runtime, input_data={"agent": agent}, output_data={"agent": agent}, tags={"agent": agent})- child_carrier = carrier_from_task_span(parent_carrier, task_span)- if child_carrier:- return child_carrier- except Exception:- return {}- return {}---def resolve_agent_carrier(- *,- state_path: Path,- sid: str,- runtime: dict[str, Any],- parent_carrier: dict[str, str],- agent: str,-) -> dict[str, str]:- """从共享状态里获取或创建持久化的 agent 聚合 carrier。"""- normalized_agent = str(agent or "main").strip() or "main"- existing = st.get_agent_span_carrier(state_path, sid, normalized_agent)- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)-- def _factory() -> dict[str, str]:- return generate_agent_carrier(runtime, parent_carrier=parent_carrier, agent=normalized_agent)-- effective_carrier = st.upsert_agent_span_atomic(state_path, sid, normalized_agent, carrier_factory=_factory)- if not isinstance(effective_carrier, dict) or not effective_carrier.get("traceparent"):- return dict(parent_carrier)- agent_parts = traceparent_parts(effective_carrier)- parent_parts = traceparent_parts(parent_carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "agent",- "span_name": "react_agent",- "agent": normalized_agent,- "trace_id": agent_parts.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": agent_parts.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- return dict(effective_carrier)---def resolve_step_carrier(- *,- state_path: Path,- sid: str,- runtime: dict[str, Any],- parent_carrier: dict[str, str],- agent: str,- message_id: str | None,- transcript_path: str,-) -> dict[str, str] | None:- """获取或创建按 message 分组使用的 step carrier。"""- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return None- existing = st.get_step_span_carrier(state_path, sid, agent, normalized_message_id)- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)-- def _factory() -> dict[str, str]:- return generate_step_carrier(- runtime,- parent_carrier=parent_carrier,- agent=agent,- message_id=normalized_message_id,- transcript_path=transcript_path,- )-- effective_carrier = st.upsert_step_span_atomic(- state_path,- sid,- agent,- normalized_message_id,- carrier_factory=_factory,- transcript_path=transcript_path,- )- if not isinstance(effective_carrier, dict) or not effective_carrier.get("traceparent"):- return None- step_parts = traceparent_parts(effective_carrier)- parent_parts = traceparent_parts(parent_carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "step",- "span_name": "react_step",- "message_id": normalized_message_id,- "agent": agent,- "trace_id": step_parts.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": step_parts.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- "transcript_path": transcript_path or "",- },- sanitizer=sanitize_payload,- )- return dict(effective_carrier)---def set_agent_aggregate_on_span(span: Any, aggregate: dict[str, Any] | None) -> None:- """把 agent 的累计指标投影成当前 span 的属性。"""- if span is None or not hasattr(span, "set_attribute") or not isinstance(aggregate, dict):- return- tokens = aggregate.get("tokens") or {}- if isinstance(tokens, dict):- for key in ("input", "output", "cache_read", "cache_creation", "total"):- if key in tokens:- span.set_attribute(f"agent.cumulative_tokens.{key}", int(tokens.get(key) or 0))- for key in ("cost_usd", "tool_duration_ms", "llm_call_count", "tool_call_count", "step_count", "event_count"):- if key in aggregate:- try:- span.set_attribute(f"agent.cumulative.{key}", int(aggregate.get(key) or 0))- except (TypeError, ValueError):- span.set_attribute(f"agent.cumulative.{key}", str(aggregate.get(key)))---def emit_assistant_span(- runtime: dict[str, Any],- *,- carrier: dict[str, str],- agent: str,- message_id: str | None,- assistant_text: str,- model: str | None = None,- transcript_path: str | None = None,- state_path: Path | None = None,- sid: str | None = None,-) -> None:- """发出一个轻量 assistant span,并按需补上 tool calls。"""- if not assistant_text or not assistant_text.strip():- return- tool_calls: list[dict[str, Any]] = []- if message_id and transcript_path:- tool_calls = collect_tool_calls_for_message(transcript_path, message_id)- output_data: dict[str, Any] = {"role": "assistant", "content": assistant_text[:8000]}- if tool_calls:- output_data["tool_calls"] = tool_calls- ctx = runtime["TracerWrapper"].extract_context(carrier)- token = runtime["otel_attach"](ctx)- try:- with runtime["get_tracer"]() as tracer:- with tracer.start_as_current_span(name="assistant_message") as span:- span.set_attribute(runtime["ZhiyanSpanAttributes"].LLM_SPAN_KIND, runtime["ZhiyanllmSpanKindValues"].LLM.value)- span_ids = span_context_ids(span)- parent_parts = traceparent_parts(carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "assistant",- "span_name": "assistant_message",- "message_id": str(message_id or ""),- "agent": agent,- "model": str(model or ""),- "tool_call_count": len(tool_calls),- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- annotate(- runtime,- input_data={"agent": agent, "message_id": message_id or "", "model": model or ""},- output_data=output_data,- tags={"message_id": str(message_id or ""), "agent": agent},- )- finally:- runtime["otel_detach"](token)---def emit_tool_span(- runtime: dict[str, Any],- *,- carrier: dict[str, str],- tool_name: str,- active_agent: str,- skills: list[str],- rules: list[str],- duration_ms: int | None = None,- tool_details: dict[str, Any] | None = None,- message_id: str | None = None,- step_grouping: str = "fallback",- state_path: Path | None = None,- sid: str | None = None,-) -> None:- """发出 tool span,并以受控大小挂载 tool payload。"""- def _truncate(value: Any, limit: int = 1200) -> Any:- text = value if isinstance(value, str) else None- if text is None:- return value- if len(text) <= limit:- return text- return text[:limit] + "...(truncated)"-- def _maybe_parse_json_text(value: Any) -> Any:- if not isinstance(value, str):- return value- text = value.strip()- if not text or text[0] not in "{[":- return value- try:- return json.loads(text)- except Exception:- return value-- def _parse_bash_result_content(value: Any) -> dict[str, Any] | None:- if not isinstance(value, str) or "Command:" not in value:- return None- normalized_value = value.replace("\\n", "\n")- markers = [- ("Command:", "command"),- ("Stdout:", "stdout"),- ("Stderr:", "stderr"),- ("Exit Code:", "exit_code"),- ("Signal:", "signal"),- ]- parsed: dict[str, Any] = {}- for idx, (marker, key) in enumerate(markers):- start = normalized_value.find(marker)- if start < 0:- continue- start += len(marker)- end = len(normalized_value)- for next_marker, _ in markers[idx + 1:]:- pos = normalized_value.find(next_marker, start)- if pos >= 0:- end = min(end, pos)- segment = normalized_value[start:end].strip()- if not segment:- continue- parsed[key] = _truncate(segment, 1200 if key in {"command", "stdout", "stderr"} else 200)- return parsed or None-- tool_input: dict[str, Any] = {"tool": tool_name, "agent": active_agent}- if skills:- tool_input["skill"] = ", ".join(skills)- if rules:- tool_input["rule"] = ", ".join(rules)- if message_id:- tool_input["message_id"] = message_id- details = dict(tool_details or {})- call_id = str(details.get("call_id") or "").strip() or None- if call_id:- tool_input["call_id"] = call_id- arguments_display_text = details.get("arguments_display_text")- if arguments_display_text:- tool_input["arguments_display_text"] = _truncate(arguments_display_text, 600)- arguments = details.get("arguments")- if arguments:- parsed_arguments = _maybe_parse_json_text(arguments)- tool_input["arguments"] = _truncate(parsed_arguments, 1200)- if isinstance(parsed_arguments, dict):- if parsed_arguments.get("command"):- tool_input["command"] = _truncate(parsed_arguments.get("command"), 1200)- if parsed_arguments.get("description"):- tool_input["description"] = _truncate(parsed_arguments.get("description"), 400)-- tool_output: dict[str, Any] = {"result": "executed"}- result_content = details.get("result_content")- if result_content is not None:- structured_result = _parse_bash_result_content(result_content)- if structured_result:- tool_output["result"] = structured_result- else:- tool_output["result_content"] = _truncate(result_content, 1600)- output_text = details.get("output_text")- if output_text:- tool_output["output_text"] = _truncate(output_text, 1600)- raw_response = details.get("raw_response")- if isinstance(raw_response, dict):- tool_output["raw_response"] = {- "exitCode": raw_response.get("exitCode"),- "signal": raw_response.get("signal"),- "interrupted": raw_response.get("interrupted"),- "sandboxDenied": raw_response.get("sandboxDenied"),- "tool_error_code": raw_response.get("tool_error_code"),- }-- ctx = runtime["TracerWrapper"].extract_context(carrier)- token = runtime["otel_attach"](ctx)- try:- with runtime["get_tracer"]() as tracer:- with tracer.start_as_current_span(name=f"{tool_name}.TOOL") as span:- span_kind_value = runtime["ZhiyanllmSpanKindValues"].TOOL.value- span.set_attribute(zhiyan_attr(runtime, "LLM_SPAN_KIND", "gen_ai.span.kind"), span_kind_value)- span.set_attribute("gen_ai.span.kind", span_kind_value)- span.set_attribute(zhiyan_attr(runtime, "TOOL_NAME", "tool.name"), tool_name)- if isinstance(tool_details, dict):- desc = tool_details.get("description") or tool_details.get("tool_description")- if isinstance(desc, str) and desc.strip():- span.set_attribute(zhiyan_attr(runtime, "TOOL_DESCRIPTION", "tool.description"), desc.strip())- tool_params = tool_input.get("arguments")- if tool_params is not None:- if not isinstance(tool_params, str):- tool_params = json.dumps(tool_params, ensure_ascii=False, default=str)- span.set_attribute(zhiyan_attr(runtime, "TOOL_PARAMETERS", "tool.parameters"), tool_params)- if duration_ms is not None:- span.set_attribute("tool.duration_ms", int(duration_ms))- span_ids = span_context_ids(span)- parent_parts = traceparent_parts(carrier)- debug_write_span(- state_path,- sid,- {- "event": "span_emit",- "span_kind": "tool",- "span_name": f"{tool_name}.TOOL",- "tool": tool_name,- "message_id": str(message_id or ""),- "call_id": call_id or "",- "step_grouping": step_grouping,- "agent": active_agent,- "trace_id": span_ids.get("trace_id", parent_parts.get("trace_id", "")),- "span_id": span_ids.get("span_id", ""),- "parent_span_id": parent_parts.get("span_id", ""),- "parent_traceparent": parent_parts.get("traceparent", ""),- },- sanitizer=sanitize_payload,- )- annotate(- runtime,- input_data=tool_input,- output_data=tool_output,- tags={"step_grouping": step_grouping, "message_id": str(message_id or "")},- )- finally:- runtime["otel_detach"](token)diff --git a/local/.cursor/skills/agent-observability/scripts/core/cls_sink.py b/local/.cursor/skills/agent-observability/scripts/core/cls_sink.pyindex e2c72391..0b5ce0f6 100644--- a/local/.cursor/skills/agent-observability/scripts/core/cls_sink.py+++ b/local/.cursor/skills/agent-observability/scripts/core/cls_sink.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from .agentlens import bootstrap+from . import envfile@@ -278,9 +278,9 @@ def _int_value(def load_config(cwd: str | None = None) -> CLSConfig:- project_root = bootstrap.project_root(cwd)- env_file = bootstrap.read_env_file(project_root / ".env")- env_local = bootstrap.read_env_file(project_root / ".env.local")+ project_root = envfile.project_root(cwd)+ env_file = envfile.read_env_file(project_root / ".env")+ env_local = envfile.read_env_file(project_root / ".env.local")return CLSConfig(enabled=_enabled_flag(env_local=env_local, env_file=env_file),endpoint=_value(diff --git a/local/.cursor/skills/agent-observability/scripts/core/collector.py b/local/.cursor/skills/agent-observability/scripts/core/collector.pyindex cfd681b2..1986ae51 100644--- a/local/.cursor/skills/agent-observability/scripts/core/collector.py+++ b/local/.cursor/skills/agent-observability/scripts/core/collector.py@@ -811,7 +811,7 @@ def find_fallback_usage_event(tool_event: dict[str, Any],usage_events: list[dict[str, Any]],) -> dict[str, Any] | None:- """当找不到直接匹配的 tool usage 时,为 AgentLens 选一条兜底 usage。"""+ """当找不到直接匹配的 tool usage 时,选一条兜底 usage 补齐 message_id。"""tool_name = str(tool_event.get("tool") or "").strip()transcript_path = str(tool_event.get("transcript_path") or "").strip()agent = str(tool_event.get("agent") or "main").strip() or "main"diff --git a/local/.cursor/skills/agent-observability/scripts/core/emitter.py b/local/.cursor/skills/agent-observability/scripts/core/emitter.pyindex a41dfc05..cbbe295d 100644--- a/local/.cursor/skills/agent-observability/scripts/core/emitter.py+++ b/local/.cursor/skills/agent-observability/scripts/core/emitter.py@@ -260,7 +260,7 @@ def build_prompt_submit_event() -> dict[str, Any]:"""构造 `user_prompt_submit` 事件,作为 turn 边界标记。- 这条记录会落到 metrics.ndjson,方便下游把 turn 和 AgentLens trace 对上。+ 这条记录会落到 metrics.ndjson,下游据此划分 turn。"""record: dict[str, Any] = {"event": "user_prompt_submit",diff --git a/local/.cursor/skills/agent-observability/scripts/core/envfile.py b/local/.cursor/skills/agent-observability/scripts/core/envfile.pynew file mode 100644index 00000000..a7acf86e--- /dev/null+++ b/local/.cursor/skills/agent-observability/scripts/core/envfile.py@@ -0,0 +1,44 @@+from __future__ import annotations+"""项目 `.env` / `.env.local` 的轻量读取辅助。"""++import os+from pathlib import Path+++def project_root(cwd: str | None = None) -> Path:+ """解析用于查找 `.env` 的项目根目录。"""+ if cwd:+ return Path(cwd).expanduser().resolve()+ env_cwd = str(os.environ.get("CODEBUDDY_PROJECT_DIR") or "").strip()+ if env_cwd:+ return Path(env_cwd).expanduser().resolve()+ return Path.cwd().resolve()+++def read_env_file(path: Path) -> dict[str, str]:+ """以轻量方式解析 shell 风格的 env 文件,不做 source。"""+ values: dict[str, str] = {}+ if not path.is_file():+ return values+ try:+ lines = path.read_text("utf-8").splitlines()+ except Exception:+ return values++ for raw_line in lines:+ line = raw_line.strip()+ if not line or line.startswith("#"):+ continue+ if line.startswith("export "):+ line = line[7:].strip()+ if "=" not in line:+ continue+ key, value = line.split("=", 1)+ key = key.strip()+ value = value.strip()+ if not key:+ continue+ if value and value[0] == value[-1] and value[0] in {"'", '"'}:+ value = value[1:-1]+ values[key] = value+ return valuesdiff --git a/local/.cursor/skills/agent-observability/scripts/core/runtime.py b/local/.cursor/skills/agent-observability/scripts/core/runtime.pyindex 9c647bc0..a37a02a4 100644--- a/local/.cursor/skills/agent-observability/scripts/core/runtime.py+++ b/local/.cursor/skills/agent-observability/scripts/core/runtime.py@@ -4,18 +4,17 @@ from __future__ import annotations这一层负责把外部 hook phase 分发到内部能力:- session-start / user-prompt-submit / pre / post / stop- 组装统一运行时路径-- 串联 collector / emitter / agentlens,并承担 transcript 运行时编排+- 串联 collector / emitter,并承担 transcript 运行时编排"""import os-import reimport timeimport tracebackfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from . import agent_identity, agentlens, collector, devflow, emitter, scanner, state as st+from . import agent_identity, collector, devflow, emitter, scanner, state as st@dataclass(frozen=True)@@ -111,44 +110,8 @@ def prompt_text_length(data: dict[str, Any]) -> int | None:return None-def extract_prompt_text(data: dict[str, Any]) -> str:- """从 hook payload 中提取可读的 prompt 文本。"""- for key in ("prompt", "user_prompt", "message", "text"):- val = data.get(key)- if isinstance(val, str) and val.strip():- return val.strip()- if isinstance(val, list):- parts = []- for item in val:- if isinstance(item, dict):- txt = item.get("text")- if isinstance(txt, str):- parts.append(txt)- elif isinstance(item, str):- parts.append(item)- if parts:- return "\n".join(parts).strip()- return ""---def derive_business_scenario(prompt_text: str) -> str | None:- """从 prompt 文本中派生一个简短业务场景标识。"""- if not prompt_text:- return None-- m = re.search(r"标题[::]\s*(.+?)(?:\s*描述[::]|\s*$)", prompt_text, re.DOTALL)- if m:- title = m.group(1).strip()[:60]- else:- title = prompt_text[:50].strip()-- sanitized = re.sub(r"[^\w\u4e00-\u9fff\-]", "-", title)- sanitized = re.sub(r"-{2,}", "-", sanitized).strip("-")- return sanitized if sanitized else None--def handle_session_start(data: dict[str, Any]) -> None:- """处理 SessionStart:预热 inventory,写 start 事件,初始化 AgentLens。"""+ """处理 SessionStart:预热 inventory,写 start 事件。"""current_sid = session_id_of(data)if not current_sid:return@@ -157,33 +120,21 @@ def handle_session_start(data: dict[str, Any]) -> None:skills_meta, rules_meta = scanner.scan_skills_and_rules(cwd_value)collector.cache_inventory(paths.state_path, current_sid, skills_meta, rules_meta)emitter.emit(paths.log_path, emitter.build_start_event(sid=current_sid, agent="main"))- agentlens.emit_session_start(state_path=paths.state_path, sid=current_sid, cwd=cwd_value, agent="main")def handle_user_prompt_submit(data: dict[str, Any]) -> None:- """处理 UserPromptSubmit:建立 turn 边界,并打开 AgentLens turn。"""+ """处理 UserPromptSubmit:建立 turn 边界。"""current_sid = session_id_of(data)if not current_sid:returnpaths = build_runtime_paths()- cwd_value = cwd(data)turn_id = derive_turn_id(data)prompt_len = prompt_text_length(data)- prompt_text = extract_prompt_text(data)- business_scenario = derive_business_scenario(prompt_text)emitter.emit(paths.log_path,emitter.build_prompt_submit_event(sid=current_sid, turn_id=turn_id, agent="main", prompt_len=prompt_len),)- agentlens.emit_turn_start(- state_path=paths.state_path,- sid=current_sid,- cwd=cwd_value,- turn_id=turn_id,- prompt_meta={"prompt_len": prompt_len} if prompt_len is not None else None,- business_scenario=business_scenario,- )def handle_pre(data: dict[str, Any]) -> None:@@ -223,7 +174,7 @@ def handle_post(data: dict[str, Any]) -> None:tool_name = str(data.get("tool_name") or "")transcript_path = collector.transcript_path(data)- turn_id = current_turn_id(paths.state_path, current_sid)+ turn_id = Noneevent_ts = time.time()tool_call_id = collector.extract_tool_call_id(data)dv_ctx = resolve_devflow(paths.state_path, current_sid, cwd_value, paths.log_path)@@ -297,21 +248,9 @@ def handle_post(data: dict[str, Any]) -> None:if duplicate_tool_context:if not usage_events:return- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=None,- usage_events=usage_events,- )returnif str(tool_event.get("message_id") or "").strip():emitter.emit(paths.log_path, tool_event)- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=tool_event,- usage_events=usage_events,- )returnfallback_usage = collector.find_fallback_usage_event(tool_event, usage_events)@@ -319,19 +258,13 @@ def handle_post(data: dict[str, Any]) -> None:if fallback_usage_mid:tool_event["message_id"] = fallback_usage_midemitter.emit(paths.log_path, tool_event)- agentlens.emit_post_step(- state_path=paths.state_path,- sid=current_sid,- tool_event=tool_event,- usage_events=usage_events,- )returnst.append_pending_tool_emit(paths.state_path, current_sid, tool_event)def handle_stop(data: dict[str, Any]) -> None:- """处理 Stop:补发 transcript 事件、汇总 session 成本并关闭 AgentLens。"""+ """处理 Stop:补发 transcript 事件、汇总 session 成本。"""current_sid = session_id_of(data)if not current_sid:return@@ -344,11 +277,11 @@ def handle_stop(data: dict[str, Any]) -> None:data=data,)transcript_path = collector.transcript_path(data)- turn_id = current_turn_id(paths.state_path, current_sid)+ turn_id = Nonedv_ctx = resolve_devflow(paths.state_path, current_sid, cwd_value, paths.log_path)task_slug = str(dv_ctx.get("task_slug") or "").strip() if dv_ctx else Nonestage = str(dv_ctx.get("current_stage") or "").strip() if dv_ctx else None- stop_events = emit_transcript_events(+ emit_transcript_events(state_path=paths.state_path,log_path=paths.log_path,sid=current_sid,@@ -369,14 +302,6 @@ def handle_stop(data: dict[str, Any]) -> None:sid=current_sid,force_emit_fallback=True,)- agentlens.emit_session_stop(- state_path=paths.state_path,- sid=current_sid,- cwd=cwd_value,- active_agent=active_agent,- transcript_path=transcript_path,- stop_events=stop_events,- )def resolve_devflow(state_path: Path, sid: str, cwd_value: str, log_path: Path) -> dict[str, Any] | None:@@ -410,19 +335,6 @@ def resolve_devflow(state_path: Path, sid: str, cwd_value: str, log_path: Path)return dv_ctx-def current_turn_id(state_path: Path, sid: str) -> str | None:- """从 state 中读取当前 session 激活中的 turn id。"""- try:- turn = st.get_current_turn(state_path, sid)- except Exception:- turn = None- if isinstance(turn, dict):- raw = turn.get("turn_id")- if isinstance(raw, str) and raw.strip():- return raw.strip()- return None--def flush_pending_tool_events(*,state_path: Path,@@ -471,21 +383,9 @@ def flush_pending_tool_events(if isinstance(tool_details, dict) and tool_details:tool_event["tool_details"] = dict(tool_details)emitter.emit(log_path, tool_event)- agentlens.emit_post_step(- state_path=state_path,- sid=sid,- tool_event=tool_event,- usage_events=[],- )continueif force_emit_fallback:emitter.emit(log_path, tool_event)- agentlens.emit_post_step(- state_path=state_path,- sid=sid,- tool_event=tool_event,- usage_events=[],- )continueremaining.append(tool_event)diff --git a/local/.cursor/skills/agent-observability/scripts/core/state.py b/local/.cursor/skills/agent-observability/scripts/core/state.pyindex 5e7d33e9..4e192bd0 100644--- a/local/.cursor/skills/agent-observability/scripts/core/state.py+++ b/local/.cursor/skills/agent-observability/scripts/core/state.py@@ -4,7 +4,6 @@- session 级 skill/rule 使用统计- 当前 agent、派发关系与历史- transcript offset、去重 claim、pending emits-- AgentLens sidecar 状态"""from __future__ import annotations@@ -174,612 +173,6 @@ def set_devflow_state(state: dict[str, Any], sid: str, updates: dict[str, Any])dv.update(updates)-def get_agentlens_session(state: dict[str, Any], sid: str) -> dict[str, Any]:- """返回某个 session 的 AgentLens sidecar payload。"""- sess = ensure_session(state, sid)- payload = sess.setdefault("_agentlens", {})- if not isinstance(payload, dict):- payload = {}- sess["_agentlens"] = payload- return payload---AGENTLENS_SCHEMA_VERSION = 2-_TURN_HISTORY_MAX = 5---def _migrate_agentlens_v1_to_v2(payload: dict[str, Any], sess: dict[str, Any] | None) -> dict[str, Any]:- """把 v1 版 ``_agentlens`` payload 转成以 turn 为中心的 v2 布局。-- v1 布局(pre-turn):- {"carrier": {...}, "enabled": bool, "session_id": "...", "app_name": "..."}- v2 布局(turn-centric):- {- "version": 2,- "session_id": "...",- "enabled": bool,- "app_name": "...",- "current_turn": {"turn_id": "legacy", "started_at": ..., "carrier": {...}, "subagent_spans": {}, "agent_spans": {}, "step_spans": {}},- "turn_history": [],- }-- 幂等约束:如果已经带有 ``version``,就原样返回。- """- if not isinstance(payload, dict):- return {"version": AGENTLENS_SCHEMA_VERSION, "enabled": False, "current_turn": None, "turn_history": []}- if payload.get("version") == AGENTLENS_SCHEMA_VERSION:- payload.setdefault("current_turn", None)- payload.setdefault("turn_history", [])- current = payload.get("current_turn")- if isinstance(current, dict):- current.setdefault("subagent_spans", {})- current.setdefault("agent_spans", {})- current.setdefault("step_spans", {})- return payload-- migrated: dict[str, Any] = {- "version": AGENTLENS_SCHEMA_VERSION,- "session_id": payload.get("session_id"),- "enabled": bool(payload.get("enabled", False)),- }- if "app_name" in payload:- migrated["app_name"] = payload.get("app_name")- if "last_error" in payload:- migrated["last_error"] = payload.get("last_error")-- legacy_carrier = payload.get("carrier")- if isinstance(legacy_carrier, dict) and legacy_carrier:- started_at = None- if isinstance(sess, dict):- try:- started_at = float(sess.get("started_at") or 0) or None- except Exception:- started_at = None- migrated["current_turn"] = {- "turn_id": "legacy",- "started_at": started_at or time.time(),- "carrier": dict(legacy_carrier),- "subagent_spans": {},- "agent_spans": {},- "step_spans": {},- }- else:- migrated["current_turn"] = None- migrated["turn_history"] = []- return migrated---def load_agentlens_session(state_path: Path, sid: str) -> dict[str, Any]:- """加载某个 session 已持久化的 AgentLens sidecar payload。-- 这里使用共享读锁,避免并发 ``update_agentlens_session`` 写入时读到撕裂数据。- 返回值会透明地把 v1 payload 迁移成 v2 副本;真正落盘迁移会在下一次写入时完成。- """- with state_read_lock(state_path):- state = load_state(state_path)- sess = state.get(sid)- if not isinstance(sess, dict):- return {}- payload = sess.get("_agentlens")- if not isinstance(payload, dict):- return {}- # 先给调用方返回迁移后的副本,真正持久化迁移留到后续写入时完成。- return _migrate_agentlens_v1_to_v2(dict(payload), sess)---def update_agentlens_session(- state_path: Path,- sid: str,- updates: dict[str, Any],- *,- clear_keys: list[str] | None = None,-) -> dict[str, Any]:- """原子地持久化某个 session 的 AgentLens sidecar 字段。-- 在合并 updates 之前会先做 v1→v2 迁移,这样磁盘上的 payload 会随着写入自然收敛到 v2。- """-- def _update(state: dict[str, Any]) -> dict[str, Any]:- sess = ensure_session(state, sid)- payload = get_agentlens_session(state, sid)- # 如果仍是 v1,就原地迁移。- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), sess)- payload.clear()- payload.update(migrated)- for key in clear_keys or []:- payload.pop(key, None)- for key, value in updates.items():- if value is None:- payload.pop(key, None)- else:- payload[key] = value- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(payload)-- return update_state_locked(state_path, _update)---def begin_turn(- state_path: Path,- sid: str,- turn_id: str,- carrier: dict[str, str],- *,- started_at: float | None = None,- max_history: int = _TURN_HISTORY_MAX,-) -> dict[str, Any]:- """在独占锁下打开一个新的 turn。-- 语义:- - 如果存在 ``current_turn``,先把它归档进有上限的 ``turn_history``。- - 为新 turn 重置 ``subagent_spans`` / ``agent_spans`` / ``step_spans``。- - 对相同 ``turn_id`` 保持幂等:重复调用直接返回已有 ``current_turn``,- 不重新生成 trace_id。-- 返回最终生成的 ``current_turn`` 字典。- """- ts = float(started_at if started_at is not None else time.time())-- def _update(state: dict[str, Any]) -> dict[str, Any]:- sess = ensure_session(state, sid)- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), sess)- payload.clear()- payload.update(migrated)-- current = payload.get("current_turn")- # 幂等:如果同一个 turn_id 还在处理中,就原样返回。- if isinstance(current, dict) and str(current.get("turn_id") or "") == str(turn_id):- return dict(current)-- # 归档上一个 turn。- if isinstance(current, dict) and current.get("turn_id"):- history = payload.setdefault("turn_history", [])- if not isinstance(history, list):- history = []- payload["turn_history"] = history- archived = {- "turn_id": current.get("turn_id"),- "started_at": current.get("started_at"),- "ended_at": ts,- "carrier_traceparent": (current.get("carrier") or {}).get("traceparent"),- }- history.append(archived)- if len(history) > max_history:- del history[: len(history) - max_history]-- new_turn = {- "turn_id": str(turn_id),- "started_at": ts,- "carrier": dict(carrier or {}),- "subagent_spans": {},- "agent_spans": {},- "step_spans": {},- }- payload["current_turn"] = new_turn- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_turn)-- return update_state_locked(state_path, _update)---def upsert_subagent_span(- state_path: Path,- sid: str,- role: str,- carrier: dict[str, str],-) -> dict[str, str]:- """在当前 turn 下登记 subagent 的 ``invoke_agent`` 子 span carrier。-- 对 `(turn, role)` 维度保持幂等:如果活跃 turn 下已经记录了该角色的 carrier,- 就直接返回已有值,不再重复创建。- """- now = time.time()-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- # 没有活跃 turn,无法登记 subagent span。- return {}- subs = current.setdefault("subagent_spans", {})- if not isinstance(subs, dict):- subs = {}- current["subagent_spans"] = subs- existing = subs.get(role)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- subs[role] = {"carrier": dict(carrier or {}), "opened_at": now}- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(carrier or {})-- return update_state_locked(state_path, _update)---def upsert_subagent_span_atomic(- state_path: Path,- sid: str,- role: str,- *,- carrier_factory: Any,-) -> dict[str, str]:- """在写锁内原子地获取或创建 subagent 的 ``invoke_agent`` carrier。-- `carrier_factory` 是一个无参可调用对象,用来生成 carrier 字典。- 只有在 span 还不存在时才会被调用,从而避免这样的 TOCTOU 竞争:- ``_generate_subagent_carrier`` 先产生了不可逆的 zhiyanllm ``invoke_agent`` span,- 随后另一个 hook 进程已经写入同一角色,导致本次创建变成孤儿。- """- now = time.time()-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- subs = current.setdefault("subagent_spans", {})- if not isinstance(subs, dict):- subs = {}- current["subagent_spans"] = subs- existing = subs.get(role)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- subs[role] = {"carrier": dict(new_carrier), "opened_at": now}- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def get_current_turn(state_path: Path, sid: str) -> dict[str, Any] | None:- """返回当前活跃的 turn 字典;如果没有打开 turn,就返回 None。"""- payload = load_agentlens_session(state_path, sid)- current = payload.get("current_turn")- return current if isinstance(current, dict) else None---def get_subagent_span_carrier(state_path: Path, sid: str, role: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 subagent span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- subs = turn.get("subagent_spans")- if not isinstance(subs, dict):- return None- rec = subs.get(role)- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None---def _empty_agent_aggregate() -> dict[str, Any]:- """创建一份空的 agent 聚合指标骨架。"""- return {- "tokens": {- "input": 0,- "output": 0,- "cache_read": 0,- "cache_creation": 0,- "total": 0,- },- "event_count": 0,- "cost_usd": 0.0,- "tool_duration_ms": 0,- "llm_call_count": 0,- "tool_call_count": 0,- "step_count": 0,- }---def _normalize_agent(agent: str | None) -> str:- """把 agent 名归一化,空值统一落到 ``main``。"""- return str(agent or "main").strip() or "main"---def _ensure_turn_agent_spans(current: dict[str, Any]) -> dict[str, Any]:- """确保当前 turn 下存在 `agent_spans` 容器。"""- agent_spans = current.setdefault("agent_spans", {})- if not isinstance(agent_spans, dict):- agent_spans = {}- current["agent_spans"] = agent_spans- return agent_spans---def _ensure_agent_span_rec(current: dict[str, Any], agent: str) -> dict[str, Any]:- """确保指定 agent 在当前 turn 下有一条完整聚合记录。"""- agent_spans = _ensure_turn_agent_spans(current)- rec = agent_spans.get(agent)- if not isinstance(rec, dict):- rec = {}- agent_spans[agent] = rec- carrier = rec.get("carrier")- if not isinstance(carrier, dict):- rec["carrier"] = {}- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- rec["aggregate"] = _empty_agent_aggregate()- return rec---def get_agent_span_carrier(state_path: Path, sid: str, agent: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 agent 分组 span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- agent_spans = turn.get("agent_spans")- if not isinstance(agent_spans, dict):- return None- rec = agent_spans.get(_normalize_agent(agent))- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None---def upsert_agent_span_atomic(- state_path: Path,- sid: str,- agent: str,- *,- carrier_factory: Any,-) -> dict[str, str]:- """原子地获取或创建 agent 分组 span carrier。"""- now = time.time()- normalized_agent = _normalize_agent(agent)-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(- dict(payload),- state.get(sid) if isinstance(state.get(sid), dict) else None,- )- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- rec = _ensure_agent_span_rec(current, normalized_agent)- existing = rec.get("carrier")- if isinstance(existing, dict) and existing.get("traceparent"):- return dict(existing)- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- rec["carrier"] = dict(new_carrier)- rec.setdefault("opened_at", now)- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def bump_agent_aggregate(- state_path: Path,- sid: str,- agent: str,- *,- usage_event: dict[str, Any] | None = None,- tool_event: dict[str, Any] | None = None,- step_created: bool = False,-) -> dict[str, Any]:- """增加活跃 turn 下按 agent 聚合的统计指标。"""- normalized_agent = _normalize_agent(agent)-- def _int(value: Any) -> int:- try:- return int(value or 0)- except Exception:- return 0-- def _float(value: Any) -> float:- try:- return float(value or 0)- except Exception:- return 0.0-- def _update(state: dict[str, Any]) -> dict[str, Any]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(- dict(payload),- state.get(sid) if isinstance(state.get(sid), dict) else None,- )- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- rec = _ensure_agent_span_rec(current, normalized_agent)- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- aggregate = _empty_agent_aggregate()- rec["aggregate"] = aggregate- tokens = aggregate.setdefault("tokens", {})- if not isinstance(tokens, dict):- tokens = {}- aggregate["tokens"] = tokens-- if step_created:- aggregate["step_count"] = _int(aggregate.get("step_count")) + 1-- if isinstance(tool_event, dict):- aggregate["tool_call_count"] = _int(aggregate.get("tool_call_count")) + 1- ms = tool_event.get("ms")- if ms is not None:- aggregate["tool_duration_ms"] = _int(aggregate.get("tool_duration_ms")) + _int(ms)-- if isinstance(usage_event, dict):- raw_tokens = usage_event.get("tokens")- if isinstance(raw_tokens, dict):- # 聚合 agent 摘要里需要暴露的字段。- for key in ("input", "output", "cache_read", "cache_creation"):- tokens[key] = _int(tokens.get(key)) + _int(raw_tokens.get(key))- # total = input + output,其中 input 已经包含 cache_read。- tokens["total"] = _int(tokens.get("input")) + _int(tokens.get("output"))- aggregate["llm_call_count"] = _int(aggregate.get("llm_call_count")) + 1- aggregate["event_count"] = _int(aggregate.get("event_count")) + 1- aggregate["cost_usd"] = round(_float(aggregate.get("cost_usd")) + _float(usage_event.get("cost_usd")), 10)-- payload["version"] = AGENTLENS_SCHEMA_VERSION- return json.loads(json.dumps(aggregate, ensure_ascii=False))-- return update_state_locked(state_path, _update)---def get_subagent_aggregate(state_path: Path, sid: str, role: str) -> dict[str, Any] | None:- """返回活跃 turn 下当前 agent 的聚合摘要。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- agent_spans = turn.get("agent_spans")- if not isinstance(agent_spans, dict):- return None- rec = agent_spans.get(_normalize_agent(role))- if not isinstance(rec, dict):- return None- aggregate = rec.get("aggregate")- if not isinstance(aggregate, dict):- return None- return json.loads(json.dumps(aggregate, ensure_ascii=False))---def _step_span_key(agent: str, message_id: str) -> str:- """为 step span 生成按 agent 与 message_id 唯一定位的 key。"""- return f"{agent}|{message_id}"---def upsert_step_span(- state_path: Path,- sid: str,- agent: str,- message_id: str,- carrier: dict[str, str],- *,- transcript_path: str | None = None,-) -> dict[str, str]:- """在当前 turn 下登记一个 step span carrier,并对 `(turn, agent, message_id)` 保持幂等。"""- now = time.time()- normalized_agent = str(agent or "main").strip() or "main"- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return {}-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- steps = current.setdefault("step_spans", {})- if not isinstance(steps, dict):- steps = {}- current["step_spans"] = steps- key = _step_span_key(normalized_agent, normalized_message_id)- existing = steps.get(key)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- steps[key] = {- "carrier": dict(carrier or {}),- "opened_at": now,- "agent": normalized_agent,- "message_id": normalized_message_id,- "transcript_path": transcript_path or "",- }- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(carrier or {})-- return update_state_locked(state_path, _update)---def upsert_step_span_atomic(- state_path: Path,- sid: str,- agent: str,- message_id: str,- *,- carrier_factory: Any,- transcript_path: str | None = None,-) -> dict[str, str]:- """在写锁内原子地获取或创建一个 step span carrier。-- `carrier_factory` 是一个无参可调用对象,用来生成 carrier 字典。- 只有在 span 还不存在时才会被调用,从而避免这样的 TOCTOU 竞争:- ``_generate_step_carrier`` 已经先产生了不可逆的 zhiyanllm span,- 但随后另一个 hook 进程已经写入同一 step,导致本次创建失去归属。- """- now = time.time()- normalized_agent = str(agent or "main").strip() or "main"- normalized_message_id = str(message_id or "").strip()- if not normalized_message_id:- return {}-- def _update(state: dict[str, Any]) -> dict[str, str]:- payload = get_agentlens_session(state, sid)- if payload.get("version") != AGENTLENS_SCHEMA_VERSION:- migrated = _migrate_agentlens_v1_to_v2(dict(payload), state.get(sid) if isinstance(state.get(sid), dict) else None)- payload.clear()- payload.update(migrated)- current = payload.get("current_turn")- if not isinstance(current, dict):- return {}- steps = current.setdefault("step_spans", {})- if not isinstance(steps, dict):- steps = {}- current["step_spans"] = steps- key = _step_span_key(normalized_agent, normalized_message_id)- existing = steps.get(key)- if isinstance(existing, dict) and isinstance(existing.get("carrier"), dict) and existing["carrier"]:- return dict(existing["carrier"])- new_carrier = carrier_factory()- if not isinstance(new_carrier, dict) or not new_carrier.get("traceparent"):- return {}- steps[key] = {- "carrier": dict(new_carrier),- "opened_at": now,- "agent": normalized_agent,- "message_id": normalized_message_id,- "transcript_path": transcript_path or "",- }- payload["version"] = AGENTLENS_SCHEMA_VERSION- return dict(new_carrier)-- return update_state_locked(state_path, _update)---def get_step_span_carrier(state_path: Path, sid: str, agent: str, message_id: str) -> dict[str, str] | None:- """返回活跃 turn 下已持久化的 step span carrier;如果没有则返回 None。"""- turn = get_current_turn(state_path, sid)- if not isinstance(turn, dict):- return None- steps = turn.get("step_spans")- if not isinstance(steps, dict):- return None- key = _step_span_key(str(agent or "main").strip() or "main", str(message_id or "").strip())- rec = steps.get(key)- if not isinstance(rec, dict):- return None- carrier = rec.get("carrier")- return dict(carrier) if isinstance(carrier, dict) and carrier else None--def get_latest_session_id(state: dict[str, Any]) -> str | None:"""返回 state 中最近启动的 session id。"""latest_sid: str | None = None@@ -1061,38 +454,6 @@ def get_last_cumulative_usage(return {}-def get_last_llm_offset(- state: dict,- sid: str,- transcript_path: str | None = None,-) -> int:- """获取最近一次处理到的 LLM source_offset,用于增量构建 I/O。"""- sess = state.get(sid)- if not isinstance(sess, dict):- return 0- scope = _get_transcript_scope(sess, transcript_path)- if isinstance(scope, dict):- v = scope.get("last_llm_offset")- if isinstance(v, (int, float)):- return int(v)- return 0---def set_last_llm_offset(- state: dict,- sid: str,- offset: int,- transcript_path: str | None = None,-) -> None:- """持久化某个 transcript 最近处理到的 LLM source_offset。"""- sess = state.get(sid)- if not isinstance(sess, dict):- return- scope = _get_transcript_scope(sess, transcript_path, create=True)- if isinstance(scope, dict):- scope["last_llm_offset"] = int(offset or 0)--def set_last_cumulative_usage(state: dict,sid: str,diff --git a/local/.cursor/skills/agent-observability/scripts/run_hook.sh b/local/.cursor/skills/agent-observability/scripts/run_hook.shindex d476810f..e73e814a 100644--- a/local/.cursor/skills/agent-observability/scripts/run_hook.sh+++ b/local/.cursor/skills/agent-observability/scripts/run_hook.sh@@ -2,15 +2,6 @@set -euPROJECT_DIR="${CODEBUDDY_PROJECT_DIR:-$(cd "$(dirname "$0")"/../../../.. && pwd -P)}"-PYTHON_BIN="$PROJECT_DIR/.venv/bin/python"MAIN_PY="$PROJECT_DIR/.codebuddy/skills/agent-observability/scripts/main.py"-# 只有当 .venv 里可用 zhiyanllm 时才优先使用该解释器;-# 否则回退到已安装 zhiyanllm 的系统 python3。-if [ -x "$PYTHON_BIN" ]; then- if "$PYTHON_BIN" -c "import zhiyanllm" 2>/dev/null; then- exec "$PYTHON_BIN" "$MAIN_PY" "$@"- fi-fi-exec python3 "$MAIN_PY" "$@"diff --git a/local/.cursor/skills/agent-observability/tests/test_build_dashboard_data.py b/local/.cursor/skills/agent-observability/tests/test_build_dashboard_data.pyindex 6ee93f75..00127338 100644--- a/local/.cursor/skills/agent-observability/tests/test_build_dashboard_data.py+++ b/local/.cursor/skills/agent-observability/tests/test_build_dashboard_data.py@@ -285,8 +285,7 @@ class TopSlowTests(unittest.TestCase):class BuildDailyAndSessionsTurnAttributionTests(unittest.TestCase):- """真实场景复现过:AgentLens(写 state.current_turn 的那套 tracing)关闭时,- tool/usage 事件自己的 turn_id 永远是 None,只有 user_prompt_submit 事件带真实+ """真实场景复现过:tool/usage 事件自己的 turn_id 永远是 None,只有 user_prompt_submit 事件带真实turn_id。修复前所有没有 turn_id 的事件会被塌缩进同一个 "?" 占位桶,看起来像"整个会话只有 1 个 turn",哪怕实际发了好几轮 prompt。"""diff --git a/local/.cursor/skills/agent-observability/tests/test_collector.py b/local/.cursor/skills/agent-observability/tests/test_collector.pyindex 05547f06..b70f127d 100644--- a/local/.cursor/skills/agent-observability/tests/test_collector.py+++ b/local/.cursor/skills/agent-observability/tests/test_collector.py@@ -12,7 +12,7 @@ SCRIPTS = ROOT / "scripts"if str(SCRIPTS) not in sys.path:sys.path.insert(0, str(SCRIPTS))-from core import agent_identity, agentlens, collector, emitter, runtime, state as st # type: ignore+from core import agent_identity, collector, emitter, runtime, state as st # type: ignoreclass CollectorTests(unittest.TestCase):@@ -550,24 +550,16 @@ class CollectorTests(unittest.TestCase):encoding="utf-8",)- emitted_calls: list[dict[str, object]] = []- original_emit_post_step = agentlens.emit_post_step- try:- agentlens.emit_post_step = lambda **kwargs: emitted_calls.append(kwargs)- runtime.flush_pending_tool_events(- state_path=state_path,- log_path=log_path,- sid=sid,- )- finally:- agentlens.emit_post_step = original_emit_post_step+ runtime.flush_pending_tool_events(+ state_path=state_path,+ log_path=log_path,+ sid=sid,+ )self.assertEqual(st.get_pending_tool_emits(state_path, sid), [])lines = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()]self.assertEqual(len(lines), 1)self.assertEqual(lines[0]["message_id"], "msg-later")- self.assertEqual(len(emitted_calls), 1)- self.assertEqual(emitted_calls[0]["tool_event"]["message_id"], "msg-later")def test_related_transcript_paths_include_subagents(self):with tempfile.TemporaryDirectory() as td:@@ -683,33 +675,6 @@ class CollectorTests(unittest.TestCase):self.assertEqual(skills_usage.get("pdf", {}).get("count"), 1)self.assertEqual(rules_usage.get("security", {}).get("count"), 1)- def test_step_span_registry_is_idempotent(self):- with tempfile.TemporaryDirectory() as td:- state_path = Path(td) / ".state.json"- sid = "s-step"- carrier = {"traceparent": "00-" + ("1" * 32) + "-" + ("2" * 16) + "-01"}- st.begin_turn(state_path, sid, "turn-1", carrier)-- first = st.upsert_step_span(- state_path,- sid,- "main",- "msg-001",- {"traceparent": "00-" + ("1" * 32) + "-" + ("3" * 16) + "-01"},- transcript_path="/tmp/demo.jsonl",- )- second = st.upsert_step_span(- state_path,- sid,- "main",- "msg-001",- {"traceparent": "00-" + ("1" * 32) + "-" + ("4" * 16) + "-01"},- transcript_path="/tmp/demo.jsonl",- )-- self.assertEqual(first, second)- self.assertEqual(st.get_step_span_carrier(state_path, sid, "main", "msg-001"), first)-if __name__ == "__main__":unittest.main()diff --git a/local/.cursor/skills/agent-observability/tests/test_runtime_flow.py b/local/.cursor/skills/agent-observability/tests/test_runtime_flow.pyindex 7bd143ba..2931ffed 100644--- a/local/.cursor/skills/agent-observability/tests/test_runtime_flow.py+++ b/local/.cursor/skills/agent-observability/tests/test_runtime_flow.py@@ -49,15 +49,13 @@ class RuntimeFlowTests(unittest.TestCase):mock.patch.object(runtime.collector, "cache_inventory"), \mock.patch.object(runtime.collector, "record_tool_usage", return_value=([], [])), \mock.patch.object(runtime.agent_identity, "resolve_active_agent_for_event", return_value=("main", None)), \- mock.patch.object(runtime, "current_turn_id", return_value="turn-1"), \mock.patch.object(runtime.collector, "extract_tool_call_id", return_value=None), \mock.patch.object(runtime, "flush_pending_tool_events"), \mock.patch.object(runtime.collector, "find_current_tool_context", return_value=None), \mock.patch.object(runtime.collector, "related_transcript_paths", return_value=["/tmp/demo.jsonl"]), \mock.patch.object(runtime, "emit_transcript_events", return_value=[]), \mock.patch.object(runtime.collector, "find_fallback_usage_event", return_value=None), \- mock.patch.object(runtime.st, "append_pending_tool_emit"), \- mock.patch.object(runtime.agentlens, "emit_post_step"):+ mock.patch.object(runtime.st, "append_pending_tool_emit"):mock_paths.return_value = runtime.RuntimePaths(base_dir=Path(td),state_path=Path(td) / ".state.json",diff --git a/local/scripts/validate.sh b/local/scripts/validate.shindex fed99247..9df7543b 100755--- a/local/scripts/validate.sh+++ b/local/scripts/validate.sh@@ -26,7 +26,7 @@ if rg --hidden -n -i \-e 'woa\.com' \-e '(^|[^[:alnum:]])oa\.com' \-e 'git\.woa' \- -e 'iwiki' \+ -e 'i[w]iki' \-e 'tapd' \-e 'internal\.tencentcloudapi' \-e 'cls\.internal\.tencentcloudapi\.com' \diff --git a/scripts/check-public.py b/scripts/check-public.pyindex 61fad30a..6b39a94d 100644--- a/scripts/check-public.py+++ b/scripts/check-public.py@@ -37,6 +37,14 @@ blocked_word_digests = {"f798533f224be82e4b330e5359083c90003e8938ec99c44c149044e50dcac3a7","5ccc8b45a1879d03f8ec36866f77dd4614d118b5604f084bd4936d39b3aa03d5","e34be4a2143785f351febc3cff274028f5ea90adc720d303c3b9e301656de8e9",+ "c528582a3d776738ee1bdac0143bac95880941ae5ec0ea5d22303dfc7bcfa4ed",+ "922cbca653ab12710227999f97bc2fa4cc3d723c5573f51c3c877092738674ae",+ "94acc5bc7885dd2d2895504c12317246d109cc84c882be2d6ec23c8678f5f311",+ "db996cc80525936a1bc24847f1d3bc7072804a79512b59b78331e029a9a095e7",+ "1073077b7d460460ec07598556d39f3cff39d68755903f215c2acf92cc35a1f2",+ "415f4f7b42b6042dce0c2ed9707bdbcc1fa10afad67dc2842c81264ea3d4d74b",+ "fa9a4893cb501e16467ac84e6651ed0d8eb915f0387d1ec1931599191b7a9717",+ "b194aec3246fe06c0877890f4e31f9b5880eb654d002252b0e966d39a3874207",}word = re.compile(r"[A-Za-z0-9_]{5,24}")# MIT requires keeping upstream copyright lines verbatim; only those lines, anddiff --git a/web/app.js b/web/app.jsindex 222cece5..3de024ca 100644--- a/web/app.js+++ b/web/app.js@@ -21,8 +21,7 @@ const state = {accessTab:localStorage.getItem('agentflow.accessTab')||'setup', accessClient:'cursor',accessCapabilities:null, accessCapabilitiesStatus:'idle', accessCapabilitiesError:'',accessTokens:[], accessTokensStatus:'idle', accessTokensError:'', revealedToken:'',- deploymentData:null, deploymentError:'', deploymentLoading:false, deploymentRepositoryId:'', deploymentBranch:'',- metricsRange:['7d','30d','90d','365d','custom'].includes(localStorage.getItem('agentflow.metricsRange'))?localStorage.getItem('agentflow.metricsRange'):'30d', metricsDateFrom:localStorage.getItem('agentflow.metricsDateFrom')||'', metricsDateTo:localStorage.getItem('agentflow.metricsDateTo')||'', metricsData:null, metricsIssues:[], metricsBenchmark:null, metricsLoading:false, metricsError:'', metricsTrendMetric:localStorage.getItem('agentflow.metricsTrendMetric')||'deliveries', metricsDeploymentData:null, metricsDeploymentError:'', metricsDeploymentLoading:false,+ metricsRange:['7d','30d','90d','365d','custom'].includes(localStorage.getItem('agentflow.metricsRange'))?localStorage.getItem('agentflow.metricsRange'):'30d', metricsDateFrom:localStorage.getItem('agentflow.metricsDateFrom')||'', metricsDateTo:localStorage.getItem('agentflow.metricsDateTo')||'', metricsData:null, metricsIssues:[], metricsLoading:false, metricsError:'', metricsTrendMetric:localStorage.getItem('agentflow.metricsTrendMetric')||'deliveries',issueSelectionMode:false, issueSelection:new Set(), issueSelectionScope:'', issueBulkDeleting:false, issueBulkDeleteProgress:null, issueBulkDeleteResult:null,listPages:{}};@@ -1352,7 +1351,6 @@ function bind(){$('#refreshApprovals').onclick=()=>renderApprovals(false);$('#refreshObs').onclick=refreshObs;$('#refreshMetrics').onclick=()=>refreshMetrics(true);- $('#refreshDeployments').onclick=()=>refreshDeployments(true);$('#exportObsReport').onclick=exportObsReport;$$('.obs-tab').forEach(btn=>btn.onclick=()=>switchObsTab(btn.dataset.obsTab));$$('.drawer-tab').forEach(btn=>btn.onclick=()=>{state.issueDetailTab=btn.dataset.dtab;$$('.drawer-tab').forEach(x=>x.classList.toggle('active',x===btn));renderIssueDetailTab()});@@ -1377,10 +1375,6 @@ function bind(){if($('#observabilityView').classList.contains('active'))refreshObs();if($('#knowledgeView')?.classList.contains('active')&&typeof renderKnowledgeView==='function')renderKnowledgeView();if($('#metricsView').classList.contains('active'))refreshMetrics();- if($('#deploymentsView').classList.contains('active')){- if(!canShowSkillhubEfficiency()){switchView('dashboard')}- else{state.deploymentData=null;state.deploymentError='';state.deploymentRepositoryId='';state.deploymentBranch='';renderDeploymentDashboard();refreshDeployments()}- }if($('#sopsView').classList.contains('active'))refreshWorkflowMetrics();};document.querySelectorAll('[data-scope-for]').forEach(bar=>{@@ -1581,7 +1575,7 @@ function settingsSidebarExpanded(){}let settingsSidebarEntryFrame=0;let settingsSidebarWasManaged=false;-const settingsManagementViews=['settings','runners','bots','projects','flow','agents','mcp','rules','skills','dockerfiles','environments','sandboxes','knowledge','metrics','deployments','businessDomains','guide','platform','businessDomainManagement'];+const settingsManagementViews=['settings','runners','bots','projects','flow','agents','mcp','rules','skills','dockerfiles','environments','sandboxes','knowledge','metrics','businessDomains','guide','platform','businessDomainManagement'];const settingsRouteMotion=matchMedia('(prefers-reduced-motion: reduce)');let settingsRouteTransition=null;let settingsRouteApplying=false;@@ -1753,7 +1747,7 @@ function setSettingsSidebarExpanded(expanded){});}}-function viewTitles(){return {management:'设置',collaboration:'AI 工作台',issues:'需求列表',bots:'Bot 管理',runs:'运行记录',metrics:'研发效能',deployments:'部署耗时',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色定义',mcp:'MCP 管理',rules:'规则管理',skills:'技能管理',dockerfiles:'Dockerfile',environments:'环境安装脚本',sandboxes:'沙箱管理',observability:'统计',projects:'项目配置',businessDomains:'业务领域',platform:'平台管理',businessDomainManagement:'领域管理',runners:'执行机器',settings:'个人配置',access:'接入方式',guide:'接入指南',knowledge:'知识中心'}}+function viewTitles(){return {management:'设置',collaboration:'AI 工作台',issues:'需求列表',bots:'Bot 管理',runs:'运行记录',metrics:'研发效能',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色定义',mcp:'MCP 管理',rules:'规则管理',skills:'技能管理',dockerfiles:'Dockerfile',environments:'环境安装脚本',sandboxes:'沙箱管理',observability:'统计',projects:'项目配置',businessDomains:'业务领域',platform:'平台管理',businessDomainManagement:'领域管理',runners:'执行机器',settings:'个人配置',access:'接入方式',guide:'接入指南',knowledge:'知识中心'}}function activeViewName(){if(state.currentView)return state.currentView;const el=document.querySelector('.view.active');return el?el.id.replace(/View$/,''):''}function setCapabilityNavExpanded(expanded){const toggle=$('#capabilityNavToggle'),group=$('#capabilityNavGroup');if(!toggle||!group)return;toggle.setAttribute('aria-expanded',String(expanded));group.hidden=!expanded;localStorage.setItem('agentflow.capabilityNavExpanded',String(expanded))}function setEnvironmentNavExpanded(expanded){const toggle=$('#environmentNavToggle'),group=$('#environmentNavGroup');if(!toggle||!group)return;toggle.setAttribute('aria-expanded',String(expanded));group.hidden=!expanded;localStorage.setItem('agentflow.environmentNavExpanded',String(expanded))}@@ -1896,7 +1890,6 @@ function switchView(name){// 手敲 #/platform 或者从别的账号留下的 localStorage 恢复进来,都要挡住。if(name==='platform'&&!isPlatformAdmin())name='collaboration';if(name==='businessDomainManagement'&&!canAccessPlatformManagement())name='collaboration';- if(name==='deployments'&&!canShowSkillhubEfficiency())name='collaboration';const previous=activeViewName();if(!settingsRouteApplying){const crossingSettings=previous!==name&&((previous==='collaboration'&&isSettingsManagementView(name))||(isSettingsManagementView(previous)&&name==='collaboration'));@@ -1973,7 +1966,6 @@ function switchView(name){if(name==='metrics'){const key=metricsQueryKey();if(state.metricsDataKey!==key&&metricsPendingKey!==key)refreshMetrics();else renderMetricsDashboard()}if(name==='approvals')renderApprovals(false)if(name==='observability')refreshObs()- if(name==='deployments'){renderDeploymentDashboard();if(!state.deploymentData&&!state.deploymentLoading&&!state.deploymentError)refreshDeployments()}if(name==='agents'){api('/api/agents',{silent:true}).then(agents=>{state.data.agents=agents;renderAgents()}).catch(e=>toast(e.message));renderAgents();applyAgentRoute()}if(name==='settings')renderPersonalSettings();if(name==='platform')renderPlatformAdminPanel();@@ -1993,4 +1985,4 @@ function switchView(name){if(name==='guide')renderGuide();if(name==='flow'){if(!state.workflow?.nodes?.some(n=>n.id===state.selectedNode))state.selectedNode=null;renderWorkflowMeta();renderCanvas();renderProperties();setFlowView('canvas');refreshGenericWorkflowRoles()}}-function renderAll(){renderUserBadge();renderPlatformNav();renderObsTabs();renderProjectSwitcher();renderIssues();renderSOPCatalog();renderWorkflowMeta();renderCanvas();renderProperties();renderAgents();renderAssets();renderMCPManagement();renderRuns();renderSync();renderProjectAdmin();renderDashboard();renderDeploymentDashboard();renderGuide();updateApprovalBadge();showDirectRunButton($('#flowView').classList.contains('active'))}+function renderAll(){renderUserBadge();renderPlatformNav();renderObsTabs();renderProjectSwitcher();renderIssues();renderSOPCatalog();renderWorkflowMeta();renderCanvas();renderProperties();renderAgents();renderAssets();renderMCPManagement();renderRuns();renderSync();renderProjectAdmin();renderDashboard();renderGuide();updateApprovalBadge();showDirectRunButton($('#flowView').classList.contains('active'))}diff --git a/web/app/access.js b/web/app/access.jsindex 018306f0..5156a60a 100644--- a/web/app/access.js+++ b/web/app/access.js@@ -45,8 +45,7 @@ async function createQuickAccessPrompt(button){renderGuide();}catch(err){button.disabled=false;button.textContent=original;toast(err.message||'创建 Token 失败','err')}}-// 对外展示的固定接入地址:devcloud 等环境经 https 访问不稳定(网关 443 链路问题),-// 接入配置统一展示并使用 http 域名,优先使用部署下发的 APP_DOMAIN,避免硬编码固定域名。+// 对外展示的固定接入地址:优先使用部署下发的 APP_DOMAIN,避免硬编码固定域名。function getPublicBaseURL(){const domain = (typeof window !== 'undefined' && (window.__AGENTFLOW_APP_DOMAIN__ || window.__AGENTFLOW_PUBLIC_BASE_URL__))|| (typeof state !== 'undefined' && state?.appDomain ? state.appDomain : '')@@ -312,7 +311,7 @@ async function revokePersonalToken(id){let commandMatches=[],commandSelectedIndex=0;function commandCatalog(){- const pages=[['dashboard','工作总览','看失败、待确认和进行中的需求'],['issues','需求列表','查看进度,触发或重试'],['approvals','待我确认','批准或退回卡住的需求'],['sops','流程模板','Issue 修复与需求开发'],['runs','运行记录','查看节点日志和产物'],['metrics','研发效能','产能、效率、质量、成本与自动化看板'],['deployments','部署耗时','按分支查看测试环境流水线耗时'],['agents','角色定义','管理角色和能力资产'],['mcp','MCP 管理','添加项目级或个人自定义 MCP'],['rules','规则管理','当前项目的行为与执行约束'],['skills','技能管理','当前项目的技能和附加文件'],['dockerfiles','Dockerfile','管理项目容器构建定义'],['environments','环境安装脚本','管理隔离环境的工具安装脚本'],['sandboxes','沙箱管理','管理项目运行隔离策略'],['observability','统计','用量分析 · Token 与质量'],['businessDomains','业务领域','分类管理与跨项目汇报'],['projects','项目配置','项目、成员和仓库'],['guide','接入指南','最小接入配置、MCP 或 REST API 接入']].filter(([view])=>view!=='deployments'||canShowSkillhubEfficiency()).map(([view,title,meta])=>({kind:'页面',title,meta,action:()=>switchView(view)}));+ const pages=[['dashboard','工作总览','看失败、待确认和进行中的需求'],['issues','需求列表','查看进度,触发或重试'],['approvals','待我确认','批准或退回卡住的需求'],['sops','流程模板','Issue 修复与需求开发'],['runs','运行记录','查看节点日志和产物'],['metrics','研发效能','产能、效率、质量、成本与自动化看板'],['agents','角色定义','管理角色和能力资产'],['mcp','MCP 管理','添加项目级或个人自定义 MCP'],['rules','规则管理','当前项目的行为与执行约束'],['skills','技能管理','当前项目的技能和附加文件'],['dockerfiles','Dockerfile','管理项目容器构建定义'],['environments','环境安装脚本','管理隔离环境的工具安装脚本'],['sandboxes','沙箱管理','管理项目运行隔离策略'],['observability','统计','用量分析 · Token 与质量'],['businessDomains','业务领域','分类管理与跨项目汇报'],['projects','项目配置','项目、成员和仓库'],['guide','接入指南','最小接入配置、MCP 或 REST API 接入']].map(([view,title,meta])=>({kind:'页面',title,meta,action:()=>switchView(view)}));const issues=(state.data.issues||[]).map(i=>({kind:'需求',title:i.title,meta:`${i.priority||'—'} · ${issueStatusLabel(i.status)}`,action:()=>openIssueDetail(i.id)}));const runs=(state.data.runs||[]).map(r=>({kind:'运行',title:runIssueTitle(r),meta:`${runDisplayStatus(r)} · ${r.workflowSnapshot?.name||r.workflowId}`,action:()=>openRunFromId(r.id)}));const sops=catalogWorkflows().map(w=>({kind:'SOP',title:w.name,meta:`${w.status==='published'?'已发布':'草稿'} · ${w.nodes?.length||0} 个节点`,action:()=>{state.workflow=clone(w);state.selectedNode=null;switchView('flow')}}));diff --git a/web/app/dashboards.js b/web/app/dashboards.jsindex 89f03945..828cab39 100644--- a/web/app/dashboards.js+++ b/web/app/dashboards.js@@ -7,60 +7,6 @@ function formatTimestamp(value){}function duration(ms){ms=Number(ms||0);if(!ms)return '—';if(ms<1000)return `${ms}ms`;if(ms<60000)return `${(ms/1000).toFixed(1)}s`;if(ms<3600000)return `${(ms/60000).toFixed(1)}m`;return `${(ms/3600000).toFixed(1)}h`}-function isSkillHubDeploymentRepository(repo){const project=String(repo?.gongfengProjectId||'').trim().toLowerCase().replace(/^\/+|\/+$/g,'');if(project==='example/team-project')return true;const urls=`${repo?.webUrl||''} ${repo?.cloneUrl||''}`.toLowerCase();return String(repo?.name||'').trim().toLowerCase()==='skillhub'&&urls.includes('example/team-project')}-function deploymentRepositories(){const project=currentProject();return (state.data?.repositories||[]).filter(r=>r.projectId===project?.id&&isSkillHubDeploymentRepository(r))}-function deploymentSelectedRepository(){const repos=deploymentRepositories();let repo=repos.find(r=>r.id===state.deploymentRepositoryId);if(!repo){const project=currentProject();repo=repos.find(r=>r.id===project?.defaultRepositoryId)||repos[0];state.deploymentRepositoryId=repo?.id||''}return repo}-function deploymentIsRunning(status){return[1,5,7,8,9].includes(Number(status))}-function deploymentStatusClass(status){if(Number(status)===2)return'succeeded';if(deploymentIsRunning(status))return'running';if([3,4,6,13].includes(Number(status)))return'failed';return''}-function deploymentQueryHTML(repo){- const branch=state.deploymentBranch||'';- return `<form id="deploymentQuery" class="deployment-query skillhub-only"><div class="deployment-fixed-source"><span>测试环境流水线</span><b>SkillHub · ${escapeHTML(repo?.name||'skillhub')}</b><small>智研项目 10001 · 流水线 10000001</small></div><label>代码分支(可选)<input name="branch" value="${escapeHTML(branch)}" placeholder="全部分支" autocomplete="off"></label><div class="deployment-query-actions"><button class="button primary" type="submit">应用筛选</button></div><div class="deployment-config-note"><span>进入页面会自动加载全部分支;分支仅用于进一步筛选。趋势统计最近 30 天,明细聚焦最近 7 天和正在部署。</span></div></form>`;-}-function renderDeploymentDashboard(){- const body=$('#deploymentBody'),live=$('#deploymentLiveState');if(!body||!state.data)return;- const project=currentProject(),repos=deploymentRepositories();- if(!project){body.innerHTML=`<div class="deployment-empty"><div><i>◇</i><h2>还没有项目</h2><p>先创建项目并绑定代码仓库,再查询测试环境部署耗时。</p><button class="button primary" type="button" data-deploy-goto-project>前往项目配置</button></div></div>`;body.querySelector('[data-deploy-goto-project]')?.addEventListener('click',()=>switchView('projects'));return}- if(!repos.length){body.innerHTML=`<div class="deployment-empty"><div><i>⌁</i><h2>当前项目没有绑定 SkillHub 仓库</h2><p>请先为「${escapeHTML(project.name)}」绑定工蜂仓库 example/team-project。</p><button class="button primary" type="button" data-deploy-goto-project>绑定 SkillHub 仓库</button></div></div>`;body.querySelector('[data-deploy-goto-project]')?.addEventListener('click',()=>switchView('projects'));return}- const repo=deploymentSelectedRepository(),query=deploymentQueryHTML(repo);- if(state.deploymentLoading){body.innerHTML=query+`<div class="deployment-loading" aria-label="正在查询"><i></i><i></i><i></i><i></i><i></i></div>`;if(live)live.innerHTML='<i></i> 正在查询智研';bindDeploymentDashboard(repo);return}- if(state.deploymentError){const credentialError=/令牌|token/i.test(state.deploymentError);body.innerHTML=query+`<div class="deployment-error"><div><i>!</i><h2>查询失败</h2><p>${escapeHTML(state.deploymentError)}</p>${credentialError?'<button class="button primary" type="button" data-open-deployment-settings>配置个人令牌</button>':'<button class="button ghost" type="button" data-deployment-retry>重新查询</button>'}</div></div>`;if(live)live.innerHTML='<i></i> 查询失败';bindDeploymentDashboard(repo);return}- const data=state.deploymentData;- if(!data){body.innerHTML=query+`<div class="deployment-empty"><div><i>↗</i><h2>正在准备部署看板</h2><p>进入页面后会自动读取 SkillHub 最近 30 天的测试环境流水线数据。</p></div></div>`;if(live)live.innerHTML='<i></i> 自动加载中';bindDeploymentDashboard(repo);return}- const records=Array.isArray(data.records)?data.records:[],summary=data.summary||{};- if(!records.length){const scope=data.branch?`分支「${escapeHTML(data.branch)}」`:'全部分支';body.innerHTML=query+`<div class="deployment-empty"><div><i>⌕</i><h2>没有找到部署记录</h2><p>${scope}最近 30 天没有流水线记录。${data.branch?'可以清空分支后查看全部部署。':'请检查流水线是否已有构建。'}</p>${data.pipelineUrl?`<a class="button ghost" href="${escapeHTML(safeURL(data.pipelineUrl))}" target="_blank" rel="noopener noreferrer">打开智研流水线 ↗</a>`:''}</div></div>`;if(live)live.innerHTML='<i></i> 暂无记录';bindDeploymentDashboard(repo);return}- const finished=Number(summary.succeeded||0)+Number(summary.failed||0);- const kpis=`<div class="deployment-kpis"><div class="deployment-kpi good"><span>近 7 天平均耗时</span><strong>${duration(summary.average7dDurationMs)}</strong><small>${summary.deployments7d||0} 次已完成部署</small></div><div class="deployment-kpi running"><span>正在部署</span><strong>${summary.running||0}</strong><small>${summary.running?'流水线仍在执行':'当前没有运行中的部署'}</small></div><div class="deployment-kpi"><span>近 30 天平均耗时</span><strong>${duration(summary.averageDurationMs)}</strong><small>${finished} 次已完成部署</small></div><div class="deployment-kpi"><span>近 30 天 P50</span><strong>${duration(summary.p50DurationMs)}</strong><small>一半部署低于此值</small></div><div class="deployment-kpi warn"><span>近 30 天 P90</span><strong>${duration(summary.p90DurationMs)}</strong><small>关注长尾部署</small></div><div class="deployment-kpi good"><span>近 30 天成功率</span><strong>${Number(summary.successRate||0).toFixed(1)}%</strong><small>${summary.succeeded||0} 成功 · ${summary.failed||0} 失败</small></div></div>`;- const total=Math.max(1,Number(summary.total)||records.length),bar=(label,count,kind)=>`<div class="deployment-breakdown-row ${kind}"><span>${label}</span><div class="deployment-breakdown-track"><i style="width:${Math.round(Number(count||0)*100/total)}%"></i></div><b>${count||0}</b></div>`;- const panels=`<div class="deployment-grid"><section class="deployment-panel"><div class="deployment-panel-head"><div><h2>近 30 天部署耗时趋势</h2><p>按自然日聚合平均耗时,空白日期表示当天没有部署</p></div>${data.pipelineUrl?`<a class="button ghost small" href="${escapeHTML(safeURL(data.pipelineUrl))}" target="_blank" rel="noopener noreferrer">智研详情 ↗</a>`:''}</div><div class="deployment-chart">${deploymentChartSVG(records)}</div></section><aside class="deployment-panel"><div class="deployment-panel-head"><div><h2>近 30 天执行结果</h2><p>当前查询共 ${summary.total||records.length} 次</p></div></div><div class="deployment-breakdown">${bar('成功',summary.succeeded,'success')}${bar('失败',summary.failed,'failed')}${bar('进行中',summary.running,'running')}</div></aside></div>`;- const cutoff7d=Date.now()-7*24*60*60*1000,tableRecords=records.filter(r=>deploymentIsRunning(r.status)||(new Date(r.startedAt).getTime()>=cutoff7d)).sort((a,b)=>Number(deploymentIsRunning(b.status))-Number(deploymentIsRunning(a.status))||String(b.startedAt||'').localeCompare(String(a.startedAt||'')));- const rows=tableRecords.map(r=>{const elapsed=deploymentIsRunning(r.status)&&!Number(r.durationMs)&&r.startedAt?Math.max(0,Date.now()-new Date(r.startedAt).getTime()):Number(r.durationMs||0),shownDuration=deploymentIsRunning(r.status)&&elapsed?`已运行 ${duration(elapsed)}`:duration(elapsed);return`<tr><td>${r.url?`<a href="${escapeHTML(safeURL(r.url))}" target="_blank" rel="noopener noreferrer">#${escapeHTML(String(r.runNumber||r.id||'—'))}</a>`:`#${escapeHTML(String(r.runNumber||r.id||'—'))}`}</td><td><span class="deployment-status ${deploymentStatusClass(r.status)}">${escapeHTML(r.statusLabel||'未知')}</span></td><td><b>${escapeHTML(shownDuration)}</b></td><td><code>${escapeHTML(r.branch||'—')}</code></td><td>${escapeHTML(formatTimestamp(r.startedAt)||'—')}</td><td>${escapeHTML(r.starter||'—')}</td><td><code>${escapeHTML(String(r.revision||'—').slice(0,10))}</code></td><td title="${escapeHTML(r.comment||'')}">${escapeHTML(r.comment||'—')}</td></tr>`}).join('');- const table=`<section class="deployment-table-section"><div class="deployment-panel-head"><div><h2>最近 7 天与正在部署</h2><p>正在部署的记录置顶,其余展示最近 7 天构建</p></div><b>${tableRecords.length} 条</b></div><div class="deployment-table-wrap"><table class="deployment-table"><thead><tr><th>构建</th><th>结果</th><th>耗时</th><th>分支</th><th>开始时间</th><th>启动人</th><th>Commit</th><th>备注</th></tr></thead><tbody>${rows||'<tr><td colspan="8" class="deployment-table-empty">最近 7 天没有部署,当前也没有正在运行的流水线</td></tr>'}</tbody></table></div></section>`;- body.innerHTML=query+kpis+panels+table;if(live)live.innerHTML=`<i></i> 更新于 ${new Date(data.queriedAt||Date.now()).toLocaleTimeString([], {hour:'2-digit',minute:'2-digit'})}`;bindDeploymentDashboard(repo);-}-function deploymentChartSVG(records){- const now=new Date(),end=new Date(now),start=new Date(now);end.setHours(23,59,59,999);start.setDate(start.getDate()-29);start.setHours(0,0,0,0);- const days=new Map();records.forEach(r=>{const at=new Date(r.startedAt),ms=Number(r.durationMs||0);if(!Number.isFinite(at.getTime())||at<start||at>end||ms<=0)return;const day=new Date(at);day.setHours(0,0,0,0);const key=day.getTime(),item=days.get(key)||{at:key,total:0,count:0};item.total+=ms;item.count++;days.set(key,item)});- const points=[...days.values()].sort((a,b)=>a.at-b.at).map(p=>({...p,durationMs:Math.round(p.total/p.count)}));if(!points.length)return`<div class="deployment-empty" style="min-height:220px;border:0"><div><p>近 30 天已查询到记录,但暂时没有完整的耗时数据。</p></div></div>`;- const w=760,h=220,p={l:48,r:15,t:12,b:30},max=Math.max(...points.map(r=>r.durationMs),1),plotW=w-p.l-p.r,plotH=h-p.t-p.b,range=Math.max(1,end.getTime()-start.getTime()),x=at=>p.l+((at-start.getTime())/range)*plotW,y=v=>p.t+plotH-(Number(v)/max)*plotH;- const coords=points.map(r=>[x(r.at),y(r.durationMs)]),line=coords.map((pt,i)=>`${i?'L':'M'}${pt[0].toFixed(1)},${pt[1].toFixed(1)}`).join(' '),area=`${line} L${coords.at(-1)[0].toFixed(1)},${p.t+plotH} L${coords[0][0].toFixed(1)},${p.t+plotH} Z`;- const grids=[0,.25,.5,.75,1].map(n=>{const yy=p.t+plotH*(1-n);return`<line class="grid" x1="${p.l}" y1="${yy}" x2="${w-p.r}" y2="${yy}"/><text x="${p.l-7}" y="${yy+3}" text-anchor="end">${escapeHTML(duration(max*n))}</text>`}).join('');- const labelDates=[start,new Date((start.getTime()+end.getTime())/2),end],labels=labelDates.map((d,i)=>`<text x="${p.l+i*plotW/2}" y="${h-5}" text-anchor="${i===0?'start':i===2?'end':'middle'}">${escapeHTML(d.toLocaleDateString([], {month:'2-digit',day:'2-digit'}))}</text>`).join('');- const dots=coords.map((pt,i)=>`<circle class="dot" cx="${pt[0]}" cy="${pt[1]}" r="3.5"><title>${escapeHTML(new Date(points[i].at).toLocaleDateString())} · 日均 ${escapeHTML(duration(points[i].durationMs))} · ${points[i].count} 次</title></circle>`).join('');- return`<svg viewBox="0 0 ${w} ${h}" role="img" aria-label="部署耗时趋势"><defs><linearGradient id="deploymentArea" x1="0" y1="0" x2="0" y2="1"><stop offset="0" style="stop-color:var(--hui-accent)" stop-opacity=".18"/><stop offset="1" style="stop-color:var(--hui-accent)" stop-opacity=".02"/></linearGradient></defs>${grids}<path class="area" d="${area}"/><path class="line" d="${line}"/>${dots}${labels}</svg>`;-}-function bindDeploymentDashboard(repo){- const form=$('#deploymentQuery');if(!form)return;- form.elements.branch.oninput=()=>{state.deploymentBranch=form.elements.branch.value};- form.onsubmit=e=>{e.preventDefault();refreshDeployments(true)};- document.querySelector('[data-open-deployment-settings]')?.addEventListener('click',()=>switchView('settings'));- document.querySelector('[data-deployment-retry]')?.addEventListener('click',()=>refreshDeployments(true));-}-async function refreshDeployments(force=false){- if(state.deploymentLoading)return;const form=$('#deploymentQuery'),repo=deploymentSelectedRepository();if(!form||!repo)return;- const branch=form.elements.branch.value.trim();state.deploymentBranch=branch;state.deploymentLoading=true;state.deploymentError='';renderDeploymentDashboard();- const q=new URLSearchParams({projectId:currentProject()?.id||'',repositoryId:repo.id,pageSize:'100'});if(branch)q.set('branch',branch);- try{state.deploymentData=await api('/api/deployment-metrics?'+q.toString(),force?{}:{silent:true})}catch(e){state.deploymentData=null;state.deploymentError=e.message||'查询失败'}finally{state.deploymentLoading=false;renderDeploymentDashboard()}-}const METRICS_WINDOWS={'7d':{days:7,label:'近 7 天',grain:'day'},@@ -123,10 +69,6 @@ function metricsNodeStageSummary(nodes,kind){(nodes||[]).forEach(node=>{const text=`${node.key||''} ${node.name||''}`;if(!patterns.some(pattern=>pattern.test(text)))return;const count=Number(node.nodeRuns||node.runs||0),avg=Number(node.averageExecutionDurationMs||0);if(count>0&&avg>0){samples+=count;total+=count*avg}});return {averageMs:samples?Math.round(total/samples):0,samples};}-function metricsDeploymentSummary(){- const win=metricsWindow(),records=(state.metricsDeploymentData?.records||[]).filter(r=>Number(r.durationMs)>0&&metricsDateInWindow(r.startedAt,win)&&!deploymentIsRunning(r.status));- return {averageMs:records.length?Math.round(records.reduce((n,r)=>n+Number(r.durationMs||0),0)/records.length):0,samples:records.length};-}function metricsDeliveryPhases(delivery){const lanes=delivery?.lanes||[],laneDuration=names=>lanes.filter(l=>names.includes(String(l.lane||'').toLowerCase())).reduce((n,l)=>n+Number(l.executionDurationMs||0),0);const measured=!!delivery?.phaseSamples;@@ -155,7 +97,7 @@ function metricsDashboardModel(){const interventionByIssue=new Map();traces.forEach(t=>{if(t.issueId)interventionByIssue.set(t.issueId,(interventionByIssue.get(t.issueId)||0)+Number(t.humanInterventions||0))});const interventions=[...aiIssueIds].reduce((n,id)=>n+(interventionByIssue.get(id)||0),0),automated=completed.filter(d=>!(interventionByIssue.get(d.issueId)||0));const tokens=completed.reduce((n,d)=>n+Number(d.tokens||0),0),knownCosts=completed.filter(d=>d.costKnown),cost=knownCosts.reduce((n,d)=>n+Number(d.costCny||0),0);- const terminal=Number(data.summary?.succeededRuns||0)+Number(data.summary?.failedRuns||0),frontend=metricsNodeStageSummary(data.nodes,'frontend'),backend=metricsNodeStageSummary(data.nodes,'backend'),test=metricsNodeStageSummary(data.nodes,'test'),deployment=metricsDeploymentSummary(),win=metricsWindow();+ const terminal=Number(data.summary?.succeededRuns||0)+Number(data.summary?.failedRuns||0),frontend=metricsNodeStageSummary(data.nodes,'frontend'),backend=metricsNodeStageSummary(data.nodes,'backend'),test=metricsNodeStageSummary(data.nodes,'test'),win=metricsWindow();const mrMergeTrend=metricsBuckets().map(bucket=>({...bucket,mergedMrs:0})),mrByKey=new Map(mrMergeTrend.map(x=>[x.key,x]));mrMerges.forEach(mr=>{const bucket=mrByKey.get(metricsBucketKey(mr.mergedAt,win.grain));if(bucket)bucket.mergedMrs++});const trend=metricsBuckets().map(bucket=>({...bucket,items:[],runs:null})),byKey=new Map(trend.map(x=>[x.key,x]));@@ -167,30 +109,17 @@ function metricsDashboardModel(){const phaseTrend=metricsBuckets({...win,grain:'day'}).map(bucket=>({...bucket,items:[]})),phaseByKey=new Map(phaseTrend.map(x=>[x.key,x]));phaseCompleted.forEach(item=>{const bucket=phaseByKey.get(metricsBucketKey(item.lastRunAt||item.firstRunAt,'day'));if(bucket)bucket.items.push(item)});phaseTrend.forEach(point=>{point.clarification=metricsPhaseAverage(point.items,'clarification').value;point.development=metricsPhaseAverage(point.items,'development').value;point.testing=metricsPhaseAverage(point.items,'testing').value;point.total=metricsPhaseAverage(point.items,'total').value;point.deliveries=point.items.length});- return {data,mrMerges,mergedMRs,mergedMRsMissingTime,mrMergeTrend,issues,requirementIssues,linkedTAPD,aiIssueIds,covered,completed,firstPass,reworked,interventions,automated,phaseTotalValues,tokens,knownCosts,cost,terminal,frontend,backend,test,deployment,trend,requirements,phaseAverages,phaseTrend,+ return {data,mrMerges,mergedMRs,mergedMRsMissingTime,mrMergeTrend,issues,requirementIssues,linkedTAPD,aiIssueIds,covered,completed,firstPass,reworked,interventions,automated,phaseTotalValues,tokens,knownCosts,cost,terminal,frontend,backend,test,trend,requirements,phaseAverages,phaseTrend,delivered:completed.length,averagePhaseTotalMs:phaseAverages.total.value,firstPassRate:completed.length?firstPass.length*100/completed.length:0,reworkRate:completed.length?reworked.length*100/completed.length:0,averageTokens:completed.length?tokens/completed.length:0,averageCost:knownCosts.length?cost/knownCosts.length:0,averageInterventions:aiIssueIds.size?interventions/aiIssueIds.size:0,automationRate:completed.length?automated.length*100/completed.length:0,coverageRate:requirementIssues.length?covered.length*100/requirementIssues.length:0,runSuccessRate:terminal?Number(data.summary?.succeededRuns||0)*100/terminal:0};}-function metricsSnapshotTrend(snapshot){- const gf=snapshot?.gongfeng||{};- if(state.metricsRange==='365d')return Object.entries(gf.mergedMonths||{}).sort(([a],[b])=>a.localeCompare(b)).map(([key,value])=>({key,label:`${Number(key.slice(5))}月`,deliveries:Number(value||0)}));- const take={"7d":1,"30d":4,"90d":13}[state.metricsRange]||4;- return Object.entries(gf.weeklyMerged||{}).sort(([a],[b])=>a.localeCompare(b)).slice(-take).map(([key,value])=>({key,label:key.replace(/^\d{4}-/,''),deliveries:Number(value||0)}));-}function metricsDisplayModel(model){- const benchmark=state.metricsBenchmark||{},snapshot=benchmark.projectId===metricsProjectId()?benchmark:{},gf=snapshot.gongfeng||{},qci=snapshot.qci||{},loop=snapshot.loop||{},tp=gf.throughput||{},totals=gf.totals||{};- const hasLive=Boolean(model.delivered||model.requirementIssues.length||model.aiIssueIds.size),hasSnapshot=Boolean(Object.keys(gf.weeklyMerged||{}).length),isSnapshot=!hasLive&&hasSnapshot;- const trend=isSnapshot?metricsSnapshotTrend(snapshot):model.trend,total=trend.reduce((n,x)=>n+Number(x.deliveries||0),0);- const firstPass=model.completed.length?model.firstPassRate:(loop.totalRuns?Number(loop.firstPassRate||0):null),runSuccess=model.terminal?model.runSuccessRate:(loop.totalRuns?Number(loop.successRate||0):null);- const coverage=model.requirementIssues.length?model.coverageRate:(loop.issues?Number(loop.uniqueIssues||0)*100/Number(loop.issues):null),tokens=model.completed.length?model.averageTokens:(loop.completedIssues?Number(loop.totalTokens||0)/Number(loop.completedIssues):null);- const deployment=model.deployment.samples?model.deployment:(isSnapshot?{averageMs:Number(qci.deploy?.avgDurationSec||0)*1000,samples:Number(qci.deploy?.sampleSize||0),snapshot:true}:model.deployment);- const deliveryCount=isSnapshot?total:model.delivered,phaseTotalMs=model.averagePhaseTotalMs,daily=isSnapshot&&state.metricsRange==='30d'?Number(tp.currentDaily||0):0;- const story=isSnapshot?`${metricsWindow().label}完成 ${deliveryCount} 个交付,近四周每个工作日稳定合入 ${Number(tp.currentDaily||0).toFixed(2)} 个。`:`${metricsWindow().label}完成 ${deliveryCount} 个需求或 Issue,${model.completed.length?`${model.firstPass.length} 个一次通过`:'等待首个完整交付闭环'}。`;- const storyFoot=isSnapshot?'当前项目暂无完整需求闭环,已自动展示 SkillHub 已验收快照;有实时数据后自动切换。':'指标来自当前项目的需求、Issue、Run、Trace 与部署记录。';- const qualitySlices=isSnapshot?[{label:'已合入',value:Number(totals.merged||0)},{label:'待合入',value:Number(totals.opened||0)},{label:'已关闭',value:Number(totals.closed||0)}]:[{label:'一次通过',value:model.firstPass.length},{label:'返工后完成',value:Math.max(0,model.completed.length-model.firstPass.length)},{label:'进行中',value:Math.max(0,model.aiIssueIds.size-model.completed.length)}];- const categorySlices=isSnapshot?(gf.repos||[]).map(r=>({label:r.name,value:Number(r.merged||0)})):(model.data.categories||[]).map(c=>({label:obsCategoryLabel(c.key),value:Number(c.completedIssues||0)})).filter(x=>x.value);- return {...model,isSnapshot,trend,deliveryCount,phaseTotalMs,deployment,firstPassRate:firstPass,reworkRate:model.completed.length?model.reworkRate:null,runSuccessRate:runSuccess,coverageRate:coverage,averageTokens:tokens,daily,story,storyFoot,qualitySlices,categorySlices,- qualityTitle:isSnapshot?'交付状态':'交付质量',qualityCaption:isSnapshot?'PR 全量状态构成':'一次通过、返工完成与进行中',categoryTitle:isSnapshot?'交付仓库':'需求类型',categoryCaption:isSnapshot?'三个代码仓的合入构成':'按 SOP 统计标签归类',snapshotTotal:isSnapshot?qualitySlices.reduce((n,x)=>n+x.value,0):model.aiIssueIds.size,- lift:isSnapshot?Number(tp.multiplier||0):0,snapshotAt:snapshot.snapshotAt||''};+ const deliveryCount=model.delivered;+ const story=`${metricsWindow().label}完成 ${deliveryCount} 个需求或 Issue,${model.completed.length?`${model.firstPass.length} 个一次通过`:'等待首个完整交付闭环'}。`;+ const storyFoot='指标来自当前项目的需求、Issue、Run 与 Trace。';+ const qualitySlices=[{label:'一次通过',value:model.firstPass.length},{label:'返工后完成',value:Math.max(0,model.completed.length-model.firstPass.length)},{label:'进行中',value:Math.max(0,model.aiIssueIds.size-model.completed.length)}];+ const categorySlices=(model.data.categories||[]).map(c=>({label:obsCategoryLabel(c.key),value:Number(c.completedIssues||0)})).filter(x=>x.value);+ return {...model,deliveryCount,phaseTotalMs:model.averagePhaseTotalMs,firstPassRate:model.completed.length?model.firstPassRate:null,reworkRate:model.completed.length?model.reworkRate:null,runSuccessRate:model.terminal?model.runSuccessRate:null,coverageRate:model.requirementIssues.length?model.coverageRate:null,averageTokens:model.completed.length?model.averageTokens:null,story,storyFoot,qualitySlices,categorySlices,+ qualityTitle:'交付质量',qualityCaption:'一次通过、返工完成与进行中',categoryTitle:'需求类型',categoryCaption:'按 SOP 统计标签归类',snapshotTotal:model.aiIssueIds.size};}function metricsMs(v){return Number(v)===0?'0ms':duration(v)}const METRICS_SLICE_COLORS=['var(--c1)','var(--c2)','var(--c3)','var(--muted-2)','var(--c4)','var(--panel-3)'];@@ -266,7 +195,7 @@ function renderMetricsDashboard(){if(state.metricsError){body.innerHTML=`<div class="metrics-empty"><div><b>看板加载失败</b><p>${escapeHTML(state.metricsError)}</p><button type="button" class="button primary" data-metrics-retry>重新加载</button></div></div>`;body.querySelector('[data-metrics-retry]').onclick=()=>refreshMetrics(true);if(live)live.innerHTML='<i></i> 加载失败';return}if(stale){body.innerHTML='<div class="metrics-loading"><div><i></i><p>正在切换到当前项目的数据…</p></div></div>';if(live)live.innerHTML='<i></i> 等待加载';return}if(!state.metricsData){body.innerHTML='<div class="metrics-empty">选择周期后查看研发效能指标</div>';return}- const raw=metricsDashboardModel(),m=metricsDisplayModel(raw),win=metricsWindow(),missing='待采集',phaseTotalFoot=m.phaseTotalValues.length?`${m.phaseTotalValues.length} 条完成项有阶段耗时`:'等待阶段耗时采集',source=metricsDemoEnabled()?'演示数据':m.isSnapshot?'SkillHub 快照':'项目实时';+ const raw=metricsDashboardModel(),m=metricsDisplayModel(raw),win=metricsWindow(),missing='待采集',phaseTotalFoot=m.phaseTotalValues.length?`${m.phaseTotalValues.length} 条完成项有阶段耗时`:'等待阶段耗时采集',source=metricsDemoEnabled()?'演示数据':'项目实时';const grainLabel=win.grain==='day'?'按日':win.grain==='week'?'按周':'按月',known=list=>list.filter(v=>v!=null);const kpis=obsKpiGroups([obsKpiGroup('交付',[@@ -287,11 +216,11 @@ function renderMetricsDashboard(){const tableCard=obsCard('metrics-requirements','每条需求 / Issue 耗时明细','研发、测试为节点执行累计;* 表示旧流程推断,悬停单元格看计时依据',`<span class="metrics-card-total">${m.requirements.length} <small>条交付项</small></span>`,metricsRequirementTable(m));const deliveryCard=metricsTrendCard('metrics-delivery','交付趋势',`${grainLabel}统计完成的需求与 Issue`,m.trend,{name:'交付',kind:'bar',integer:true,get:p=>Number(p.deliveries||0),format:v=>String(Math.round(v))},()=>metricsTrendSVG(m.trend,'deliveries'),{empty:!m.trend.some(p=>Number(p.deliveries)>0),emptyText:'当前日期范围暂无交付',expand:true});const coverage=obsKpi(metricsKpi({label:'AI 工作项覆盖率',value:m.coverageRate!=null?percent(m.coverageRate):missing,meter:m.coverageRate||0,foot:m.requirementIssues.length?`${m.covered.length} / ${m.requirementIssues.length} 个需求与 Issue · ${m.linkedTAPD} 个关联 TAPD`:'等待工作项创建'}));- const categoryCard=obsCard('metrics-category',m.categoryTitle,m.categoryCaption,'',metricsDonutBlock('metrics-category',m.categorySlices,m.isSnapshot?m.deliveryCount:m.completed.length,m.isSnapshot?'合入':'交付项')+`<div class="metrics-split obs-ks">${coverage}</div>`);+ const categoryCard=obsCard('metrics-category',m.categoryTitle,m.categoryCaption,'',metricsDonutBlock('metrics-category',m.categorySlices,m.completed.length,'交付项')+`<div class="metrics-split obs-ks">${coverage}</div>`);const mrSub=`${grainLabel}统计需求 / Issue 关联 MR;合入目标分支即计数,包含集成分支,同一 MR 只计一次${m.mergedMRsMissingTime?`。${m.mergedMRsMissingTime} 个已合入 MR 缺少合入时间,暂未计入日期统计`:''}`;const mrCard=metricsTrendCard('metrics-mr','MR 合入趋势',mrSub,m.mrMergeTrend,{name:'MR 合入',kind:'bar',integer:true,get:p=>Number(p.mergedMrs||0),format:v=>String(Math.round(v))},()=>metricsTrendSVG(m.mrMergeTrend,'mergedMrs'),{empty:!m.mrMergeTrend.some(p=>Number(p.mergedMrs)>0),emptyText:'当前日期范围暂无已合入 MR',expand:true,height:200,tools:`<span class="metrics-card-total">${m.mergedMRs} <small>个 MR</small></span>`,after:`<details class="metrics-mr-details"><summary>查看合入明细${m.mrMerges.length>80?'(最近 80 条)':''}</summary>${metricsMRMergeTable(m.mrMerges)}</details>`});const rework=obsKpi(metricsKpi({label:'返工率(代理)',value:m.reworkRate!=null?percent(m.reworkRate):missing,meter:m.reworkRate||0,foot:m.completed.length?`${m.reworked.length} / ${m.completed.length} 条完成需求;多 Run、失败、节点返工或重开`:'等待完成需求'}));- const qualityCard=obsCard('metrics-quality',m.qualityTitle,m.qualityCaption,'',metricsDonutBlock('metrics-quality',m.qualitySlices,m.snapshotTotal,m.isSnapshot?'MR':'需求')+`<div class="metrics-split obs-ks">${rework}</div>`);+ const qualityCard=obsCard('metrics-quality',m.qualityTitle,m.qualityCaption,'',metricsDonutBlock('metrics-quality',m.qualitySlices,m.snapshotTotal,'需求')+`<div class="metrics-split obs-ks">${rework}</div>`);const deliveredRows=p=>[['完成项',`${p.deliveries||0} 条`]];const firstPassCard=metricsTrendCard('metrics-firstpass','一次通过率趋势',`${grainLabel}观察交付质量变化`,m.trend,{name:'一次通过率',kind:'line',percent:true,get:p=>p.deliveries?p.firstPass:null,format:v=>percent(v),emptyLabel:'无完成项',rows:deliveredRows},()=>metricsTrendSVG(m.trend,'firstPass'),{empty:!m.completed.length,emptyText:'等待完成需求'});const autoKpis=obsKpiGroup('人工与稳定性',[@@ -316,22 +245,16 @@ function metricsReleaseCharts(body){if(typeof obsExpandState!=='undefined'&&obsExpandState?.card?.closest?.('#metricsView'))obsCollapse({silent:true});if(typeof obsDisposeCharts==='function')obsDisposeCharts(body);}-let metricsRequestSeq=0,metricsPendingKey='',metricsDeploymentRequestSeq=0;+let metricsRequestSeq=0,metricsPendingKey='';function metricsProjectId(){return state.projectFilter||currentProject()?.id||''}function metricsQueryKey(){return [metricsProjectId(),state.metricsRange,state.metricsDateFrom,state.metricsDateTo].join('|')}function invalidateMetricsForProjectChange(){- metricsRequestSeq++;metricsPendingKey='';metricsDeploymentRequestSeq++;- state.metricsData=null;state.metricsDataKey='';state.metricsIssues=[];state.metricsBenchmark=null;state.metricsLoading=false;state.metricsError='';- state.metricsDeploymentData=null;state.metricsDeploymentError='';state.metricsDeploymentLoading=false;+ metricsRequestSeq++;metricsPendingKey='';+ state.metricsData=null;state.metricsDataKey='';state.metricsIssues=[];state.metricsLoading=false;state.metricsError='';}async function refreshMetrics(force=false){const seq=++metricsRequestSeq,key=metricsQueryKey();metricsPendingKey=key;const win=metricsWindow(),projectId=metricsProjectId(),q=new URLSearchParams({projectId,from:win.from.toISOString(),to:win.to.toISOString(),grain:win.grain});state.metricsLoading=true;state.metricsError='';renderMetricsDashboard();- if(metricsDemoEnabled()){const demo=metricsDemoSnapshot(win);state.metricsData=demo.analytics;state.metricsDataKey=key;state.metricsIssues=demo.issues;state.metricsBenchmark=null;state.metricsLoading=false;metricsPendingKey='';renderMetricsDashboard();return}- try{const [analytics,issues,benchmark]=await Promise.all([api('/api/analytics?'+q.toString(),force?{}:{silent:true}),api('/api/issues?projectId='+encodeURIComponent(projectId),{silent:true}),projectId==='skillhub'&&canShowSkillhubEfficiency()?api('/api/analytics/skillhub',{silent:true}).catch(()=>null):Promise.resolve(null)]);if(seq!==metricsRequestSeq||key!==metricsQueryKey())return;state.metricsData=analytics;state.metricsDataKey=key;state.metricsIssues=issues;state.metricsBenchmark=benchmark?.projectId===projectId?benchmark:null}catch(e){if(seq===metricsRequestSeq&&key===metricsQueryKey())state.metricsError=e.message||'加载失败'}finally{if(seq===metricsRequestSeq){metricsPendingKey='';state.metricsLoading=false;renderMetricsDashboard()}}- if(seq===metricsRequestSeq&&deploymentRepositories().length&&!state.metricsDeploymentData&&!state.metricsDeploymentLoading)refreshMetricsDeployment();-}-async function refreshMetricsDeployment(){- const repo=deploymentRepositories()[0],project=currentProject();if(!repo||!project)return;const seq=++metricsDeploymentRequestSeq;state.metricsDeploymentLoading=true;state.metricsDeploymentError='';renderMetricsDashboard();const q=new URLSearchParams({projectId:project.id,repositoryId:repo.id,pageSize:'100'});- try{const data=await api('/api/deployment-metrics?'+q.toString(),{silent:true});if(seq===metricsDeploymentRequestSeq&&project.id===metricsProjectId())state.metricsDeploymentData=data}catch(e){if(seq===metricsDeploymentRequestSeq&&project.id===metricsProjectId()){state.metricsDeploymentData=null;state.metricsDeploymentError=e.message||'智研流水线暂不可用'}}finally{if(seq===metricsDeploymentRequestSeq){state.metricsDeploymentLoading=false;renderMetricsDashboard()}}+ if(metricsDemoEnabled()){const demo=metricsDemoSnapshot(win);state.metricsData=demo.analytics;state.metricsDataKey=key;state.metricsIssues=demo.issues;state.metricsLoading=false;metricsPendingKey='';renderMetricsDashboard();return}+ try{const [analytics,issues]=await Promise.all([api('/api/analytics?'+q.toString(),force?{}:{silent:true}),api('/api/issues?projectId='+encodeURIComponent(projectId),{silent:true})]);if(seq!==metricsRequestSeq||key!==metricsQueryKey())return;state.metricsData=analytics;state.metricsDataKey=key;state.metricsIssues=issues}catch(e){if(seq===metricsRequestSeq&&key===metricsQueryKey())state.metricsError=e.message||'加载失败'}finally{if(seq===metricsRequestSeq){metricsPendingKey='';state.metricsLoading=false;renderMetricsDashboard()}}}function metricHealth(m, liveCount=0){if(liveCount)return {key:'active',label:'运行中',hint:`${liveCount} 个实例执行中`};if(!m?.totalRuns)return {key:'never',label:'从未运行',hint:'需要首次验证'};if(m.waitingRuns)return {key:'active',label:'待审批',hint:`${m.waitingRuns} 个实例等待门禁`};if(m.failedRuns&&m.lastRunStatus==='failed')return {key:'blocked',label:'有阻塞',hint:'最近运行失败'};if(m.succeededRuns)return {key:'closed',label:'已闭环',hint:`${percent(m.closureRate)} 闭环率`};return {key:'blocked',label:'未闭环',hint:'尚无成功运行'}}diff --git a/web/app/harness-motion.js b/web/app/harness-motion.jsindex 968e5524..a4116e6f 100644--- a/web/app/harness-motion.js+++ b/web/app/harness-motion.js@@ -1151,7 +1151,7 @@settings: "settings", bots: "robot", projects: "users", flow: "workflow",agents: "user", mcp: "connector", rules: "doc", skills: "skills",dockerfiles: "layers", environments: "terminal", sandboxes: "server",- knowledge: "brain", metrics: "chart", deployments: "clock",+ knowledge: "brain", metrics: "chart",businessDomains: "layers", businessDomainManagement: "layers",observability: "token", guide: "doc", platform: "gate",};diff --git a/web/app/harness-ui.css b/web/app/harness-ui.cssindex fddf1803..afcce586 100644--- a/web/app/harness-ui.css+++ b/web/app/harness-ui.css@@ -73,7 +73,7 @@ html[data-theme="dark"] {* 原生 Harness 页面:#issuesView #runsView #assetsView #approvalsView #observabilityView #mcpView #botsView #knowledgeView* 设置区视图(1200px 居中容器、页头与按钮映射):* #settingsView #botsView #projectsView #runnersView #agentsView #mcpView #assetsView #knowledgeView- * #metricsView #deploymentsView #businessDomainsView #guideView #platformView #businessDomainManagementView+ * #metricsView #businessDomainsView #guideView #platformView #businessDomainManagementView* 弹窗:#agentModal #customMcpModal #requirementModal(新建需求向导,布局见 requirement-wizard.css)* #flowView 与工作区其他页面不在列表内。*/@@ -85,7 +85,7 @@ html[data-theme="dark"] {/* 设置区旧页面:旧基础令牌(styles / product-v3 / collaboration)在这些作用域内改为引用 --hui-*,* 只改变颜色,不改变任何尺寸与布局。 */-:is(#settingsView, #projectsView, #repoDrawer, .pw-root, #runnersView, #agentsView, #agentModal, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) {+:is(#settingsView, #projectsView, #repoDrawer, .pw-root, #runnersView, #agentsView, #agentModal, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) {--text: var(--hui-text);--text-strong: var(--hui-text);--muted: var(--hui-muted);@@ -118,13 +118,13 @@ html[data-theme="dark"] {--v3-accent-ink: var(--hui-accent);}/* 上面把 --blue 映射为强调色后,旧规则里以 --blue 为实心底的白字在暗色下对比不足,统一改用 --hui-on-accent */-:is(#settingsView, #projectsView, #repoDrawer, .pw-root, #runnersView, #agentsView, #agentModal, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.member-avatar.owner, .pager-page.active, .access-recommended) {+:is(#settingsView, #projectsView, #repoDrawer, .pw-root, #runnersView, #agentsView, #agentModal, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.member-avatar.owner, .pager-page.active, .access-recommended) {color: var(--hui-on-accent);}/* 设置区:页头与内容外层容器居中、最大 1200px;页面内部布局不变。* product-v4.css 用 !important 清掉了这些元素的 max-width / margin,这里同样需要 !important。 */-:is(#settingsView, #botsView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView).page-view.active > :not(.agent-row-menu) {+:is(#settingsView, #botsView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView).page-view.active > :not(.agent-row-menu) {box-sizing: border-box;width: 100%;max-width: 1200px !important;@@ -133,13 +133,13 @@ html[data-theme="dark"] {}/* 设置区页头:H1 22px/600,说明 13px 次级色 */-:is(#settingsView, #botsView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph, .kb-head) h1 {+:is(#settingsView, #botsView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph, .kb-head) h1 {color: var(--hui-text);font: 600 22px/1.25 var(--hui-sans);letter-spacing: -.02em;}-:is(#settingsView, #botsView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph) h1 + p,-:is(#settingsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) .page-heading > div > p:last-child,+:is(#settingsView, #botsView, #projectsView, #runnersView, #agentsView, #mcpView, #assetsView, #knowledgeView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) :is(.page-heading, .pa-ph) h1 + p,+:is(#settingsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView) .page-heading > div > p:last-child,#knowledgeView .kb-head-desc {color: var(--hui-secondary);font-size: 13px;@@ -167,7 +167,7 @@ html[data-theme="dark"] {:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView) .button.small { height: 28px; min-height: 28px; padding: 0 10px; font-size: 12.5px; }:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView) .button.hui-icon-button { width: 32px; padding: 0; }-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button,+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button,:is(#knowledgeView, #kbDrawer) .kb-btn {border: 1px solid var(--hui-border-strong);border-radius: 7px;@@ -178,7 +178,7 @@ html[data-theme="dark"] {transform: none;transition: background-color .18s var(--hui-ease-flow), color .18s var(--hui-ease-flow), border-color .18s var(--hui-ease-flow);}-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:hover:not(:disabled),+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:hover:not(:disabled),:is(#knowledgeView, #kbDrawer) .kb-btn:hover:not(:disabled) {border-color: var(--hui-border-strong);background: var(--hui-canvas);@@ -186,17 +186,17 @@ html[data-theme="dark"] {box-shadow: none;transform: none;}-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:focus-visible,+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:focus-visible,:is(#knowledgeView, #kbDrawer) .kb-btn:focus-visible,.credential-btn:focus-visible {outline: 2px solid var(--hui-focus-ring);outline-offset: 1px;}-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:disabled,+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button:disabled,:is(#knowledgeView, #kbDrawer) .kb-btn:disabled { opacity: .45; cursor: not-allowed; }/* 实心强调:每页只有一个页面级主操作(弹窗/抽屉内另计) */-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark),+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark),:is(#knowledgeView, #kbDrawer) .kb-btn.primary,#issuesView #newIssue,.credential-btn.primary {@@ -204,7 +204,7 @@ html[data-theme="dark"] {background: var(--hui-accent);color: var(--hui-on-accent);}-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark):hover:not(:disabled),+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) :is(.button.primary, .button.dark):hover:not(:disabled),:is(#knowledgeView, #kbDrawer) .kb-btn.primary:hover:not(:disabled),#issuesView #newIssue:hover,.credential-btn.primary:hover:not(:disabled) {@@ -214,24 +214,24 @@ html[data-theme="dark"] {}/* 淡紫行内主操作 */-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft {+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft {border-color: transparent;background: var(--hui-accent-soft);color: var(--hui-accent);}-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft:hover:not(:disabled) {+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #requirementModal) .button.hui-btn-soft:hover:not(:disabled) {border-color: transparent;background: color-mix(in srgb, var(--hui-accent) 16%, var(--hui-surface));color: var(--hui-accent-hover);}/* 删除类:描边 */-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline {+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline {border-color: color-mix(in srgb, var(--hui-error) 30%, var(--hui-border));background: var(--hui-surface);color: var(--hui-error);}-:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline:hover:not(:disabled) {+:is(#issuesView, #assetsView, #approvalsView, #mcpView, #botsView, #settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #customMcpModal, #requirementModal, .pw-root) .button.danger-outline:hover:not(:disabled) {border-color: color-mix(in srgb, var(--hui-error) 30%, var(--hui-border));background: color-mix(in srgb, var(--hui-error) 6%, var(--hui-surface));color: var(--hui-error);@@ -314,7 +314,7 @@ html[data-theme="dark"] {.hui-input,#botsContent :is(.input, .select),:is(#knowledgeView, #kbDrawer) .kb-input,-:is(#settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #requirementModal, .pw-root, .credential-scrim) :is(.input, .select, .textarea) {+:is(#settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #requirementModal, .pw-root, .credential-scrim) :is(.input, .select, .textarea) {border: 1px solid var(--hui-border-strong);border-radius: 8px;background-color: var(--hui-surface);@@ -322,11 +322,11 @@ html[data-theme="dark"] {box-shadow: none;transition: border-color .15s ease, box-shadow .15s ease;}-:is(.hui-input, #botsContent .input, :is(#knowledgeView, #kbDrawer) .kb-input, :is(#settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #requirementModal, .pw-root, .credential-scrim) :is(.input, .select, .textarea))::placeholder { color: var(--hui-tertiary); }+:is(.hui-input, #botsContent .input, :is(#knowledgeView, #kbDrawer) .kb-input, :is(#settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #requirementModal, .pw-root, .credential-scrim) :is(.input, .select, .textarea))::placeholder { color: var(--hui-tertiary); }.hui-input:focus,#botsContent :is(.input, .select):focus,:is(#knowledgeView, #kbDrawer) .kb-input:focus,-:is(#settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #deploymentsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #requirementModal, .pw-root, .credential-scrim) :is(.input, .select, .textarea):focus {+:is(#settingsView, #projectsView, #runnersView, #agentsView, #metricsView, #businessDomainsView, #guideView, #platformView, #businessDomainManagementView, #agentModal, #requirementModal, .pw-root, .credential-scrim) :is(.input, .select, .textarea):focus {outline: 0;border-color: var(--hui-accent);box-shadow: 0 0 0 3px var(--hui-accent-soft);diff --git a/web/app/obs-charts.js b/web/app/obs-charts.jsindex fde7508c..8bc7620b 100644--- a/web/app/obs-charts.js+++ b/web/app/obs-charts.js@@ -257,40 +257,6 @@ function obsOwnersOption(rows,opts){});}-// ---------- SkillHub 提效 -----------function obsStackBarOption(labels,stacks,opts,extra){- const o=obsChartOpts(opts),t=o.theme;- extra=extra||{};- const totals=labels.map((_,i)=>stacks.reduce((n,s)=>n+(Number(s.values[i])||0),0));- const series=stacks.map((s,si)=>({name:s.name,type:'bar',stack:'total',barMaxWidth:extra.barMaxWidth||36,itemStyle:{color:s.color,borderRadius:si===stacks.length-1?[2,2,0,0]:0},data:labels.map((_,i)=>Number(s.values[i])||0),animationDelay:obsBarDelay(o,extra.delayStep||35),- label:extra.showTotal&&si===stacks.length-1?{show:true,position:'top',color:t.text,fontWeight:600,fontSize:11,formatter:p=>totals[p.dataIndex]||''}:undefined}));- if(extra.markFrom!=null&&extra.markFrom>=0&&labels.length){- series[0].markArea={silent:true,itemStyle:{color:t.text,opacity:.05},data:[[{xAxis:labels[Math.min(extra.markFrom,labels.length-1)]},{xAxis:labels[labels.length-1]}]]};- }- return obsChartBase(o,{- grid:{left:6,right:8,top:extra.showTotal?22:12,bottom:4,containLabel:true},- tooltip:{...obsTooltipBase(t),trigger:'axis',axisPointer:{type:'shadow',shadowStyle:{color:t.text,opacity:.04}},formatter:params=>{const idx=params[0]?.dataIndex;return obsTooltipRows(labels[idx],[...stacks.map(s=>[s.name,String(Number(s.values[idx])||0)]),['合计',String(totals[idx]||0)]])}},- xAxis:obsCategoryAxis(t,labels,extra.xInterval!=null?{axisLabel:{color:t.muted2,fontSize:10.5,interval:extra.xInterval}}:{}),- yAxis:obsValueAxis(t,v=>String(v)),- series,- });-}-function obsSkillhubMonthlyOption(d,opts){- const o=obsChartOpts(opts),t=o.theme,gf=d?.gongfeng||{};- const months=Object.keys(gf.mergedMonths||{}).sort();- return obsStackBarOption(months.map(m=>Number(m.slice(5))+'月'),[{name:'老库',color:t.c4,values:months.map(m=>gf.monthlyLegacy?.[m]||0)},{name:'大仓',color:t.c1,values:months.map(m=>gf.monthlyMonorepo?.[m]||0)}],opts,{showTotal:true});-}-function obsSkillhubWeeklyOption(d,opts){- const o=obsChartOpts(opts),t=o.theme,gf=d?.gongfeng||{};- const keys=Object.keys(gf.weeklyMerged||{}).sort().slice(-12);- return obsStackBarOption(keys.map(k=>'W'+k.slice(-2)),[{name:'老库',color:t.c4,values:keys.map(k=>gf.weeklyLegacy?.[k]||0)},{name:'大仓',color:t.c1,values:keys.map(k=>gf.weeklyMonorepo?.[k]||0)}],opts,{markFrom:Math.max(0,keys.length-4),barMaxWidth:28});-}-function obsSkillhubDeployOption(snap,opts){- const o=obsChartOpts(opts),t=o.theme,daily=snap?.dailySample||{};- const labels=daily.labels||[];- return obsStackBarOption(labels,[{name:'后端',color:t.c1,values:daily.backend||[]},{name:'前端',color:t.c2,values:daily.frontend||[]},{name:'E2E',color:t.c3,values:daily.e2e||[]}],opts,{xInterval:4,delayStep:12,barMaxWidth:18});-}-// ---------- 研发效能 ----------const OBS_PHASES=[['clarification','澄清','c1'],['development','研发','c2'],['testing','测试','c3']];const OBS_PHASE_TOP_LABEL_MAX=45;diff --git a/web/app/observability.js b/web/app/observability.jsindex 5c140b77..59838b50 100644--- a/web/app/observability.js+++ b/web/app/observability.js@@ -10,25 +10,8 @@ function isPreviewHost(){const domain=String((typeof state!=='undefined'&&state.appDomain)||(typeof window!=='undefined'&&window.__AGENTFLOW_APP_DOMAIN__)||'').toLowerCase();return host==='loopforge-test.example.com'||domain==='loopforge-test.example.com'||host.includes('-test.')||isLoopbackHost(host);}-function isSkillHubProject(p){- p=p||currentProject();- const blob=[p?.id,p?.key,p?.name].map(x=>String(x||'').toLowerCase()).join(' ');- return blob.includes('skillhub');-}-function canShowSkillhubEfficiency(){return false}-function renderObsTabs(){- const show=canShowSkillhubEfficiency();- const tab=$('#obsSkillhubTab');- if(tab)tab.hidden=!show;- const btn=$('.nav[data-view="deployments"]');- if(btn)btn.hidden=!show;- if(!show&&state.obsTab==='skillhub')state.obsTab='overview';-}-function obsNormalizeTab(tab){- if(tab==='delivery')return 'delivery';- if(tab==='skillhub'&&canShowSkillhubEfficiency())return 'skillhub';- return 'overview';-}+function renderObsTabs(){state.obsTab=obsNormalizeTab(state.obsTab)}+function obsNormalizeTab(tab){return tab==='delivery'?'delivery':'overview'}function obsScope(){return state.obsScope==='project'?'project':'user'}function obsTrendGrain(){return ['day','week','month','all'].includes(state.obsTrendGrain)?state.obsTrendGrain:'all'}function obsApiGrain(){return obsTrendGrain()==='all'?'month':obsTrendGrain()}@@ -364,11 +347,7 @@ async function switchObsTab(tab){tab=obsNormalizeTab(tab);state.obsTab=tab;$$('#obsTabs .obs-tab').forEach(x=>x.classList.toggle('active',x.dataset.obsTab===tab));- if(tab==='skillhub'){- const host=$('#obsBody');- if(host)host.innerHTML=`<div class="obs-pane active"><div class="detail-empty">正在加载 SkillHub 提效数据…</div></div>`;- await refreshSkillhubEfficiency();- }else if(tab==='delivery'&&!state.obsAnalyticsFull){+ if(tab==='delivery'&&!state.obsAnalyticsFull){const host=$('#obsBody');if(host)host.innerHTML=`<div class="obs-pane active"><div class="detail-empty">正在加载交付数据…</div></div>`;try{@@ -378,20 +357,6 @@ async function switchObsTab(tab){}renderObservability();}-async function refreshSkillhubEfficiency(){- if(!canShowSkillhubEfficiency()){state.skillhubEfficiency=null;state.skillhubDeploy=null;state.skillhubDeployError='';return}- const repo=deploymentSelectedRepository();- const project=currentProject();- const q=repo?new URLSearchParams({projectId:project?.id||'',repositoryId:repo.id,pageSize:'100'}):null;- const [board,deploy]=await Promise.allSettled([- api('/api/analytics/skillhub',{silent:true}),- q?api('/api/deployment-metrics?'+q.toString(),{silent:true}):Promise.reject(new Error('当前项目未绑定 SkillHub 仓库,快照里的 QCI 数仍可用')),- ]);- if(board.status==='fulfilled')state.skillhubEfficiency=board.value;- else{state.skillhubEfficiency=null;toast(board.reason?.message||'提效数据加载失败')}- if(deploy.status==='fulfilled'){state.skillhubDeploy=deploy.value;state.skillhubDeployError=''}- else{state.skillhubDeploy=null;state.skillhubDeployError=deploy.reason?.message||'部署数据加载失败'}-}async function refreshObs(){if(refreshObsPending)return refreshObsPending;refreshObsPending=(async()=>{@@ -402,10 +367,7 @@ async function refreshObs(){try{const opt={silent:true};const overview=state.obsTab!=='delivery';- const [analytics]=await Promise.all([- api('/api/analytics'+analyticsQuery({overview}),opt),- state.obsTab==='skillhub'?refreshSkillhubEfficiency():Promise.resolve(),- ]);+ const analytics=await api('/api/analytics'+analyticsQuery({overview}),opt);state.analytics=analytics;if(!overview)state.obsAnalyticsFull=true;}catch(e){toast(e.message)}@@ -602,9 +564,7 @@ function renderObservability(){obsDisposeSelects();obsCardBuilders={};const tab=state.obsTab;- if(tab==='skillhub'){- host.innerHTML=`<div class="obs-pane active">${obsSkillhub()}</div>`;- }else{+ {const html=tab==='delivery'?obsDelivery():obsOverview();host.innerHTML=`<div class="obs-pane active">${obsFilterBar()}${html}</div>`;state.obsSelects=obsEnhanceSelects(host);@@ -859,8 +819,8 @@ function obsHtmlRows(list){return obsRow(cells,attrs.trim(),cls);});}-function obsDetailScope(){return state.obsTab==='skillhub'?'skillhub':'overview'}-function obsDetailGroups(){return obsDetailScope()==='skillhub'?obsSkillhubDetailGroups():obsUsageDetailGroups(obsScopedView())}+function obsDetailScope(){return 'overview'}+function obsDetailGroups(){return obsUsageDetailGroups(obsScopedView())}function obsDetailItems(groups){return (groups||obsDetailGroups()).flatMap(g=>g.items).filter(Boolean)}function obsDetailCurrent(groups){const items=obsDetailItems(groups);@@ -1367,186 +1327,6 @@ function obsCrossProjectTable(){:`该责任人目前只在当前项目有执行记录,个人与项目切换不会把其他项目加进来。`;return {key:'projects',title:'该责任人在各项目',sub:note,tables:[{headers:['项目','运行','需求','Tokens','成本'],rows:rows.map(r=>obsRow([`<b>${escapeHTML(obsProjectName(r.projectId))}</b>${r.projectId===current?'<span class="obs-pill">当前</span>':''}`,String(r.runs||0),String(r.uniqueIssues||0),formatTokens(r.tokens),costLabel(r.costCny,r.costKnown)],'',r.projectId===current?'obs-current-project':''))}]};}-// ---------- SkillHub 提效 -----------function obsSkillhub(){- const d=state.skillhubEfficiency;- if(!d)return `<div class="detail-empty">正在加载 SkillHub 提效数据…</div>`;- obsCardBuilders={detail:obsDetailCard};- const qci=d.qci||{};- const deploy30=(qci.backend?.recent30d||0)+(qci.frontend?.recent30d||0);- const snap=d.snapshotAt?new Date(d.snapshotAt).toLocaleString():'—';- const kpis=obsKpiGroups([obsKpiGroup('提效',[- {label:'已合入',value:'725',foot:'大仓 210 · 老库 515'},- {label:'近 4 周日均',value:'6.45',foot:'129 个 / 20 个工作日'},- {label:'相对起步',value:'7.82',unit:'×',foot:'起步 8 周日均 0.83'},- {label:'测试环境部署',value:'1589',foot:`近 30 天 ${deploy30||375} · E2E 482`},- ],`快照 ${escapeHTML(snap)}`)]);- const vs=`<div class="sh-vs"><article><span>起步 · 前 8 周</span><b>0.83</b><em>每个工作日</em><p>33 个已合入 · 40 个工作日</p></article><article class="is-now"><span>近 4 周</span><b>6.45</b><em>每个工作日</em><p>129 个已合入 · 大仓 125 · 7.82 倍</p></article></div>`;- const legend='<div class="obs-legend"><span><i style="background:var(--c4)"></i>老库</span><span><i style="background:var(--c1)"></i>大仓</span></div>';- const svg=obsSkillhubCharts(d);- const monthly=obsChartSlot('sh-monthly',{- empty:!Object.keys(d.gongfeng?.mergedMonths||{}).length,- option:(theme,reduced)=>obsSkillhubMonthlyOption(d,obsChartFormatters(theme,reduced)),- fallback:()=>obsSkillhubChartSvg(svg,0)- },260);- const weekly=obsChartSlot('sh-weekly',{- empty:!Object.keys(d.gongfeng?.weeklyMerged||{}).length,- option:(theme,reduced)=>obsSkillhubWeeklyOption(d,obsChartFormatters(theme,reduced)),- fallback:()=>obsSkillhubChartSvg(svg,1)- },260);- return `<div class="sh-page">- <p class="obs-note">合入从起步每天不到 1 个,到近四周每个工作日 6.45 个。</p>- ${kpis}- ${vs}- <div class="obs-grid2 is-wide-left">- ${obsCard('sh-monthly','每月已合入','',legend,monthly,{expand:true,klass:'sh-chart-hero'})}- ${obsCard('sh-weekly','近 12 周','阴影为近 4 周',legend,weekly,{expand:true})}- </div>- ${obsSkillhubDeployCard()}- ${obsDetailCard()}- </div>`;-}-function obsSkillhubChartSvg(html,index){- const tpl=document.createElement('template');- tpl.innerHTML=html;- const cards=tpl.content.querySelectorAll('.sh-chart-card');- return cards[index]?cards[index].outerHTML:'';-}-function obsSkillhubDeployCard(){- const snap=state.skillhubEfficiency?.qci||{};- const deploy=snap.deploy||{},e2e=snap.e2e||{},backend=snap.backend||{},frontend=snap.frontend||{};- const err=state.skillhubDeployError;- const backendURL=safeURL(deploy.url||snap.url||'');- const frontendURL=safeURL((snap.pipelines||[]).find(p=>p.id===10000002)?.url||'');- const e2eURL=safeURL(e2e.url||'');- const open=url=>url?` · <a href="${escapeHTML(url)}" target="_blank" rel="noopener noreferrer">打开</a>`:'';- const chart=obsChartSlot('sh-deploy',{- empty:!(snap.dailySample?.labels||[]).length,emptyText:'暂无每日部署样本',- option:(theme,reduced)=>obsSkillhubDeployOption(snap,obsChartFormatters(theme,reduced)),- fallback:()=>obsSkillhubDeployCharts(snap)- },240);- const legend='<div class="obs-legend"><span><i style="background:var(--c1)"></i>后端</span><span><i style="background:var(--c2)"></i>前端</span><span><i style="background:var(--c3)"></i>E2E</span></div>';- const body=`<div class="obs-signal-row"><div><b data-obs-count>${backend.runNum||0}</b><span>后端测试环境${open(backendURL)}</span></div><div><b data-obs-count>${frontend.runNum||0}</b><span>前端测试环境${open(frontendURL)}</span></div><div><b data-obs-count>${e2e.runNum||0}</b><span>独立 E2E${open(e2eURL)}</span></div></div><h4 class="obs-sub-title">每天部署次数</h4>${chart}${legend}${err?`<p class="sh-note">实时接口:${escapeHTML(err)}</p>`:''}`;- return obsCard('sh-deploy','测试环境部署',`智研 ${snap.projectId||10001} · ${snap.countedPipelines||13} 条流水线`,'',body,{expand:true});-}-function obsSkillhubDetailGroups(){- const d=state.skillhubEfficiency||{};- const gf=d.gongfeng||{},local=d.localWorkflows||{},loop=d.loop||{},snap=d.qci||{};- const repos=(gf.repos||[]).map(r=>{- const url=safeURL(r.url||'');- const name=url?`<a href="${escapeHTML(url)}" target="_blank" rel="noopener noreferrer">${escapeHTML(r.name)}</a>`:escapeHTML(r.name);- return obsRow([`${name}<div class="muted">${escapeHTML(r.path||'')}</div>`,String(r.created||0),`<b>${r.merged||0}</b>`,String(r.opened||0),escapeHTML((r.lastAt||'').slice(0,10))]);- });- const authors=(gf.authors||[]).map(a=>obsRow([escapeHTML(a.username),String(a.mrs||0)]));- const pipes=(snap.pipelines||[]).map(p=>{- const url=safeURL(p.url||'');- const name=url?`<a href="${escapeHTML(url)}" target="_blank" rel="noopener noreferrer">${escapeHTML(p.name||'')}</a>`:escapeHTML(p.name||'');- return obsRow([escapeHTML(p.kind||''),`${name}<div class="muted">${escapeHTML(p.era||'')}</div>`,`<b>${p.runNum||0}</b>`,String(p.recent30d||0)]);- });- const stages=local.backendStageHits||{};- const stageRows=[['01-requirement','需求'],['02-design','设计'],['03-code','编码'],['04-e2e','E2E']].map(([k,l])=>obsRow([l,`${stages[k]||0} / ${local.backendUnique||0}`]));- const links=(d.evidence||[]).map(e=>`<a class="sh-link" href="${escapeHTML(safeURL(e.url))}" target="_blank" rel="noopener noreferrer">${escapeHTML(e.label)}</a>`).join('');- const hasLoop=loop.issues||loop.totalRuns||loop.doneIssues;- return [- {group:'代码仓库',items:[- {key:'repos',title:'仓库',tables:[{headers:['仓库','创建','已合入','打开','最近合入'],rows:repos}]},- {key:'authors',title:'作者 TOP',sub:'三库合计',tables:[{headers:['作者','PR / MR'],rows:authors}]},- ]},- {group:'部署',items:[- pipes.length?{key:'pipelines',title:'流水线',sub:`${snap.countedPipelines||pipes.length} 条计入统计`,tables:[{headers:['类型','流水线','累计','近 30 天'],rows:pipes}]}:null,- ]},- {group:'工作流',items:[- {key:'backend',title:'后端工作流',sub:`${local.backendUnique||0} 条`,tables:[{headers:['阶段','覆盖'],rows:stageRows}]},- {key:'local',title:'本地产物',count:3,html:`<div class="obs-signal-row"><div><b>${local.frontendWorkflows||0}</b><span>前端工作流</span></div><div><b>${local.backendKnowledgeDocs||0}</b><span>知识文档</span></div><div><b>${local.backendE2eFiles||0}</b><span>E2E 文档</span></div></div>`},- hasLoop?{key:'loop',title:'Loop 运行',count:loop.totalRuns||0,html:obsSkillhubLoopCard(loop)}:null,- ]},- {group:'说明',items:[- {key:'evidence',title:'数据来源',count:(d.evidence||[]).length,html:`<div class="sh-links">${links||'<span class="muted">暂无</span>'}</div>`},- (d.insights||[]).length?{key:'insights',title:'结论 · AI 分析',count:d.insights.length,html:obsSkillhubInsights(d.insights)}:null,- ]},- ];-}-function obsSkillhubCharts(d){- const gf=d.gongfeng||{};- const months=Object.keys(gf.mergedMonths||{}).sort();- const weekKeys=Object.keys(gf.weeklyMerged||{}).sort().slice(-12);- const legend=`<div class="sh-chart-legend"><span><i class="legacy"></i>老库</span><span><i class="mono"></i>大仓</span></div>`;- return `<div class="sh-charts">- ${obsSkillhubChart({title:'每月已合入',klass:'sh-chart-hero',labels:months.map(m=>Number(m.slice(5))+'月'),stacks:[{color:'var(--c4)',values:months.map(m=>gf.monthlyLegacy?.[m]||0)},{color:'var(--c1)',values:months.map(m=>gf.monthlyMonorepo?.[m]||0)}],showValue:true,legend})}- ${obsSkillhubChart({title:'近 12 周',labels:weekKeys.map(k=>'W'+k.slice(-2)),stacks:[{color:'var(--c4)',values:weekKeys.map(k=>gf.weeklyLegacy?.[k]||0)},{color:'var(--c1)',values:weekKeys.map(k=>gf.weeklyMonorepo?.[k]||0)}],markFrom:weekKeys.length-4,legend})}- </div>`;-}-function obsSkillhubChart({title,klass,labels,stacks,showValue,markFrom,legend,xStep}){- const cols=labels||[];- if(!cols.length||!stacks?.length)return '';- const w=640,h=248,l=42,r=10,t=22,b=30;- const plotW=w-l-r,plotH=h-t-b;- const totals=cols.map((_,i)=>stacks.reduce((s,st)=>s+(Number(st.values[i])||0),0));- const max=Math.max(1,...totals);- const gap=cols.length>8?6:16;- const barW=Math.max(8,(plotW-gap*(cols.length+1))/cols.length);- const step=xStep||(cols.length>10?Math.ceil(cols.length/6):1);- const yTicks=[0,0.5,1].map(p=>{- const y=t+plotH*(1-p),val=Math.round(max*p);- return `<line x1="${l}" y1="${y.toFixed(1)}" x2="${w-r}" y2="${y.toFixed(1)}"/><text class="obs-chart-y" x="${l-8}" y="${(y+3).toFixed(1)}" text-anchor="end">${val}</text>`;- }).join('');- let mark='';- if(markFrom!=null&&markFrom>=0){- const x1=l+gap+markFrom*(barW+gap)-gap/2;- const x2=l+gap+(cols.length-1)*(barW+gap)+barW+gap/2;- mark=`<rect x="${x1.toFixed(1)}" y="${t}" width="${Math.max(0,x2-x1).toFixed(1)}" height="${plotH}" style="fill:var(--c1);opacity:.08"></rect>`;- }- const bars=cols.map((lb,i)=>{- const x=l+gap+i*(barW+gap);- let y=t+plotH;- const rects=stacks.map(st=>{- const bh=plotH*(Number(st.values[i])||0)/max;- y-=bh;- return `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${barW.toFixed(1)}" height="${Math.max(0,bh).toFixed(1)}" style="fill:${st.color}"></rect>`;- }).join('');- const n=totals[i];- const value=showValue&&n?`<text x="${(x+barW/2).toFixed(1)}" y="${Math.max(12,y-6).toFixed(1)}" text-anchor="middle" class="sh-bar-n">${n}</text>`:'';- const tick=i===0||i===cols.length-1||i%step===0?`<text x="${(x+barW/2).toFixed(1)}" y="${h-10}" text-anchor="middle">${escapeHTML(lb)}</text>`:'';- return `<g>${rects}${value}${tick}</g>`;- }).join('');- return `<div class="obs-card sh-chart-card ${klass||''}">- <div class="sh-chart-head"><b>${escapeHTML(title)}</b>${legend||''}</div>- <svg class="sh-bars" viewBox="0 0 ${w} ${h}" role="img" aria-label="${escapeHTML(title)}">${yTicks}${mark}${bars}</svg>- </div>`;-}-function obsSkillhubLoopCard(loop){- if(!loop||!(loop.issues||loop.totalRuns||loop.doneIssues))return '';- return `<div class="obs-card" style="margin-bottom:14px">- <div class="obs-card-title">Loop 运行</div>- <div class="obs-signal-row">- <div><b>${loop.issues||0}</b><span>平台需求</span></div>- <div><b>${loop.doneIssues||0}</b><span>已闭环</span></div>- <div><b>${loop.totalRuns||0}</b><span>SOP 运行</span></div>- </div>- </div>`;-}-function obsSkillhubInsights(items){- if(!items.length)return '';- const rows=items.map(it=>`<details class="sh-insight"><summary>${escapeHTML(it.title||'')}</summary><p>${escapeHTML(it.body||'')}</p></details>`).join('');- return `<section class="sh-appendix"><div class="sh-chart-head"><b>结论</b><span class="sub">AI 分析 · 点开看</span></div><div class="sh-insights">${rows}</div></section>`;-}-function obsSkillhubDeployCharts(snap){- const daily=snap.dailySample||{};- const labels=daily.labels||[];- const countLegend=`<div class="sh-chart-legend"><span><i style="background:var(--c1)"></i>后端</span><span><i style="background:var(--c2)"></i>前端</span><span><i style="background:var(--c3)"></i>E2E</span></div>`;- return `<div class="sh-charts is-single" style="margin-top:12px">${obsSkillhubChart({- title:'每天部署次数',- klass:'sh-chart-hero',- labels,- stacks:[- {color:'var(--c1)',values:daily.backend||[]},- {color:'var(--c2)',values:daily.frontend||[]},- {color:'var(--c3)',values:daily.e2e||[]}- ],- legend:countLegend,- xStep:5- })}</div>`;-}const OBS_DELIVERY_FILTERS=[['all','全部'],['delivered','已交付'],['sop','SOP 成功'],['direct','对话改代码'],['withmr','有 PR'],['mr','PR 已合入'],['baseline','已合入基线'],['github','GitHub'],['local','本地']];function obsDeliveryMRs(it){const list=it.mrs?.length?it.mrs:it.mrUrl?[{url:it.mrUrl,project:it.mrProject,iid:it.mrIid,state:it.mrState}]:[];@@ -1676,17 +1456,6 @@ function obsDeliveriesCard(){const body=`<div class="obs-chips">${chips}</div>${obsDetailTable(def.tables[0],'','')}`;return obsCard('deliveries','需求交付明细','耗时为该需求最近一次执行的端到端时间;执行耗时 = 该需求全部执行按 SOP 节点求和;周期为首次执行到最后一次执行。「已合入 / 已交付」只统计默认分支。',`<button type="button" class="obs-btn" data-obs-export-csv="deliveries">${obsIcon('download')}CSV</button>`,body,{klass:'obs-deliveries'});}-function buildSkillhubReportHTML(){- const d=state.skillhubEfficiency;- if(!d||!canShowSkillhubEfficiency())return '';- const gf=d.gongfeng||{},loop=d.loop||{},local=d.localWorkflows||{},tp=gf.throughput||{},totals=gf.totals||{};- const repoRows=(gf.repos||[]).map(r=>`<tr><td>${escapeHTML(r.name)}</td><td>${r.created||0}</td><td>${r.merged||0}</td><td>${r.opened||0}</td><td>${r.closed||0}</td></tr>`).join('');- const insightRows=(d.insights||[]).map(c=>`<tr><td>${escapeHTML(c.title)}</td><td>${escapeHTML(c.body||'')}</td></tr>`).join('');- return `<section class="block"><h2>SkillHub 提效看板</h2>- <p>已合入 PR ${totals.merged||0} · 近窗口日均 ${tp.currentDaily||'—'} · Loop 闭环 ${loop.doneIssues||0}/${loop.issues||0} · 本地工作流 ${local.backendUnique||0}+${local.frontendWorkflows||0}</p></section>- ${obsReportTable('PR / MR',['仓库','创建','已合入','打开','关闭'],repoRows)}- ${obsReportTable('AI 分析',['结论','依据'],insightRows)}`;-}function obsPlain(v){return String(v==null?'':v).replace(/<[^>]+>/g,'')}function obsReportScope(){const project=currentProject();@@ -1707,7 +1476,6 @@ async function exportObsReport(){state.analytics=await api('/api/analytics'+analyticsQuery({overview:false}),{silent:true});state.obsAnalyticsFull=true;}- if(canShowSkillhubEfficiency()&&!state.skillhubEfficiency)await refreshSkillhubEfficiency();const html=buildObsReportHTML();const blob=new Blob([html],{type:'text/html;charset=utf-8'});const a=document.createElement('a');@@ -1776,7 +1544,6 @@ ${obsReportTable('SOP 版本对比',['SOP','版本','运行','成功率','Tokens${obsReportTable(obsGrainCaption()+'趋势',['周期','运行','需求','成功','失败','Tokens','成本','执行耗时'],trendRows)}${projectRows?obsReportTable('各项目用量',['项目','运行','需求','Tokens','成本'],projectRows):''}${obsReportTable('交付明细',['单号','标题','SOP','流程','责任人','Tokens','成本','PR','交付'],deliveryRows)}-${buildSkillhubReportHTML()}<footer>由 AgentFlow 用量分析导出。日志与 Trace 请在运行记录中查看。</footer></div></body></html>`;}diff --git a/web/app/runs.js b/web/app/runs.jsindex fc378833..a3e1267b 100644--- a/web/app/runs.js+++ b/web/app/runs.js@@ -984,6 +984,22 @@ function graphNodeView(r,nodeId){}return view;}+// Stage window: when this stage's nodes started and finished, shown next to the stage label.+function stageTimeRange(r,stage){+ const entries=(stage||[]).map(node=>r?.nodes?.[node.id]).filter(item=>item&&item.startedAt);+ const starts=entries.map(item=>new Date(item.startedAt).getTime()).filter(value=>Number.isFinite(value));+ if(!starts.length)return null;+ const running=entries.some(item=>!item.finishedAt);+ const ends=running?[]:entries.map(item=>new Date(item.finishedAt).getTime()).filter(value=>Number.isFinite(value));+ return {start:Math.min(...starts),end:ends.length?Math.max(...ends):null,running:running||!ends.length};+}+function stageTimeLabel(r,stage){+ const range=stageTimeRange(r,stage);+ if(!range)return '';+ const start=new Date(range.start).toLocaleTimeString();+ const end=range.running||range.end===null?'现在':new Date(range.end).toLocaleTimeString();+ return `${start} → ${end}`;+}function runNodeIcon(kind){const types=typeof FLOW_NODE_TYPES==='object'&&FLOW_NODE_TYPES?FLOW_NODE_TYPES:{};const name=types[kind]?.icon||'bot';@@ -1103,7 +1119,7 @@ function renderRunDetail(r){const runTabs=['overview:概览','trace:实时轨迹','logs:Worker日志','workspace:工作区'];if(previewEnabled)runTabs.push('preview:前端预览');runTabs.push('eval:智能评测');- host.innerHTML=`<div class="run-detail-main"><header class="run-detail-header"><div class="run-detail-topbar"><button class="button ghost small run-back-inline" data-run-back>← 返回运行列表</button><div class="run-breadcrumb"><span>${issueRef}</span><i>›</i><span>${escapeHTML(wf.name)}</span></div>${r.executionContext?.parentRunId?`<button class="button ghost small" data-open-parent-run="${escapeHTML(r.executionContext.parentRunId)}">↑ 返回父 SOP 运行</button>`:''}<div class="run-header-actions">${issueId?`<button class="button primary small" data-open-issue="${escapeHTML(issueId)}">打开需求</button>`:''}${!r.pauseRequested?refreshRunSOPButtonHTML(r):''}<button class="button ghost small" data-open-flow>查看流程定义</button>${['queued','running','waiting'].includes(r.status)?'<button class="button danger-outline small" data-cancel-run>取消运行</button>':'<button class="button danger-outline small" data-delete-run>删除记录</button>'}</div></div><div class="run-header-main"><div><h2>${escapeHTML(ctx.issue?.title||wf.name)}</h2><p>${escapeHTML(r.input||'无运行输入')}</p></div><div class="run-status-wrap"><span class="status ${runDisplayStatusClass(r)}">${runDisplayStatus(r)}</span>${r.status==='failed'&&!gongfengIssueClosed(ctx.issue)?'<button class="button primary small" data-resume-run>↻ 重试运行</button>':''}${canManuallyPassFailedNode(r)&&!gongfengIssueClosed(ctx.issue)?`<button class="button ghost small" data-pass-node="${escapeHTML(r.id)}" data-node="${escapeHTML(failedNodeId(r))}">手动通过</button>`:''}</div></div><div class="run-header-meta"><span class="run-meta-chip run-id-chip" title="${escapeHTML(r.id)}">Run <code>${escapeHTML(r.id.slice(-12))}</code><button type="button" class="run-id-copy" data-copy-run title="复制完整 Run ID" aria-label="复制 Run ID"><svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/><path d="M10.5 5.5V3.5A1.5 1.5 0 0 0 9 2H3.5A1.5 1.5 0 0 0 2 3.5V9A1.5 1.5 0 0 0 3.5 10.5H5.5"/></svg></button></span>${runModeChipHTML(r,wf)}${runExecutionChipHTML(r)}<span class="run-meta-chip"><svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-1px;margin-right:4px;"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>启动于 ${new Date(r.createdAt).toLocaleString()}</span><span class="run-meta-chip" title="${escapeHTML(runTimingTitle(r))}"><svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-1px;margin-right:4px;"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>执行 ${runElapsed(r)}${runWallNote(r)}</span></div></header><div class="run-section-label"><b>执行详情</b><div class="run-section-label-actions"><button class="button ghost small" data-export-logs title="下载本次运行全部节点的 Worker 日志">导出全部日志</button><div class="run-tabs" role="tablist">${runTabs.map(t=>{const[k,label]=t.split(':');return `<button class="run-tab ${runDetailTab===k?'active':''}" data-run-tab="${k}">${label}</button>`}).join('')}</div></div></div><div class="run-pane" data-run-pane="overview" ${runDetailTab==='overview'?'':'hidden'}><section class="run-context-grid">${runProgressCellHTML(r,wf,progress,graphNodes)}<div data-run-usage>${liveUsageHTML(r)}</div><div><span>交付物</span><b>${(r.artifacts||[]).length} 个不可变快照</b><small>按节点和尝试次数保留版本</small></div></section></section>${alignPanelHTML}${runIsGroupMode(r)?`<details class="run-sop-snapshot"><summary><div><b>已冷冻 SOP 快照</b><span>历史协作 · ${graphNodes.length} 个节点可展开审计</span></div></summary>`:''}<section class="run-graph-section"><div class="section-heading"><div><h3>节点执行拓扑</h3><span>点击节点查看该节点的输出、产物和执行事件</span></div><div class="graph-legend"><span><i class="succeeded"></i>完成</span><span><i class="running"></i>运行中</span><span><i class="waiting_approval"></i>待审批</span><span><i></i>未开始</span></div></div><div class="run-graph">${graphNodes.map((n,index)=>{const gv=graphNodeView(r,n.id),meta=nodeMeta(n),arts=(r.artifacts||[]).filter(a=>a.nodeId===n.id).length;return `${index?'<span class="graph-arrow">→</span>':''}<button class="graph-node ${gv.cls} ${state.selectedRunNode===n.id?'selected':''}" data-run-node="${escapeHTML(n.id)}"><span class="node-icon ${meta.kind}">${runNodeIcon(meta.kind)}</span><div><b>${escapeHTML(n.name)}</b><small>${escapeHTML(gv.text)}</small></div>${arts?`<em>${arts} 产物</em>`:''}</button>`}).join('')}</div></section><div class="node-drilldown"><section class="node-inspector"><div class="section-heading"><div class="node-inspector-title"><h3>${escapeHTML(selected?.name||'节点详情')}</h3><span class="node-activity-inline" ${nr.activity?'':'hidden'}>当前活动:<b>${escapeHTML(nr.activity||'')}</b></span><span class="node-inspector-model">${escapeHTML(nr.provider||'未分配')}${nr.model?` · ${escapeHTML(nr.model)}`:''}</span></div><span class="status ${nr.status||'pending'}">${statusText(nr.status)||'待执行'}</span></div><div class="node-facts"><div><span>执行次数</span><b>${nr.attempt||0}</b></div><div><span>返工</span><b>${nr.reworkCount||0}</b></div><div><span>Token</span><b>${formatTokens(nr.usage?.totalTokens)}</b></div><div><span>工具调用</span><b>${nr.toolCalls||0}</b></div></div>${childSOPPanelHTML(r,selected?.id)}${gateResultCardHTML(nr)}${canRerunFromHere(r,selected?.id)?`<div class="node-rerun-row"><button type="button" class="button ghost small" data-rerun-from-here="${escapeHTML(selected.id)}">从这里重跑</button><small>保留上游结果,从本节点及下游重跑</small></div>`:''}${nr.output?`<div class="node-output"><div><b>节点输出</b><button data-copy-output>复制</button></div><pre>${escapeHTML(displayNodeOutput(nr.output))}</pre></div>`:'<div class="node-output empty"><b>节点输出</b><p>节点完成后,结构化输出会显示在这里。</p></div>'}<div class="runtime-details"><span>Sandbox <code>${escapeHTML(nr.sandboxId||'—')}</code></span><span>Session <code>${escapeHTML(nr.sessionId||'—')}</code></span><span>${nr.startedAt?`${new Date(nr.startedAt).toLocaleTimeString()} → ${nr.finishedAt?new Date(nr.finishedAt).toLocaleTimeString():'现在'}`:'尚未调度'}</span></div></section><section class="node-artifacts"><div class="section-heading"><div><h3>节点交付物</h3><span>${nodeArtifacts.length} 个版本</span></div></div><div class="node-artifact-list">${nodeArtifacts.map(a=>`<button class="node-artifact-card" data-artifact="${escapeHTML(a.id)}"><span class="artifact-file-icon">${a.mediaType==='application/json'?'{}':'MD'}</span><div><b>${escapeHTML(a.name)}</b><span>${escapeHTML(a.path)}</span><small>attempt ${a.attempt} · ${Math.max(1,Math.ceil((a.size||0)/1024))} KB · ${(a.sha256||'').slice(0,10)}</small></div><i>预览 ›</i></button>`).join('')||'<div class="empty-inline"><span>◇</span><p>此节点还没有登记交付物</p></div>'}</div></section></div>${runIsGroupMode(r)?'</details>':''}</div><div class="run-pane" data-run-pane="trace" ${runDetailTab==='trace'?'':'hidden'}><section class="trace-section"><div class="section-heading"><div><h3>${telemetrySectionTitle(telAdapter)}</h3><span>${telPage?`${telemetry.length} 条已加载`:'加载最近 100 条'}</span></div><div class="trace-heading-actions">${telemetrySourceTabs(telAdapter,'data-tel-adapter')}${telPage?.hasMore?`<button class="button ghost small" data-tel-more>加载更早的 100 条</button>`:''}</div></div><div class="telemetry-feed">${telPage?([...telemetry].reverse().map(telemetryItemHTML).join('')||`<div class="empty-inline"><p>${telemetryEmptyHint(telAdapter)}</p></div>`):'<div class="empty-inline"><p>正在加载轨迹…</p></div>'}</div></section></div><div class="run-pane" data-run-pane="logs" ${runDetailTab==='logs'?'':'hidden'}><section class="worker-log-section"><div class="section-heading"><div><h3>Worker 日志</h3><span>${logPage?`${visibleWorkerLogs(logPage.items).length} 条调用`:(logBusy?'正在接收…':'实时加载最近调用')}</span></div><div class="worker-log-heading-actions">${logPage?.hasMore?`<button class="button ghost small" data-logs-more>加载更早的 100 条</button>`:''}</div></div><div class="worker-log-feed">${logPage?(visibleWorkerLogs(logPage.items).map(logLineHTML).join('')||'<div class="empty-inline"><p>该节点没有日志</p></div>'):'<div class="empty-inline"><p>正在加载 Worker 实时日志…</p></div>'}</div></section></div></div>`; host.querySelector('.run-detail-main')?.insertAdjacentHTML('beforeend',`<div class="run-pane" data-run-pane="workspace" ${runDetailTab==='workspace'?'':'hidden'}>${workspacePaneHTML(r)}</div>${previewEnabled?`<div class="run-pane" data-run-pane="preview" ${runDetailTab==='preview'?'':'hidden'}>${previewPaneHTML(r)}</div>`:''}<div class="run-pane" data-run-pane="eval" ${runDetailTab==='eval'?'':'hidden'}>${runEvalPaneHTML(r)}</div>`);+ host.innerHTML=`<div class="run-detail-main"><header class="run-detail-header"><div class="run-detail-topbar"><button class="button ghost small run-back-inline" data-run-back>← 返回运行列表</button><div class="run-breadcrumb"><span>${issueRef}</span><i>›</i><span>${escapeHTML(wf.name)}</span></div>${r.executionContext?.parentRunId?`<button class="button ghost small" data-open-parent-run="${escapeHTML(r.executionContext.parentRunId)}">↑ 返回父 SOP 运行</button>`:''}<div class="run-header-actions">${issueId?`<button class="button primary small" data-open-issue="${escapeHTML(issueId)}">打开需求</button>`:''}${!r.pauseRequested?refreshRunSOPButtonHTML(r):''}<button class="button ghost small" data-open-flow>查看流程定义</button>${['queued','running','waiting'].includes(r.status)?'<button class="button danger-outline small" data-cancel-run>取消运行</button>':'<button class="button danger-outline small" data-delete-run>删除记录</button>'}</div></div><div class="run-header-main"><div><h2>${escapeHTML(ctx.issue?.title||wf.name)}</h2><p>${escapeHTML(r.input||'无运行输入')}</p></div><div class="run-status-wrap"><span class="status ${runDisplayStatusClass(r)}">${runDisplayStatus(r)}</span>${r.status==='failed'&&!gongfengIssueClosed(ctx.issue)?'<button class="button primary small" data-resume-run>↻ 重试运行</button>':''}${canManuallyPassFailedNode(r)&&!gongfengIssueClosed(ctx.issue)?`<button class="button ghost small" data-pass-node="${escapeHTML(r.id)}" data-node="${escapeHTML(failedNodeId(r))}">手动通过</button>`:''}</div></div><div class="run-header-meta"><span class="run-meta-chip run-id-chip" title="${escapeHTML(r.id)}">Run <code>${escapeHTML(r.id.slice(-12))}</code><button type="button" class="run-id-copy" data-copy-run title="复制完整 Run ID" aria-label="复制 Run ID"><svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/><path d="M10.5 5.5V3.5A1.5 1.5 0 0 0 9 2H3.5A1.5 1.5 0 0 0 2 3.5V9A1.5 1.5 0 0 0 3.5 10.5H5.5"/></svg></button></span>${runModeChipHTML(r,wf)}${runExecutionChipHTML(r)}<span class="run-meta-chip"><svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-1px;margin-right:4px;"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>启动于 ${new Date(r.createdAt).toLocaleString()}</span><span class="run-meta-chip" title="${escapeHTML(runTimingTitle(r))}"><svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-1px;margin-right:4px;"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>执行 ${runElapsed(r)}${runWallNote(r)}</span></div></header><div class="run-section-label"><b>执行详情</b><div class="run-section-label-actions"><button class="button ghost small" data-export-logs title="下载本次运行全部节点的 Worker 日志">导出全部日志</button><div class="run-tabs" role="tablist">${runTabs.map(t=>{const[k,label]=t.split(':');return `<button class="run-tab ${runDetailTab===k?'active':''}" data-run-tab="${k}">${label}</button>`}).join('')}</div></div></div><div class="run-pane" data-run-pane="overview" ${runDetailTab==='overview'?'':'hidden'}><section class="run-context-grid">${runProgressCellHTML(r,wf,progress,graphNodes)}<div data-run-usage>${liveUsageHTML(r)}</div><div><span>交付物</span><b>${(r.artifacts||[]).length} 个不可变快照</b><small>按节点和尝试次数保留版本</small></div></section></section>${alignPanelHTML}${runIsGroupMode(r)?`<details class="run-sop-snapshot"><summary><div><b>已冷冻 SOP 快照</b><span>历史协作 · ${graphNodes.length} 个节点可展开审计</span></div></summary>`:''}<section class="run-graph-section"><div class="section-heading"><div><h3>节点执行拓扑</h3><span>点击节点查看该节点的输出、产物和执行事件</span></div><div class="graph-legend"><span><i class="succeeded"></i>完成</span><span><i class="running"></i>运行中</span><span><i class="waiting_approval"></i>待审批</span><span><i></i>未开始</span></div></div><div class="run-graph">${graphNodes.map((n,index)=>{const gv=graphNodeView(r,n.id),meta=nodeMeta(n),arts=(r.artifacts||[]).filter(a=>a.nodeId===n.id).length;return `${index?'<span class="graph-arrow">→</span>':''}<button class="graph-node ${gv.cls} ${state.selectedRunNode===n.id?'selected':''}" data-run-node="${escapeHTML(n.id)}"><span class="node-icon ${meta.kind}">${runNodeIcon(meta.kind)}</span><div><b>${escapeHTML(n.name)}</b><small>${escapeHTML(gv.text)}</small></div>${arts?`<em>${arts} 产物</em>`:''}</button>`}).join('')}</div></section><div class="node-drilldown"><section class="node-inspector"><div class="section-heading"><div class="node-inspector-title"><h3>${escapeHTML(selected?.name||'节点详情')}</h3><span class="node-activity-inline" ${nr.activity?'':'hidden'}>当前活动:<b>${escapeHTML(nr.activity||'')}</b></span><span class="node-inspector-model">${escapeHTML(nr.provider||'未分配')}${nr.model?` · ${escapeHTML(nr.model)}`:''}</span></div><span class="status ${nr.status||'pending'}">${statusText(nr.status)||'待执行'}</span></div><div class="node-facts"><div><span>执行次数</span><b>${nr.attempt||0}</b></div><div><span>返工</span><b>${nr.reworkCount||0}</b></div><div><span>Token</span><b>${formatTokens(nr.usage?.totalTokens)}</b></div><div><span>工具调用</span><b>${nr.toolCalls||0}</b></div></div>${childSOPPanelHTML(r,selected?.id)}${gateResultCardHTML(nr)}${canRerunFromHere(r,selected?.id)?`<div class="node-rerun-row"><button type="button" class="button ghost small" data-rerun-from-here="${escapeHTML(selected.id)}">从这里重跑</button><small>保留上游结果,从本节点及下游重跑</small></div>`:''}${nr.output?`<div class="node-output"><div><b>节点输出</b><button data-copy-output>复制</button></div><pre>${escapeHTML(displayNodeOutput(nr.output))}</pre></div>`:'<div class="node-output empty"><b>节点输出</b><p>节点完成后,结构化输出会显示在这里。</p></div>'}<div class="runtime-details"><span>Sandbox <code>${escapeHTML(nr.sandboxId||'—')}</code></span><span>Session <code>${escapeHTML(nr.sessionId||'—')}</code></span></div></section><section class="node-artifacts"><div class="section-heading"><div><h3>节点交付物</h3><span>${nodeArtifacts.length} 个版本</span></div></div><div class="node-artifact-list">${nodeArtifacts.map(a=>`<button class="node-artifact-card" data-artifact="${escapeHTML(a.id)}"><span class="artifact-file-icon">${a.mediaType==='application/json'?'{}':'MD'}</span><div><b>${escapeHTML(a.name)}</b><span>${escapeHTML(a.path)}</span><small>attempt ${a.attempt} · ${Math.max(1,Math.ceil((a.size||0)/1024))} KB · ${(a.sha256||'').slice(0,10)}</small></div><i>预览 ›</i></button>`).join('')||'<div class="empty-inline"><span>◇</span><p>此节点还没有登记交付物</p></div>'}</div></section></div>${runIsGroupMode(r)?'</details>':''}</div><div class="run-pane" data-run-pane="trace" ${runDetailTab==='trace'?'':'hidden'}><section class="trace-section"><div class="section-heading"><div><h3>${telemetrySectionTitle(telAdapter)}</h3><span>${telPage?`${telemetry.length} 条已加载`:'加载最近 100 条'}</span></div><div class="trace-heading-actions">${telemetrySourceTabs(telAdapter,'data-tel-adapter')}${telPage?.hasMore?`<button class="button ghost small" data-tel-more>加载更早的 100 条</button>`:''}</div></div><div class="telemetry-feed">${telPage?([...telemetry].reverse().map(telemetryItemHTML).join('')||`<div class="empty-inline"><p>${telemetryEmptyHint(telAdapter)}</p></div>`):'<div class="empty-inline"><p>正在加载轨迹…</p></div>'}</div></section></div><div class="run-pane" data-run-pane="logs" ${runDetailTab==='logs'?'':'hidden'}><section class="worker-log-section"><div class="section-heading"><div><h3>Worker 日志</h3><span>${logPage?`${visibleWorkerLogs(logPage.items).length} 条调用`:(logBusy?'正在接收…':'实时加载最近调用')}</span></div><div class="worker-log-heading-actions">${logPage?.hasMore?`<button class="button ghost small" data-logs-more>加载更早的 100 条</button>`:''}</div></div><div class="worker-log-feed">${logPage?(visibleWorkerLogs(logPage.items).map(logLineHTML).join('')||'<div class="empty-inline"><p>该节点没有日志</p></div>'):'<div class="empty-inline"><p>正在加载 Worker 实时日志…</p></div>'}</div></section></div></div>`; host.querySelector('.run-detail-main')?.insertAdjacentHTML('beforeend',`<div class="run-pane" data-run-pane="workspace" ${runDetailTab==='workspace'?'':'hidden'}>${workspacePaneHTML(r)}</div>${previewEnabled?`<div class="run-pane" data-run-pane="preview" ${runDetailTab==='preview'?'':'hidden'}>${previewPaneHTML(r)}</div>`:''}<div class="run-pane" data-run-pane="eval" ${runDetailTab==='eval'?'':'hidden'}>${runEvalPaneHTML(r)}</div>`);if(keepFrame){const fresh=host.querySelector('iframe[data-vscode-frame]');if(fresh)fresh.replaceWith(existingFrame);}if(keepPreview){const fresh=host.querySelector('iframe[data-preview-frame]');if(fresh)fresh.replaceWith(existingPreviewFrame);}const headerActions=host.querySelector('.run-header-actions');if(r.status==='running'&&headerActions)headerActions.querySelector('[data-cancel-run]')?.insertAdjacentHTML('beforebegin','<button class="button ghost small" data-pause-run>暂停运行</button>');@@ -1133,7 +1149,7 @@ function renderRunDetail(r){if(pg.child){const note=`<p class="child-sop-trace-note">这是 SOP 节点,下面显示的是子 SOP 运行 <code>${escapeHTML(pg.runId.slice(-12))}</code> 全部节点的内容。</p>`;host.querySelectorAll('.trace-section>.section-heading,.worker-log-section>.section-heading').forEach(h=>h.insertAdjacentHTML('afterend',note))}const runMeta=host.querySelector('.run-header-meta');if(runMeta)runMeta.insertAdjacentHTML('beforeend',`${taskTriggerBadge(ctx.task)}<span class="run-meta-chip">Sandbox <code>${escapeHTML(r.sandboxId||'—')}</code></span>`);const nodeSandbox=host.querySelector('.runtime-details span:first-child');if(nodeSandbox)nodeSandbox.remove();- const graph=host.querySelector('.run-graph');if(graph){graph.querySelectorAll('.graph-arrow').forEach(arrow=>arrow.remove());const stages=workflowStages(runIsGroupMode(r)?{...wf,nodes:graphNodes}:wf);graph.classList.add('is-staged');stages.forEach((stage,index)=>{const column=document.createElement('div');column.className='graph-stage'+(stage.length>1?' is-parallel':'');const caption=document.createElement('span');caption.className='graph-stage-label';caption.textContent=`阶段 ${index+1}${stage.length>1?` · 并行 ${stage.length}`:''}`;column.append(caption);for(const node of stage){const button=graph.querySelector(`[data-run-node="${CSS.escape(node.id)}"]`),parents=(wf.edges||[]).filter(edge=>edge.target===node.id).map(edge=>nodes.find(item=>item.id===edge.source)?.name).filter(Boolean);if(!button)continue;if(parents.length)button.querySelector('small').append(` · 上游 ${parents.join('、')}`);column.append(button)}if(column.children.length>1)graph.append(column)})}+ const graph=host.querySelector('.run-graph');if(graph){graph.querySelectorAll('.graph-arrow').forEach(arrow=>arrow.remove());const stages=workflowStages(runIsGroupMode(r)?{...wf,nodes:graphNodes}:wf);graph.classList.add('is-staged');stages.forEach((stage,index)=>{const column=document.createElement('div');column.className='graph-stage'+(stage.length>1?' is-parallel':'');const caption=document.createElement('span');caption.className='graph-stage-label';const captionName=document.createElement('span');captionName.className='graph-stage-name';captionName.textContent=`阶段 ${index+1}${stage.length>1?` · 并行 ${stage.length}`:''}`;caption.append(captionName);const stageTime=stageTimeLabel(r,stage);if(stageTime){const stageTimeEl=document.createElement('em');stageTimeEl.className='graph-stage-time';stageTimeEl.textContent=stageTime;caption.append(stageTimeEl)}column.append(caption);for(const node of stage){const button=graph.querySelector(`[data-run-node="${CSS.escape(node.id)}"]`),parents=(wf.edges||[]).filter(edge=>edge.target===node.id).map(edge=>nodes.find(item=>item.id===edge.source)?.name).filter(Boolean);if(!button)continue;if(parents.length)button.querySelector('small').append(` · 上游 ${parents.join('、')}`);column.append(button)}if(column.children.length>1)graph.append(column)})}host.querySelector('[data-run-back]')?.addEventListener('click',()=>showRunList());host.querySelectorAll('[data-run-tab]').forEach(b=>b.onclick=()=>{const key=b.dataset.runTab;if((state.runDetailTab||'overview')===key)return;state.runDetailTab=key;host.querySelectorAll('[data-run-tab]').forEach(x=>x.classList.toggle('active',x.dataset.runTab===key));host.querySelectorAll('[data-run-pane]').forEach(p=>p.hidden=p.dataset.runPane!==key);if(key==='workspace')loadRunWorkspace(r.id);if(key==='preview')loadRunPreview(r.id);else stopPreviewPoll();if(key==='eval')loadRunEval(r.id)});host.querySelectorAll('[data-run-node]').forEach(b=>b.onclick=()=>selectRunNode(b.dataset.runNode));host.querySelectorAll('[data-tel-adapter]').forEach(b=>b.onclick=()=>{if((state.runTelemetryAdapter||'live')===b.dataset.telAdapter)return;state.runTelemetryAdapter=b.dataset.telAdapter;state.runTelemetry=null;renderRunDetail(state.activeRun||r)});host.querySelector('[data-logs-load]')?.addEventListener('click',()=>loadRunLogs(pg.runId,pg.nodeId,false));host.querySelector('[data-logs-more]')?.addEventListener('click',()=>loadRunLogs(pg.runId,pg.nodeId,true));host.querySelector('[data-tel-load]')?.addEventListener('click',()=>loadRunTelemetry(pg.runId,pg.nodeId,false));host.querySelector('[data-tel-more]')?.addEventListener('click',()=>loadRunTelemetry(pg.runId,pg.nodeId,true));host.querySelector('[data-open-issue]')?.addEventListener('click',ev=>{ev.preventDefault();ev.stopPropagation();openIssueDetail(ev.currentTarget.dataset.openIssue||issueId,'sop')});host.querySelectorAll('[data-rerun-from-here]').forEach(b=>b.onclick=()=>openRerunFromNode(state.activeRun||r,b.dataset.rerunFromHere));host.querySelector('[data-copy-run]')?.addEventListener('click',()=>copyText(r.id,'Run ID 已复制'));host.querySelector('[data-export-logs]')?.addEventListener('click',()=>downloadRunLogs(r.id));host.querySelector('[data-copy-output]')?.addEventListener('click',()=>copyText(displayNodeOutput(nr.output),'节点输出已复制'));host.querySelector('[data-open-flow]')?.addEventListener('click',()=>{state.workflow=clone(state.data.workflows.find(w=>w.id===r.workflowId)||wf);state.selectedNode=selected?.id||null;switchView('flow');renderAll()});host.querySelector('[data-cancel-run]')?.addEventListener('click',async ()=>{if(await afConfirm({title:'取消运行确认',message:r.status==='queued'?'确定取消排队?此运行将不会启动,之后可删除记录。':'确定取消这次运行?正在执行的节点会被终止。',confirmText:r.status==='queued'?'取消排队':'确认取消',isDanger:true}))runAction(r.id,'cancel',{})});host.querySelector('[data-delete-run]')?.addEventListener('click',()=>deleteRun(r.id));host.querySelectorAll('[data-resume-run]').forEach(b=>b.addEventListener('click',ev=>resumeRun(b.dataset.resumeRun||r.id,ev.currentTarget)));host.querySelectorAll('[data-pass-node]').forEach(b=>b.onclick=()=>passFailedNode(b.dataset.passNode,b.dataset.node,b));host.querySelectorAll('[data-artifact]').forEach(b=>b.onclick=()=>previewArtifact(state.activeRun||r,b.dataset.artifact));host.querySelectorAll('[data-approve]').forEach(b=>b.onclick=()=>runAction(r.id,'approve',withHumanContext({nodeId:b.dataset.approve,context:readHumanContext(b)})));host.querySelectorAll('[data-reject]').forEach(b=>b.onclick=async ()=>{const reason=await afPrompt({title:'打回返工',message:'请输入打回原因:',defaultValue:'验证未通过,请修复后重新提交'});if(reason!==null&&reason!==undefined)runAction(r.id,'reject',withHumanContext({nodeId:b.dataset.reject,targetId:b.dataset.target,reason,context:readHumanContext(b)}))});host.querySelectorAll('[data-retry-node]').forEach(b=>b.onclick=()=>retryWaitingNode(r.id,b.dataset.retryNode,b));host.querySelectorAll('[data-decline-retry]').forEach(b=>b.onclick=()=>declineRetry(r.id,b.dataset.declineRetry));host.querySelectorAll('[data-realign-run]').forEach(b=>b.onclick=()=>realignBaseline(b.dataset.realignRun));diff --git a/web/deployment-dashboard.css b/web/deployment-dashboard.cssdeleted file mode 100644index b1eb8293..00000000--- a/web/deployment-dashboard.css+++ /dev/null@@ -1,96 +0,0 @@-.deployment-body{display:grid;gap:16px;padding-bottom:28px}-.deployment-query{display:grid;grid-template-columns:minmax(180px,1.2fr) minmax(220px,1.8fr) minmax(130px,.8fr) minmax(130px,.8fr) auto;gap:12px;align-items:end;padding:18px;border:1px solid var(--border,#e5e9f2);border-radius:14px;background:var(--panel,#fff);box-shadow:0 2px 10px rgba(23,36,62,.04)}-.deployment-query.skillhub-only{grid-template-columns:minmax(250px,1fr) minmax(260px,1.2fr) auto}-.deployment-query label{display:grid;gap:6px;color:var(--muted,#667085);font-size:12px}-.deployment-query input,.deployment-query select{height:38px;width:100%;padding:0 11px;border:1px solid var(--border,#dfe4ec);border-radius:8px;background:var(--panel,#fff);color:var(--text,#182230);font:inherit}-.deployment-query input:focus,.deployment-query select:focus{outline:2px solid rgba(91,140,255,.18);border-color:#5b8cff}-.deployment-fixed-source{display:grid;gap:4px}-.deployment-fixed-source span{color:var(--muted,#667085);font-size:12px}-.deployment-fixed-source b{color:var(--text,#182230);font-size:14px}-.deployment-fixed-source small{color:#667085;font-size:11px}-.deployment-query-actions{display:flex;gap:8px}-.deployment-config-note{grid-column:1/-1;display:flex;align-items:center;justify-content:space-between;gap:12px;padding-top:3px;color:var(--muted,#667085);font-size:12px}-.deployment-config-note b{color:var(--text,#344054)}-.deployment-kpis{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px}-.deployment-kpi{padding:16px 18px;border:1px solid var(--border,#e5e9f2);border-radius:12px;background:var(--panel,#fff)}-.deployment-kpi span{display:block;color:var(--muted,#667085);font-size:12px}-.deployment-kpi strong{display:block;margin-top:7px;color:var(--text,#101828);font-size:25px;line-height:1}-.deployment-kpi small{display:block;margin-top:7px;color:var(--muted,#98a2b3);font-size:11px}-.deployment-kpi.good strong{color:#16875d}-.deployment-kpi.warn strong{color:#d97706}-.deployment-kpi.running strong{color:#b66c09}-.deployment-grid{display:grid;grid-template-columns:minmax(0,1.75fr) minmax(260px,.75fr);gap:16px}-.deployment-panel{min-width:0;padding:18px;border:1px solid var(--border,#e5e9f2);border-radius:14px;background:var(--panel,#fff)}-.deployment-panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:16px}-.deployment-panel-head h2{margin:0;color:var(--text,#182230);font-size:15px}-.deployment-panel-head p{margin:4px 0 0;color:var(--muted,#667085);font-size:12px}-.deployment-chart{height:250px}-.deployment-chart svg{display:block;width:100%;height:100%;overflow:visible}-.deployment-chart .grid{stroke:var(--border,#e6eaf0);stroke-width:1}-.deployment-chart .area{fill:url(#deploymentArea)}-.deployment-chart .line{fill:none;stroke:#5b8cff;stroke-width:2.5;stroke-linejoin:round;stroke-linecap:round}-.deployment-chart .dot{fill:#fff;stroke:#5b8cff;stroke-width:2}-.deployment-chart text{fill:var(--muted,#7b8494);font-size:10px}-.deployment-breakdown{display:grid;gap:13px}-.deployment-breakdown-row{display:grid;grid-template-columns:64px 1fr 28px;gap:9px;align-items:center;font-size:12px}-.deployment-breakdown-row span{color:var(--muted,#667085)}-.deployment-breakdown-row b{text-align:right;color:var(--text,#344054)}-.deployment-breakdown-track{height:8px;overflow:hidden;border-radius:99px;background:var(--soft,#eef1f6)}-.deployment-breakdown-track i{display:block;height:100%;border-radius:inherit;background:#5b8cff}-.deployment-breakdown-row.success i{background:#20a474}-.deployment-breakdown-row.failed i{background:#e55353}-.deployment-breakdown-row.running i{background:#e3a229}-.deployment-table-wrap{overflow:auto;border:1px solid var(--border,#e5e9f2);border-radius:14px;background:var(--panel,#fff)}-.deployment-table-section{padding:18px;border:1px solid var(--border,#e5e9f2);border-radius:14px;background:var(--panel,#fff)}-.deployment-table-section .deployment-table-wrap{margin:0 -18px -18px;border-width:1px 0 0;border-radius:0 0 14px 14px}-.deployment-table-section>.deployment-panel-head>b{color:var(--muted,#667085);font-size:12px}-.deployment-table{width:100%;border-collapse:collapse;white-space:nowrap}-.deployment-table th{padding:11px 14px;background:var(--soft,#f8f9fb);color:var(--muted,#667085);font-size:11px;font-weight:600;text-align:left}-.deployment-table td{padding:13px 14px;border-top:1px solid var(--border,#edf0f4);color:var(--text,#344054);font-size:12px}-.deployment-table tbody tr:hover{background:rgba(91,140,255,.035)}-.deployment-table a{color:#4f76dc;text-decoration:none}-.deployment-table code{font-size:11px}-.deployment-table td.deployment-table-empty{padding:34px;text-align:center;color:var(--muted,#667085)}-.deployment-status{display:inline-flex;align-items:center;gap:6px;padding:3px 8px;border-radius:99px;background:#f2f4f7;color:#667085}-.deployment-status:before{width:6px;height:6px;border-radius:50%;background:currentColor;content:""}-.deployment-status.succeeded{background:#e9f8f1;color:#16875d}-.deployment-status.failed{background:#fff0f0;color:#c63f3f}-.deployment-status.running{background:#fff7e4;color:#b66c09}-.deployment-empty,.deployment-error{display:grid;place-items:center;min-height:330px;padding:36px;border:1px dashed var(--border,#dfe4ec);border-radius:14px;background:var(--panel,#fff);text-align:center}-.deployment-empty>div,.deployment-error>div{max-width:520px}-.deployment-empty i,.deployment-error i{display:grid;place-items:center;width:54px;height:54px;margin:0 auto 14px;border-radius:15px;background:#eef3ff;color:#5b8cff;font-size:24px;font-style:normal}-.deployment-empty h2,.deployment-error h2{margin:0 0 8px;color:var(--text,#182230);font-size:18px}-.deployment-empty p,.deployment-error p{margin:0;color:var(--muted,#667085);font-size:13px;line-height:1.7}-.deployment-empty .button,.deployment-error .button{margin-top:16px}-.deployment-error i{background:#fff0f0;color:#d44}-.deployment-loading{display:grid;grid-template-columns:repeat(5,1fr);gap:12px}-.deployment-loading i{height:92px;border-radius:12px;background:linear-gradient(90deg,var(--soft,#f3f4f6),#fafafa,var(--soft,#f3f4f6));background-size:200% 100%;animation:deploymentShimmer 1.2s infinite}-@keyframes deploymentShimmer{to{background-position:-200% 0}}-@media(max-width:1100px){.deployment-query,.deployment-query.skillhub-only{grid-template-columns:repeat(2,minmax(0,1fr))}.deployment-query-actions{grid-column:1/-1}.deployment-kpis{grid-template-columns:repeat(3,1fr)}.deployment-grid{grid-template-columns:1fr}}-@media(max-width:700px){.deployment-query,.deployment-query.skillhub-only,.deployment-kpis{grid-template-columns:1fr}.deployment-config-note{align-items:flex-start;flex-direction:column}.deployment-loading{grid-template-columns:1fr 1fr}}-/* Harness 外观:颜色、圆角与阴影统一引用 --hui-*;布局不变。 */-.deployment-query,.deployment-kpi,.deployment-panel,.deployment-table-section{border-color:var(--hui-border);border-radius:14px;background:var(--hui-surface);box-shadow:var(--hui-panel-shadow)}-.deployment-query input,.deployment-query select{border-color:var(--hui-border-strong);border-radius:7px;background:var(--hui-surface);color:var(--hui-text)}-.deployment-query input:focus,.deployment-query select:focus{outline:0;border-color:var(--hui-accent);box-shadow:0 0 0 3px var(--hui-accent-soft)}-.deployment-fixed-source small{color:var(--hui-muted)}-.deployment-kpi.good strong{color:var(--hui-success)}-.deployment-kpi.warn strong,.deployment-kpi.running strong{color:var(--hui-warn)}-.deployment-chart .line{stroke:var(--hui-accent)}-.deployment-chart .dot{fill:var(--hui-surface);stroke:var(--hui-accent)}-.deployment-breakdown-track{background:var(--hui-soft)}-.deployment-breakdown-track i{background:var(--hui-accent)}-.deployment-breakdown-row.success i{background:var(--hui-success)}-.deployment-breakdown-row.failed i{background:var(--hui-error)}-.deployment-breakdown-row.running i{background:var(--hui-warn)}-.deployment-table-wrap{border-color:var(--hui-border);background:var(--hui-surface)}-.deployment-table th{background:var(--hui-canvas);color:var(--hui-muted)}-.deployment-table td{border-top-color:var(--hui-border-soft);color:var(--hui-text)}-.deployment-table a{color:var(--hui-accent)}-.deployment-status{background:color-mix(in srgb,var(--hui-neutral) 8%,var(--hui-surface));color:var(--hui-neutral)}-.deployment-status.succeeded{background:color-mix(in srgb,var(--hui-success) 8%,var(--hui-surface));color:var(--hui-success)}-.deployment-status.failed{background:color-mix(in srgb,var(--hui-error) 8%,var(--hui-surface));color:var(--hui-error)}-.deployment-status.running{background:color-mix(in srgb,var(--hui-warn) 8%,var(--hui-surface));color:var(--hui-warn)}-.deployment-empty,.deployment-error{border-color:var(--hui-border-strong);background:var(--hui-surface)}-.deployment-empty i{background:var(--hui-soft);color:var(--hui-secondary)}-.deployment-error i{background:color-mix(in srgb,var(--hui-error) 8%,var(--hui-surface));color:var(--hui-error)}-.deployment-loading i{background:linear-gradient(90deg,var(--hui-soft),var(--hui-canvas),var(--hui-soft));background-size:200% 100%}diff --git a/web/embed.go b/web/embed.goindex 32f7929a..9574909a 100644--- a/web/embed.go+++ b/web/embed.go@@ -2,5 +2,5 @@ package webimport "embed"-//go:embed boot.js i18n.js i18n-en.js preferences.css login.html login.js bot-bind.html bot-bind.js boot-theme.js gongfeng-oauth-done.html gongfeng-oauth-done.js index.html vscode.html vscode.js vscode.css app.js app assistant-models.css chat-codex.css orchestrate.js deployment-dashboard.css metrics-dashboard.css business-domains.css bots.css knowledge.js knowledge.css mcp-setup.txt styles.css assets.css platform.css observability.css artifacts.css sops.css sync.css access.css product-v3.css product-v4.css images/credentials/*.svg images/loopforge-logo.png favicon.ico favicon.png favicon.svg apple-touch-icon.png mcp-icons monaco vendor vscode-web extensions all:native-chat+//go:embed boot.js i18n.js i18n-en.js preferences.css login.html login.js bot-bind.html bot-bind.js boot-theme.js gongfeng-oauth-done.html gongfeng-oauth-done.js index.html vscode.html vscode.js vscode.css app.js app assistant-models.css chat-codex.css orchestrate.js metrics-dashboard.css business-domains.css bots.css knowledge.js knowledge.css mcp-setup.txt styles.css assets.css platform.css observability.css artifacts.css sops.css sync.css access.css product-v3.css product-v4.css images/credentials/*.svg images/loopforge-logo.png favicon.ico favicon.png favicon.svg apple-touch-icon.png mcp-icons monaco vendor vscode-web extensions all:native-chatvar Files embed.FSdiff --git a/web/harness_design_system_test.go b/web/harness_design_system_test.goindex a57d23de..8987d5df 100644--- a/web/harness_design_system_test.go+++ b/web/harness_design_system_test.go@@ -125,7 +125,7 @@ func TestHarnessStylesheetLoadOrder(t *testing.T) {if base := slices.Index(links, "/product-v4.css"); shared < 0 || base < 0 || shared < base {t.Fatalf("/%s must load after /product-v4.css, got %v", harnessUICSS, links)}- for _, page := range []string{"/bots.css", "/knowledge.css", "/metrics-dashboard.css", "/deployment-dashboard.css", "/business-domains.css", "/app/mcp.css", "/app/issues-list.css", "/app/assets-harness.css", "/app/observability-harness.css", "/app/approvals-harness.css"} {+ for _, page := range []string{"/bots.css", "/knowledge.css", "/metrics-dashboard.css", "/business-domains.css", "/app/mcp.css", "/app/issues-list.css", "/app/assets-harness.css", "/app/observability-harness.css", "/app/approvals-harness.css"} {if at := slices.Index(links, page); at < 0 || at < shared {t.Errorf("%s must load after /%s, got %v", page, harnessUICSS, links)}@@ -139,7 +139,7 @@ func TestSettingsAreaUsesOneCenteredContainer(t *testing.T) {t.Fatalf("%s is missing the settings container rule", harnessUICSS)}views := container[1]- for _, view := range []string{"#settingsView", "#botsView", "#projectsView", "#runnersView", "#agentsView", "#mcpView", "#assetsView", "#knowledgeView", "#metricsView", "#deploymentsView", "#businessDomainsView", "#guideView", "#platformView", "#businessDomainManagementView"} {+ for _, view := range []string{"#settingsView", "#botsView", "#projectsView", "#runnersView", "#agentsView", "#mcpView", "#assetsView", "#knowledgeView", "#metricsView", "#businessDomainsView", "#guideView", "#platformView", "#businessDomainManagementView"} {if !strings.Contains(views, view) {t.Errorf("settings container must include %s", view)}diff --git a/web/images/credentials/iwiki.svg b/web/images/credentials/iwiki.svgdeleted file mode 100644index d980eb27..00000000--- a/web/images/credentials/iwiki.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" role="img"><image width="100" height="100" preserveAspectRatio="xMidYMid meet" href="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDI1LjIuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9Il/lm77lsYJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgdmlld0JveD0iMCAwIDUwMCA1MDAiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDUwMCA1MDA7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojRkZGRkZGO30KCS5zdDF7ZmlsbDojMDA1MkQ5O30KPC9zdHlsZT4KPHBhdGggY2xhc3M9InN0MCIgZD0iTTc5LjUsMjEyLjVoMjAuMmwtMTYuMSw5Mi4xSDYzLjVDNjMuNSwzMDQuNiw3OS41LDIxMi41LDc5LjUsMjEyLjV6IE04NS42LDE3Ni42aDIwLjhsLTMuNywyMC44SDgxLjgKCUM4MS44LDE5Ny40LDg1LjYsMTc2LjYsODUuNiwxNzYuNnoiLz4KPGc+Cgk8cGF0aCBjbGFzcz0ic3QxIiBkPSJNMjUwLDUwMEwyNTAsNTAwQzExMS45LDUwMCwwLDM4OC4xLDAsMjUwdjBDMCwxMTEuOSwxMTEuOSwwLDI1MCwwaDBjMTM4LjEsMCwyNTAsMTExLjksMjUwLDI1MHYwCgkJQzUwMCwzODguMSwzODguMSw1MDAsMjUwLDUwMHoiLz4KCTxnPgoJCTxnPgoJCQk8cGF0aCBjbGFzcz0ic3QwIiBkPSJNNTcuMywzMDguM2wxNS41LTg4LjZoMTkuNGwtMTUuNSw4OC42SDU3LjN6IE03NSwyMDUuMWwzLjYtMjBoMjBsLTMuNiwyMEg3NXoiLz4KCQkJPHBhdGggY2xhc3M9InN0MCIgZD0iTTI0Mi4yLDE4OS45aDE4LjZsLTQ3LjIsMTE4LjNoLTI1LjJsLTUuMi04OGwtMzkuMSw4OEgxMTlsLTEuNC0xMTguM2gyMC45bC0wLjMsOTIuN2w0MC42LTkyLjdoMjIuOAoJCQkJbDQuNyw5Mi43TDI0Mi4yLDE4OS45eiIvPgoJCQk8cGF0aCBjbGFzcz0ic3QwIiBkPSJNMjU5LjYsMzA4LjNsMTUuNS04OC42aDE5LjRMMjc5LDMwOC4zSDI1OS42eiBNMjc3LjIsMjA1LjFsMy42LTIwaDIwbC0zLjYsMjBIMjc3LjJ6Ii8+CgkJCTxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik0zOTguMiwyMTkuNmwtMzIuNyw0MGwxOCw0OC42aC0yMC45bC0xMy45LTM5LjRoLTEzLjNsLTYuOSwzOS40aC0xOS40bDIxLjctMTI0LjdoMTkuNEwzMzgsMjUzLjRoMTIuNQoJCQkJbDI2LjMtMzMuOEgzOTguMnoiLz4KCQkJPHBhdGggY2xhc3M9InN0MCIgZD0iTTQwMy4yLDMwOC4zbDE1LjUtODguNmgxOS40bC0xNS41LDg4LjZINDAzLjJ6IE00MjAuOSwyMDUuMWwzLjYtMjBoMjBsLTMuNiwyMEg0MjAuOXoiLz4KCQk8L2c+Cgk8L2c+CjwvZz4KPC9zdmc+Cg=="/></svg>diff --git a/web/images/credentials/km.svg b/web/images/credentials/km.svgdeleted file mode 100644index 0fa255ad..00000000--- a/web/images/credentials/km.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" role="img"><image width="100" height="100" preserveAspectRatio="xMidYMid meet" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYwAAAGMCAYAAADJOZVKAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChXaW5kb3dzKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCREFBNTg1MTgzOTExMUU2QTUyNDk1REM4QTZEQzhDOSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCREFBNTg1MjgzOTExMUU2QTUyNDk1REM4QTZEQzhDOSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkJEQUE1ODRGODM5MTExRTZBNTI0OTVEQzhBNkRDOEM5IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkJEQUE1ODUwODM5MTExRTZBNTI0OTVEQzhBNkRDOEM5Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+HY6J6QAAIgFJREFUeNrs3QmUVMW9x/Gann2GadyQRQVXQCMIggqiuEQxARzUF+MelxeNaFzjEhUhojFxjXFPcHnGPWpcEI0roKKgAoKICioiyiIuMPs+r/49NYjI0DNM962qe7+fc+p4DirTXd1Tv3tvVf0rY/ubViqs0VW3brp10q2Hbrvq1tP8WVy3Drrl65alW6b5fzJMA+C2RtNEvW51ulXqVqZbiW5LdVug2zzdFuu20vzZMrquSVaE33uebkN020u3XXTrpVt33TbVLZuvBhA6a1/cxczvuVwAbmb+TC4Qh63139fq9r1uX+i20ATJDN2m6VZFYITfAN1O0G2QuYOQcMjl9wjAekigbGnaQPNn1SZE5A5kum736zYzMokbgUdScsXwe932NAGRw+8BgBSpMQHytm636vYidxh+KdCtr25n6jZKNc07MMcAIB3kArSzbofqNlI1zYc8rdttus3VrYLAcJOExBG6HavbTnyPAQRMLkyLdDveNJn3eEi3/5jw8P8NhuCR1AjdztJtb/NhAYBLSnV7U7dbdJvk8xuJefzaj9LtA92e1O0QwgKAo4rMGPWkGbOOIjCCe73DdfvE3OrJcliWwALwQbYZsx4yY9hw38Zgn16sPHqaaW7pdvD87ghAdMXMGDbJjGkjCIzUkbmJV3SbqFs/vmsAQqSfGdteMWMdgdGO13a/6cgDFUtjAYRThhnjXjFjnrPjsqsvTJbHLldNS9Py+D4BiIA8M+YtN2MggZGEbICRTS+Pq6YCgAAQNZ3MGChjYVcCY/2O0e193YoVj58ARFuGGQvnmrGRwFjLA6ZxVwEAP9hirfEx8oEhFWM/1O04xTJZAGhpnD7OjJU9ohoYUqxLHkH15vsAAEn1NmPmoVELjCtV0zZ5ynkAQOsVmbHzShs/3Ea12odVUy0VJrYBoO3keOjLdNtRBTwhHuQdhtSNl4qNRxMWANAuGWYsfVMFeChcUIERV03n4Q7mcwaAlJExVeY1OoQlMGTjiZT05VAjAEi9nmaM7ex7YGyn2yzdtuYzBYC06a7be2bM9TIwttJtmm5d+CwBIO26mDF3K98CQ56nyWRMVz5DAAhMVzP2pmVOIx2BIRUXZ5lbJABAsLqbMTjllb5THRiyr2OyYoIbAGzayYzFKd1rl+rAeFC3QXxWAGDdIDMmOxkY43Q7ks8IAJwhY/KfXAuM4bpdrtjBDQAukTF5jBmjnQgMWcL1iGqqbwIAcIuMzY+qFCy3bW9gyCz8q4qqswDgsg5mrG7Xyqn2BsbtqmlbOgDAbT3NmG0lMGQy5UQ+AwDwxomqHYuTNjYwttTtNsWxqgDgk5gZu7cMMjD+qVsn+h4AvNPJjOGBBMZhuhXT5wDgrWIzlqc1MHJMMrHfAgD8lWHG8jad1tfWwLhb8SgKAMKgkxnT0xIY/XX7FX0MAKHxKzO2pzQw5L+7QaWhXC4AwBoZ029Uraxq29rA+IVu+9O3ABA6++l2SCoD42rFRDcAhJGM7X9OVWBIlcPd6FMACC0Z40ekIjBuoS8BIPRubm9gyAz6dvQjAITedirJSthkgTFeMXcBAFGQYcb8jQoMmbvYiT4EgMjYSW3gdL4NBcbZqpVrcwEAoZBlxv42BUZv3fah7wAgcvYxGdDqwPiNboX0GwBETqHJgFYFRoFuR9NnABBZx5gsSBoYfXTblv4CgMjqYbIgaWCcoVhKCwBRlmGyIGlgcJoeAKA4WWD8XLeO9BMARF5HkwktBsZZisdRAICmLDhrQ4ExiD4CAKwvE9YOjH66bUb/AACMzUw2/CQwTtItm/4BABjZJht+Ehg8jgIArGvQuoEhB4H3oF8AAOvoYTJiTWDsq5i/AAD81GYmI9YExu665dAvAIB15JiMWBMYfegTAEAL+jQHhrTe9AcAoAW9JCskLDrrtg39AQBoQXfJCgmMrXXblP4AALRAMmJrCYzNFRv2AAAtk4zYXAKD/RcAgGR6SGDsSj8AAJLYVQKjF/0AAEiipwRGN/oBAJBENwmMIvoBAJBEXAKjkH4AACRRKIFRQD8AAJIokMDIoh8AAElkSWBk0g8AgCQStaQy6AcAQBIZBAYAoNWBAQAAgQEASA0CAwBAYAAACAwAAIEBACAwAAAEBgCAwAAAgMAAABAYAAACAwBAYAAACAwAAIEBACAwAAAgMAAABAYAgMAAABAYAAACAwBAYAAACAwAAAgMAACBAQAgMAAABAYAgMAAABAYAAACAwAAAgMAQGAAAAgMAACBAQAgMAAABAYAIPyyovrGPz1ni0B/3g5//yaS/XzagHx18T6FVl/Dg3Or1NjJZU59H47/z2r11pJaRqAUOmC7HHVXcZzfae4w4KNRvXPVRZbD4uXPatQVU8qc65sL9i5UGXxFUiYnM0ONGVpIRxAY8NFB2+eo6w4usjoovre8Tp37fKmqb3Svf/p1yVIH7ZDDFyVFTumfp7bdJJOOIDDgm/56MLzpl0Uq0+K3a3lZgxr9bImqrGt0tp/OH1yoYtxmtFvnDjF15p4FdASBAd/02iJL3XtYR5WfZW8kLK1uVKc8XaK+Lm9wuq96bp6pRvXK5UvTThcPKVQF2SQvgQGvdCuKqXtGxVVRrr1f3tp6pUZPKlEff1PnRZ+dM7hAZfMkpV13s8W9CV0CA17ZLD+mHjiio+rSwe5X6rJXy7xafbRNPFP9+md5fIE2ZvDS1yXj9u/A4gECAz4pzMlQE4rjqoflScc7361UT8yv8q7/fr9ngdVHeL46Ugdtn85ZdASBAV/I45R/jIwnVv3Y9PRH1er6aeVe9uGWhTF1Yj/uMtoinpuhLtibiW4CA97I1BfF1w8rUoO3ybb6OuQR1MUvl6pGj/vy1AEFVud+fHPuoILEY1AQGPCEPD8e2dPuhOPiVfXq7OdLE5PdPtskL0Oduns+X6pWkNVlx/elrwgMeOOsvQrUcX3tPkb5rrJBnfx0SeKfYXBy/3y1RQG/kq25UMmkmwgM+EGCQh4J2CQb8k59piRxhxEWspdg9B5cOW/I8J1y1aCts+kIAgO+/MLKFZ5NMldx0YtlidIfYXNsnzy1VRG/lusjK8ku2Zd6UQQGvCCT2zceUpSY7LZJVkM9t7A6lH0sRfTOGcTqn/U5Xd99dSNMCQy4r2/nLHXHiLj1XclSqlz2W4TZYb3z1A6bsv17bbLB8dQBPK4jMOA82ZB3t+WSH2LyIjdLlaeaTOieN5i7jLVdNrRQ5Way7JjAgNOk1Md9h8etr3mX2lDnveBmqfJ0+MVOuexiNvbtnq0OphQ8gQG3yR2FFBOUxwE2SalyqT4rVWijQq6lz+cuI3G3dbnlRRYgMJCErEi5uzieKFduU3OpcgmNqBnaI0fttVW0l5DKBj3mcwgMuHxVpy9v5QCkAd3sDlby+EkeQ/lSqjwdLhwS3WWk8hj0XFaMERhwlzwKuebgosQRq7bJBLdMdEdZ/65Z6sDtovn8XooLxqmvRWDA4V9SfUV7+M72D6SRpbOyhBZKna8Hzqgd5SoT/kdyTgiBAXedNiBfnT7Q/lr3SQv9LVWeDjtvkWW9yGPQd7lSTYDzzgkMOGpU71x10T72n5dLuY+LXyxTjXwkPyLP8qNScE/ucPt3YUkxgQEnyXzFdcOKrB91KYUEpaCgFBbEj8nmySN3Cf8jmg45GU5cuIDAwHrIlZysiLK9iTZspcrT4ey9ClReyI9ylbL5nSjxTmDAPbLH4t7DOlo/T1oOPzrrudJQlSpPh84dYuqEvuG9y5D9Fif1o14UgQHnSNXPexyoDyUPn+R41elf1vKhtMLvBuYnHtuEkezozmJEIjDgFtkQ9cARHRN1omyT1VBPf1TNh9JKm+rP7rchPMpVakVJzSgQGHCIXJ1OKI4nJlFte3x++EuVp8Mp/fMTwREWUoVWqtGCwIBD5CyLO0fGVT8Hliy+taRWjXm1jA9lIxTq0B89MDx3GXLOhe0ClyAwsBZZBXX9sKLEqXm2SW2o0ZNKEpPd2DjH75anuobg9Dl5D6dzjjmBAbfIzlkXdguvKI9eqfJ0kMc4v9/T/8J8Fw0ptL5KDwQG1iJr249zYDmmbMg749lolipPB9nIt+0m/j7K2WOrbHVor1w+SAIDrpCgcKFEtJQqP/f50kTpD6SGlArx9ZAleUQ6dr9Cxb0FgQFHDN8pN/EoygVSqvzlz2r4UFL9GffMVbt08q/u0tF98rx83QQGQkkmt288xH7JD/GvOZQqTxcfj3LdJC9Dv2aW0RIYcMJuXbLUHSPiiWW0tsldxVVTKVWeTgdsl6MGdvNn05uEhYQGCAxYJhvy7iq2X/JDyHyFzFvUsyAq7eR0Oh/IYyh5HAUCA5ZJqY/7Do8nSn/Y9lVpA6XKAyQrjob2cPsoV7mEkYnuTG4uCAzYJXcUUkzQhR2zssdCwoJS5cG6cEiB06uOZAmtBBsIDFgkG5/uLo4nypXbJru3ZRe37OZGsORxz3BHj3ItyM5Qf+RgJAIDdsntvRyANMCBSc/mUuVSJwp2nOPoUa5n7lmQOM8DBAYskccP1xxclDhi1QV3vlNJqXLL5BCi/9nZrUll2Y1+Sn8mugkMWHXBkEJ1+M5uPIKQoLjhTZbPukCOcs1xaGZ5zNBCp14PCIzIkZPXTnekxLU8gpJHUayHcoNUgD3WkaWr+22bk9gnAgIDlozqnasuHOLGBOLnq+opVe6gM/bIT5ybYZMct8rBSAQGLJL5iuuGFTmxfFKWzVKq3E2bF8TUyf3s3oGepH++zKmAwIAF/btkJVZEufA4WDbkyV6Lxau4tXCVnP1tqwRHJx1YUlYfBAYskD0W9x7W0YnDZuR+glLl7pPNnKcPtDNoX7RPYeL8eBAYCNhWRbHELm4X6kOJ66eVU6rcEyfslhf4/ge5E3Zl9R4IjEiRulD3H9ExUSfKBVKm/M53K/lgPJGn70jP3CO4u4xYRtNxwNxbEBgImNzSTyiOJyrQukDuKuQgJPjlqF3zVPeOwXyHjvxZnurTmYORCAwESs6yuHNkXPXr4sYvn9SGOu+/lCr3kSxvPS+AQ5biuRnelFkHgREasgrq+mFFiVPzXLC8rGn5bEUtaeGrkT1zVc/N03uXIWfH2yyt/+oi5tUIjAiSZ8AjHak6KnssJCwkNODxL7q+CPnD3unbRCdhdHxfe/s+quoa1fgplKYhMCJG1q4f19eNsg7y+OkMSpWH5kpYNn3275qeR5xykWOzSu7t71SqJSXsCSIwIkSCQm7rXSET3G9Sqjzl5Eq42tJk0AVpuMsYvlOuGrS1vcenUp5mwkxW7hEYETJC/9LJVZorZOmsLKFF6smV8O1v2xngZGDfp3vqBnfZSHrJvnbrRY2bXKZqWI1BYESFTG7fcEiRM2cdS6ly2ZyH9JEr4s8tlVWRu4xUfdWkanK3InvDyKSF1eqNL7gLJjAiYrcuWeqOEfHEMloXSLmPS14uo1R5mskjqfFT7YSy7JMYtmP7S45LUPx2gL2Jblm19+fXuLAhMCJCNuTdVexOyQ8pJCgFBau5vQ/E1M9r1Iuf2pkAP39wYbvvaOVRlM3aZn+fXqFWsHqPwIgCKfVx3+Fxq+vW1yalyk9+uiTxTwTnyqllicq/Qdtxs0x1WDuOcpW5EJnstmXBt/Xq3veY6CYwIkDuKKSY4DZxN55DyeFHv5tYSqlyC5aWNqhbZ1RY+dln7ZW/UY9CZfmszQUaEq9jJ5epeq5tCIywk1t4CQspV+4C+eWT41VnLWPi0JZ7ZlepT78PPqzlguWYXdt+lyEb9NK9a3xDnvqwWr3zFd9XAiPAQdsGeWYsByDt3jXbmb6Q1VCyKgr2yJJQW0Udz9yzQBVkt/73QR6h2twrVFLdqP7yBhPdBEaAsixcHMmv5DXDihK7bV3x0PuUKnfFtC9qE0tEg7ZFQUyd2K/1dxlSXDBucZHGDW+Wq28reBZFYITcBUMK1eG93TlU5q0ltWr8VEqVu0SWiNoo8HjqgALVsRUhIMtxpXy5LfO+rlMPv89mUgIjAk4fmO/Ma5HaUKMnlSQmu+EOWSJ68/TgJ8AlLE5LcpSrxIlMdMcs3Vw0NJqJblZ8ExgITnOpcqlCC/fIUtGF3waf5PJYSh5PtUSOXO1v8WyWR+dVqTmcIU9gIDiy3v+0iZQqd1md/mjGTQl+p70sBJEJ8PWRkx8v2sdevSjZG3T9m0x0ExgIjNzKn/t8qfrga67SXDfjy1o18ePgJ8Blie369gZJyf1OBfaGimunVahVVdwRExgIjCzblDO54YerXytXZTXBDpKyie+cdZbM7rBppjqpn735t5lLa9XjHzDRTWAgMBNmUarcNysrGtTf3gp+Ary4d26ibEizMfsVJs4Et3JXLI/nJpdTCJPAQFDkruI6Njp56f65lerDgE87zFzrKNcDtstRQ3vY2zf0rznBv38QGJElpcpl3oKliH6SK+w/WbjCPniHHLXHVtlqzFB7E90ryhvUTdMr+BIQGAhCc6lyG5VQkTrvLq1VT34Y7AS4bLWYcGhcbbuJvXpRf3k9+DkcEBiRdfOMCkqVh4QMniUB75uxeUaLVCGwsUoMBEZkyeE2cuYG/CfBf0NE9iFI9QE5oxsEBgIku3aljLorp/mhfaSGUhT20Nw9u9JKqXcQGJEnZ264dF44Np4sXJAr74YQP9a3eZgUCAxog7fJVtccVKS4z/Df7OV16rEQb2Ibb+m4WhAYWMuo3rmJ8urw37XTykNZJmPyohr10qdUIiAw4AQpr35Mnzw6wnMSFtdNC9cEeLWcODiVzaUEBpwybr8OiUdU8Nu/PwhXqe873qlUS1Yz0U1gwCky+S2T4DIZDn/JxLeUQA/DDv7PV9Wrf3BMMIEBN8kyW1luyx4Nv72/ok49EoLjSq+YUq5qqF1DYMBdEhbs0fCfbObzeTf/8wur1WuLmegmMOA89mj4b3V1o7rmDT/3LVTUNqqrXmOim8CAN2QC/Ir9O9ARHntifpWatazWu9cttc44KpjAgGeO2jUvseQWfpKn/3LIkE/TAAu/rVf3zmaim8CAl2RTn2zug5/mr6xTD8zxYwBuCrgyVcfNBYEBP8nUt5QPYY+Gv/42vSJxrKvrnv6oWs34qpYPjMCAz9ij4bfS6kb119fdnkQu8eA1gsBAKzXv0ehcyNfCR3L1/rbDV+9/e6vci7sgEBhoJdmjcfvIuMrPYo+Gb5rnB+odHJNlnuXBuVV8SAQGwqZflyx10y+LVCaZ4Z0FsgLpPbcmwKWUydhXw1HKhMAA1uOg7XPUOPZoeEn2OKxwaI+DFEucvbyOD4bAQJgd15c9Gj4qr2lUVzsyufx9ZUPoyrETGEAL2KPhp2cXVKu3ltifAL92WkUoD3wiMGDVG1/UOvmMt3mPRv+uLLf1je0NcrOXhftIWQIDVrz8WY065anV6tznS50MDdmj8c9D46rHJlQq9Mmn39eru2bZmQCX7/FYHVjcWxAYSKH3ltetCYrnFlY7Gxqb5cfUvaPiiX/CH7e9XaGWlgZ/myGlSmQpLQgMpMjiVfXq1GdKVGXdDwkhoXGeo6EhdxgTitmj4RMpI/7ngMuIy+a8G9+qoPMJDKSKlHY+9onV6z0AZ5LDocEeDf/895NgDyq6WgdUWQ0PowgMpITU/Tnl6ZINngfgcmjIHo2x7NHwSlBHoU7/slZN/LiaDicwkAq19UqNnlSiPv4m+fPdRGj8183QOL5vXmKfBvzw+ap6NWFmeifAZUXWOCa6CQykhvwiXfxyaZvWx09a4G5oyE5wuduAH+54p1ItKalP299/96xK9cl39XQ0gYFUuH5aeaKiaFtJaJzvYGjIPIbMZ8i8BtwniyuumpqeCXBZiXXr20x0ExhICanUeee7G/9I4FlHQ0NWTMnKKfZo+EH2/ExelPoJ8KteK0usyAKBgXaSFSpXTClr998jofGHF9wLDfZo+EUmwKtT+CWa+nmNeuGTGjqWwEAqzPgydWU/ZAWKi6Ehdxh3jixK7AqH22QeQ+YzUkGC54qpFBckMOAsCY0LHAyNAd2yE3Wn2KLhvn++W5nYONped76Tmr8HBAbS6BlHQ0Mq20qFW7hN7gzGt/POQILiH+9W0pkEBgiNjSdnaLBHw31TPq9RL3268XMP8iiqmmP0CAz4FRoXvuheaLBHww/jp5b9qJZZa8kkt0x2g8CAZ2Rvh2uh0bxHYzf2aDhN9k/c1sb9E7J8VpbRgsCAx6FxkWOhIXs0bh8RV1068DVz2d2zqtRn37d+4vpWSyXTQWAghZ5yMDQkLO4ZFVdFuaydcpUUJWztPiEp/XH3LCa6CQyEJjQudiw0em2Rpe7Qdxrs0XCXHBEsZ7FsiHylbB/7CgIDKfakg6ExeBv2aLhODlraUHkP2f8j5ctBYCCMofGSW6HBHg23yfkst8xY/wS4HIh09Wvs6CYwEN7Q+NC90JA9Gr/ahT0arrpn9vpLlMuRq3L0KggMEBqBuurADolHVHBP8yFIa5u/sk49MIeJbhAYkQmNPzoUGjL5LZPgMhkO98g8xTPmmFX5yozVAcKGbhAYEfIfx0JDltnKclv2aLjpr6+XJ+Yt/j2vSs1eVkeHgMCIYmhc8rI7V4vs0XDXivIGdeXUcnXtNCa6QWBE1hPzq5wKDfZouOtx/V1ZVcWzKBAYkQ+NSx0KDZkAv3xoBz4YgMCAq1ePLoWGlEOXJbcACAw4HBoNjoSGbOqTzX0ACAw4GhqXOBIaMvUt5UPYowEQGCA0kmKPBkBgwIPQuPQVN0KjeY/GZvl8PQECA0567IOm0HBhSkP2aEwojicOYQJAYMDR0JDHUy6ERr8uWYljXjPJDIDAAKGRzEHb56hx+7NHAyAw4HRoXOpIaLBHAyAw4Lh/OxQa7NEACAwQGq0i0xhX/7xDYl4DAIEBh0PjMgdWT+VlZSRWTvXYhEqFAIEBZz06z43QkL0Z97JHAyAw4H5ojHEgNOQOgz0aAIEBxz3iSGiwRwMgMEBotJrs0bhk30I+EIDAAKGR3Mn98xP7NAAQGHA8NC5/1X5oyE5wudsAQGDAYQ+/bz80ZB5D5jPYowEQGCA0kspnjwZAYMCf0BhrOTTYowEQGPDEQw6Ehtxh3DK8KHFyHwACA46HxrjJdkNj0NbZibPB2aIBEBhw3INz7YeGVLaVCrcACAx4EBp/shwacoYGezQAAgMeeMCB0GCPBkBgwKPQuGKKvdBo3qOxSyf2aAAEBpx3/xy7odG8R6NLB77uAIEBQiMJCYt7RsVVUS5rpwACA16ExniLodFriyx1x4g4ezSAjZSx/U0rGyP3pnWLB3ilWVWnVHV9I982Q67ybV6plNU2qvoGPgegrSI5EyhD9+pqBnBbSul7wEs8kgIAEBgAAAIDAEBgAAAIDAAAgQEAIDAAACAwAAAEBgCAwAAAEBgAAAIDAEBgAAAIDAAACAwAAIEBACAwAAAEBgCAwAAAEBgAAAIDAAACAwBAYAAACAwAAIEBACAwAAAEBgCAwAAAgMAAABAYAAACAwBAYAAACAwAAIEBACAwAAAgMAAABAYAILUaJTAa6QcAAIEBAEhZYDTQDwCAJBokMGrpBwBAEnUSGBX0AwAgiQoJjHL6AQCQRLkERin9AABIokQCYyn9AABIYqkExsf0AwAgiQUSGPPoBwBAEvMkMBbTDwCAJBZLYHyr2IsBAGiZZMS3Ehhf6vY9/QEAaIFkxJcSGCt0W0J/AABaIBmxormW1Ef0BwCgBZIRDc3nYbxPfwAAWpDIiObAmKVbDX0CAFhHjcmINYHxum7f0S8AgHV8ZzJiTWBUKfZjAAB+arHJiB+d6T2dfgEArGNNNqwdGP+n2MAHAPhBrcmGnwTGe4p5DADAD74z2fCTwPjRrQcAIPJ+lAnrBsYtujXSRwAQeZIFt20oMF7RbTX9BACRJ1nw0oYCQzxDPwFA5E1c9w/WFxi3Kx5LAUCUNZosSBoYUjOETXwAEF2SAXNbExgVuj1MfwFAZD1isiBpYIgH1vcfAwBCr1y3+9b3L1oKjPm6vUG/AUDkyNj/UVsCQ/xdtzr6DgAiQ8b8m1v6lxsKjOd0+4T+A4DI+MSM/W0ODDFWscQWAKKg0Yz5amMD4zHdFtGPABB6i8yYv9GBIc6mHwEg9JKO9a0JjEm6zaEvASC05pqxvt2BIS5TzGUAQBjJ2H5pa/7D1gbGC7pNpV8BIHSmmjE+ZYEha3MvUOYgcABAKFSbsb1Ve+5ibfiLZ+r2OP0LAKHxmBnbWyXWxr/8f3X7hj4GAO/JWH5qW/6HtgZGjfkBTIADgL8azVjepmmG2Eb8oKfUek5iAgB4Y6IZy9sktpE/TJJpJX0OAN5Zqdr4KKq9gfG1bmfq1kDfA4A3GszY/XWQgSFkdv1++h8AvHG/SlIvKl2BIU7XbQGfAQA4b4EZszdaewNDZtgP1K2MzwIAnFVmxup2bb6OpeCFfKXb0Yr5DABwUYMZo79q718US9ELkiqHVyn2ZwCAS2RMvlq1ohJtkIEhxql2TKYAAFJOxuTLU/WXxVL84o7TbTqfEQBYN92MySmT6sCQiocH6LaQzwoArFloxuK6VP6lsTS8UJmF3123L/jMACBwMvYOVGk4jiKWphcsS7j21m0Znx0ABGaZGXtL0vGXx9L4wmUJ1xDdlvMZAkDaLTdj7lfp+gGxNL+BRarp8dRXfJYAkDbyGKqfGXPTJhbAG5FbpF0UE+EAkA5S8uNnuq1I9w+KBfSG5HnarooltwCQSjKm7qYCKs8UC/CNyWl9g3V7VLEjHADao9GMpTKmVgX1Q2MW3qjUNJGt6vV85gDQZvVmDD066B8cs/SGx+h2uG6lfPYA0GqlZuwcY+OHxyy+cTlTVp69fcx3AACS+tiMmRNtvYCY5Q6QJWC9VdMpUDyiAoCfkrHxX2asXGTzhcQc6ZDfqKbncSv5bgDAGjImHqPbiS68mJhDHfO4bn10e1axigpAtDWasVDGRGeOjYg51kmy8eRQ3X6t2zd8ZwBE0DdmDDxUBbAZz+fAWPtuo7NuD6sA1xgDgEVVZszrasZA58Qc7jw5h/ZY3Q7WbYriMRWAcGo0Y9zBZsyrc/WFxjzozDdU00Egcns2h+8WgBCRMW2UGePecP3FxjzqWDnEXCrfjtDtM3MHAgA+3lHIGDbSjGkTfXnhMc86WkLiOd12MLdu83Wr5fsHwAO1Zsw6xoxhk3y78I153PlSeEtK+so2+RdUQNUaAaCNSs0YdbgZsx719Y1kheDDmGRaP/OByJ3HjnxHAVj2iW4P6faEbnPD8IYytr8pdJurC3Trq9to3Yp16yjvk+8ugDSTuYnVuj2j2x0mJCrC9AazQvihyQc0Xf1wWNPPdTtHtz1121S3HL7XAFJEzvn5Xre3dbtFt5fC/GazIvCBvmKaGKDbCbrtrds2JkBy+c4DaKVqExBLdHtTNRVOnRmVN58VsQ975lofbp5uQ3TbSzWdOd5Lt+4mRLL5vQAir9aEwxe6LdRtnm4zdJumIlqBIivCX4aqde4+hGzJ76ZbJ916qKbCXz3Nn8V1K9Qt3/Rbpvl/MhRzJIAPGtUPFSOkZLjsqK7UrVy3Et2W6rZAt/d1W6yaKsXKny2j65r8vwADAPPLkTyTx0GpAAAAAElFTkSuQmCC"/></svg>diff --git a/web/images/credentials/zhiyan-build.svg b/web/images/credentials/zhiyan-build.svgdeleted file mode 100644index d2f95cae..00000000--- a/web/images/credentials/zhiyan-build.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" role="img"><image width="100" height="100" preserveAspectRatio="xMidYMid meet" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIUAAACOCAYAAAAfHcv/AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAHYcAAB2HAY/l8WUAABc1SURBVHhe7VwHeBVVFrYjYmctoCBlpTdpIqBUpSpSFZSyrIBCaKETWEowSCf03gmRCAFhCVU6AQIC6b2QQnrvhbPzn2TeJpmB90heyJvk/t93PsKd9t6cf875z7l33jMkIFAIghQCCghSCCggSCGggCCFgAKCFAIKCFIIKCBIIaCAIIWAAoIUAgoIUggoIEghoIAghYACghQCCghSCCggSCGggCBFPjx8+JDSMnIoPimbEpKzKT0zh8fKGwQpJMDvyWnZ5OqXQluPRpL56iCaYn2f9jpEkff9NCZKeUK5J0Vm1kPyD02n/aei6dtp3lRngDPV7HuPrc5AZxoy15eOXIyl4IgMys4uH1Gj3JIiJ+chhUVlkP2FWBplFUBNf3TRkaGwtRjuShNXBtFJx3iKjMuknDKeUsodKaARUqRUcelOIs3eGExf/OxBtfqpkyG//bP/PfpyvCct2hFKtzySKS0deiPvpGUM5YoUcKJHQCpZSo7tPsmrQKow1Op/50x9pDSz0uYBBYalc8Qpayg3pIhJyKItRyJpwCwfajT40anCUGs21JV+nOdHtmeipchTtoRomScFKoc/L8fRdxa+km5wVXVwUQ1pB3pj+AJ/uvh3ImWVESFaZkmBsO7im8KlZat/uVFtSROoOdYYBr3R5t9uNG9rCPmHpGtea5RJUkTGZtJau3Amg5oTS9LajXKnPSeiuPmlVZQJUqCiQGRISMqmU9fj6Zup3lRLxWFPyz4ecI/7G5fvJlJyajaXsFrqjGqeFLjX8UlZdNMticyWBVI9qTpQc1RpGDTMrA3BdNc7mZJStBM5NE2K1PQcqcRMoxVSedh65NNPFYZap7EetMU+gvwkvZGRafqViiZJkZmVQ15BabRVKjF7m3urOsLUDEJ3kFQB2ZyKpoCwdMo24f6GpkiR25rOpEPnY2nM4gBq8L3ppApDrdEQF5q8KohOXIuj6Pgsk6xUNEOKRCknQ0SixET5V9uA1rSpGqLG52Pcae7mELp8J9Hkml8mTwo8SZihhG7oNtGT6g7SXnR4lCHSoVJCGgyPycz7xqUPkycFcu/pG/HUfLhxu5GmZF3NPDlimAo0ECkekqtfKg2d71eiXcnSsroDnXla3jc4Le8blz40kT4QLRBeNxwKp/aj3VVvrjENbWu1cWMammtdpAix1yGaYhOyTGq21aRJkZOTQwkJaZSVldv4AUFQio5dGijl4+LPdKpZ3xnevF7i/O1E6jzWU3Wf4lrDwS7c1AqJzODvBWRkZlFSslSqZpe+6DRpUixZc4re/ticvh22kc5e8KD4xFQpauRwn+KcUwINnOVLjX8oPjnqS4Kvx2Qvsj0TQ4nJ2boyMS4xmzbZR1DHXzyoXjEFLiIDOpzD5vtLpEuRCC9FQIkAMbHJdPj4Hera35reazCNbP64oXsISgsmTYo+QzfSS1XN2Ko3nU0Wvx6lO873KTkFM5EPc512OIKFWlF6FsjnWHm1cHsoRyC1hhKmw+/5pND0dSiF3XleQ+1cj7PGQ1yol7kX/S6RDl1YpIrEpDRydPKj8TN/l8gwXfc9LRbaU3p6Vt7VSwcmTYqvf9igu1mwlz8cTy27WNHqzefIxT2EQy7IAZG2aGcofTXBsJIVmgGzmeh5YFleugGrtTGx5eAYT+Ok1NUaU/EG9ElA1N5TvMnaNlyXKuDwW3cD6deVJ6h+2/kFvh9MkEIPCpNCtrf+mZtSDtg7UUhYHBMDayaRUrA8Hw5/lNOaSOlm5CJ/OnA6mqLinqyjiOvAudv+jKQh//F9pK5BNEHKsdgUTI4uSUw6RAffgEjaYXNNShWrqdJHE1W/myCFHjyKFLJ92GQWjRi/m4463KX4hFSeosZq60N/xdLPSwJ5yVx+R2H1Fd7rwJJ+OLioQEpxD0ilNb+H09dSJJAX/uLfViPcmJgnrsVL6S03koVHJpDNoZs0cOQW+kedqarfRTZBCj3QRwpYhQ/MqGmHRTR13iEpR/tzSsFMpNf9NNpsH0nfz/Flxy3ZE0a3parCmLOUaE9jzQRWXCF1DVvgzyUmJrxAnJTUDDp3yYPGTT9AddvMU/38hU2QQg8MIYVsr9ecRG17LqWFy46Tj38Eh2voAM/AVHKWhGJJrYRCvMGi4L+9kslH0jZIFVlSdeQsaZ7pCw5T885W9OojUoWaCVLowZOQAlbhg/Gs5HsNXkf77G5wSnmaQKqIik6iDTsvUue+q+gfdadyJFP7rI8yQQo9eFJSyFaxWi45vvtpK12+7kOZmSVb9yNapEtpy+GcK/X4bi1VlnQDKiW1z6bPBCn0oKikkK1itQmSGJ1JcxYfpYiokptwCg6NpV+m2dA7UmQoKhlkE6TQg+KSIr993Po/tF+qANA0QiexGMUHpwnoBnQjrbf8Re/V/3/zqbgmSKEHxiSFbAjvlxx9ckvYIkxCya3pYyedqV3PZcWODIVNkEIPSoIUsPcbziCzmbbkeMuf4uJTDOpZgEBRMUlSielJw8ftklLFNNVzF9cEKfSgpEgBgxht0cWKlq8/Q14+4ZSR8WhHpKVl0j3XYJq/9Dg1bLeQqxy1cxrDBCn0oCRJIRta5qMm7WViqAFRxNkthPoM3UCv1Zikeg5jmiCFHjwNUqCP0H3gGrp1NyjvqgUBUly54UtNOy5SPd7YJkihByVNCpSQ/f+1hY6fdqGERPVGF+QGhOWBw07UXRKpb9Y2Vz2XsUyQQg9KihSvVJtALbsupnXbzpO71wN2AiICVnrlF534O7d8zZ3HwFqOxdYnqWH7BVTRyFWHbIIUelASpHi3/jSaJwlGV88wSknJYIc/iIinNVvPS1XFbrp204/JARw/7UxDxmynHfuvcgmLfdHnQKqZZHGQ3v54iuo1imOCFHpgTFKg2hggpQqnO4HsWJSYqWkZ3JruPmgtvVNvGr1aYyLNtjyic0q/EZt43UMVqYTtN2IzXXb05ZY5ogdIcvaiB6+NULteUU2QQg+MRYpPOv1Kx07f06UGRAIfvwgaYbZb0giTC+w7cfZBSkvPfTGnU99VBbahczlZihD3Q2J050Jnc5etI9VqblFg36KaIIUeFIcU0A21WszhqXTMXMKJcjdy5cazVANOrKI87nGkkK3xF5ZSSrlGMXEpvJAY5w4Lj6fJcw5SVSmqFEdvCFLoQVFI8Ur1CVS71VwaZb6P/na5T5lZ2ZQlkQG64dCxO9S25zLV42QzhBQwpKPeQ9bTyb/cKFIiHdJRekYWl6+DR2+n6s1m84ScGvEeZ4IUevAkpEC/oWqjGdRLcpTd0dtcYsJR0TFJdP6KF42csIcqVde/2MVQUshWWRKbkyzs6MbtAJ0YBUkQSbr0W03vSlrlSdZUCFLogaGkQO8Agg8lZlBevoeYxMTXTEt7qimlEUMd86SkgFWQrN5n82nRihN0UxKyqVL5CkKiS/qb9Slq33s5rwxTO7awCVLogT5SIHdjuRveB0FVkZWdzWs0UW6u3nTuiZwhW1FIIRvI+dXANbRlz2Xy8Y9kEQoHX7jqRZPn2jFx1I7Lb4IUevA4UtRuOYfMpRt99pInOxFPZuiDeNq27wrn+qKucSgOKWTDwp5B/95KtoedKDIqkSMX0tmxU840Zsp+TnNqx8EEKfRAjRRYIv/9qG1ka+8kiccEXtYPgQfBhyltLKZ5uRizmMYgBQzVD2ZUx06zoauS+MQsLMgRFBxDO22uSd9tvWoUE6TQg/ykQFXR4ZsVtF2KBAFB0VKawDufD8lNShV4+hCaDRGS+sxYpGCTKg84vkkHS17ZHRKa++ISSOzlG05rtvxFrb5cXGChjiCFHowy3883Fj0FC6uj5OoRqnuPNDo2mV9ARmPqjVoFG1DFMaOSIp9VrjOFWn/1G+sNzKPgO0AMO90NpPGzfpdSykz+rsvWnmZdVJowaVIEh8XR3t+v83ujeHpwI+Ewuz9vU9seS59YRBpiJUUK2UDgL6VS9cwFd26mcbtdIsmN2/5cSkdE5mqQ0oRJkyI/cKNcpEiB1wRLcvq6pEkhG94JmTzHjvyDoqTvxpczGZg8KUAGrI1cJZWY6Deo3WBj2tMihWz12y6gXQccpepE/LyRwQApLl3zpgbtFqjeVGPb0yYFrEu/VXTz7wC+pilAE6Tw9ougsdMP0EfNZht9SX1he5qkQNmKeZq5i//kUtVUoAlNATF2PzSWVm/+i74cYM3zDWo32Rj2tEiB9Rvf/LiBtu29wj9VUNriMj80IzQBNIDuugST5Yr/UpvuS/hJU7vhxbGSJgV6KXj5eMWGM+Th/YBb4aYGTZFChrzqafxMW6rWdJbqzS+qlSQp6nw6j2ZZHqGrN325DDVVaJIUAMItwi6W0w0es53eqGmcBlZJkALzMOi6XrzqTbF4I43PbrrQLClkoAHkFxhFu20d6bMeS4stRI1JikrVJ1C3gWu42QZNZEq64XHQPCkA3GzoDV//SG59YxmempMMMWORomH7hbRx10WuKrDYVyuEAMoEKWTgxsOhN6Saf+jYnUXqfBaXFOhUms2w5XkaeWZUayhTpMgPvBR86NjfT7zQpqikkBfYnJEEcGn/Ym5xUWZJIQOLXCyX/5en1g35QbInJcXrksBt9LklLwXEb2uXBZR5UgAI4ZhMG5237gJrM9QcDDOIFFXM6DVeJ7GI10mYUjfSGCgXpJCB5f5/nrxH/UdsphqfWKgu5tVHCiztx+quYeN20QWpxNR6qlBDuSIFgKjxIDyetu+7mruWM9+PpcMeRwo0yvCLe7b2t3jmVosi0hCUO1LIwOomtMytVjlQm25LOB3A8fjlXpkUPQev4zG8Wtixz0qy3nyOPH3Cy2R0yI9ySwoATzqWxOG3NudYHeUo4HDOjd8oA/ba3eAXi61WO/ArBKbcmjYmyjUpZOCFY/zOJhbTymtAASx8waQV3j8tq6lCDYIUAgoIUggoIEghoIAghYACghQCCghSCCggSCGgQJkgBfoMaWlpbFlZpfseZllAmSDFhQsXyMzMjObNm0d37tzJG316ABEvX75MDg4OBtnp06fJ3d0972jTg+ZJER4eTl26dKEXXniBPvnkE77pvr6+BSwqKoqjiYeHB+3bt++RdvToUYqJyf9ziFl6j4F5enpS9+7dqWnTpgZZ+/btaePGjXwNU4SmSeHi4kL9+/enF198kZ555hl67bXX+KY3b968gG3fvp1SUlLI0tKSPvjgg0dajRo16MSJE5SdnTvhlZSUREuXLlXdV7YPP/yQiVi5cmX+HM8++yx/lueee47//9JLL/HfGIPh/zgGn8lUoVlSJCYmUufOnalChQocJd566y165ZVX+MY///zz9Oqrr/LY22+/zU8z9Ea/fv105GnXrh19/vnnbLVq1eJzwHlHjhzRkSI+Pp6mT5/O299//33eB8fjvCAQxuvWrUt+fn507tw52rJlC/8f+yByHDx4kE6dOkVt2rThz4TjbW1t6eLFi/TgwQO+hilCs6RATq5SpQo/rYcOHaKAgAAaO3YsOwROwBMfGRnJBkLA0fXq1eMnGWRKSEjgSABbvHgxP+kVK1aka9eu6dIH/k1NTaW4uDjasWMHvfHGG+zYzZs3U3R0NJ8D5ERqgl2/fp3Jgs9gbm7O505OTubPg+u+8847PIZ9TXmCTbOkgPPgzKCgIEpPTyd/f39q1KgRP+0jR45krZGRkaEzPPVwKp5YbJcB3WBhYcFRBmEdKamww0CsGTNmsLPr16/P1y4MOPrMmTP08ssvM7l+++03Hrt//z41aNCAj4Xm0QI0SQo8oYMGDaJq1aqxIxEt3nvvPX4aYa+//jqPy9a3b1+uDkAY5PQFCxbknSn3XKNHj+ZtrVu3ZmGaHyDI1atX2aHYZ8yYMaqhH8SDTsD1cc1du3bxuKOjoy56DBkyhMdMHZokBZ6+Pn36UM2aNemjjz7SCU1EAWgIOKV69ersDNj48ePJxsaG98GTvHv37rwz5Z5rwIABvA3kCQ4OztuSSwiEezz1ODfIt3fvXk5F2JY/omC/OXPm8HmaNWvG4hNAakOaw3h+MpoyNEkK5Ol79+7xE7x27VrWA3iKQRCQ5ZdffqFVq1bR+fPnOc8jtaxYsYIdU6lSJRaFSDmwW7duUceOHXkbyINUIQPOv3nzJjVu3Ji3f/rpp7Rp0yYWj2fPnqWwsDBOP9gPZS+iF/br2rUrnxfj+BwQphiH8MSYTCpThWY1RWZmJjetOnTowCEbUWP27Nn07bffck7H+MmTJ7kUBeBwOAaRYu7cubR+/Xq2qVOn6sI7IgLSiYyIiAhuiuH82A7dAbH47rvvcjTC8ehtIHrgb7nyaNWqFa1cuZLHUfHgmhifP38+jx07dkz3uUwRmiQFRCPSQcuWLTlCQPxt27aNHQrt8MUXX3BK+eyzz9gJqBBQIsIxMLk8hOFvjMHxKF0RPQA8ycuWLWNxiu34F5ECfQ9EG4xNmjSJxS1KXIzhs2Ac50VJjHE5tcGwD8YQmVDRmCo0Rwo4y9vbm5/En3/+mYWfvb09l50ASsjjx4/TxIkTeZu1tTWFhIRwE2rChAmPNDgYlQdCO4AUBV0iOxRP/x9//MHpQB63srKiTp06MVHkMZAAUatFixacdkACjCPKYAznGTduHEc6U4UmSYGIgJITYg6aYv/+/XTgwAGdQfljHA5cvXo19xg2bNhA69atK2AYs7OzIy8vL+47wFFyrkcfRCYEogjSEq65Z88eTh0Yg4iEdkCJOmLECN4XumbNmjU8js8i6xFUNhiDocIRmqKEAD1Qu3ZtdkRRDFoCToOjCz+56Gyi2sATjnSA3gZ0AATrm2++yZ1UJycn7kUgqvTq1UvnfGdnZz4HxGiTJk14fPjw4TymBWiWFHjS0JlEHochZIMghhja0xCLcBb6FsuXL9dpCRlIQWhJy9oAIhb7zJw5k49B2xtdVHwOVCGogKBPUNZCwwDQM/hcuM7ChQt5TAvQLCmgIRo2bMg3HE2s0NBQFqCGGKoKpA6kADgccxaylpCByIEpbjgafQakhNjYWPrpp5/4OPQi0MQCKVCB4HNAjII8iB7AkiVLuFrBNohYrUCzpECTCbkdNxwOQp8ATjPEAgMDdY0mnAO6Qi3HY3ob+6DUhH5AvwOzshhDPwQ6BMf98MMPPIYoBIIAINnkyZN16Qc9Fa1As6RAU0pOAcjvcK6hVrVqVV1VgGiDOQs1TJkyhfdB1YB2NTQEUhbG0L+A4AUZEQ0QPbBOAhELQIdz6NChHGmgQXx8fHhcC9AsKfB0o6UNB4EcderUMdiQ59HgwrGYOkdFoIavv/6a90F/At1RVDXoS2AMjS4IT6Qh/B8NKghfOXUgkvXu3Zu3QczKZNECNEsKlJvy0z5t2jTuXhpqO3fu1HUf4fjCk2AAnIumGPYB6Xr06MGVBYQnhC00AlriaJBhH0zI5Y84d+/e5ciBbSBH/va5qUOzpMB6Bbl9jD4FptANNcx9yK3tYcOG8RK8wkCZiQoDJChsEJ4oNzErCs0AkmC+Q646ABBEjipojkHgagWaJAUmoQYPHswCDje9Z8+enL8NNTy5SB/I9+hkYtq7MJAaUKqi1V3Y0PjCRBna6SAEzlV4eR0aV3KXE70NkEwr0CQpIPC6devG/QK0lYtq0CRoVatVHhhDClEzlKvolMrrMtu2bcuViAwcC+JgOz7j4cOHVYlnqtAkKdBEQosbncjiGJpTbm5ueWc1HCg3r1y5wroC57l06VIBYuFvV1dX3XaITJBJK9AkKXDTkULwxBbHcI6iOKvw9Qs3vgCMydtxjfykMXVoVmgKlBwEKQQUEKQQUECQQkABQQoBBQQpBBQQpBBQQJBCQAFBCgEFBCkEFBCkEFBAkEJAAUEKAQUEKQQUEKQQUECQQkABQQoBBQQpBBQQpBBQQJBCQAFBCgEFBCkECoHof9yJvcED8z1wAAAAAElFTkSuQmCC"/></svg>diff --git a/web/index.html b/web/index.htmlindex 365052d2..d557d629 100644--- a/web/index.html+++ b/web/index.html@@ -22,7 +22,6 @@<link rel="stylesheet" href="/product-v4.css?v=20261031req2"><link rel="stylesheet" href="/app/harness-ui.css?v=20261031req1"><link rel="stylesheet" href="/assistant-models.css">- <link rel="stylesheet" href="/deployment-dashboard.css?v=20260920r2"><link rel="stylesheet" href="/metrics-dashboard.css?v=20261030obs1"><link rel="stylesheet" href="/knowledge.css?v=20261030r2"><link rel="stylesheet" href="/business-domains.css">@@ -169,7 +168,6 @@<p>数据洞察</p><button class="nav" data-view="metrics"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="chart" data-icon-motion="idle" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M4 19V5"/><path d="M4 19h16"/><path d="M8 17V9"/><path d="M12 17V7"/><path d="M16 17v-5"/></svg></span><span class="nav-label">研发效能</span></button>- <button class="nav" data-view="deployments" hidden><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="clock" data-icon-motion="idle" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg></span><span class="nav-label">部署耗时</span></button><button class="nav" data-view="businessDomains"><span class="nav-icon"><svg class="agent-icon harness-icon " data-icon="layers" data-icon-motion="idle" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><g class="motion"><rect class="p0" x="4" y="4" width="14" height="14" rx="2"/><path class="p1" d="m7 20 10.5-.1A2.5 2.5 0 0 0 20 17.4V8" pathLength="100"/></g></svg></span><span class="nav-label">业务领域</span></button><p>开放能力</p><button class="nav" data-view="guide"><span class="nav-icon"><svg class="agent-icon harness-icon" data-icon="doc" data-icon-motion="idle" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path pathLength="1" d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path pathLength="1" d="M14 3v5h5"/><path pathLength="1" d="M9 13h6"/><path pathLength="1" d="M9 17h6"/></svg></span><span class="nav-label">接入指南</span></button>@@ -326,15 +324,6 @@</div></section>- <!-- 测试环境部署耗时 -->- <section id="deploymentsView" class="view page-view">- <div class="page-heading deployment-heading">- <div><p class="eyebrow">测试环境</p><h1>部署耗时</h1><p>自动展示 SkillHub 最近 7 天部署耗时、正在部署的流水线和 30 天趋势。</p></div>- <div class="heading-actions"><span id="deploymentLiveState" class="live-state"><i></i> 自动加载中</span><button id="refreshDeployments" class="button ghost" type="button">↻ 刷新</button></div>- </div>- <div id="deploymentBody" class="deployment-body"></div>- </section>-<!-- 待我处理 --><section id="approvalsView" class="view page-view"><div class="page-heading approvals-heading">@@ -646,7 +635,6 @@<div class="obs-tabs" id="obsTabs" role="tablist" aria-label="统计分类"><button class="obs-tab active" role="tab" data-obs-tab="overview"><svg class="agent-icon harness-icon" data-icon="token" width="14" height="14" aria-hidden="true"></svg>用量</button><button class="obs-tab" role="tab" data-obs-tab="delivery"><svg class="agent-icon harness-icon" data-icon="flag" width="14" height="14" aria-hidden="true"></svg>交付<i id="obsDeliveryCount" hidden></i></button>- <button class="obs-tab" data-obs-tab="skillhub" id="obsSkillhubTab" role="tab" hidden><svg class="agent-icon harness-icon" data-icon="sparkles" width="14" height="14" aria-hidden="true"></svg>提效</button></div></div><div class="heading-actions">diff --git a/web/obs_charts_test.js b/web/obs_charts_test.jsindex b4c68a07..17a81a21 100644--- a/web/obs_charts_test.js+++ b/web/obs_charts_test.js@@ -266,18 +266,6 @@ function fireVisible(ctx) {const owners = ctx.obsOwnersOption([{ name: 'u', delivered: 2, active: 1, undelivered: 3 }], opts);same(owners.series.map(s => s.data[0]), [2, 1, 3]);-- const sh = { gongfeng: { mergedMonths: { '2026-01': 1, '2026-02': 1 }, monthlyLegacy: { '2026-01': 3, '2026-02': 1 }, monthlyMonorepo: { '2026-01': 1, '2026-02': 4 },- weeklyMerged: Object.fromEntries(Array.from({ length: 14 }, (_, i) => [`2026-W${String(i + 1).padStart(2, '0')}`, 1])), weeklyLegacy: {}, weeklyMonorepo: { '2026-W14': 6 } } };- const monthly = ctx.obsSkillhubMonthlyOption(sh, opts);- same(monthly.series.map(s => s.data), [[3, 1], [1, 4]]);- assert.equal(monthly.series[1].label.formatter({ dataIndex: 1 }), 5, 'bar top shows stack total');- const weekly = ctx.obsSkillhubWeeklyOption(sh, opts);- assert.equal(weekly.xAxis.data.length, 12);- same(weekly.series[0].markArea.data[0].map(x => x.xAxis), ['W11', 'W14']);- const deploy = ctx.obsSkillhubDeployOption({ dailySample: { labels: ['a', 'b'], backend: [1, 2], frontend: [0, 1], e2e: [3, 0] } }, opts);- assert.equal(deploy.series.length, 3);- assert.equal(ctx.obsSkillhubDeployOption({}, { theme, reduced: true }).animation, false);})();// ---------- 研发效能 option ----------diff --git a/web/observability.css b/web/observability.cssindex 9e475415..44999cd4 100644--- a/web/observability.css+++ b/web/observability.css@@ -273,7 +273,9 @@ html[data-theme="light"] .worker-log-line pre,html[data-theme="dark"] .worker-lo.run-graph.is-staged{display:flex;align-items:stretch;gap:0 40px;overflow-x:auto;padding:6px 4px 10px}.graph-stage{position:relative;flex:0 0 220px;display:flex;flex-direction:column;gap:10px;padding:8px;border:1px dashed transparent;border-radius:12px;box-sizing:border-box}.graph-stage.is-parallel{border-color:var(--line-strong);background:color-mix(in srgb,var(--blue) 3%,transparent)}-.graph-stage-label{font-size:10px;color:var(--muted-2);letter-spacing:.02em}+.graph-stage-label{display:flex;align-items:baseline;justify-content:space-between;gap:6px;font-size:10px;color:var(--muted-2);letter-spacing:.02em}+.graph-stage-name{white-space:nowrap}+.graph-stage-time{font-style:normal;font-size:9.5px;color:var(--muted-2);font-variant-numeric:tabular-nums;white-space:nowrap}.graph-stage.is-parallel .graph-stage-label{color:var(--blue)}.graph-stage>.graph-node:nth-child(2){margin-top:auto}.graph-stage>.graph-node:last-child{margin-bottom:auto}.run-graph.is-staged .graph-node::after{display:none}diff --git a/web/product-v4.css b/web/product-v4.cssindex 72743fcb..a61f8992 100644--- a/web/product-v4.css+++ b/web/product-v4.css@@ -3505,7 +3505,7 @@ html[data-theme="dark"] #runnersView{--rv-term:#0a0a0b;--rv-codex:#3f3f46}}/* 列表页:数据少或为空时主列表卡片与空状态填满视图剩余高度;内容超出一屏时视图自然撑高,仍由 main 滚动。 */-:is(#issuesView,#approvalsView,#sopsView,#agentsView,#assetsView,#botsView,#deploymentsView,#runnersView,#guideView).page-view.active{display:flex;flex-direction:column}+:is(#issuesView,#approvalsView,#sopsView,#agentsView,#assetsView,#botsView,#runnersView,#guideView).page-view.active{display:flex;flex-direction:column}#approvalsView .approval-list:has(>.approval-empty){flex:1 1 auto}#approvalsView .approval-list>.approval-empty{flex:1 1 auto;display:flex;flex-direction:column;align-items:center;justify-content:center}#sopsView .sop-page:has(>#sopCatalog>.empty-properties){flex:1 1 auto}@@ -3516,7 +3516,6 @@ html[data-theme="dark"] #runnersView{--rv-term:#0a0a0b;--rv-codex:#3f3f46}#botsView #botsContent{flex:1 1 auto}#botsView #botsContent>.bot-panel{flex:1 1 auto}#botsView #botsContent>.bot-panel:has(>.bot-guide:only-child){display:flex;flex-direction:column;justify-content:center}-#deploymentsView #deploymentBody:has(>:is(.deployment-empty,.deployment-error):only-child){flex:1 1 auto;padding-bottom:0}#guideView #accessBody{flex:1 1 auto;display:flex;flex-direction:column}#guideView #accessBody>:is(.quick-wrap:has(>.access-tokens:only-child),.access-tokens,.access-grid){flex:1 1 auto}#guideView #accessBody>.quick-wrap:has(>.access-tokens:only-child),diff --git a/web/syntax_test.go b/web/syntax_test.goindex c9e19ed8..c582fd8e 100644--- a/web/syntax_test.go+++ b/web/syntax_test.go@@ -182,9 +182,9 @@ const deliveries = [{issueId:'issue-1',lastRunAt:now,firstRunAt:now,clarificationDurationMs:600000,developmentDurationMs:1200000,testDurationMs:1800000,cycleDurationMs:7200000,phaseSamples:{clarification:1,development:1,testing:1}},{issueId:'issue-2',lastRunAt:now,firstRunAt:now,clarificationDurationMs:2400000,developmentDurationMs:3000000,cycleDurationMs:18000000,phaseSamples:{clarification:1,development:1,testing:0}},];-const state = {metricsRange:'7d',metricsData:{deliveries,runTraces:[],nodes:[],summary:{}},metricsIssues:issues,metricsDeploymentData:null};+const state = {metricsRange:'7d',metricsData:{deliveries,runTraces:[],nodes:[],summary:{}},metricsIssues:issues};function currentProject(){return {id:'project'}}-eval(code.slice(code.indexOf('function metricsWindow('), code.indexOf('function metricsSnapshotTrend(')));+eval(code.slice(code.indexOf('function metricsWindow('), code.indexOf('function metricsMs(')));const model = metricsDashboardModel();assert.equal(model.delivered, 2);assert.deepEqual(model.phaseTotalValues, [3600000,5400000]);@@ -213,7 +213,7 @@ const METRICS_WINDOWS={};const state={metricsRange:'custom',metricsDateFrom:'2026-10-20',metricsDateTo:'2026-10-21',metricsIssues:[],metricsData:{summary:{mergedMrs:2,mergedMrsMissingTime:3},deliveries:[],mrMerges:[{mrProject:'org/frontend',mrIid:1,mrUrl:'https://git.example.com/org/frontend/merge_requests/1',targetBranch:'agentflow/integration',issueId:'old-requirement',title:'Earlier delivery',mergedAt:'2026-10-19T16:30:00Z'},{mrProject:'org/backend',mrIid:1,mrUrl:'https://git.example.com/org/backend/merge_requests/1',targetBranch:'master',issueId:'old-requirement',title:'Earlier delivery',mergedAt:'2026-10-20T16:30:00Z'},-]},metricsBenchmark:{projectId:'project',gongfeng:{weeklyMerged:{'2026-W43':999}}}};+]}};function currentProject(){return {id:'project'}}function metricsProjectId(){return 'project'}function obsCategoryLabel(value){return value}@@ -229,7 +229,7 @@ assert.equal(metricsBucketKey('2026-10-18T16:30:00Z','week'),'2026-W43','local Massert.equal(metricsBucketKey('2026-10-18T15:30:00Z','week'),'2026-W42','local Sunday stays in the previous week');assert.equal(metricsBucketKey('2026-10-31T16:30:00Z','month'),'2026-11');const display=metricsDisplayModel(model);-assert.equal(display.mergedMRs,2,'a benchmark snapshot must not substitute its merge totals');+assert.equal(display.mergedMRs,2);assert.equal(display.mrMergeTrend,model.mrMergeTrend);eval(code.slice(code.indexOf('function metricsMRMergeTable('),code.indexOf('function metricsSectionHead(')));eval(code.slice(code.indexOf('function formatTimestamp('),code.indexOf('function duration(')));@@ -245,7 +245,7 @@ assert.ok(metricsMRMergeTable([]).includes('当前日期范围暂无已合入 MR}}-func TestMetricsSnapshotAndCachedDataStayWithinSelectedProject(t *testing.T) {+func TestMetricsCachedDataStaysWithinSelectedProject(t *testing.T) {node, err := exec.LookPath("node")if err != nil {t.Skip("node not installed")@@ -254,9 +254,8 @@ func TestMetricsSnapshotAndCachedDataStayWithinSelectedProject(t *testing.T) {const assert = require('node:assert/strict');const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8');const state = {- projectFilter:'lightvela', metricsRange:'30d', metricsData:{deliveries:[]},- metricsDataKey:'skillhub|30d||', metricsLoading:false, metricsError:'',- metricsBenchmark:{projectId:'skillhub',gongfeng:{weeklyMerged:{'2026-W40':425},totals:{merged:425}},loop:{totalRuns:10,firstPassRate:64,issues:10,uniqueIssues:8,completedIssues:5,totalTokens:500}},+ projectFilter:'project-b', metricsRange:'30d', metricsData:{deliveries:[]},+ metricsDataKey:'project-a|30d||', metricsLoading:false, metricsError:'',};function metricsProjectId(){return state.projectFilter}function metricsQueryKey(){return [state.projectFilter,state.metricsRange,'',''].join('|')}@@ -266,19 +265,15 @@ function obsCategoryLabel(value){return value}const body={innerHTML:''},live={innerHTML:''};function $(selector){return selector==='#metricsBody'?body:selector==='#metricsLiveState'?live:null}function metricsDashboardModel(){throw new Error('stale data must not be rendered')}-eval(code.slice(code.indexOf('function metricsSnapshotTrend('),code.indexOf('function metricsMs(')));-const empty={delivered:0,requirementIssues:[],aiIssueIds:new Set(),trend:[],completed:[],firstPass:[],terminal:0,deployment:{samples:0},averagePhaseTotalMs:null,firstPassRate:0,runSuccessRate:0,coverageRate:0,averageTokens:0,reworkRate:0,data:{categories:[]}};-const lightvela=metricsDisplayModel(empty);-assert.equal(lightvela.isSnapshot,false);-assert.equal(lightvela.deliveryCount,0);-assert.equal(lightvela.firstPassRate,null);-assert.equal(lightvela.coverageRate,null);-assert.equal(lightvela.averageTokens,null);-state.projectFilter='skillhub';-const skillhub=metricsDisplayModel(empty);-assert.equal(skillhub.isSnapshot,true);-assert.equal(skillhub.deliveryCount,425);-state.projectFilter='lightvela';+eval(code.slice(code.indexOf('function metricsDisplayModel('),code.indexOf('function metricsMs(')));+const empty={delivered:0,requirementIssues:[],aiIssueIds:new Set(),trend:[],completed:[],firstPass:[],terminal:0,averagePhaseTotalMs:null,firstPassRate:0,runSuccessRate:0,coverageRate:0,averageTokens:0,reworkRate:0,data:{categories:[]}};+const display=metricsDisplayModel(empty);+assert.equal(display.deliveryCount,0);+assert.equal(display.firstPassRate,null);+assert.equal(display.coverageRate,null);+assert.equal(display.averageTokens,null);+assert.equal(display.qualityTitle,'交付质量');+assert.match(display.storyFoot,/当前项目/);eval(code.slice(code.indexOf('function renderMetricsDashboard('),code.indexOf('let metricsRequestSeq=')));renderMetricsDashboard();assert.match(body.innerHTML,/正在切换到当前项目的数据/);@@ -300,27 +295,25 @@ func TestMetricsRefreshIgnoresPreviousProjectResponse(t *testing.T) {script := `const assert = require('node:assert/strict');const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8');-const state={projectFilter:'lightvela',metricsRange:'30d',metricsDateFrom:'',metricsDateTo:'',metricsData:null,metricsIssues:[],metricsBenchmark:null,metricsLoading:false,metricsError:'',metricsDeploymentData:null,metricsDeploymentLoading:false};+const state={projectFilter:'project-a',metricsRange:'30d',metricsDateFrom:'',metricsDateTo:'',metricsData:null,metricsIssues:[],metricsLoading:false,metricsError:''};function currentProject(){return {id:state.projectFilter}}function metricsWindow(){return {from:new Date('2026-09-01T00:00:00Z'),to:new Date('2026-10-01T00:00:00Z'),grain:'day'}}function renderMetricsDashboard(){}function metricsDemoEnabled(){return false}-function canShowSkillhubEfficiency(){return true}-function deploymentRepositories(){return []}const calls=[];let resolveOld;-function api(path){calls.push(path);if(path.startsWith('/api/analytics?')&&path.includes('projectId=lightvela'))return new Promise(resolve=>{resolveOld=resolve});if(path.startsWith('/api/analytics?'))return Promise.resolve({deliveries:[]});if(path.startsWith('/api/issues?'))return Promise.resolve([]);return Promise.resolve({projectId:'skillhub',gongfeng:{weeklyMerged:{'2026-W40':425}}})}+function api(path){calls.push(path);if(path.startsWith('/api/analytics?')&&path.includes('projectId=project-a'))return new Promise(resolve=>{resolveOld=resolve});if(path.startsWith('/api/analytics?'))return Promise.resolve({deliveries:[{issueId:'new-project'}]});if(path.startsWith('/api/issues?'))return Promise.resolve([]);throw new Error('unexpected request '+path)}eval(code.slice(code.indexOf('let metricsRequestSeq='),code.indexOf('function metricHealth(')));async function check(){const old=refreshMetrics();- assert.equal(calls.some(path=>path.startsWith('/api/analytics/skillhub')),false);- state.projectFilter='skillhub';invalidateMetricsForProjectChange();+ state.projectFilter='project-b';invalidateMetricsForProjectChange();resolveOld({deliveries:[{issueId:'old-project'}]});await old;assert.equal(state.metricsData,null);await refreshMetrics();- assert.equal(state.metricsBenchmark.projectId,'skillhub');- state.projectFilter='lightvela';invalidateMetricsForProjectChange();- assert.equal(state.metricsBenchmark,null);+ assert.equal(state.metricsData.deliveries[0].issueId,'new-project');+ assert.equal(state.metricsDataKey,'project-b|30d||');+ assert.deepEqual(calls.map(path=>path.split('?')[0]),['/api/analytics','/api/issues','/api/analytics','/api/issues']);+ state.projectFilter='project-a';invalidateMetricsForProjectChange();assert.equal(state.metricsData,null);}check().catch(error=>{console.error(error);process.exitCode=1});@@ -485,9 +478,9 @@ assert.equal(http[0].timeoutSec, 30);const direct = mcpImportCandidates({id:'nested',name:'Nested',transport:'stdio',stdio:{command:'node',args:['server.js'],environment:{PORT:3000}}});assert.equal(direct[0].command, 'node');assert.deepEqual(direct[0].environment, {PORT:'3000'});-const fragment = '"knot": {\u00a0"url": "[http://mcp.example.com/open/mcp](http://mcp.example.com/open/mcp)", "headers": {"x-api-token": "secret"}}';+const fragment = '"gateway": {\u00a0"url": "[http://mcp.example.com/open/mcp](http://mcp.example.com/open/mcp)", "headers": {"x-api-token": "secret"}}';const pasted = mcpImportCandidates(mcpParseJSONText(fragment));-assert.equal(pasted[0].id, 'knot');+assert.equal(pasted[0].id, 'gateway');assert.equal(pasted[0].transport, 'http');assert.equal(pasted[0].url, 'http://mcp.example.com/open/mcp');assert.deepEqual(pasted[0].headers, {'x-api-token':'secret'});@@ -822,7 +815,7 @@ assert.equal(credentialNextKind({}).key, 'gitToken');// Each kind saves and deletes only its own fields.assert.deepEqual(credentialSavePayload(cred.kind('gitToken'), {secret: ' ghp_1 '}), {gitToken: 'ghp_1'});-assert.deepEqual(credentialSavePayload(cred.kind('codeBuddyApiKey'), {secret: '', extra: 'devcloud'}), {codeBuddyApiKey: '', codeBuddyInternetEnvironment: 'devcloud'});+assert.deepEqual(credentialSavePayload(cred.kind('codeBuddyApiKey'), {secret: '', extra: 'ioa'}), {codeBuddyApiKey: '', codeBuddyInternetEnvironment: 'ioa'});assert.deepEqual(credentialSavePayload(cred.kind('codeBuddyApiKey'), {secret: '', extra: ''}), {codeBuddyApiKey: '', codeBuddyInternetEnvironment: ''});assert.deepEqual(credentialSavePayload(cred.kind('codexApiKey'), {secret: 'sk-1'}), {codexApiKey: 'sk-1'});assert.deepEqual(credentialClearPayload(cred.kind('codexApiKey')), {codexApiKeyClear: true, codexBaseUrl: ''});@@ -991,7 +984,7 @@ const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8')global.escapeHTML = value => String(value);global.state = {currentUser: {id: 7}, projectFilter: 'alpha',- mcpMarket: [{id: '61', aliases: ['gongfeng'], url: 'https://mcpgw.knot.example.com/gongfeng'}],+ mcpMarket: [{id: '61', aliases: ['gongfeng'], url: 'https://mcp-gateway.example.com/gongfeng'}],data: {users: [{id: 7, gitTokenConfigured: true}], mcpServers: []}};global.userById = id => state.data.users.find(u => Number(u.id) === Number(id));@@ -1014,7 +1007,7 @@ state.data.mcpServers = [{scope: 'project', projectId: 'beta', marketId: '61'}];assert.equal(genericRequirementRows(workflow)[2].ok, false);// Without market metadata the name/url fallback still recognises 工蜂.state.mcpMarket = [];-state.data.mcpServers = [{scope: 'project', projectId: 'alpha', name: 'Gongfeng MCP', url: 'https://mcpgw.knot.example.com/gongfeng'}];+state.data.mcpServers = [{scope: 'project', projectId: 'alpha', name: 'Gongfeng MCP', url: 'https://mcp-gateway.example.com/gongfeng'}];assert.equal(genericRequirementRows(workflow)[2].ok, true);assert.ok(code.includes('通用模板为只读'));assert.ok(code.includes('data-adopt-generic'));@@ -1125,10 +1118,10 @@ global.state = {data: {issues: [{id:'iss-afp', projectId:'platform'}],tasks: [{runId:'run-afp', issueId:'iss-afp'}],- repositories: [{id:'repo-skillhub', projectId:'platform'}],+ repositories: [{id:'repo-platform', projectId:'platform'}],runs: [{id:'run-afp', status:'waiting', executionContext:{responsibleUserId:7}},- {id:'run-align', status:'waiting', workflowId:'scheduled-baseline-align', executionContext:{projectId:'platform', responsibleUserId:7}, repository:{name:'SkillHub', repositoryId:'repo-skillhub'}},+ {id:'run-align', status:'waiting', workflowId:'scheduled-baseline-align', executionContext:{projectId:'platform', responsibleUserId:7}, repository:{name:'SkillHub', repositoryId:'repo-platform'}},{id:'run-gslb', status:'waiting', executionContext:{projectId:'gslb', responsibleUserId:7}},{id:'run-other-user', status:'waiting', executionContext:{projectId:'gslb', responsibleUserId:99}},]@@ -1318,7 +1311,7 @@ func TestRequirementDirectCreateUI(t *testing.T) {}}-func TestDeploymentDurationDashboardIsEmbedded(t *testing.T) {+func TestDeploymentDurationDashboardIsNotShipped(t *testing.T) {html, err := os.ReadFile("index.html")if err != nil {t.Fatal(err)@@ -1327,22 +1320,18 @@ func TestDeploymentDurationDashboardIsEmbedded(t *testing.T) {if err != nil {t.Fatal(err)}- css, err := os.ReadFile("deployment-dashboard.css")- if err != nil {- t.Fatal(err)- }- for _, want := range []string{`data-view="deployments" hidden`, `id="deploymentsView"`, `/deployment-dashboard.css?v=20260920r2`, `自动展示 SkillHub 最近 7 天部署耗时`} {- if !strings.Contains(string(html), want) {- t.Fatalf("deployment dashboard markup is missing %q", want)+ for _, unwanted := range []string{`data-view="deployments"`, `id="deploymentsView"`, `/deployment-dashboard.css`, `data-obs-tab="skillhub"`} {+ if strings.Contains(string(html), unwanted) {+ t.Fatalf("index.html still ships removed dashboard markup %q", unwanted)}}- for _, want := range []string{"renderDeploymentDashboard", "/api/deployment-metrics?", "10000001", "deploymentChartSVG", "if(branch)q.set('branch',branch)", "最近 7 天与正在部署"} {- if !strings.Contains(string(app), want) {- t.Fatalf("deployment dashboard behavior is missing %q", want)+ for _, unwanted := range []string{"renderDeploymentDashboard", "/api/deployment-metrics", "refreshSkillhubEfficiency"} {+ if strings.Contains(string(app), unwanted) {+ t.Fatalf("app bundle still ships removed dashboard behavior %q", unwanted)}}- if !strings.Contains(string(css), ".deployment-kpis") || !strings.Contains(string(css), ".deployment-chart") {- t.Fatal("deployment dashboard styles are incomplete")+ if _, err := os.Stat("deployment-dashboard.css"); err == nil {+ t.Fatal("deployment-dashboard.css should not be shipped")}}@@ -1480,7 +1469,7 @@ func TestUsageAnalysisUI(t *testing.T) {t.Fatal(err)}page := string(html)- for _, want := range []string{`data-obs-tab="overview"><svg class="agent-icon harness-icon" data-icon="token" width="14" height="14" aria-hidden="true"></svg>用量`, `data-obs-tab="delivery"><svg class="agent-icon harness-icon" data-icon="flag" width="14" height="14" aria-hidden="true"></svg>交付`, `data-obs-tab="skillhub"`, `id="exportObsReport"`} {+ for _, want := range []string{`data-obs-tab="overview"><svg class="agent-icon harness-icon" data-icon="token" width="14" height="14" aria-hidden="true"></svg>用量`, `data-obs-tab="delivery"><svg class="agent-icon harness-icon" data-icon="flag" width="14" height="14" aria-hidden="true"></svg>交付`, `id="exportObsReport"`} {if !strings.Contains(page, want) {t.Fatalf("usage analysis UI missing %q", want)}@@ -1495,7 +1484,7 @@ func TestUsageAnalysisUI(t *testing.T) {t.Fatal(err)}code := string(js)- for _, want := range []string{"ensureObsUserFilter", "obsRunMatchesUser", "exportObsReport", "buildObsReportHTML", "userDisplay(user)", "assigneeUserId", "各模型用量", "每人每日用量", "成员汇总", "data-obs-scope", "setObsScope", "需求类型分布", "SOP 版本对比", "节点质量明细", "setObsTrendGrain", "obsTrendChart", "该责任人在各项目", "data-obs-grain", "grain=", "全部", "obsApiGrain", "obsRangeCaption", "obsPeriodPicker", "setObsPeriod", "obsScopedView", "data-obs-period", "不含暂停/恢复", "Loop 指标", "workflow_task_id", "averageTokensPerRun", "toolSuccessRate", "runTraces", "obs-traces", "isSkillHubProject", "canShowSkillhubEfficiency", "isPreviewHost", "showDirectRunButton", "obsSkillhub", "obsSkillhubInsights", "obsSkillhubChart", "obsSkillhubCharts", "weeklyLegacy", "sh-chart-hero", "obsSkillhubDeployCard", "obsSkillhubDeployCharts", "dailySample", "countedPipelines", "前端测试环境", "AI 分析", "weeklyMerged", `nav[data-view="deployments"]`, "/api/analytics/skillhub", "/api/deployment-metrics"} {+ for _, want := range []string{"ensureObsUserFilter", "obsRunMatchesUser", "exportObsReport", "buildObsReportHTML", "userDisplay(user)", "assigneeUserId", "各模型用量", "每人每日用量", "成员汇总", "data-obs-scope", "setObsScope", "需求类型分布", "SOP 版本对比", "节点质量明细", "setObsTrendGrain", "obsTrendChart", "该责任人在各项目", "data-obs-grain", "grain=", "全部", "obsApiGrain", "obsRangeCaption", "obsPeriodPicker", "setObsPeriod", "obsScopedView", "data-obs-period", "不含暂停/恢复", "Loop 指标", "workflow_task_id", "averageTokensPerRun", "toolSuccessRate", "runTraces", "obs-traces", "isPreviewHost", "showDirectRunButton"} {if !strings.Contains(code, want) {t.Fatalf("app.js is missing %q", want)}@@ -1656,13 +1645,13 @@ func TestIssueTitleFuzzySearch(t *testing.T) {const assert = require('node:assert/strict');const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8');eval(code.slice(code.indexOf('function normalizeIssueTitleSearch('), code.indexOf('function filteredIssues(')));-const issue = {number: 42, title: '全量 PHPUnit-回归', description: '覆盖 DNSPod 主流程', externalRef: {externalId: 'TAPD-100'}};+const issue = {number: 42, title: '全量 PHPUnit-回归', description: '覆盖 DemoDNS 主流程', externalRef: {externalId: 'TAPD-100'}};const project = {key: 'DP'};assert.equal(issueMatchesQuery(issue, project, 'php unit'), true);assert.equal(issueMatchesQuery(issue, project, '回归 php'), true);assert.equal(issueMatchesQuery(issue, project, 'PHPUNIT回归'), true);assert.equal(issueMatchesQuery(issue, project, 'DP-42'), true);-assert.equal(issueMatchesQuery(issue, project, 'DNSPod'), true);+assert.equal(issueMatchesQuery(issue, project, 'DemoDNS'), true);assert.equal(issueMatchesQuery(issue, project, '不存在的标题'), false);`if out, err := exec.Command(node, "-e", script).CombinedOutput(); err != nil {@@ -1750,7 +1739,7 @@ assert.equal(rootGit.length, 1);assert.equal(rootGit[0].name, 'workspace');assert.equal(sourceControlRootPath('workspace'), '/');assert.equal(sourceControlRootPath('.'), '/');-assert.equal(sourceControlRootPath('dnspod-web'), '/dnspod-web');+assert.equal(sourceControlRootPath('demodns-web'), '/demodns-web');eval(extension.slice(extension.indexOf('function changesForRepo('), extension.indexOf('function changesSignature(')));assert.equal(changesForRepo([{path:'e2e-cases.md'}, {path:'a/main.go', repository:'a'}], 'workspace').length, 1);assert.equal(changesForRepo([{path:'e2e-cases.md'}, {path:'a/main.go', repository:'a'}], 'a').length, 1);@@ -2409,7 +2398,7 @@ func TestResearchEfficiencyDashboardUI(t *testing.T) {t.Fatal(err)}code := string(js)- for _, want := range []string{"renderMetricsDashboard", "refreshMetrics", "metricsDisplayModel", "metricsTrendSVG", "metricsPhaseTrendSVG", "metricsRequirementTable", "metricsDonut", "metricsDemoEnabled", "metricsDemoSnapshot", "演示数据", "/api/analytics/skillhub", "当前项目暂无完整需求闭环", "交付数(含 Issue)", "平均已采集耗时", "已采集耗时", "每条需求 / Issue 耗时明细", "平均澄清耗时", "平均研发耗时", "平均测试耗时", "测试环境部署耗时", "AI 工作项覆盖率", "Run 成功率"} {+ for _, want := range []string{"renderMetricsDashboard", "refreshMetrics", "metricsDisplayModel", "metricsTrendSVG", "metricsPhaseTrendSVG", "metricsRequirementTable", "metricsDonut", "metricsDemoEnabled", "metricsDemoSnapshot", "演示数据", "交付数(含 Issue)", "平均已采集耗时", "已采集耗时", "每条需求 / Issue 耗时明细", "平均澄清耗时", "平均研发耗时", "平均测试耗时", "AI 工作项覆盖率", "Run 成功率"} {if !strings.Contains(code, want) {t.Fatalf("研发效能看板脚本缺少 %q", want)}@@ -2577,7 +2566,7 @@ func TestRunElapsedShowsExecutionTimeNotWallClock(t *testing.T) {script := `const assert = require('node:assert/strict');const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8');-eval(code.slice(code.indexOf('function duration('), code.indexOf('function isSkillHubDeploymentRepository(')));+eval(code.slice(code.indexOf('function duration('), code.indexOf('function metricsDemoEnabled(')));eval(code.slice(code.indexOf('function runFinishedAt('), code.indexOf('function relativeTime(')));const hour = 3600000, created = new Date(Date.now() - 45 * hour).toISOString();const settled = {status:'succeeded', createdAt:created, timing:{executionMs:5*hour, wallMs:45*hour, waitingMs:40*hour, asOf:new Date(Date.now()-hour).toISOString()}};diff --git a/webtest/tests/app-shell.test.mjs b/webtest/tests/app-shell.test.mjsindex 42bf22fb..890c0180 100644--- a/webtest/tests/app-shell.test.mjs+++ b/webtest/tests/app-shell.test.mjs@@ -14,7 +14,7 @@ test('list paging, catalog visibility, URL safety, and workflow helpers return cstate.mcpMarket=[{id:'market-gh',name:'GitHub',aliases:['github'],description:'Git'},{id:'market-gf',name:'工蜂',aliases:['gongfeng'],description:'Git'},- {id:'market-wiki',name:'Wiki',aliases:['iwiki']}+ {id:'market-wiki',name:'Wiki',aliases:['wiki-docs']}];state.data.workflows.push({id:'generic-1',name:'Generic',generic:true,nodes:[]},{id:'shared-1',name:'Shared',projectId:'other',shared:true,nodes:[]});const mcp=genericTemplateMCPOptions(['gongfeng','custom']);diff --git a/webtest/tests/dashboards.test.mjs b/webtest/tests/dashboards.test.mjsindex a624ae47..c83d1101 100644--- a/webtest/tests/dashboards.test.mjs+++ b/webtest/tests/dashboards.test.mjs@@ -2,41 +2,20 @@ import test from 'node:test';import assert from 'node:assert/strict';import { loadApp, settle } from '../lib/load-app.mjs';-test('deployment dashboard renders SkillHub KPIs, trend, statuses, filtering, and API query', async (t) => {+test('metrics dashboard ships without a deployment view or external pipeline requests', async (t) => {const app = await loadApp();t.after(app.close);- app.evaluate(`- const repo=state.data.repositories[0];- repo.name='skillhub';repo.gongfengProjectId='example/team-project';- state.deploymentData={- queriedAt:'2026-10-30T12:00:00Z',pipelineUrl:'https://qci.example/pipeline',- summary:{total:3,succeeded:1,failed:1,running:1,deployments7d:2,average7dDurationMs:90000,averageDurationMs:120000,p50DurationMs:100000,p90DurationMs:180000,successRate:50},- records:[- {id:'101',runNumber:101,status:2,statusLabel:'成功',durationMs:90000,branch:'main',startedAt:'2026-10-30T08:00:00Z',starter:'alice',revision:'abcdef123456',comment:'release',url:'https://qci.example/101'},- {id:'102',runNumber:102,status:3,statusLabel:'失败',durationMs:180000,branch:'feature',startedAt:'2026-10-29T08:00:00Z',starter:'bob',revision:'fedcba654321',comment:'test'},- {id:'103',runNumber:103,status:1,statusLabel:'运行中',durationMs:0,branch:'main',startedAt:'2026-10-31T02:00:00Z',starter:'ci',revision:'123456789012',comment:'deploy'}- ]- };- renderDeploymentDashboard();- `);- const body = app.document.querySelector('#deploymentBody');- assert.match(body.textContent, /近 7 天平均耗时|1\.5m|正在部署|近 30 天成功率|50\.0%/);- assert.match(body.textContent, /#101|#102|#103|release|运行中/);- assert.ok(body.querySelector('svg[aria-label="部署耗时趋势"]'));- assert.equal(app.evaluate(`deploymentStatusClass(2)`), 'succeeded');- assert.equal(app.evaluate(`deploymentStatusClass(8)`), 'running');- assert.equal(app.evaluate(`deploymentStatusClass(13)`), 'failed');- assert.equal(app.evaluate(`duration(3600000)`), '1.0h');-- app.router.get(/^\/api\/deployment-metrics\?/, call => ({ queriedAt: '2026-10-31T03:00:00Z', branch: new URL(call.url).searchParams.get('branch'), summary: {}, records: [] }));- const form = body.querySelector('#deploymentQuery');- form.elements.branch.value = 'release/v2';- form.elements.branch.dispatchEvent(new app.window.Event('input', { bubbles: true }));- form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));- await settle(5);- const call = app.router.calls.find(c => c.path === '/api/deployment-metrics');- assert.match(call.search, /projectId=project-1|repositoryId=repo-1|branch=release%2Fv2/);- assert.match(body.textContent, /分支「release\/v2」最近 30 天没有流水线记录/);+ assert.equal(app.document.querySelector('#deploymentsView'), null);+ assert.equal(app.document.querySelector('[data-view="deployments"]'), null);+ assert.equal(app.evaluate(`typeof renderDeploymentDashboard`), 'undefined');+ app.router.get(/^\/api\/analytics\?/, { summary: {}, deliveries: [], trend: [] });+ app.router.get(/^\/api\/issues\?/, []);+ await app.evaluate(`refreshMetrics(true)`);+ await settle(3);+ assert.deepEqual(app.router.calls.filter(c => c.path.startsWith('/api/analytics') || c.path.startsWith('/api/deployment')).map(c => c.path), ['/api/analytics']);+ const text = app.document.querySelector('#metricsBody').textContent;+ assert.match(text, /交付数(含 Issue)/);+ assert.doesNotMatch(text, /SkillHub|部署耗时|快照/);});test('metrics helpers calculate windows, phases, source identity, buckets, and SVG summaries', async (t) => {diff --git a/webtest/tests/obs-charts.test.mjs b/webtest/tests/obs-charts.test.mjsindex 9e7e9ad5..d025cf07 100644--- a/webtest/tests/obs-charts.test.mjs+++ b/webtest/tests/obs-charts.test.mjs@@ -18,8 +18,6 @@ test('observability chart options expose meaningful series, labels, tooltips, anconst heat=obsHeatOption([{weekday:1,hour:9,runs:2,tokens:90},{weekday:1,hour:9,runs:1,tokens:10},{weekday:9,hour:30,runs:8}], 'runs', opts);const funnel=obsFunnelOption([{name:'需求',value:10},{name:'运行',value:8},{name:'交付',value:3}],{...opts,active:2});const owners=obsOwnersOption([{name:'Alice',delivered:3,active:2,undelivered:1,durationLabel:'2h',tokens:400}],opts);- const stack=obsStackBarOption(['9月','10月'],[{name:'老库',color:theme.c4,values:[1,2]},{name:'大仓',color:theme.c1,values:[3,5]}],opts,{showTotal:true,markFrom:1});- const skill={gongfeng:{mergedMonths:{'2026-09':4,'2026-10':7},monthlyLegacy:{'2026-09':1},monthlyMonorepo:{'2026-09':3,'2026-10':7},weeklyMerged:{'2026-W39':2},weeklyLegacy:{'2026-W39':1},weeklyMonorepo:{'2026-W39':1}},dailySample:{labels:['10/1'],backend:[2],frontend:[1],e2e:[3]}};return {trendSeries:trend.map(x=>x.series.length),trendTip:trend[0].tooltip.formatter([{dataIndex:1}]),@@ -33,10 +31,6 @@ test('observability chart options expose meaningful series, labels, tooltips, anfunnel:obsFunnelStats([{name:'需求',value:10},{name:'运行',value:8},{name:'交付',value:3}]),funnelLabel:funnel.series[0].label.formatter({dataIndex:2}),ownerTip:owners.tooltip.formatter([{dataIndex:0}]),- stackTotal:stack.series[1].label.formatter({dataIndex:1}),- monthly:obsSkillhubMonthlyOption(skill,opts).series.length,- weekly:obsSkillhubWeeklyOption(skill,opts).series.length,- deploy:obsSkillhubDeployOption(skill,opts).series.length,escaped:obsEsc('<x>'),theme:obsEChartsTheme('light').mode};@@ -55,10 +49,6 @@ test('observability chart options expose meaningful series, labels, tooltips, anassert.equal(result.funnel.worst, 2);assert.match(result.funnelLabel, /最大流失/);assert.match(result.ownerTip, /Alice|400 tok/);- assert.equal(result.stackTotal, 7);- assert.equal(result.monthly, 2);- assert.equal(result.weekly, 2);- assert.equal(result.deploy, 3);assert.equal(result.escaped, '<x>');assert.equal(result.theme, 'light');});diff --git a/webtest/tests/observability-views.test.mjs b/webtest/tests/observability-views.test.mjsindex a02d58d0..c6894f74 100644--- a/webtest/tests/observability-views.test.mjs+++ b/webtest/tests/observability-views.test.mjs@@ -2,55 +2,21 @@ import test from 'node:test';import assert from 'node:assert/strict';import { chooseOption, loadApp, settle } from '../lib/load-app.mjs';-const skillhub = {- snapshotAt: '2026-10-30T08:00:00Z',- gongfeng: {- mergedMonths: { '2026-09': 4, '2026-10': 9 },- monthlyLegacy: { '2026-09': 3, '2026-10': 2 },- monthlyMonorepo: { '2026-09': 1, '2026-10': 7 },- weeklyMerged: { '2026-W40': 2, '2026-W41': 3, '2026-W42': 4 },- weeklyLegacy: { '2026-W40': 1 }, weeklyMonorepo: { '2026-W40': 1, '2026-W41': 3, '2026-W42': 4 },- repos: [{ name: 'skillhub', path: 'ai/skillhub', created: 10, merged: 8, opened: 2, lastAt: '2026-10-29', url: 'https://git.example/skillhub' }],- authors: [{ username: 'alice', mrs: 8 }],- },- qci: {- projectId: 10001, countedPipelines: 3,- backend: { runNum: 10, recent30d: 5 }, frontend: { runNum: 8, recent30d: 4 },- e2e: { runNum: 6, url: 'https://qci.example/e2e' },- deploy: { url: 'https://qci.example/deploy' },- pipelines: [{ id: 10000002, name: 'Web', kind: '前端', era: '当前', runNum: 8, recent30d: 4, url: 'https://qci.example/web' }],- dailySample: { labels: ['10/28', '10/29'], backend: [2, 3], frontend: [1, 2], e2e: [1, 1] },- },- localWorkflows: { backendUnique: 3, backendStageHits: { '01-requirement': 3, '02-design': 2, '03-code': 3, '04-e2e': 1 }, frontendWorkflows: 2, backendKnowledgeDocs: 4, backendE2eFiles: 1 },- loop: { issues: 5, doneIssues: 4, totalRuns: 7 },- evidence: [{ label: '验收证据', url: 'https://example.com/evidence' }],- insights: [{ title: '吞吐提升', body: '近四周保持增长。' }],-};--test('SkillHub observability renders KPI, charts, deployment evidence, and detail tables', async (t) => {+test('observability tabs only expose usage and delivery views', async (t) => {const app = await loadApp();t.after(app.close);app.evaluate(`- state.skillhubEfficiency=${JSON.stringify(skillhub)};- state.skillhubDeployError='实时部署接口暂不可达';state.obsTab='skillhub';obsEChartsFailed=true;- renderObservability();+ renderAll();`);await settle(3);- const text = app.document.querySelector('#obsBody').textContent;assert.equal(app.evaluate(`state.obsTab`), 'overview');- assert.equal(app.document.querySelector('#obsSkillhubTab')?.hidden ?? true, true);- assert.doesNotMatch(text, /测试环境部署|后端测试环境/);- assert.match(app.evaluate(`obsSkillhubDeployCard()`), /后端测试环境|实时接口:实时部署接口暂不可达/);- const groups = app.evaluate(`obsSkillhubDetailGroups().map(g=>({group:g.group,items:g.items.filter(Boolean).map(i=>i.title)}))`);- assert.equal(groups.length, 4);- assert.match(JSON.stringify(groups), /仓库|流水线|Loop 运行|数据来源|结论/);- const legacy = app.evaluate(`obsSkillhubCharts(state.skillhubEfficiency)`);- assert.match(legacy, /每月已合入|近 12 周|sh-bars/);- assert.match(app.evaluate(`obsSkillhubDeployCharts(state.skillhubEfficiency.qci)`), /每天部署次数|后端|E2E/);- assert.match(app.evaluate(`obsSkillhubInsights(state.skillhubEfficiency.insights)`), /吞吐提升|近四周保持增长/);- assert.match(app.evaluate(`obsSkillhubLoopCard(state.skillhubEfficiency.loop)`), /平台需求|已闭环|SOP 运行/);+ assert.equal(app.evaluate(`obsNormalizeTab('delivery')`), 'delivery');+ assert.equal(app.evaluate(`obsNormalizeTab('anything-else')`), 'overview');+ assert.deepEqual([...app.document.querySelectorAll('[data-obs-tab]')].map(b => b.dataset.obsTab), ['overview', 'delivery']);+ assert.equal(app.evaluate(`obsDetailScope()`), 'overview');+ assert.equal(app.evaluate(`typeof refreshSkillhubEfficiency`), 'undefined');});test('observability period, scope, query, user, and filtering helpers preserve their business semantics', async (t) => {@@ -100,9 +66,7 @@ test('period-scoped analytics and external source dialog expose trace metrics ant.after(app.close);app.router.get('/api/insights/v1/sources?projectId=project-1', [{ id: 'src-1', name: 'Review CI', tokenPrefix: 'af_x', expiresAt: '2027-01-01T00:00:00Z' }]);app.router.post('/api/insights/v1/sources', call => ({ ...call.body, id: 'src-2', token: 'secret-token' }));- app.router.get(/^\/api\/analytics\?/, call => call.search.includes('skillhub') ? skillhub : { summary: {}, trend: [], runTraces: [] });- app.router.get('/api/analytics/skillhub', skillhub);- app.router.get(/^\/api\/deployment-metrics\?/, { records: [], summary: {} });+ app.router.get(/^\/api\/analytics\?/, { summary: {}, trend: [], runTraces: [] });app.evaluate(`state.currentUser={id:1,isGuest:false,isPlatformAdmin:true};state.data.users=[{id:1,loginName:'alice'}];@@ -132,7 +96,7 @@ test('period-scoped analytics and external source dialog expose trace metrics anassert.equal(app.evaluate(`obsCacheStats(obsScopedView()).rate`), 100 / 3);assert.equal(app.evaluate(`obsRunMatchesUser({executionContext:{responsibleUserId:1}},1)`), true);app.evaluate(`- state.data.repositories[0].name='skillhub';+ state.data.repositories[0].name='team-service';state.data.repositories[0].gongfengProjectId='example/team-project';state.obsScope='user';state.obsUserFilter='1';state.obsOriginFilter='internal';state.obsSourceFilter='tapd';setObsScope('project');@@ -141,9 +105,7 @@ test('period-scoped analytics and external source dialog expose trace metrics anawait settle(5);assert.equal(app.evaluate(`state.obsScope`), 'project');assert.equal(app.evaluate(`state.obsOriginFilter`), '');- await app.evaluate(`refreshSkillhubEfficiency()`);- assert.equal(app.evaluate(`state.skillhubEfficiency`), null);- assert.ok(!app.router.calls.some(c => c.path === '/api/analytics/skillhub'));+ assert.ok(!app.router.calls.some(c => c.path.startsWith('/api/analytics/') || c.path.startsWith('/api/deployment')));await app.evaluate(`openObsSources()`);await settle(3);diff --git a/webtest/tests/runs-detail.test.mjs b/webtest/tests/runs-detail.test.mjsindex a42b1d41..ccc699cf 100644--- a/webtest/tests/runs-detail.test.mjs+++ b/webtest/tests/runs-detail.test.mjs@@ -132,3 +132,38 @@ test('conversation workspaces are listed by requirement or goal, never as 自由const found = app.evaluate(`state.runQuery='对话改代码';renderRuns();document.querySelectorAll('#runList .run-card').length`);assert.equal(found, 3);});++test('run detail topology shows each stage time window beside its stage label', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ const workflow = app.evaluate('structuredClone(state.data.workflows[0])');+ const nodes = Object.fromEntries((workflow.nodes || []).map((node, i) => [node.id, {+ status: 'succeeded', attempt: 1,+ startedAt: `2026-10-21T10:0${i}:00Z`, finishedAt: `2026-10-21T10:0${i + 3}:00Z`,+ }]));+ const run = {+ ...app.evaluate('structuredClone(state.data.runs[0])'), status: 'succeeded',+ finishedAt: '2026-10-21T10:09:00Z', workflowSnapshot: workflow, nodes,+ };+ app.router.get('/api/runs/run-1', run);+ app.evaluate(`state.data.runs=[${JSON.stringify(run)}];state.selectedRun='run-1';state.activeRun=state.data.runs[0]`);+ app.evaluate(`switchView('runs');showRunDetail('run-1')`);+ await settle(6);++ const labels = [...app.document.querySelectorAll('#runsView .graph-stage-label')];+ const stageIds = app.evaluate(`workflowStages(${JSON.stringify(workflow)}).map(stage=>stage.map(node=>node.id))`);+ assert.equal(labels.length, stageIds.length, 'every stage should keep its label');+ stageIds.forEach((ids, index) => {+ const label = labels[index];+ assert.match(label.querySelector('.graph-stage-name').textContent, /^\u9636\u6bb5 \d/);+ const starts = ids.map((id) => new Date(nodes[id].startedAt).getTime());+ const ends = ids.map((id) => new Date(nodes[id].finishedAt).getTime());+ const expected = `${new Date(Math.min(...starts)).toLocaleTimeString()} \u2192 ${new Date(Math.max(...ends)).toLocaleTimeString()}`;+ assert.equal(label.querySelector('.graph-stage-time').textContent, expected,+ 'stage label should show the stage start and finish time');+ });++ const runtime = app.document.querySelector('#runsView .node-inspector .runtime-details');+ assert.ok(runtime, 'node inspector should keep the runtime details row');+ assert.doesNotMatch(runtime.textContent, /\u2192/, 'time window is no longer repeated under the node output');+});