feat(assessments): add live workbench and scoped intent controls
This commit is contained in:
parent
dcdf05f75a
commit
ffc15f4402
|
|
@ -1,9 +1,9 @@
|
|||
name: Deep assessments
|
||||
on:
|
||||
push:
|
||||
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/assessment-exploration-views.js', 'web/static/js/assessment-node-panel.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml']
|
||||
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/assessment-exploration-views.js', 'web/static/js/assessment-node-panel.js', 'web/static/js/assessment-workbench.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml']
|
||||
pull_request:
|
||||
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/assessment-exploration-views.js', 'web/static/js/assessment-node-panel.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml']
|
||||
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/assessment-exploration-views.js', 'web/static/js/assessment-node-panel.js', 'web/static/js/assessment-workbench.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
# Changelog
|
||||
|
||||
## 2026-11-15 · 深度测评工作台与完整链路
|
||||
|
||||
- 探索图增加主链路/执行记录两种视图,跨页引用和原始上下游分页导航;归档按真实分支分组,重新引用后重新计冷却轮次,漏洞与人工线索保持可见,旧归档链接继续可读。
|
||||
- 详情默认展示运行概览:规划/验收阶段、活跃意图、工具活动、Pi 原生会话状态、队列数量、最近进展和下次唤醒;无变化时不重建正文,保留定向补充草稿和阅读位置。
|
||||
- 增加单条意图暂停、继续、优先级和定向补充。独立取消执行上下文,补充持久化后通过 Pi 原生 steer 只发送到目标会话;手动暂停不会被整任务继续或规划器绕过。
|
||||
- 测评报告补齐当前账号可读的关联漏洞、全部独立复核记录、已保存回执摘录和来源链接;原有批量任务行为保持不变。
|
||||
|
||||
## 2026-11-15 · 深度测评开始与整任务暂停
|
||||
|
||||
- 开始/继续统一续接原 Pi 会话;暂停同时取消本测评的规划与执行步骤、清除自动重试安排,阻止晚到重试及后台恢复队列覆盖手动暂停。
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@
|
|||
|
||||
工作区提供返回列表入口,保留列表筛选、分页和已有深链。资产图和探索图使用更大的画布,节点详情可收起;自动刷新、切换视图和画布尺寸变化会保留缩放与位置。「适应画布」查看全图,「整理布局」重新排列节点。长中文标签自动换行,完整内容在节点详情中查看。
|
||||
|
||||
点击详情默认进入运行概览。概览展示规划/独立验收阶段、当前意图、工具运行及已有输出、Pi 原生模型/工具/压缩状态、队列计数、最近进展和下次唤醒。数据来自现有执行回执、Pi 事件及任务账本;刷新不会额外调用模型或启动任务。无变化时不重建正文,定向补充的草稿、焦点和阅读位置保留。
|
||||
|
||||
节点详情默认使用较宽的阅读栏,可拖动图与详情之间的分隔线调整宽度;键盘聚焦分隔线后,左右方向键调整,Home 或双击恢复默认宽度。「展开阅读」将当前节点铺满工作区,点击「返回图」恢复分栏。摘要、执行说明、原始回执和来源分别展示;正文独立滚动,自动刷新保留阅读位置和已展开的来源,切换节点从顶部开始。窄屏改为上下布局,也可展开阅读。
|
||||
|
||||
较大图显示缩略导航,可点击定位,也可聚焦后用方向键平移。节点类型和状态、关系颜色帮助区分链路;选中节点显示其相连关系的文字,位于画布外或缩得过小时自动定位到可读尺度。循环引用的回边保留,只在计算层级时避开,避免整组挤成单列。多个目标资产链接在正文中折叠展示,不占据固定底部操作区。全图仍按节点分页,大图概览不能保证每个节点的文字同时清晰,可选中节点或展开关联分支阅读。
|
||||
|
|
@ -46,6 +48,10 @@
|
|||
|
||||
借鉴 ARTEX 的冷热分层:活跃方向及其依赖、证据祖先保持可见。已经完成或撤下、连续多轮不参与活跃链路的历史步骤,按引用折叠为归档节点。新方向再次依赖旧步骤或旧证据时,相关链路会重新显示。折叠不删除原步骤、原始观察或工具结果,不改变完成条件。
|
||||
|
||||
归档按真实依赖/证据分支分组,并持久化连续冷却的起始轮次;重新被引用后重新计时。已登记漏洞、目标和人工线索不会因来源步骤归档而隐藏,归档的对外关系标明「经归档」。旧版按 ID 批次建立的归档改标「已替代」,原 ID 和成员仍可展开,不删除历史记录。
|
||||
|
||||
默认「主链路」收起观察和工具回执,关系标明「经执行记录」;切换「执行记录」或展开分支可查看原文。分页保留跨页引用节点,当前页最多展示 80 个引用;更多关联会明确计数,节点详情提供独立分页的完整上下游列表。跨页引用与归档投影都是视图,原始节点和边保持不变;显示与导航均遵守漏洞读取权限。
|
||||
|
||||
会话摘要由 **Pi 原生压缩**生成并沉淀为图中的记忆节点。业务图的冷分支归档保存成员索引及已有结果摘录,不另起一套模型压缩循环。摘要是模型派生的续接材料,证据仍应回查执行回执。
|
||||
|
||||
界面支持平移、缩放、适应画布、节点选择、原文分页及归档展开。大图分页面显示,分页大小仅影响本次展示,不限制总节点数;步骤清单也可分页查看。
|
||||
|
|
@ -110,6 +116,12 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills
|
|||
|
||||
运行中补充方向先入库,再通过 Pi 原生 `steer()` 投递给活跃执行步骤,恢复后也可回查。协作者需以自己的执行身份继续任务。
|
||||
|
||||
意图队列支持单条暂停/继续、优先级调整和定向补充。暂停一条意图只取消其执行上下文,其他意图和规划器继续工作;用户暂停标记持久保存,整任务继续和重启不会自动解除,规划器也不能退休该意图来绕过暂停。继续只恢复这一条的排队状态;整任务若已暂停,仍需手动开始整任务。优先级调整不抢占正在执行的步骤。
|
||||
|
||||
「给此意图补充方向」先保存到该意图及探索图,再通过对应 Pi 会话的原生 `steer()` 投递;暂停、排队或尚未绑定会话时保存供续跑使用。定向补充不广播给其他 worker。活跃及自动恢复中的测评只允许当前执行账号定向继续或发送执行指令,协作者可先暂停并以自己的账号继续。
|
||||
|
||||
下载的 Markdown 报告包含目标、步骤、事实、人工补充,以及当前账号有权读取的关联漏洞、复现内容和完整复核历史。每条复核绑定其原始回执摘录和可返回测评的链接;摘录不替代完整执行会话。运行中导出属于阶段报告,已登记与已独立确认分别标识。
|
||||
|
||||
## 恢复语义
|
||||
|
||||
点击「开始 / 继续」后自动规划并执行本测评的待办步骤;点击「暂停」后停止新派发,取消规划器与全部在执行的步骤,等待所管执行资源收尾后显示「已暂停」。自动重试、等待新进展和待恢复状态也可暂停;手动暂停后不会被后台恢复队列或服务重启重新启动。打开页面、查看详情和刷新均不会启动任务。
|
||||
|
|
@ -134,13 +146,13 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills
|
|||
| `GET /api/deep-assessments/options` | 可用项目、角色与模型渠道 |
|
||||
| `GET / POST /api/deep-assessments` | 查询列表(`archived=true` 查看归档)/ 创建草稿 |
|
||||
| `GET / DELETE /api/deep-assessments/:id` | 详情 / 删除非活动测评 |
|
||||
| `GET /api/deep-assessments/:id?step_limit=50&step_offset=0` | 最近步骤的分页详情 |
|
||||
| `POST /api/deep-assessments/:id/control/:action` | start、pause、cancel、guidance、answer、retry、archive、restore |
|
||||
| `GET /api/deep-assessments/:id?step_limit=50&step_offset=0&runtime=true` | 分页详情与运行概览;`step_order=queue&step_status=needs_review` 定位待核对步骤 |
|
||||
| `POST /api/deep-assessments/:id/control/:action` | start、pause、cancel、guidance、answer、retry、archive、restore,以及 intent-pause、intent-resume、intent-priority、intent-guidance |
|
||||
| `GET / POST /api/deep-assessments/:id/assets` | 查看共享/关联资产图,或关联资产;`asset_id` 查询服务端点 |
|
||||
| `GET /api/deep-assessments/:id/intents?status=&offset=0` | 优先级队列和状态计数 |
|
||||
| `GET /api/deep-assessments/:id/facts?confidence=&offset=0` | 分页读取观察/推断事实 |
|
||||
| `GET /api/deep-assessments/:id/graph?scope=&limit=80&offset=0` | 折叠图或展开指定节点 |
|
||||
| `GET /api/deep-assessments/:id/graph/node?node_id=…&offset=0` | 节点原文 |
|
||||
| `GET /api/deep-assessments/:id/graph?scope=&view=summary&limit=80&offset=0` | 主链路或 `view=full` 执行记录;包含分页边界计数及引用 |
|
||||
| `GET /api/deep-assessments/:id/graph/node?node_id=…&offset=0&links_offset=0` | 原文及独立分页的上下游关系 |
|
||||
| `GET /api/deep-assessments/:id/vulnerabilities?limit=20&offset=0` | 当前账号可读的关联漏洞 |
|
||||
| `GET /api/deep-assessments/:id/vulnerabilities/:vulnerabilityId` | 属于该测评的漏洞详情和来源步骤 |
|
||||
| `GET /api/deep-assessments/:id/steps/:stepId` | 单个步骤,用于跨分页定位 |
|
||||
|
|
@ -150,6 +162,8 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills
|
|||
|
||||
控制请求携带 `revision`;结果不明的步骤重试另需 `reconciled:true`,资源清理未确认另需 `cleanup_confirmed:true`。
|
||||
|
||||
单条意图操作另传 `step_id`;调整优先级传 `priority`(1–1000),定向补充传 `message`。响应的 `guidance_delivered` 表示是否已投递到当前 Pi 会话;未投递时已保存,后续继续生效。
|
||||
|
||||
## 验证边界
|
||||
|
||||
隔离回归验证旧预算不生效、超过原步骤/分段上限仍能继续、冷分支折叠与活跃链路恢复、原始 Pi 摘要回查、图来源隔离、重启恢复和真实 Pi SDK 模拟模型闭环。浏览器回归检查无预算表单、图渲染、节点读取、抽屉交互、桌面与手机布局,原批量任务回归仍保留。
|
||||
|
|
|
|||
|
|
@ -909,6 +909,11 @@ CREATE TABLE IF NOT EXISTS deep_assessments (
|
|||
name TEXT NOT NULL, status TEXT NOT NULL, payload TEXT NOT NULL, updated_at DATETIME NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_deep_assessments_status ON deep_assessments(status,updated_at);
|
||||
CREATE TABLE IF NOT EXISTS deep_assessment_cold (
|
||||
task_id TEXT NOT NULL REFERENCES deep_assessments(id) ON DELETE CASCADE,
|
||||
node_id TEXT NOT NULL, since_round INTEGER NOT NULL,
|
||||
PRIMARY KEY(task_id,node_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS deep_assessment_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, task_id TEXT NOT NULL REFERENCES deep_assessments(id) ON DELETE CASCADE,
|
||||
step_id TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL, message TEXT NOT NULL, created_at DATETIME NOT NULL
|
||||
|
|
|
|||
|
|
@ -0,0 +1,104 @@
|
|||
package deepassessment
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type LivePhase struct {
|
||||
Active bool `json:"active"`
|
||||
Planning bool `json:"planning"`
|
||||
Reviewing bool `json:"reviewing"`
|
||||
Workers int `json:"workers"`
|
||||
}
|
||||
|
||||
func (e *Engine) setPhase(task, phase string, value bool) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
p := e.phases[task]
|
||||
if phase == "planning" {
|
||||
p.Planning = value
|
||||
} else {
|
||||
p.Reviewing = value
|
||||
}
|
||||
e.phases[task] = p
|
||||
}
|
||||
func (e *Engine) Live(task string) LivePhase {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
p := e.phases[task]
|
||||
_, p.Active = e.active[task]
|
||||
p.Workers = len(e.workers[task])
|
||||
return p
|
||||
}
|
||||
|
||||
// User control is persisted before cancellation. A step pause neither cancels
|
||||
// another worker nor changes the task's manual pause latch.
|
||||
func (e *Engine) ControlStep(task, step, action, message string, priority int, revision int64) error {
|
||||
return e.ControlStepAs(task, step, action, message, priority, revision, "")
|
||||
}
|
||||
func (e *Engine) ControlStepAs(task, step, action, message string, priority int, revision int64, actor string) error {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
cancel := e.workers[task][step]
|
||||
kind := "intent_" + action
|
||||
err := e.Store.Change(task, step, kind, message, func(t *Task) error {
|
||||
if t.Archived || t.Status == "completed" || t.Status == "cancelled" || Active(t.Status) && t.Status != "running" {
|
||||
return ErrConflict
|
||||
}
|
||||
automatic := Active(t.Status) || t.Status == "recovering" || t.Status == "waiting_retry" || t.Status == "waiting_progress"
|
||||
if actor != "" && (action == "resume" || action == "guidance") && automatic && t.ExecutorID != actor {
|
||||
return fmt.Errorf("请先暂停测评,再以当前账号继续后操作意图")
|
||||
}
|
||||
if revision > t.Revision || (action != "pause" && action != "guidance" && revision != t.Revision) {
|
||||
return ErrConflict
|
||||
}
|
||||
st := t.Step(step)
|
||||
if st == nil {
|
||||
return fmt.Errorf("unknown intent")
|
||||
}
|
||||
if st.Status == "completed" || st.Status == "retired" {
|
||||
return fmt.Errorf("intent has already finished")
|
||||
}
|
||||
switch action {
|
||||
case "pause":
|
||||
if st.Status == "uncertain" || st.Status == "cleanup_unconfirmed" {
|
||||
return fmt.Errorf("请先核对原执行结果")
|
||||
}
|
||||
if st.Status == "running" && cancel == nil {
|
||||
return fmt.Errorf("执行会话状态已变化,请刷新后重试")
|
||||
}
|
||||
st.UserPaused = true
|
||||
if st.Status == "running" || st.Status == "pausing" {
|
||||
st.Status = "pausing"
|
||||
} else {
|
||||
st.Status = "paused"
|
||||
}
|
||||
case "resume":
|
||||
if st.Status != "paused" || cancel != nil {
|
||||
return fmt.Errorf("请等待此意图暂停完成后再继续")
|
||||
}
|
||||
st.UserPaused = false
|
||||
st.Status = "pending"
|
||||
case "priority":
|
||||
if priority < 1 || priority > 1000 {
|
||||
return fmt.Errorf("priority must be between 1 and 1000")
|
||||
}
|
||||
st.Priority = priority
|
||||
case "guidance":
|
||||
note := strings.TrimSpace(message)
|
||||
if note == "" || utf8.RuneCountInString(note) > 8000 {
|
||||
return fmt.Errorf("意图补充内容为空或过长")
|
||||
}
|
||||
st.Guidance = append(st.Guidance, note)
|
||||
default:
|
||||
return fmt.Errorf("unknown intent action")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err == nil && action == "pause" && cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
|
@ -17,12 +17,14 @@ type Engine struct {
|
|||
Runtime Runtime
|
||||
mu sync.Mutex
|
||||
active map[string]context.CancelFunc
|
||||
workers map[string]map[string]context.CancelFunc
|
||||
phases map[string]LivePhase
|
||||
closed bool
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func NewEngine(s *Store, r Runtime) *Engine {
|
||||
return &Engine{Store: s, Runtime: r, active: map[string]context.CancelFunc{}}
|
||||
return &Engine{Store: s, Runtime: r, active: map[string]context.CancelFunc{}, workers: map[string]map[string]context.CancelFunc{}, phases: map[string]LivePhase{}}
|
||||
}
|
||||
|
||||
func (e *Engine) Start(id, executor string, revision int64) error {
|
||||
|
|
@ -77,6 +79,9 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro
|
|||
step := &t.Steps[i]
|
||||
if step.Status == "uncertain" && resolved[step.ID] && !unknown[step.ID] {
|
||||
step.Status = "pending"
|
||||
if step.UserPaused {
|
||||
step.Status = "paused"
|
||||
}
|
||||
repairedStep = true
|
||||
}
|
||||
}
|
||||
|
|
@ -111,7 +116,7 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro
|
|||
go func() {
|
||||
defer e.wg.Done()
|
||||
defer cancel()
|
||||
defer func() { e.mu.Lock(); delete(e.active, id); e.mu.Unlock() }()
|
||||
defer func() { e.mu.Lock(); delete(e.active, id); delete(e.workers, id); delete(e.phases, id); e.mu.Unlock() }()
|
||||
e.run(ctx, id)
|
||||
}()
|
||||
return nil
|
||||
|
|
@ -339,6 +344,8 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
if workers[step.ID] || !t.Ready(step) {
|
||||
continue
|
||||
}
|
||||
workerCtx, workerCancel := context.WithCancel(ctx)
|
||||
e.mu.Lock()
|
||||
err = e.Store.Change(id, step.ID, "step_started", step.Title, func(current *Task) error {
|
||||
s := current.Step(step.ID)
|
||||
if current.Status != "running" || ctx.Err() != nil || s == nil || !current.Ready(*s) {
|
||||
|
|
@ -348,16 +355,26 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
s.Attempts++
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
if e.workers[id] == nil {
|
||||
e.workers[id] = map[string]context.CancelFunc{}
|
||||
}
|
||||
e.workers[id][step.ID] = workerCancel
|
||||
}
|
||||
e.mu.Unlock()
|
||||
if err != nil {
|
||||
workerCancel()
|
||||
stop("blocked", err.Error())
|
||||
return
|
||||
}
|
||||
workers[step.ID] = true
|
||||
launch(func() result {
|
||||
out, runErr := e.Runtime.Run(ctx, t, step, func(conversation, summary string) error {
|
||||
defer workerCancel()
|
||||
defer func() { e.mu.Lock(); delete(e.workers[id], step.ID); e.mu.Unlock() }()
|
||||
out, runErr := e.Runtime.Run(workerCtx, t, step, func(conversation, summary string) error {
|
||||
return e.Store.Change(id, step.ID, "checkpoint", summary, func(current *Task) error {
|
||||
s := current.Step(step.ID)
|
||||
if s == nil || s.Status != "running" {
|
||||
if s == nil || (s.Status != "running" && !(s.Status == "pausing" && s.UserPaused)) {
|
||||
return ErrConflict
|
||||
}
|
||||
if conversation != "" {
|
||||
|
|
@ -377,11 +394,13 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
if runErr != nil {
|
||||
resultMessage = runErr.Error()
|
||||
}
|
||||
userPausedResult := false
|
||||
persistErr := e.Store.Change(id, step.ID, "step_result", resultMessage, func(current *Task) error {
|
||||
s := current.Step(step.ID)
|
||||
if s == nil || s.Status != "running" {
|
||||
if s == nil || (s.Status != "running" && !(s.Status == "pausing" && s.UserPaused)) {
|
||||
return ErrConflict
|
||||
}
|
||||
userPausedResult = s.UserPaused
|
||||
if len(out.Evidence) > 0 {
|
||||
s.Evidence = out.Evidence
|
||||
}
|
||||
|
|
@ -396,6 +415,10 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
if runErr != nil {
|
||||
s.Summary = runErr.Error()
|
||||
}
|
||||
} else if out.Status == "completed" && out.Summary != "" && runErr == nil && workerCtx.Err() == nil && !s.UserPaused {
|
||||
s.Status = "completed"
|
||||
} else if s.UserPaused {
|
||||
s.Status = "paused"
|
||||
} else if ctx.Err() != nil {
|
||||
s.Status = "pending"
|
||||
} else if errors.Is(runErr, ErrRetryable) {
|
||||
|
|
@ -423,7 +446,7 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
}
|
||||
return nil
|
||||
})
|
||||
if persistErr == nil && errors.Is(runErr, ErrRetryable) {
|
||||
if persistErr == nil && !userPausedResult && errors.Is(runErr, ErrRetryable) {
|
||||
persistErr = runErr
|
||||
}
|
||||
return result{kind: "worker", id: step.ID, err: persistErr}
|
||||
|
|
@ -445,8 +468,10 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
return
|
||||
}
|
||||
planning = true
|
||||
e.setPhase(id, "planning", true)
|
||||
needPlan = false
|
||||
launch(func() result {
|
||||
defer e.setPhase(id, "planning", false)
|
||||
p, err := e.Runtime.Plan(ctx, snapshot)
|
||||
return result{kind: "plan", proposal: p, err: err, guidance: len(snapshot.Guidance), revision: snapshot.Revision, changeVersion: change}
|
||||
})
|
||||
|
|
@ -474,7 +499,9 @@ func (e *Engine) run(parent context.Context, id string) {
|
|||
}
|
||||
}
|
||||
reviewing = true
|
||||
e.setPhase(id, "reviewing", true)
|
||||
launch(func() result {
|
||||
defer e.setPhase(id, "reviewing", false)
|
||||
v, err := e.Runtime.Review(ctx, t)
|
||||
return result{kind: "review", verdict: v, err: err, guidance: len(t.Guidance), changeVersion: change}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -5,34 +5,42 @@ import (
|
|||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
ID string `json:"id"`
|
||||
StepID string `json:"step_id,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
State string `json:"state"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Source json.RawMessage `json:"source"`
|
||||
Round int `json:"updated_round"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Boundary bool `json:"boundary,omitempty"`
|
||||
DetailCount int `json:"detail_count,omitempty"`
|
||||
ID string `json:"id"`
|
||||
StepID string `json:"step_id,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
State string `json:"state"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Source json.RawMessage `json:"source"`
|
||||
Round int `json:"updated_round"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
type Edge struct {
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Relation string `json:"relation"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Relation string `json:"relation"`
|
||||
Projection string `json:"projection,omitempty"`
|
||||
References int `json:"references,omitempty"`
|
||||
}
|
||||
type Graph struct {
|
||||
Nodes []Node `json:"nodes"`
|
||||
Edges []Edge `json:"edges"`
|
||||
Total int `json:"total"`
|
||||
Folded int `json:"folded"`
|
||||
NextOffset int `json:"next_offset"`
|
||||
HasMore bool `json:"has_more"`
|
||||
View string `json:"view,omitempty"`
|
||||
PrimaryCount int `json:"primary_count"`
|
||||
BoundaryTotal int `json:"boundary_total"`
|
||||
BoundaryMore int `json:"boundary_more"`
|
||||
DetailsHidden int `json:"details_hidden"`
|
||||
Nodes []Node `json:"nodes"`
|
||||
Edges []Edge `json:"edges"`
|
||||
Total int `json:"total"`
|
||||
Folded int `json:"folded"`
|
||||
NextOffset int `json:"next_offset"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
func graphNode(tx *sql.Tx, task string, n Node) error {
|
||||
|
|
@ -67,7 +75,7 @@ func syncGraph(tx *sql.Tx, t *Task, step, kind, message string, eventID int64) e
|
|||
}
|
||||
}
|
||||
for _, st := range t.Steps {
|
||||
source, _ := json.Marshal(map[string]any{"conversation_id": st.ConversationID, "evidence": st.Evidence, "depends_on": st.DependsOn, "source_ids": st.Sources, "asset_ids": st.AssetIDs, "priority": stepPriority(st)})
|
||||
source, _ := json.Marshal(map[string]any{"conversation_id": st.ConversationID, "evidence": st.Evidence, "depends_on": st.DependsOn, "source_ids": st.Sources, "asset_ids": st.AssetIDs, "priority": stepPriority(st), "user_paused": st.UserPaused, "guidance_count": len(st.Guidance)})
|
||||
for _, asset := range st.AssetIDs {
|
||||
if _, err := tx.Exec("INSERT OR IGNORE INTO deep_assessment_assets(task_id,asset_id) SELECT ?,id FROM assets WHERE id=?", t.ID, asset); err != nil {
|
||||
return err
|
||||
|
|
@ -111,6 +119,16 @@ func syncGraph(tx *sql.Tx, t *Task, step, kind, message string, eventID int64) e
|
|||
}
|
||||
}
|
||||
}
|
||||
if eventID > 0 && kind == "intent_guidance" && step != "" {
|
||||
id := fmt.Sprintf("guidance:intent:%d", eventID)
|
||||
source, _ := json.Marshal(map[string]any{"provenance": "authenticated_user", "event_id": eventID})
|
||||
if err := graphNode(tx, t.ID, Node{ID: id, StepID: step, Kind: "guidance", State: "user", Title: Clip(message, 100), Body: message, Source: source, Round: t.Rounds}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := graphEdge(tx, t.ID, id, stepNode(step), "guides"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if eventID > 0 && strings.TrimSpace(message) != "" && (kind == "checkpoint" || kind == "step_result" || kind == "review_gap") {
|
||||
id := fmt.Sprintf("observation:%d", eventID)
|
||||
state := "note"
|
||||
|
|
@ -194,33 +212,84 @@ func (s *Store) PrepareGraph(id string) error {
|
|||
return err
|
||||
}
|
||||
hot := hotGraph(nodes, edges)
|
||||
active := map[string]bool{}
|
||||
for _, n := range nodes {
|
||||
if n.Kind != "digest" {
|
||||
continue
|
||||
}
|
||||
var source struct {
|
||||
Version int `json:"archive_version"`
|
||||
}
|
||||
_ = json.Unmarshal(n.Source, &source)
|
||||
if source.Version != 2 && n.State != "superseded" {
|
||||
// Preserve old archive IDs and membership for existing links, but stop
|
||||
// treating unrelated ID batches as a single current branch.
|
||||
n.State = "superseded"
|
||||
if err = graphNode(tx, id, n); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if source.Version == 2 && n.State == "folded" {
|
||||
active[n.ID] = true
|
||||
}
|
||||
}
|
||||
covered := map[string]bool{}
|
||||
for _, edge := range edges {
|
||||
if edge.Relation == "contains" {
|
||||
if edge.Relation == "contains" && active[edge.Source] {
|
||||
covered[edge.Target] = true
|
||||
}
|
||||
}
|
||||
var cold []Node
|
||||
stamps := map[string]int{}
|
||||
stampRows, stampErr := tx.Query("SELECT node_id,since_round FROM deep_assessment_cold WHERE task_id=?", id)
|
||||
if stampErr != nil {
|
||||
return stampErr
|
||||
}
|
||||
for stampRows.Next() {
|
||||
var key string
|
||||
var round int
|
||||
if stampErr = stampRows.Scan(&key, &round); stampErr != nil {
|
||||
stampRows.Close()
|
||||
return stampErr
|
||||
}
|
||||
stamps[key] = round
|
||||
}
|
||||
stampErr = stampRows.Err()
|
||||
stampRows.Close()
|
||||
if stampErr != nil {
|
||||
return stampErr
|
||||
}
|
||||
for _, n := range nodes {
|
||||
if n.Kind == "step" && (n.State == "completed" || n.State == "retired") && !hot[n.ID] && !covered[n.ID] && task.Rounds-n.Round >= 6 {
|
||||
cold = append(cold, n)
|
||||
if n.Kind != "step" {
|
||||
continue
|
||||
}
|
||||
if (n.State == "completed" || n.State == "retired") && !hot[n.ID] {
|
||||
since, ok := stamps[n.ID]
|
||||
if !ok || since > task.Rounds {
|
||||
since = task.Rounds
|
||||
if _, err = tx.Exec("INSERT INTO deep_assessment_cold(task_id,node_id,since_round) VALUES(?,?,?) ON CONFLICT(task_id,node_id) DO UPDATE SET since_round=excluded.since_round", id, n.ID, since); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !covered[n.ID] && task.Rounds-since >= 6 {
|
||||
cold = append(cold, n)
|
||||
}
|
||||
} else if _, ok := stamps[n.ID]; ok {
|
||||
if _, err = tx.Exec("DELETE FROM deep_assessment_cold WHERE task_id=? AND node_id=?", id, n.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(cold, func(i, j int) bool { return cold[i].ID < cold[j].ID })
|
||||
// A batch size is a compaction granularity, not a lifetime step limit.
|
||||
for len(cold) >= 4 {
|
||||
n := min(20, len(cold))
|
||||
members := cold[:n]
|
||||
cold = cold[n:]
|
||||
for _, members := range coldBranches(cold, nodes, edges) {
|
||||
ids := []string{}
|
||||
var summary strings.Builder
|
||||
for _, member := range members {
|
||||
ids = append(ids, member.ID)
|
||||
fmt.Fprintf(&summary, "[%s] %s · %s\n%s\n", member.ID, member.State, member.Title, Clip(member.Body, 240))
|
||||
}
|
||||
sum := sha256.Sum256([]byte(strings.Join(ids, "\x00")))
|
||||
sum := sha256.Sum256([]byte("branch-v2\x00" + strings.Join(ids, "\x00")))
|
||||
digest := fmt.Sprintf("digest:%x", sum[:12])
|
||||
src, _ := json.Marshal(map[string]any{"members": ids, "member_count": len(ids), "provenance": "lossless-index; expand original nodes; Pi summaries are separate memory nodes"})
|
||||
src, _ := json.Marshal(map[string]any{"archive_version": 2, "members": ids, "member_count": len(ids), "provenance": "connected-branch reference index; original records and Pi summaries retained"})
|
||||
if err = graphNode(tx, id, Node{ID: digest, Kind: "digest", State: "folded", Title: fmt.Sprintf("历史分支 · %d", len(ids)), Body: summary.String(), Source: src, Round: task.Rounds}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -310,139 +379,7 @@ func (s *Store) Graph(id, scope string, limit, offset int) (Graph, error) {
|
|||
}
|
||||
|
||||
func (s *Store) GraphVisible(id, scope string, limit, offset int, allow func(Node) bool) (Graph, error) {
|
||||
if limit < 1 || limit > 200 {
|
||||
limit = 80
|
||||
}
|
||||
if offset < 0 {
|
||||
return Graph{}, fmt.Errorf("invalid offset")
|
||||
}
|
||||
if err := s.PrepareGraph(id); err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
nodes, edges, err := readGraph(s.DB, id)
|
||||
if err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
if allow != nil {
|
||||
kept := []Node{}
|
||||
ids := map[string]bool{}
|
||||
for _, n := range nodes {
|
||||
if allow(n) {
|
||||
kept = append(kept, n)
|
||||
ids[n.ID] = true
|
||||
}
|
||||
}
|
||||
nodes = kept
|
||||
keptEdges := []Edge{}
|
||||
for _, edge := range edges {
|
||||
if ids[edge.Source] && ids[edge.Target] {
|
||||
keptEdges = append(keptEdges, edge)
|
||||
}
|
||||
}
|
||||
edges = keptEdges
|
||||
}
|
||||
hot := hotGraph(nodes, edges)
|
||||
byID := map[string]Node{}
|
||||
for _, n := range nodes {
|
||||
byID[n.ID] = n
|
||||
}
|
||||
hiddenSteps := map[string]bool{}
|
||||
for _, e := range edges {
|
||||
if e.Relation == "contains" && !hot[e.Target] {
|
||||
hiddenSteps[byID[e.Target].StepID] = true
|
||||
}
|
||||
}
|
||||
selected := map[string]bool{}
|
||||
if scope != "" {
|
||||
node, ok := byID[scope]
|
||||
if !ok {
|
||||
return Graph{}, sql.ErrNoRows
|
||||
}
|
||||
selected[scope] = true
|
||||
if node.Kind == "digest" {
|
||||
for _, e := range edges {
|
||||
if e.Source == scope && e.Relation == "contains" {
|
||||
selected[e.Target] = true
|
||||
}
|
||||
}
|
||||
} else if node.StepID != "" {
|
||||
selected[stepNode(node.StepID)] = true
|
||||
}
|
||||
}
|
||||
visible := []Node{}
|
||||
folded := 0
|
||||
for _, n := range nodes {
|
||||
if n.ID == "goal" {
|
||||
continue
|
||||
}
|
||||
include := true
|
||||
if scope != "" {
|
||||
include = selected[n.ID] || selected[stepNode(n.StepID)]
|
||||
} else if n.StepID != "" && hiddenSteps[n.StepID] {
|
||||
include = false
|
||||
folded++
|
||||
}
|
||||
if include && scope == "" && n.Kind == "digest" {
|
||||
count := 0
|
||||
for _, e := range edges {
|
||||
if e.Source == n.ID && e.Relation == "contains" && !hot[e.Target] {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
include = false
|
||||
} else {
|
||||
n.Title = fmt.Sprintf("历史分支 · %d", count)
|
||||
}
|
||||
}
|
||||
if include {
|
||||
visible = append(visible, n)
|
||||
}
|
||||
}
|
||||
priority := func(n Node) int {
|
||||
if n.Kind == "step" && hot[n.ID] {
|
||||
return 0
|
||||
}
|
||||
if n.Kind == "digest" {
|
||||
return 1
|
||||
}
|
||||
if n.Kind == "step" {
|
||||
return 2
|
||||
}
|
||||
if n.Kind == "memory" {
|
||||
return 3
|
||||
}
|
||||
if n.Kind == "observation" {
|
||||
return 4
|
||||
}
|
||||
return 5
|
||||
}
|
||||
sort.SliceStable(visible, func(i, j int) bool { return priority(visible[i]) < priority(visible[j]) })
|
||||
out := Graph{Nodes: []Node{}, Edges: []Edge{}, Total: len(visible), Folded: folded}
|
||||
root := byID["goal"]
|
||||
root.Body = Clip(root.Body, 240)
|
||||
out.Nodes = append(out.Nodes, root)
|
||||
offset = min(offset, len(visible))
|
||||
end := min(len(visible), offset+limit)
|
||||
if offset < len(visible) {
|
||||
for _, n := range visible[offset:end] {
|
||||
n.Body = Clip(n.Body, 400)
|
||||
n.Source = json.RawMessage(`{}`)
|
||||
out.Nodes = append(out.Nodes, n)
|
||||
}
|
||||
}
|
||||
out.NextOffset = end
|
||||
out.HasMore = end < len(visible)
|
||||
included := map[string]bool{}
|
||||
for _, n := range out.Nodes {
|
||||
included[n.ID] = true
|
||||
}
|
||||
for _, e := range edges {
|
||||
if included[e.Source] && included[e.Target] {
|
||||
out.Edges = append(out.Edges, e)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
return s.GraphViewVisible(id, scope, "", limit, offset, allow)
|
||||
}
|
||||
|
||||
func (s *Store) Node(id, nodeID string, offset int) (map[string]any, error) {
|
||||
|
|
@ -507,7 +444,7 @@ func (s *Store) SearchNodes(task, query, step string, offset int) ([]Node, error
|
|||
if offset < 0 {
|
||||
return nil, fmt.Errorf("invalid offset")
|
||||
}
|
||||
rows, err := s.DB.Query(`SELECT id,step_id,kind,state,title,substr(body,max(1,instr(lower(body),lower(?))-200),1600),source,updated_round,updated_at FROM deep_assessment_nodes WHERE task_id=? AND kind<>'finding' AND (?='' OR step_id=?) AND (instr(lower(title),lower(?))>0 OR instr(lower(body),lower(?))>0) ORDER BY updated_at DESC,id LIMIT 20 OFFSET ?`, query, task, step, step, query, query, offset)
|
||||
rows, err := s.DB.Query(`SELECT id,step_id,kind,state,title,substr(body,max(1,instr(lower(body),lower(?))-200),1600),source,updated_round,updated_at FROM deep_assessment_nodes WHERE task_id=? AND kind<>'finding' AND NOT(kind='digest' AND state='superseded') AND (?='' OR step_id=?) AND (instr(lower(title),lower(?))>0 OR instr(lower(body),lower(?))>0) ORDER BY updated_at DESC,id LIMIT 20 OFFSET ?`, query, task, step, step, query, query, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,6 +29,9 @@ func TestGraphFoldsColdHistoryAndRevivesActiveDependencies(t *testing.T) {
|
|||
if err := s.SavePiSummary(task.ID, "0", "fixture-session", "entry", full); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.PrepareGraph(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Change(task.ID, "", "planning", "advance", func(v *Task) error { v.Rounds = 10; return nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,375 @@
|
|||
package deepassessment
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Group only steps connected by real evidence/dependency relations. A shared
|
||||
// global goal does not make otherwise unrelated directions one historical branch.
|
||||
func coldBranches(cold, nodes []Node, edges []Edge) [][]Node {
|
||||
byID := map[string]Node{}
|
||||
owner := map[string]string{}
|
||||
adj := map[string][]string{}
|
||||
for _, n := range cold {
|
||||
byID[n.ID] = n
|
||||
adj[n.ID] = nil
|
||||
}
|
||||
for _, n := range nodes {
|
||||
if n.StepID != "" && n.Kind != "finding" && n.Kind != "guidance" {
|
||||
owner[n.ID] = stepNode(n.StepID)
|
||||
}
|
||||
}
|
||||
for _, e := range edges {
|
||||
a, b := owner[e.Source], owner[e.Target]
|
||||
if a != b && a != "" && b != "" && e.Relation != "contains" {
|
||||
if _, ok := byID[a]; ok {
|
||||
if _, ok = byID[b]; ok {
|
||||
adj[a] = append(adj[a], b)
|
||||
adj[b] = append(adj[b], a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
keys := []string{}
|
||||
for id := range byID {
|
||||
keys = append(keys, id)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
seen := map[string]bool{}
|
||||
out := [][]Node{}
|
||||
for _, id := range keys {
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
queue := []string{id}
|
||||
seen[id] = true
|
||||
group := []Node{}
|
||||
for len(queue) > 0 {
|
||||
next := queue[0]
|
||||
queue = queue[1:]
|
||||
group = append(group, byID[next])
|
||||
sort.Strings(adj[next])
|
||||
for _, child := range adj[next] {
|
||||
if !seen[child] {
|
||||
seen[child] = true
|
||||
queue = append(queue, child)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Components are reference indexes, not generated summaries or model budgets.
|
||||
for len(group) > 0 {
|
||||
n := min(20, len(group))
|
||||
chunk := append([]Node(nil), group[:n]...)
|
||||
sort.Slice(chunk, func(i, j int) bool { return chunk[i].ID < chunk[j].ID })
|
||||
out = append(out, chunk)
|
||||
group = group[n:]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func visibleGraph(nodes []Node, edges []Edge, allow func(Node) bool) ([]Node, []Edge) {
|
||||
ids := map[string]bool{}
|
||||
kept := []Node{}
|
||||
for _, n := range nodes {
|
||||
if allow == nil || allow(n) {
|
||||
ids[n.ID] = true
|
||||
kept = append(kept, n)
|
||||
}
|
||||
}
|
||||
links := []Edge{}
|
||||
for _, e := range edges {
|
||||
if ids[e.Source] && ids[e.Target] {
|
||||
links = append(links, e)
|
||||
}
|
||||
}
|
||||
return kept, links
|
||||
}
|
||||
|
||||
func projectGraph(nodes []Node, edges []Edge, scope, view string, coldEligible map[string]bool) ([]Node, []Edge, map[string]Node, int, int, error) {
|
||||
byID := map[string]Node{}
|
||||
for _, n := range nodes {
|
||||
byID[n.ID] = n
|
||||
}
|
||||
if scope != "" {
|
||||
if _, ok := byID[scope]; !ok {
|
||||
return nil, nil, nil, 0, 0, sql.ErrNoRows
|
||||
}
|
||||
}
|
||||
hot := hotGraph(nodes, edges)
|
||||
expanded := map[string]bool{}
|
||||
if scope != "" {
|
||||
n := byID[scope]
|
||||
if n.StepID != "" {
|
||||
expanded[n.StepID] = true
|
||||
}
|
||||
if n.Kind == "digest" {
|
||||
for _, e := range edges {
|
||||
if e.Source == scope && e.Relation == "contains" {
|
||||
expanded[byID[e.Target].StepID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
archived := map[string]string{}
|
||||
digestCounts := map[string]int{}
|
||||
for _, e := range edges {
|
||||
if e.Relation == "contains" && byID[e.Source].Kind == "digest" && byID[e.Source].State == "folded" && coldEligible[e.Target] && !hot[e.Target] && !expanded[byID[e.Target].StepID] {
|
||||
archived[byID[e.Target].StepID] = e.Source
|
||||
digestCounts[e.Source]++
|
||||
}
|
||||
}
|
||||
representatives := map[string]string{}
|
||||
folded, hidden := 0, 0
|
||||
detailCounts := map[string]int{}
|
||||
for _, n := range nodes {
|
||||
representatives[n.ID] = n.ID
|
||||
if n.Kind == "digest" && (n.State != "folded" || digestCounts[n.ID] == 0) && n.ID != scope {
|
||||
representatives[n.ID] = ""
|
||||
continue
|
||||
}
|
||||
if n.Kind != "finding" && n.Kind != "goal" && n.Kind != "guidance" && n.StepID != "" && archived[n.StepID] != "" {
|
||||
representatives[n.ID] = archived[n.StepID]
|
||||
folded++
|
||||
continue
|
||||
}
|
||||
if view == "summary" && (n.Kind == "receipt" || n.Kind == "observation") {
|
||||
parent := stepNode(n.StepID)
|
||||
if _, ok := byID[parent]; !ok {
|
||||
parent = "goal"
|
||||
}
|
||||
representatives[n.ID] = parent
|
||||
hidden++
|
||||
detailCounts[parent]++
|
||||
}
|
||||
}
|
||||
representative := func(id string) string {
|
||||
for i := 0; i < 3; i++ {
|
||||
next := representatives[id]
|
||||
if next == id || next == "" {
|
||||
return next
|
||||
}
|
||||
id = next
|
||||
}
|
||||
return id
|
||||
}
|
||||
allVisible := map[string]Node{}
|
||||
primary := []Node{}
|
||||
for _, n := range nodes {
|
||||
if representative(n.ID) != n.ID {
|
||||
continue
|
||||
}
|
||||
if n.Kind == "digest" && n.ID != scope {
|
||||
n.Title = fmt.Sprintf("历史分支 · %d", digestCounts[n.ID])
|
||||
}
|
||||
n.DetailCount = detailCounts[n.ID]
|
||||
allVisible[n.ID] = n
|
||||
if n.ID != "goal" && (scope == "" || n.ID == scope || expanded[n.StepID]) {
|
||||
primary = append(primary, n)
|
||||
}
|
||||
}
|
||||
projected := []Edge{}
|
||||
seen := map[string]int{}
|
||||
for _, e := range edges {
|
||||
if e.Relation == "contains" && e.Source != scope {
|
||||
continue
|
||||
}
|
||||
a, b := representative(e.Source), representative(e.Target)
|
||||
if a == "" || b == "" || a == b {
|
||||
continue
|
||||
}
|
||||
if a != e.Source || b != e.Target {
|
||||
e.Projection = "details"
|
||||
if byID[a].Kind == "digest" || byID[b].Kind == "digest" {
|
||||
e.Projection = "archive"
|
||||
}
|
||||
e.References = 1
|
||||
}
|
||||
e.Source, e.Target = a, b
|
||||
key := a + "\x00" + e.Relation + "\x00" + b + "\x00" + e.Projection
|
||||
if at, ok := seen[key]; ok {
|
||||
projected[at].References += e.References
|
||||
continue
|
||||
}
|
||||
seen[key] = len(projected)
|
||||
projected = append(projected, e)
|
||||
}
|
||||
return primary, projected, allVisible, folded, hidden, nil
|
||||
}
|
||||
|
||||
func (s *Store) GraphViewVisible(id, scope, view string, limit, offset int, allow func(Node) bool) (Graph, error) {
|
||||
if scope == "goal" {
|
||||
scope = ""
|
||||
}
|
||||
if limit < 1 || limit > 200 {
|
||||
limit = 80
|
||||
}
|
||||
if offset < 0 {
|
||||
return Graph{}, fmt.Errorf("invalid offset")
|
||||
}
|
||||
if view != "" && view != "full" && view != "summary" {
|
||||
return Graph{}, fmt.Errorf("invalid graph view")
|
||||
}
|
||||
if err := s.PrepareGraph(id); err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
nodes, edges, err := readGraph(s.DB, id)
|
||||
if err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
nodes, edges = visibleGraph(nodes, edges, allow)
|
||||
eligible := map[string]bool{}
|
||||
rows, err := s.DB.Query("SELECT node_id FROM deep_assessment_cold WHERE task_id=? AND since_round <= (SELECT COALESCE(json_extract(payload,'$.rounds'),0)-6 FROM deep_assessments WHERE id=?)", id, id)
|
||||
if err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if err = rows.Scan(&key); err != nil {
|
||||
rows.Close()
|
||||
return Graph{}, err
|
||||
}
|
||||
eligible[key] = true
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
primary, links, byID, folded, hidden, err := projectGraph(nodes, edges, scope, view, eligible)
|
||||
if err != nil {
|
||||
return Graph{}, err
|
||||
}
|
||||
priority := func(n Node) int {
|
||||
if n.ID == scope {
|
||||
return -1
|
||||
}
|
||||
switch n.Kind {
|
||||
case "finding":
|
||||
return 0
|
||||
case "guidance":
|
||||
return 1
|
||||
case "step":
|
||||
if n.State != "completed" && n.State != "retired" {
|
||||
return 2
|
||||
}
|
||||
return 6
|
||||
case "fact":
|
||||
return 3
|
||||
case "memory":
|
||||
return 4
|
||||
case "digest":
|
||||
return 5
|
||||
case "observation":
|
||||
return 7
|
||||
}
|
||||
return 8
|
||||
}
|
||||
sort.SliceStable(primary, func(i, j int) bool { return priority(primary[i]) < priority(primary[j]) })
|
||||
out := Graph{Nodes: []Node{}, Edges: []Edge{}, Total: len(primary), Folded: folded, DetailsHidden: hidden, View: view}
|
||||
included := map[string]bool{}
|
||||
page := map[string]bool{}
|
||||
appendNode := func(n Node, boundary bool) {
|
||||
n.Body = Clip(n.Body, 400)
|
||||
n.Source = json.RawMessage(`{}`)
|
||||
n.Boundary = boundary
|
||||
out.Nodes = append(out.Nodes, n)
|
||||
included[n.ID] = true
|
||||
}
|
||||
if root, ok := byID["goal"]; ok {
|
||||
appendNode(root, false)
|
||||
}
|
||||
offset = min(offset, len(primary))
|
||||
end := min(len(primary), offset+limit)
|
||||
for _, n := range primary[offset:end] {
|
||||
appendNode(n, false)
|
||||
page[n.ID] = true
|
||||
}
|
||||
out.PrimaryCount = end - offset
|
||||
out.NextOffset = end
|
||||
out.HasMore = end < len(primary)
|
||||
references := map[string]bool{}
|
||||
ids := []string{}
|
||||
addRef := func(id string) {
|
||||
if !included[id] && !references[id] {
|
||||
references[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
parents := map[string][]string{}
|
||||
for _, e := range links {
|
||||
parents[e.Target] = append(parents[e.Target], e.Source)
|
||||
}
|
||||
// Prefer the nearest upstream lineage before downstream context. This keeps
|
||||
// a paged dependency chain connected back to its goal whenever it fits.
|
||||
for _, n := range primary[offset:end] {
|
||||
for _, parent := range parents[n.ID] {
|
||||
addRef(parent)
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(ids); i++ {
|
||||
for _, parent := range parents[ids[i]] {
|
||||
addRef(parent)
|
||||
}
|
||||
}
|
||||
for _, e := range links {
|
||||
if page[e.Source] {
|
||||
addRef(e.Target)
|
||||
}
|
||||
}
|
||||
out.BoundaryTotal = len(ids)
|
||||
for i, id := range ids {
|
||||
if i >= 80 {
|
||||
out.BoundaryMore++
|
||||
continue
|
||||
}
|
||||
appendNode(byID[id], true)
|
||||
}
|
||||
for _, e := range links {
|
||||
if included[e.Source] && included[e.Target] {
|
||||
out.Edges = append(out.Edges, e)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type RelationReference struct {
|
||||
Direction string `json:"direction"`
|
||||
Relation string `json:"relation"`
|
||||
Node Node `json:"node"`
|
||||
}
|
||||
|
||||
func (s *Store) RelationsVisible(task, node string, offset int, allow func(Node) bool) (map[string]any, error) {
|
||||
if offset < 0 {
|
||||
return nil, fmt.Errorf("invalid offset")
|
||||
}
|
||||
nodes, edges, err := readGraph(s.DB, task)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, edges = visibleGraph(nodes, edges, allow)
|
||||
byID := map[string]Node{}
|
||||
for _, n := range nodes {
|
||||
n.Body = Clip(n.Body, 160)
|
||||
n.Source = json.RawMessage(`{}`)
|
||||
byID[n.ID] = n
|
||||
}
|
||||
if _, ok := byID[node]; !ok {
|
||||
return nil, sql.ErrNoRows
|
||||
}
|
||||
refs := []RelationReference{}
|
||||
for _, e := range edges {
|
||||
if e.Target == node {
|
||||
refs = append(refs, RelationReference{"upstream", e.Relation, byID[e.Source]})
|
||||
}
|
||||
if e.Source == node {
|
||||
refs = append(refs, RelationReference{"downstream", e.Relation, byID[e.Target]})
|
||||
}
|
||||
}
|
||||
offset = min(offset, len(refs))
|
||||
end := min(offset+30, len(refs))
|
||||
return map[string]any{"relations": refs[offset:end], "relations_total": len(refs), "relations_next_offset": end, "relations_has_more": end < len(refs)}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
package deepassessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIntentPauseAndResumeDoNotCancelSibling(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "one", Status: "pending"}, {ID: "two", Status: "pending"}}
|
||||
return nil
|
||||
})
|
||||
var one, two atomic.Int32
|
||||
e := NewEngine(s, fakeRuntime{plan: func(context.Context, *Task) (Proposal, error) { return Proposal{}, nil }, run: func(ctx context.Context, _ *Task, st Step, _ func(string, string) error) (Outcome, error) {
|
||||
if st.ID == "one" {
|
||||
one.Add(1)
|
||||
} else {
|
||||
two.Add(1)
|
||||
}
|
||||
<-ctx.Done()
|
||||
return Outcome{}, ctx.Err()
|
||||
}})
|
||||
t.Cleanup(e.Close)
|
||||
current, _ := s.Get(task.ID)
|
||||
if err := e.Start(task.ID, task.OwnerID, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current = await(t, s, task.ID, func(v *Task) bool { return one.Load() == 1 && two.Load() == 1 })
|
||||
if err := e.ControlStep(task.ID, "one", "pause", "", 0, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current = await(t, s, task.ID, func(v *Task) bool { return v.Step("one").Status == "paused" && e.Live(task.ID).Workers == 1 })
|
||||
if current.Status != "running" || current.Step("two").Status != "running" || !current.Step("one").UserPaused {
|
||||
t.Fatal(current)
|
||||
}
|
||||
if err := e.ControlStep(task.ID, "two", "priority", "", 1, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, _ = s.Get(task.ID)
|
||||
if err := e.ControlStep(task.ID, "one", "resume", "", 0, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current = await(t, s, task.ID, func(v *Task) bool { return one.Load() == 2 })
|
||||
if two.Load() != 1 || current.Step("two").Priority != 1 {
|
||||
t.Fatal("sibling was restarted", current)
|
||||
}
|
||||
if err := e.Stop(task.ID, current.Revision, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
await(t, s, task.ID, func(v *Task) bool { return v.Status == "paused" })
|
||||
}
|
||||
|
||||
func TestIntentPauseSurvivesTaskStartAndPlannerCannotRetireIt(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "held", Instruction: "held", Status: "pending"}, {ID: "other", Instruction: "other", Status: "pending"}}
|
||||
return nil
|
||||
})
|
||||
var held, other atomic.Int32
|
||||
e := NewEngine(s, fakeRuntime{plan: func(context.Context, *Task) (Proposal, error) { return Proposal{}, nil }, run: func(ctx context.Context, _ *Task, st Step, _ func(string, string) error) (Outcome, error) {
|
||||
if st.ID == "held" {
|
||||
held.Add(1)
|
||||
} else {
|
||||
other.Add(1)
|
||||
}
|
||||
<-ctx.Done()
|
||||
return Outcome{}, ctx.Err()
|
||||
}})
|
||||
t.Cleanup(e.Close)
|
||||
current, _ := s.Get(task.ID)
|
||||
if err := e.ControlStep(task.ID, "held", "pause", "", 0, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, _ = s.Get(task.ID)
|
||||
if err := ApplyProposal(current, Proposal{Retire: []string{"held"}}); err == nil {
|
||||
t.Fatal("planner overrode a user-paused intent")
|
||||
}
|
||||
current, _ = s.Get(task.ID)
|
||||
if err := e.Start(task.ID, task.OwnerID, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current = await(t, s, task.ID, func(v *Task) bool { return other.Load() == 1 })
|
||||
if held.Load() != 0 || current.Step("held").Status != "paused" {
|
||||
t.Fatal(current)
|
||||
}
|
||||
e.Close()
|
||||
if err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, _ = s.Get(task.ID)
|
||||
if current.Step("held").Status != "paused" {
|
||||
t.Fatal(current)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntentResumeCannotUseAnotherExecutorsPendingRecovery(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Status = "waiting_progress"
|
||||
v.Steps = []Step{{ID: "held", Status: "paused", UserPaused: true}}
|
||||
return nil
|
||||
})
|
||||
e := NewEngine(s, fakeRuntime{})
|
||||
t.Cleanup(e.Close)
|
||||
current, _ := s.Get(task.ID)
|
||||
for _, action := range []string{"resume", "guidance"} {
|
||||
if err := e.ControlStepAs(task.ID, "held", action, "direction", 100, current.Revision, "different-executor"); err == nil {
|
||||
t.Fatal("other executor controlled active recovery", action)
|
||||
}
|
||||
}
|
||||
current, _ = s.Get(task.ID)
|
||||
if !current.Step("held").UserPaused || len(current.Step("held").Guidance) > 0 {
|
||||
t.Fatal(current)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
package deepassessment
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ToolActivity struct {
|
||||
ID string `json:"id"`
|
||||
StepID string `json:"step_id"`
|
||||
Tool string `json:"tool"`
|
||||
Status string `json:"status"`
|
||||
ExecutionID string `json:"execution_id,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
OutputBytes int64 `json:"output_bytes,omitempty"`
|
||||
}
|
||||
type RuntimeOverview struct {
|
||||
Sessions map[string]SessionActivity `json:"sessions"`
|
||||
Intents []IntentActivity `json:"intents"`
|
||||
Live LivePhase `json:"live"`
|
||||
Counts map[string]int `json:"counts"`
|
||||
Tools []ToolActivity `json:"tools"`
|
||||
Recent []Event `json:"recent"`
|
||||
Facts int `json:"facts"`
|
||||
Findings int `json:"findings"`
|
||||
FindingsVisible bool `json:"findings_visible"`
|
||||
AssetNames map[string]string `json:"asset_names"`
|
||||
}
|
||||
type SessionActivity struct {
|
||||
Stage string `json:"stage"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
type IntentActivity struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
AssetIDs []string `json:"asset_ids"`
|
||||
ConversationID string `json:"conversation_id"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
func (s *Store) RecentEvents(task string, limit int) ([]Event, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
limit = 8
|
||||
}
|
||||
rows, err := s.DB.Query("SELECT id,step_id,kind,message,created_at FROM deep_assessment_events WHERE task_id=? ORDER BY id DESC LIMIT ?", task, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Event{}
|
||||
for rows.Next() {
|
||||
var e Event
|
||||
if err = rows.Scan(&e.ID, &e.StepID, &e.Kind, &e.Message, &e.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Read from the existing host execution registry and Pi-backed task ledger.
|
||||
// No model call, tool execution or task transition is needed to refresh the view.
|
||||
func (s *Store) RuntimeOverview(t *Task) (RuntimeOverview, error) {
|
||||
out := RuntimeOverview{Counts: map[string]int{}, Tools: []ToolActivity{}, Recent: []Event{}, AssetNames: map[string]string{}}
|
||||
for _, st := range t.Steps {
|
||||
out.Counts[st.Status]++
|
||||
if st.Status == "running" || st.Status == "pausing" || st.Status == "uncertain" || st.Status == "cleanup_unconfirmed" {
|
||||
out.Intents = append(out.Intents, IntentActivity{st.ID, st.Title, st.Status, st.AssetIDs, st.ConversationID, Clip(st.Summary, 300)})
|
||||
}
|
||||
}
|
||||
if err := s.DB.QueryRow("SELECT COUNT(*) FROM deep_assessment_facts WHERE task_id=?", t.ID).Scan(&out.Facts); err != nil {
|
||||
return out, err
|
||||
}
|
||||
events, err := s.RecentEvents(t.ID, 8)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Recent = events
|
||||
for i := range out.Recent {
|
||||
out.Recent[i].Message = Clip(out.Recent[i].Message, 400)
|
||||
}
|
||||
rows, err := s.DB.Query(`SELECT e.id,ss.step_id,e.tool_name,e.status,e.start_time,e.partial_output_updated_at,COALESCE(e.partial_output_bytes,0)
|
||||
FROM tool_executions e JOIN deep_assessment_sessions ss ON ss.conversation_id=e.conversation_id
|
||||
WHERE ss.task_id=? AND e.status IN ('queued','running') ORDER BY e.start_time DESC LIMIT 16`, t.ID)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
represented := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var v ToolActivity
|
||||
var updated sql.NullTime
|
||||
if err = rows.Scan(&v.ID, &v.StepID, &v.Tool, &v.Status, &v.StartedAt, &updated, &v.OutputBytes); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
v.ExecutionID = v.ID
|
||||
v.UpdatedAt = v.StartedAt
|
||||
if updated.Valid {
|
||||
v.UpdatedAt = updated.Time
|
||||
}
|
||||
out.Tools = append(out.Tools, v)
|
||||
represented[v.StepID+"\x00"+v.Tool] = true
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
rows, err = s.DB.Query("SELECT id,step_id,tool,status,execution_id,updated_at FROM deep_assessment_calls WHERE task_id=? AND status IN ('running','uncertain') ORDER BY updated_at DESC LIMIT 16", t.ID)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var v ToolActivity
|
||||
if err = rows.Scan(&v.ID, &v.StepID, &v.Tool, &v.Status, &v.ExecutionID, &v.UpdatedAt); err != nil {
|
||||
return out, err
|
||||
}
|
||||
v.StartedAt = v.UpdatedAt
|
||||
if !represented[v.StepID+"\x00"+v.Tool] {
|
||||
out.Tools = append(out.Tools, v)
|
||||
}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
|
@ -43,6 +43,9 @@ func (s *Store) RetryStep(id, step string, revision int64, reconciled bool) erro
|
|||
return err
|
||||
}
|
||||
st.Status = "pending"
|
||||
if st.UserPaused {
|
||||
st.Status = "paused"
|
||||
}
|
||||
st.StalledSegments = 0
|
||||
t.Status = "paused"
|
||||
if t.Question != "" {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
|
|
@ -113,6 +114,11 @@ func (s *Store) change(id, step, kind, message string, version *int64, fn func(*
|
|||
if err = syncGraph(tx, &t, step, kind, message, eventID); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.HasPrefix(kind, "intent_") {
|
||||
if err = Signal(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
|
@ -246,6 +252,11 @@ func (s *Store) Recover() error {
|
|||
st.Status = "uncertain"
|
||||
} else if st.Status == "running" || st.Status == "interrupted" {
|
||||
st.Status = "pending"
|
||||
if st.UserPaused {
|
||||
st.Status = "paused"
|
||||
}
|
||||
} else if st.Status == "pausing" && st.UserPaused {
|
||||
st.Status = "paused"
|
||||
}
|
||||
}
|
||||
if len(unknown) > 0 {
|
||||
|
|
|
|||
|
|
@ -54,6 +54,8 @@ type Task struct {
|
|||
}
|
||||
|
||||
type Step struct {
|
||||
UserPaused bool `json:"user_paused,omitempty"`
|
||||
Guidance []string `json:"guidance,omitempty"`
|
||||
AssetIDs []string `json:"asset_ids,omitempty"`
|
||||
Priority int `json:"priority,omitempty"`
|
||||
Sources []string `json:"source_ids,omitempty"`
|
||||
|
|
@ -211,11 +213,13 @@ func ApplyProposal(t *Task, p Proposal) error {
|
|||
s.Evidence = nil
|
||||
s.LastProgress = ""
|
||||
s.StalledSegments = 0
|
||||
s.UserPaused = false
|
||||
s.Guidance = nil
|
||||
all = append(all, s)
|
||||
}
|
||||
for _, id := range p.Retire {
|
||||
s := t.Step(id)
|
||||
if s == nil || s.Status == "running" || s.Status == "completed" || (s.Status == "cleanup_unconfirmed" || s.Status == "uncertain") {
|
||||
if s == nil || s.UserPaused || s.Status == "pausing" || s.Status == "running" || s.Status == "completed" || (s.Status == "cleanup_unconfirmed" || s.Status == "uncertain") {
|
||||
return fmt.Errorf("cannot retire step %s", id)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,272 @@
|
|||
package deepassessment
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArchiveKeepsFindingsAndProjectsBranchLineage(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
if err := s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "a", Title: "branch A", Instruction: "A", Status: "completed"}, {ID: "b", Title: "branch B", Instruction: "B", Status: "completed", DependsOn: []string{"a"}}, {ID: "other", Title: "separate", Instruction: "other", Status: "completed"}}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, _ := s.DB.Begin()
|
||||
for _, n := range []Node{{ID: "fact:b", StepID: "b", Kind: "fact", State: "observed", Title: "original fact", Body: "original"}, {ID: "finding:kept", StepID: "b", Kind: "finding", State: "confirmed", Title: "confirmed finding", Body: "proof"}} {
|
||||
if err := graphNode(tx, task.ID, n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
graphEdge(tx, task.ID, "step:b", "fact:b", "produces")
|
||||
graphEdge(tx, task.ID, "fact:b", "finding:kept", "supports")
|
||||
graphEdge(tx, task.ID, "step:b", "finding:kept", "produces")
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.PrepareGraph(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.Change(task.ID, "", "advance", "", func(v *Task) error { v.Rounds = 10; return nil })
|
||||
g, err := s.GraphViewVisible(task.ID, "", "summary", 80, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
visible := map[string]Node{}
|
||||
archives := 0
|
||||
for _, n := range g.Nodes {
|
||||
visible[n.ID] = n
|
||||
if n.Kind == "digest" {
|
||||
archives++
|
||||
record, _ := s.Node(task.ID, n.ID, 0)
|
||||
var source struct {
|
||||
Members []string `json:"members"`
|
||||
}
|
||||
json.Unmarshal(record["node"].(Node).Source, &source)
|
||||
if len(source.Members) > 1 && strings.Contains(strings.Join(source.Members, ","), "other") {
|
||||
t.Fatal("unrelated branches were batched")
|
||||
}
|
||||
}
|
||||
}
|
||||
if visible["finding:kept"].ID == "" || archives != 2 {
|
||||
t.Fatal(g)
|
||||
}
|
||||
proof := false
|
||||
for _, edge := range g.Edges {
|
||||
if edge.Target == "finding:kept" && edge.Relation == "supports" && edge.Projection == "archive" {
|
||||
proof = true
|
||||
}
|
||||
}
|
||||
if !proof {
|
||||
t.Fatal("folding disconnected finding evidence", g.Edges)
|
||||
}
|
||||
if _, err = s.Node(task.ID, "fact:b", 0); err != nil {
|
||||
t.Fatal("original evidence was removed", err)
|
||||
}
|
||||
hidden, err := s.GraphViewVisible(task.ID, "", "summary", 80, 0, func(n Node) bool { return n.Kind != "finding" })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, n := range hidden.Nodes {
|
||||
if n.Kind == "finding" {
|
||||
t.Fatal("private finding leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphPaginationRetainsBoundariesAndCompleteRelationPaging(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "work", Title: "work", Instruction: "work", Status: "pending"}}
|
||||
return nil
|
||||
})
|
||||
tx, _ := s.DB.Begin()
|
||||
for i := 0; i < 110; i++ {
|
||||
id := fmt.Sprintf("fact:%03d", i)
|
||||
if err := graphNode(tx, task.ID, Node{ID: id, Kind: "fact", State: "observed", Title: id}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
graphEdge(tx, task.ID, id, "step:work", "informs")
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g, err := s.GraphViewVisible(task.ID, "", "summary", 1, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g.PrimaryCount != 1 || g.BoundaryTotal != 110 || g.BoundaryMore != 30 || len(g.Nodes) != 82 {
|
||||
t.Fatal(g)
|
||||
}
|
||||
for _, edge := range g.Edges {
|
||||
if edge.Source != "goal" && !strings.HasPrefix(edge.Source, "fact:") {
|
||||
t.Fatal(edge)
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for offset := 0; ; {
|
||||
result, err := s.RelationsVisible(task.ID, "step:work", offset, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, ref := range result["relations"].([]RelationReference) {
|
||||
seen[ref.Node.ID] = true
|
||||
}
|
||||
if !result["relations_has_more"].(bool) {
|
||||
break
|
||||
}
|
||||
offset = result["relations_next_offset"].(int)
|
||||
}
|
||||
if len(seen) != 111 {
|
||||
t.Fatal("cross-page relations were lost", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummaryViewRetainsExecutionProvenanceAndFullView(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error { v.Steps = []Step{{ID: "one", Status: "running"}}; return nil })
|
||||
tx, _ := s.DB.Begin()
|
||||
graphNode(tx, task.ID, Node{ID: "receipt:one", Kind: "receipt", StepID: "one", Title: "output", Body: "original receipt"})
|
||||
graphNode(tx, task.ID, Node{ID: "fact:one", Kind: "fact", StepID: "one", Title: "fact"})
|
||||
graphEdge(tx, task.ID, "step:one", "receipt:one", "executes")
|
||||
graphEdge(tx, task.ID, "receipt:one", "fact:one", "supports")
|
||||
tx.Commit()
|
||||
summary, err := s.GraphViewVisible(task.ID, "", "summary", 80, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.DetailsHidden != 1 {
|
||||
t.Fatal(summary)
|
||||
}
|
||||
projected := false
|
||||
for _, n := range summary.Nodes {
|
||||
if n.Kind == "receipt" {
|
||||
t.Fatal("raw receipt flooded main view")
|
||||
}
|
||||
}
|
||||
for _, e := range summary.Edges {
|
||||
if e.Source == "step:one" && e.Target == "fact:one" && e.Projection == "details" {
|
||||
projected = true
|
||||
}
|
||||
}
|
||||
if !projected {
|
||||
t.Fatal(summary.Edges)
|
||||
}
|
||||
full, err := s.GraphViewVisible(task.ID, "receipt:one", "full", 1, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if full.Nodes[1].ID != "receipt:one" || full.Nodes[1].Boundary {
|
||||
t.Fatal("selected node was paginated away", full)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevivedArchiveRequiresContinuousColdRoundsAndKeepsOldLinks(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "old", Title: "old", Instruction: "old direction", Status: "completed"}}
|
||||
return nil
|
||||
})
|
||||
if err := s.PrepareGraph(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.Change(task.ID, "", "advance", "", func(v *Task) error { v.Rounds = 7; return nil })
|
||||
graph, err := s.Graph(task.ID, "", 80, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive := ""
|
||||
for _, n := range graph.Nodes {
|
||||
if n.Kind == "digest" {
|
||||
archive = n.ID
|
||||
}
|
||||
}
|
||||
if archive == "" {
|
||||
t.Fatal("cold branch not archived")
|
||||
}
|
||||
s.Change(task.ID, "", "revive", "", func(v *Task) error {
|
||||
v.Rounds = 8
|
||||
return ApplyProposal(v, Proposal{Steps: []Step{{ID: "live", Title: "live", Instruction: "new direction", DependsOn: []string{"old"}}}})
|
||||
})
|
||||
if _, err = s.Graph(task.ID, "", 80, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.Change(task.ID, "", "settle", "", func(v *Task) error { v.Rounds = 9; v.Step("live").Status = "completed"; return nil })
|
||||
contains := func(g Graph, id string) bool {
|
||||
for _, n := range g.Nodes {
|
||||
if n.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
graph, _ = s.Graph(task.ID, "", 80, 0)
|
||||
if !contains(graph, "step:old") {
|
||||
t.Fatal("revived branch folded immediately")
|
||||
}
|
||||
s.Change(task.ID, "", "advance", "", func(v *Task) error { v.Rounds = 14; return nil })
|
||||
graph, _ = s.Graph(task.ID, "", 80, 0)
|
||||
if !contains(graph, "step:old") {
|
||||
t.Fatal("cold grace window lost")
|
||||
}
|
||||
s.Change(task.ID, "", "advance", "", func(v *Task) error { v.Rounds = 15; return nil })
|
||||
graph, _ = s.Graph(task.ID, "", 80, 0)
|
||||
if contains(graph, "step:old") {
|
||||
t.Fatal("cold archive did not return")
|
||||
}
|
||||
if _, err = s.Node(task.ID, archive, 0); err != nil {
|
||||
t.Fatal("archive link was removed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyArchiveIsSupersededWithoutDeletingItsMembers(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "one", Instruction: "one", Status: "completed"}}
|
||||
return nil
|
||||
})
|
||||
tx, _ := s.DB.Begin()
|
||||
graphNode(tx, task.ID, Node{ID: "digest:legacy", Kind: "digest", State: "folded", Title: "legacy", Source: json.RawMessage(`{"members":["step:one"]}`)})
|
||||
graphEdge(tx, task.ID, "digest:legacy", "step:one", "contains")
|
||||
tx.Commit()
|
||||
if _, err := s.Graph(task.ID, "", 80, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old, err := s.Node(task.ID, "digest:legacy", 0)
|
||||
if err != nil || old["node"].(Node).State != "superseded" {
|
||||
t.Fatal(old, err)
|
||||
}
|
||||
expanded, err := s.Graph(task.ID, "digest:legacy", 80, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, n := range expanded.Nodes {
|
||||
found = found || n.ID == "step:one"
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("old archive no longer expands")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedGraphRetainsUpstreamChainAcrossPages(t *testing.T) {
|
||||
s, task := fixture(t)
|
||||
s.Change(task.ID, "", "seed", "", func(v *Task) error {
|
||||
v.Steps = []Step{{ID: "a", Status: "pending"}, {ID: "b", Status: "pending", DependsOn: []string{"a"}}, {ID: "c", Status: "pending", DependsOn: []string{"b"}}}
|
||||
return nil
|
||||
})
|
||||
graph, err := s.GraphViewVisible(task.ID, "step:c", "summary", 1, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodes := map[string]bool{}
|
||||
for _, n := range graph.Nodes {
|
||||
nodes[n.ID] = true
|
||||
}
|
||||
if !nodes["goal"] || !nodes["step:a"] || !nodes["step:b"] || !nodes["step:c"] || len(graph.Edges) != 3 {
|
||||
t.Fatal("upstream path was cut at the page boundary", graph)
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import (
|
|||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/deepassessment"
|
||||
"cyberstrike-ai/internal/security"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
|
@ -283,9 +284,60 @@ func (h *AgentHandler) GetDeepAssessment(c *gin.Context) {
|
|||
deepAssessmentError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(200, deepAssessmentView(c, t))
|
||||
view := deepAssessmentView(c, t)
|
||||
if c.Query("runtime") == "true" {
|
||||
live, readErr := h.deepAssessments.Store.RuntimeOverview(t)
|
||||
if readErr != nil {
|
||||
deepAssessmentError(c, readErr)
|
||||
return
|
||||
}
|
||||
live.Live = h.deepAssessments.Live(t.ID)
|
||||
live.Sessions = h.deepAssessmentRuntime.sessionActivity(t.ID)
|
||||
session, _ := security.CurrentSession(c)
|
||||
if security.SessionHasPermission(c, "vulnerability:read") {
|
||||
live.FindingsVisible = true
|
||||
live.Findings, readErr = h.db.CountVulnerabilitiesForAccess(database.VulnerabilityListFilter{AssessmentID: t.ID}, database.RBACListAccess{UserID: session.UserID, Scope: session.ScopeFor("vulnerability:read")})
|
||||
if readErr != nil {
|
||||
deepAssessmentError(c, readErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
if security.SessionHasPermission(c, "asset:read") {
|
||||
for _, step := range t.Steps {
|
||||
if step.Status != "running" && step.Status != "pausing" {
|
||||
continue
|
||||
}
|
||||
for i, id := range step.AssetIDs {
|
||||
if i >= 3 {
|
||||
break
|
||||
}
|
||||
a, readErr := h.db.GetAsset(id, database.RBACListAccess{UserID: session.UserID, Scope: session.ScopeFor("asset:read")})
|
||||
if readErr == nil {
|
||||
live.AssetNames[id] = a.Host
|
||||
if a.Host == "" {
|
||||
live.AssetNames[id] = a.IP
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
view["runtime"] = live
|
||||
}
|
||||
c.JSON(200, view)
|
||||
}
|
||||
func (h *AgentHandler) DeepAssessmentEvents(c *gin.Context) {
|
||||
if c.Query("latest") == "true" {
|
||||
events, err := h.deepAssessments.Store.RecentEvents(c.Param("id"), 100)
|
||||
if err != nil {
|
||||
deepAssessmentError(c, err)
|
||||
return
|
||||
}
|
||||
for i, j := 0, len(events)-1; i < j; i, j = i+1, j-1 {
|
||||
events[i], events[j] = events[j], events[i]
|
||||
}
|
||||
c.JSON(200, gin.H{"events": events})
|
||||
return
|
||||
}
|
||||
after, _ := strconv.ParseInt(c.Query("after"), 10, 64)
|
||||
list, err := h.deepAssessments.Store.Events(c.Param("id"), after)
|
||||
if err != nil {
|
||||
|
|
@ -315,6 +367,7 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) {
|
|||
Message string `json:"message"`
|
||||
StepID string `json:"step_id"`
|
||||
Reconciled bool `json:"reconciled"`
|
||||
Priority int `json:"priority"`
|
||||
}
|
||||
if !deepAssessmentBody(c, &req) {
|
||||
return
|
||||
|
|
@ -334,10 +387,17 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) {
|
|||
deepAssessmentError(c, fmt.Errorf("请先恢复归档,再操作测评"))
|
||||
return
|
||||
}
|
||||
if action == "guidance" && deepassessment.Active(t.Status) && t.ExecutorID != session.UserID {
|
||||
automaticPending := deepassessment.Active(t.Status) || t.Status == "recovering" || t.Status == "waiting_retry" || t.Status == "waiting_progress"
|
||||
if (action == "guidance" || action == "intent-guidance" || action == "intent-resume") && automaticPending && t.ExecutorID != session.UserID {
|
||||
c.JSON(403, gin.H{"error": "请先暂停,再以当前账号继续任务后补充方向"})
|
||||
return
|
||||
}
|
||||
if action == "intent-guidance" && automaticPending {
|
||||
if _, err = h.deepAssessmentRuntime.principal(t); err != nil {
|
||||
c.JSON(403, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
if action == "start" || action == "answer" || action == "guidance" {
|
||||
t.ExecutorID = session.UserID
|
||||
if _, err = h.deepAssessmentRuntime.principal(t); err != nil {
|
||||
|
|
@ -364,6 +424,14 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
switch action {
|
||||
case "intent-pause", "intent-resume", "intent-priority", "intent-guidance":
|
||||
if action == "intent-resume" && automaticPending {
|
||||
if _, err = h.deepAssessmentRuntime.principal(t); err != nil {
|
||||
c.JSON(403, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
err = h.deepAssessments.ControlStepAs(id, req.StepID, strings.TrimPrefix(action, "intent-"), req.Message, req.Priority, *req.Revision, session.UserID)
|
||||
case "archive", "restore":
|
||||
err = h.deepAssessments.SetArchived(id, *req.Revision, action == "archive")
|
||||
case "start":
|
||||
|
|
@ -417,6 +485,13 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) {
|
|||
h.deepAssessmentRuntime.steer(id, req.Message)
|
||||
}
|
||||
response := deepAssessmentView(c, t)
|
||||
if action == "intent-guidance" {
|
||||
delivered, deliveryErr := h.deepAssessmentRuntime.steerStep(id, req.StepID)
|
||||
response["guidance_delivered"] = delivered
|
||||
if deliveryErr != nil {
|
||||
response["guidance_queued"] = true
|
||||
}
|
||||
}
|
||||
if action == "answer" {
|
||||
if err = h.deepAssessments.Start(id, session.UserID, t.Revision); err != nil {
|
||||
response["start_error"] = err.Error()
|
||||
|
|
@ -438,10 +513,28 @@ func (h *AgentHandler) DeepAssessmentReport(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "生成时间:%s\n\n[打开本次测评](%s)\n\n", time.Now().UTC().Format(time.RFC3339), assessmentReportLink(c, t.ID, "", "overview"))
|
||||
fmt.Fprintf(&b, "# %s\n\n状态:%s\n\n## 目标\n%s\n\n## 范围\n%s\n\n## 验收条件\n%s\n\n## 当前结论\n%s\n\n## 路线\n%s\n", t.Name, t.Status, t.Objective, t.Scope, t.Criteria, t.Summary, t.Strategy)
|
||||
fmt.Fprintf(&b, "\n## 运行记录\n\n模式:持续执行\n\n累计规划:%d\n\n累计 Token:%d\n", t.Rounds, t.TokensUsed)
|
||||
fmt.Fprintf(&b, "\n## 运行记录\n\n类型:长程测评(当前状态见上方)\n\n累计规划:%d\n\n累计 Token:%d\n", t.Rounds, t.TokensUsed)
|
||||
if len(t.Guidance) > 0 {
|
||||
b.WriteString("\n## 人工补充\n")
|
||||
for _, note := range t.Guidance {
|
||||
reportLiteral(&b, note)
|
||||
}
|
||||
}
|
||||
for _, s := range t.Steps {
|
||||
fmt.Fprintf(&b, "\n## %s · %s [%s]\n\n%s\n\n前置:%s\n\n%s\n\n执行会话:%s\n\n证据回执:%s\n", s.ID, s.Title, s.Status, s.Instruction, strings.Join(s.DependsOn, ", "), s.Summary, s.ConversationID, strings.Join(s.Evidence, ", "))
|
||||
priority := s.Priority
|
||||
if priority == 0 {
|
||||
priority = 100
|
||||
}
|
||||
fmt.Fprintf(&b, "\n优先级:%d · 用户暂停:%t\n\n[打开来源意图与回执](%s)\n", priority, s.UserPaused, assessmentReportLink(c, t.ID, s.ID, "evidence"))
|
||||
if len(s.Guidance) > 0 {
|
||||
b.WriteString("\n### 对此意图的人工补充\n")
|
||||
for _, note := range s.Guidance {
|
||||
reportLiteral(&b, note)
|
||||
}
|
||||
}
|
||||
}
|
||||
for offset := 0; ; offset += 20 {
|
||||
facts, err := h.deepAssessments.Store.Facts(t.ID, "", offset)
|
||||
|
|
@ -456,6 +549,10 @@ func (h *AgentHandler) DeepAssessmentReport(c *gin.Context) {
|
|||
break
|
||||
}
|
||||
}
|
||||
if err = h.appendAssessmentFindingsReport(c, t, &b); err != nil {
|
||||
deepAssessmentError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Disposition", `attachment; filename="task-`+t.ID+`.md"`)
|
||||
c.Data(200, "text/markdown; charset=utf-8", []byte(b.String()))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ func (h *AgentHandler) DeepAssessmentGraph(c *gin.Context) {
|
|||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "80"))
|
||||
offset, _ := strconv.Atoi(c.Query("offset"))
|
||||
session, _ := security.CurrentSession(c)
|
||||
graph, err := h.deepAssessments.Store.GraphVisible(c.Param("id"), c.Query("scope"), limit, offset, func(n deepassessment.Node) bool {
|
||||
graph, err := h.deepAssessments.Store.GraphViewVisible(c.Param("id"), c.Query("scope"), c.Query("view"), limit, offset, func(n deepassessment.Node) bool {
|
||||
return n.Kind != "finding" || security.SessionHasPermission(c, "vulnerability:read") && h.db.UserCanAccessResource(session.UserID, session.ScopeFor("vulnerability:read"), "vulnerability", findingNodeID(n.ID))
|
||||
})
|
||||
if err != nil {
|
||||
|
|
@ -40,6 +40,18 @@ func (h *AgentHandler) DeepAssessmentNode(c *gin.Context) {
|
|||
deepAssessmentError(c, err)
|
||||
return
|
||||
}
|
||||
linksOffset, _ := strconv.Atoi(c.Query("links_offset"))
|
||||
session, _ := security.CurrentSession(c)
|
||||
links, err := h.deepAssessments.Store.RelationsVisible(c.Param("id"), c.Query("node_id"), linksOffset, func(n deepassessment.Node) bool {
|
||||
return n.Kind != "finding" || security.SessionHasPermission(c, "vulnerability:read") && h.db.UserCanAccessResource(session.UserID, session.ScopeFor("vulnerability:read"), "vulnerability", findingNodeID(n.ID))
|
||||
})
|
||||
if err != nil {
|
||||
deepAssessmentError(c, err)
|
||||
return
|
||||
}
|
||||
for key, value := range links {
|
||||
node[key] = value
|
||||
}
|
||||
c.JSON(200, node)
|
||||
}
|
||||
func assessmentGraphTools() []agentruntime.Tool {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,131 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/deepassessment"
|
||||
"cyberstrike-ai/internal/security"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func assessmentReportLink(c *gin.Context, task, step, tab string) string {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
q := url.Values{"assessment_id": {task}, "tab": {tab}}
|
||||
if step != "" {
|
||||
q.Set("step_id", step)
|
||||
}
|
||||
return scheme + "://" + c.Request.Host + "/#deep-assessments?" + q.Encode()
|
||||
}
|
||||
func reportLiteral(b *strings.Builder, text string) {
|
||||
fence := "```"
|
||||
for strings.Contains(text, fence) {
|
||||
fence += "`"
|
||||
}
|
||||
fmt.Fprintf(b, "\n%s\n%s\n%s\n", fence, text, fence)
|
||||
}
|
||||
func (h *AgentHandler) reportReviews(task, finding string) ([]database.AssessmentFindingReview, error) {
|
||||
rows, err := h.db.Query("SELECT id,step_id,verdict,reason,evidence_json,created_at FROM deep_assessment_finding_reviews WHERE task_id=? AND vulnerability_id=? ORDER BY created_at,id", task, finding)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []database.AssessmentFindingReview{}
|
||||
for rows.Next() {
|
||||
var r database.AssessmentFindingReview
|
||||
var evidence string
|
||||
if err = rows.Scan(&r.ID, &r.StepID, &r.Verdict, &r.Reason, &evidence, &r.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(evidence), &r.Evidence); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (h *AgentHandler) reportReceipt(b *strings.Builder, c *gin.Context, task, step, ref string) error {
|
||||
var id, tool, state, result, execution string
|
||||
err := h.db.QueryRow("SELECT id,tool,status,result,execution_id FROM deep_assessment_calls WHERE task_id=? AND step_id=? AND (id=? OR execution_id=?)", task, step, ref, ref).Scan(&id, &tool, &state, &result, &execution)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(b, "\n**回执 %s** · %s · %s\n\n[回到来源步骤与回执](%s)\n\n执行记录:%s\n\n已保存的回执摘录(完整执行过程请打开来源会话):\n", id, tool, state, assessmentReportLink(c, task, step, "evidence"), execution)
|
||||
reportLiteral(b, result)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *AgentHandler) appendAssessmentFindingsReport(c *gin.Context, t *deepassessment.Task, b *strings.Builder) error {
|
||||
b.WriteString("\n## 关联漏洞与复核\n\n以下仅包含当前账号有权查看的关联漏洞;已登记不等于已确认,复核结论单独列出。\n")
|
||||
if !security.SessionHasPermission(c, "vulnerability:read") {
|
||||
b.WriteString("\n当前账号没有漏洞读取权限,未导出漏洞详情。\n")
|
||||
return nil
|
||||
}
|
||||
session, _ := security.CurrentSession(c)
|
||||
access := database.RBACListAccess{UserID: session.UserID, Scope: session.ScopeFor("vulnerability:read")}
|
||||
filter := database.VulnerabilityListFilter{AssessmentID: t.ID, SummaryOnly: true}
|
||||
count := 0
|
||||
for offset := 0; ; offset += 50 {
|
||||
rows, err := h.db.ListVulnerabilitiesByGroupForAccess(50, offset, filter, access, "none", "latest")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if !h.db.UserCanAccessResource(session.UserID, access.Scope, "vulnerability", row.ID) {
|
||||
continue
|
||||
}
|
||||
v, err := h.db.GetVulnerability(row.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if v.AssessmentID != t.ID {
|
||||
continue
|
||||
}
|
||||
v.AssessmentReviews, err = h.reportReviews(t.ID, v.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count++
|
||||
fmt.Fprintf(b, "\n### %d. %s\n\n漏洞 ID:%s · 严重程度:%s · 状态:%s\n\n来源意图:%s · %s\n\n[测评中的漏洞与证据](%s)\n", count, strings.ReplaceAll(v.Title, "\n", " "), v.ID, v.Severity, v.Status, v.AssessmentStepID, v.AssessmentStepTitle, assessmentReportLink(c, t.ID, v.AssessmentStepID, "evidence")+"&vulnerability_id="+url.QueryEscape(v.ID))
|
||||
for _, field := range []struct{ name, text string }{{"目标", v.Target}, {"说明", v.Description}, {"前置条件", v.Preconditions}, {"复现步骤", v.ReproSteps}, {"复现证据", v.Evidence}, {"影响", v.Impact}, {"修复建议", v.Recommendation}, {"复测说明", v.RetestNotes}, {"复测历史", v.RetestLog}} {
|
||||
if field.text != "" {
|
||||
fmt.Fprintf(b, "\n#### %s\n", field.name)
|
||||
reportLiteral(b, field.text)
|
||||
}
|
||||
}
|
||||
independent := false
|
||||
for _, review := range v.AssessmentReviews {
|
||||
independent = independent || review.Verdict != "reported"
|
||||
}
|
||||
if !independent {
|
||||
b.WriteString("\n尚无独立复核记录。\n")
|
||||
}
|
||||
for _, review := range v.AssessmentReviews {
|
||||
label := "独立复核"
|
||||
if review.Verdict == "reported" {
|
||||
label = "首次登记"
|
||||
}
|
||||
fmt.Fprintf(b, "\n#### %s · %s\n\n意图:%s · 时间:%s\n\n[查看复核步骤与原始回执](%s)\n", label, review.Verdict, review.StepID, review.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), assessmentReportLink(c, t.ID, review.StepID, "evidence"))
|
||||
reportLiteral(b, review.Reason)
|
||||
for _, ref := range review.Evidence {
|
||||
if err := h.reportReceipt(b, c, t.ID, review.StepID, ref); err != nil {
|
||||
return fmt.Errorf("读取关联复核回执失败: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(rows) < 50 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
b.WriteString("\n当前账号可见的关联漏洞为 0;这不代表全部资产不存在漏洞。\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -30,6 +30,14 @@ type deepAssessmentRuntime struct {
|
|||
snapshot func() (*config.Config, error)
|
||||
}
|
||||
|
||||
type assessmentStepControl struct {
|
||||
mu sync.Mutex
|
||||
activityMu sync.RWMutex
|
||||
native agentruntime.Control
|
||||
sent int
|
||||
activity deepassessment.SessionActivity
|
||||
}
|
||||
|
||||
func (r *deepAssessmentRuntime) principal(t *deepassessment.Task) (authctx.Principal, error) {
|
||||
access, err := r.h.db.ResolveRBACAccess(t.ExecutorID)
|
||||
if err != nil || access == nil || !access.User.Enabled {
|
||||
|
|
@ -231,7 +239,7 @@ func transientDeepAssessmentModelError(err error) bool {
|
|||
func (r *deepAssessmentRuntime) Plan(ctx context.Context, t *deepassessment.Task) (deepassessment.Proposal, error) {
|
||||
var p deepassessment.Proposal
|
||||
err := r.generate(ctx, t, `你是深度测评的规划器。本轮是全新的 Pi 会话,决策只依赖持久态势、队列、事实和原始回执,不依赖前一轮对话。只规划,不执行探测。
|
||||
步骤就是意图:一句话的开放方向,大于命令、小于整个任务。具体资产须填写 asset_ids(先查询 assessment_assets);来源事实填 source_ids;priority 为 1–1000,数字越小越优先,默认 100。方向先入队,执行并行数不会限制保存的方向总量。
|
||||
步骤就是意图:一句话的开放方向,大于命令、小于整个任务。具体资产须填写 asset_ids(先查询 assessment_assets);来源事实填 source_ids;priority 为 1–1000,数字越小越优先,默认 100。方向先入队,执行并行数不会限制保存的方向总量。用户手动暂停的意图(user_paused=true 或 paused/pausing)只能由用户继续;不得退休、重命名或复制方向绕过暂停,其他可行意图照常推进。每条意图的 guidance 只约束该意图。
|
||||
先用 assessment_intents 检查未执行及在跑方向,禁止换措辞重复派发。查看 observed/inferred 事实及真实回执;失败状态、负面推断、版本号不能自动证明方向封死。reported 漏洞需派另一条独立意图实际复现并提交 assessment_review_finding,不能只读报告自证。发现高价值入口应深入,覆盖统计用于验收而非浅测刷数。
|
||||
只在有材料性新事实、资产或不同验证机理时重新探索旧方向;没有新方向时提交空增量等待,禁止为保持运行编造方向。强依赖方向保留在队列中等前置完成。
|
||||
每次只增加 0 到 8 个具体、有边界的步骤(单次增量,不限制累计数量)。参考探索图与 Pi 历史摘要,先展开相关历史、核对原证据;source_ids 可引用启发本步骤的图节点 ID,留下复用链路。保留一条清楚的长期路线,按依赖逐步推进。可并行的步骤没有依赖;需要前一步结果的步骤必须 depends_on。每一步由完整 Pi Agent 执行,不要拆成单条命令。
|
||||
|
|
@ -306,7 +314,15 @@ func (r *deepAssessmentRuntime) Run(ctx context.Context, t *deepassessment.Task,
|
|||
if err = checkpoint(conv.ID, initialSummary); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if latest, readErr := h.deepAssessments.Store.Get(t.ID); readErr == nil {
|
||||
if current := latest.Step(step.ID); current != nil {
|
||||
step.Guidance = current.Guidance
|
||||
}
|
||||
}
|
||||
contract := fmt.Sprintf("Assessment mandate (authoritative user task):\nGoal: %s\nScope: %s\nAcceptance: %s\nThis step [%s]: %s\n%s", t.Objective, t.Scope, t.Criteria, step.ID, step.Title, step.Instruction)
|
||||
for _, note := range step.Guidance[max(0, len(step.Guidance)-12):] {
|
||||
contract += "\nUser direction for this intent: " + note
|
||||
}
|
||||
snapshot, snapshotErr := r.intentSnapshot(t, step)
|
||||
if snapshotErr != nil {
|
||||
return out, snapshotErr
|
||||
|
|
@ -412,6 +428,7 @@ func (r *deepAssessmentRuntime) Run(ctx context.Context, t *deepassessment.Task,
|
|||
}
|
||||
runCtx = multiagent.WithPiRunOptions(runCtx, multiagent.PiRunOptions{Native: native,
|
||||
Event: func(e agentruntime.Event) {
|
||||
r.trackStepActivity(t.ID, step.ID, e)
|
||||
if err := r.piSummary(t.ID, step.ID, e); err != nil {
|
||||
cancel(err)
|
||||
}
|
||||
|
|
@ -425,7 +442,8 @@ func (r *deepAssessmentRuntime) Run(ctx context.Context, t *deepassessment.Task,
|
|||
},
|
||||
Bind: func(control agentruntime.Control) func() {
|
||||
key := t.ID + "/" + step.ID
|
||||
r.controls.Store(key, control)
|
||||
r.controls.Store(key, &assessmentStepControl{native: control, sent: len(step.Guidance)})
|
||||
_, _ = r.steerStep(t.ID, step.ID)
|
||||
return func() { r.controls.Delete(key) }
|
||||
},
|
||||
BeforeTool: func(c context.Context, call agentruntime.ToolCall) error {
|
||||
|
|
@ -436,7 +454,8 @@ func (r *deepAssessmentRuntime) Run(ctx context.Context, t *deepassessment.Task,
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Status != "running" {
|
||||
currentStep := current.Step(step.ID)
|
||||
if current.Status != "running" || currentStep == nil || currentStep.Status != "running" || currentStep.UserPaused || c.Err() != nil {
|
||||
return fmt.Errorf("assessment stopped")
|
||||
}
|
||||
if assessmentInternalTool(call.Name) {
|
||||
|
|
@ -788,8 +807,87 @@ func assessmentInternalTool(name string) bool {
|
|||
func (r *deepAssessmentRuntime) steer(task, note string) {
|
||||
r.controls.Range(func(key, value any) bool {
|
||||
if strings.HasPrefix(key.(string), task+"/") {
|
||||
_ = value.(agentruntime.Control).Steer(note)
|
||||
if value.(*assessmentStepControl).native.Steer != nil {
|
||||
_ = value.(*assessmentStepControl).native.Steer(note)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (r *deepAssessmentRuntime) steerStep(task, step string) (bool, error) {
|
||||
value, ok := r.controls.Load(task + "/" + step)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
control := value.(*assessmentStepControl)
|
||||
control.mu.Lock()
|
||||
defer control.mu.Unlock()
|
||||
if control.native.Steer == nil {
|
||||
return false, nil
|
||||
}
|
||||
t, err := r.h.deepAssessments.Store.Get(task)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
st := t.Step(step)
|
||||
if st == nil {
|
||||
return false, fmt.Errorf("unknown intent")
|
||||
}
|
||||
if t.Status != "running" || st.Status != "running" || st.UserPaused {
|
||||
return false, nil
|
||||
}
|
||||
for control.sent < len(st.Guidance) {
|
||||
if err = control.native.Steer(st.Guidance[control.sent]); err != nil {
|
||||
return false, err
|
||||
}
|
||||
control.sent++
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *deepAssessmentRuntime) trackStepActivity(task, step string, event agentruntime.Event) {
|
||||
value, ok := r.controls.Load(task + "/" + step)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
control := value.(*assessmentStepControl)
|
||||
stage := ""
|
||||
tool := ""
|
||||
switch event.Type {
|
||||
case "agent_start", "turn_start", "message_start", "message_update", "compaction_end":
|
||||
stage = "model"
|
||||
case "tool_execution_start", "tool_execution_update":
|
||||
stage = "tool"
|
||||
var data struct {
|
||||
ToolName string `json:"toolName"`
|
||||
}
|
||||
_ = json.Unmarshal(event.Data, &data)
|
||||
tool = data.ToolName
|
||||
case "compaction_start":
|
||||
stage = "compacting"
|
||||
case "auto_retry_start":
|
||||
stage = "retrying"
|
||||
case "tool_execution_end", "agent_end", "agent_settled":
|
||||
stage = "idle"
|
||||
default:
|
||||
return
|
||||
}
|
||||
control.activityMu.Lock()
|
||||
control.activity = deepassessment.SessionActivity{Stage: stage, Tool: tool, UpdatedAt: time.Now().UTC()}
|
||||
control.activityMu.Unlock()
|
||||
}
|
||||
func (r *deepAssessmentRuntime) sessionActivity(task string) map[string]deepassessment.SessionActivity {
|
||||
out := map[string]deepassessment.SessionActivity{}
|
||||
r.controls.Range(func(key, value any) bool {
|
||||
prefix := task + "/"
|
||||
if strings.HasPrefix(key.(string), prefix) {
|
||||
control := value.(*assessmentStepControl)
|
||||
control.activityMu.RLock()
|
||||
out[strings.TrimPrefix(key.(string), prefix)] = control.activity
|
||||
control.activityMu.RUnlock()
|
||||
}
|
||||
return true
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/agentruntime"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/deepassessment"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
)
|
||||
|
||||
func TestDeepAssessmentTargetedGuidancePersistsAndUsesOnlyOnePiControl(t *testing.T) {
|
||||
h, task := deepAssessmentFixture(t)
|
||||
h.deepAssessments.Store.Change(task.ID, "", "seed", "", func(v *deepassessment.Task) error {
|
||||
v.Status = "running"
|
||||
v.Steps = []deepassessment.Step{{ID: "one", Status: "running"}, {ID: "two", Status: "running"}}
|
||||
return nil
|
||||
})
|
||||
var first, second []string
|
||||
h.deepAssessmentRuntime.controls.Store(task.ID+"/one", &assessmentStepControl{native: agentruntime.Control{Steer: func(note string) error { first = append(first, note); return nil }}})
|
||||
h.deepAssessmentRuntime.controls.Store(task.ID+"/two", &assessmentStepControl{native: agentruntime.Control{Steer: func(note string) error { second = append(second, note); return nil }}})
|
||||
current, _ := h.deepAssessments.Store.Get(task.ID)
|
||||
if err := h.deepAssessments.ControlStep(task.ID, "one", "guidance", "Only review this intent", 0, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if _, err := h.deepAssessmentRuntime.steerStep(task.ID, "one"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if len(first) != 1 || len(second) != 0 {
|
||||
t.Fatal(first, second)
|
||||
}
|
||||
h.deepAssessmentRuntime.trackStepActivity(task.ID, "one", agentruntime.Event{Type: "compaction_start"})
|
||||
h.deepAssessmentRuntime.trackStepActivity(task.ID, "two", agentruntime.Event{Type: "tool_execution_start", Data: json.RawMessage(`{"toolName":"fixture-read","args":{"private":"not exposed"}}`)})
|
||||
activity := h.deepAssessmentRuntime.sessionActivity(task.ID)
|
||||
if activity["one"].Stage != "compacting" || activity["two"].Tool != "fixture-read" {
|
||||
t.Fatal(activity)
|
||||
}
|
||||
if len(h.deepAssessmentRuntime.sessionActivity("foreign-task")) != 0 {
|
||||
t.Fatal("cross-task runtime activity exposed")
|
||||
}
|
||||
current, _ = h.deepAssessments.Store.Get(task.ID)
|
||||
if len(current.Guidance) != 0 || len(current.Step("one").Guidance) != 1 {
|
||||
t.Fatal(current)
|
||||
}
|
||||
h.deepAssessments.Store.Change(task.ID, "", "seed", "", func(v *deepassessment.Task) error {
|
||||
v.Step("one").Status = "paused"
|
||||
v.Step("one").UserPaused = true
|
||||
return nil
|
||||
})
|
||||
current, _ = h.deepAssessments.Store.Get(task.ID)
|
||||
if err := h.deepAssessments.ControlStep(task.ID, "one", "guidance", "Saved for later", 0, current.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delivered, err := h.deepAssessmentRuntime.steerStep(task.ID, "one")
|
||||
if err != nil || delivered || len(first) != 1 {
|
||||
t.Fatal(delivered, err, first)
|
||||
}
|
||||
graph, err := h.deepAssessments.Store.Graph(task.ID, "", 80, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := 0
|
||||
for _, n := range graph.Nodes {
|
||||
if n.Kind == "guidance" {
|
||||
if n.StepID != "one" {
|
||||
t.Fatal(n)
|
||||
}
|
||||
found++
|
||||
}
|
||||
}
|
||||
if found != 2 {
|
||||
t.Fatal("targeted directions lack durable provenance", found)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepAssessmentRuntimeOverviewUsesTaskScopedRecords(t *testing.T) {
|
||||
h, task := deepAssessmentFixture(t)
|
||||
conv, _ := h.db.CreateConversation("own step", database.ConversationCreateMeta{})
|
||||
h.db.SetResourceOwner("conversation", conv.ID, task.OwnerID)
|
||||
h.deepAssessments.Store.Change(task.ID, "one", "checkpoint", "saved progress", func(v *deepassessment.Task) error {
|
||||
v.Status = "running"
|
||||
v.Steps = []deepassessment.Step{{ID: "one", Title: "Active fixture", Status: "running", ConversationID: conv.ID}}
|
||||
return nil
|
||||
})
|
||||
for _, exec := range []*mcp.ToolExecution{{ID: "own-exec", ToolName: "fixture-read", Status: "running", ConversationID: conv.ID, StartTime: time.Now(), Arguments: map[string]any{}}, {ID: "foreign-exec", ToolName: "private-tool", Status: "running", ConversationID: "foreign", StartTime: time.Now(), Arguments: map[string]any{}}} {
|
||||
if err := h.db.SaveToolExecution(exec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
router := assessmentRouter(h, task.OwnerID)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task?runtime=true&step_limit=1", nil))
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), "own-exec") || strings.Contains(w.Body.String(), "foreign-exec") {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
var data struct {
|
||||
Runtime deepassessment.RuntimeOverview `json:"runtime"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &data)
|
||||
if len(data.Runtime.Intents) != 1 || data.Runtime.Counts["running"] != 1 || len(data.Runtime.Recent) == 0 {
|
||||
t.Fatal(data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepAssessmentReportIncludesAuthorizedFindingsReviewsAndReceipts(t *testing.T) {
|
||||
h, task := deepAssessmentFixture(t)
|
||||
origin, _ := h.db.CreateConversation("origin", database.ConversationCreateMeta{})
|
||||
review, _ := h.db.CreateConversation("review", database.ConversationCreateMeta{})
|
||||
h.db.SetResourceOwner("conversation", origin.ID, task.OwnerID)
|
||||
h.db.SetResourceOwner("conversation", review.ID, task.OwnerID)
|
||||
h.deepAssessments.Store.Change(task.ID, "", "seed", "", func(v *deepassessment.Task) error {
|
||||
v.Steps = []deepassessment.Step{{ID: "origin", Status: "running", ConversationID: origin.ID}, {ID: "review", Status: "running", ConversationID: review.ID}}
|
||||
return nil
|
||||
})
|
||||
for _, step := range []string{"origin", "review"} {
|
||||
call := agentruntime.ToolCall{ID: step + "-call", Name: "fixture-read"}
|
||||
if err := h.deepAssessments.Store.BeginCall(task.ID, step, call); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.deepAssessments.Store.FinishCall(call, agentruntime.ToolResult{Content: step + " preserved evidence\n``` literal fence", ExecutionID: step + "-execution"}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
v, err := h.db.CreateVulnerability(&database.Vulnerability{ID: "visible-finding", ConversationID: origin.ID, Title: "Visible finding", Severity: "high", ReproSteps: "First reproduce the fixture", Evidence: "Recorded proof", EvidenceReceiptIDs: []string{"origin-call"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = h.db.ReviewAssessmentFinding(task.ID, "review", v.ID, "confirmed", "Independent fixture confirmation", []string{"review-call"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Report history is not limited to the inspector's newest 100 review rows.
|
||||
for i := 0; i < 101; i++ {
|
||||
_, err = h.db.Exec("INSERT INTO deep_assessment_finding_reviews(id,vulnerability_id,task_id,step_id,verdict,reason,evidence_json,created_at) VALUES(?,?,?,'review','inconclusive',?,'[]',?)", fmt.Sprint("history-", i), v.ID, task.ID, fmt.Sprint("history marker ", i), time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
other, _ := h.db.CreateRBACUser("private-owner", "Private owner", "hash", true, nil)
|
||||
privateConv, _ := h.db.CreateConversation("private origin", database.ConversationCreateMeta{})
|
||||
h.db.SetResourceOwner("conversation", privateConv.ID, other.ID)
|
||||
h.deepAssessments.Store.Change(task.ID, "", "seed", "", func(v *deepassessment.Task) error {
|
||||
v.Steps = append(v.Steps, deepassessment.Step{ID: "private-origin", Status: "completed", ConversationID: privateConv.ID})
|
||||
return nil
|
||||
})
|
||||
private, err := h.db.CreateVulnerability(&database.Vulnerability{ID: "private-finding", ConversationID: privateConv.ID, Title: "DO_NOT_EXPORT", Severity: "low"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.db.SetResourceOwner("vulnerability", private.ID, other.ID)
|
||||
router := assessmentFindingRouter(h, task.OwnerID, map[string]bool{"assessments:read": true, "vulnerability:read": true})
|
||||
router.GET("/api/deep-assessments/:id/report", h.DeepAssessmentReport)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task/report", nil))
|
||||
text := w.Body.String()
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, text)
|
||||
}
|
||||
for _, expected := range []string{"Visible finding", "Independent fixture confirmation", "origin preserved evidence", "review preserved evidence", "history marker 0", "history marker 100", "vulnerability_id=visible-finding", "````"} {
|
||||
if !strings.Contains(text, expected) {
|
||||
t.Fatal("report missing", expected)
|
||||
}
|
||||
}
|
||||
if strings.Contains(text, "DO_NOT_EXPORT") {
|
||||
t.Fatal("report leaked a private finding")
|
||||
}
|
||||
without := assessmentRouter(h, task.OwnerID)
|
||||
w = httptest.NewRecorder()
|
||||
without.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task/report", nil))
|
||||
if w.Code != 200 || strings.Contains(w.Body.String(), "Visible finding") || strings.Contains(w.Body.String(), "Independent fixture confirmation") {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
|
@ -21,7 +21,7 @@ async function fixture(t){
|
|||
const batch={id:'batch-finding',title:'批量任务原有漏洞',severity:'medium',status:'open',description:'batch fixture',target:'https://batch.example.test',task_id:'same-id',task_queue_id:'batch-queue',task_queue_title:'原批量队列',created_at:now,updated_at:now};
|
||||
const state={task,sourceStep,finding,batch,requests:[],errors:[],canOpen:true};
|
||||
const locale=JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<','\\u003c');
|
||||
const scripts=['router','auth','modal','vulnerability','assessment-finding-links','vulnerability-workspace','assessment-node-panel','assessment-exploration-views','deep-assessment-graph','deep-assessments'].map(x=>`<script src="/static/js/${x}.js"></script>`).join('');
|
||||
const scripts=['router','auth','modal','vulnerability','assessment-finding-links','vulnerability-workspace','assessment-workbench','assessment-node-panel','assessment-exploration-views','deep-assessment-graph','deep-assessments'].map(x=>`<script src="/static/js/${x}.js"></script>`).join('');
|
||||
const styles=['style','mobile','vulnerability-workspace','vulnerability-list','deep-assessments','design-system'].map(x=>`<link rel="stylesheet" href="/static/css/${x}.css">`).join('');
|
||||
const html=`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${styles}</head><body><div class="container"><main class="main-layout"><section class="content-area">${div('page-deep-assessments')}${div('page-vulnerabilities')}<div class="page" id="page-chat"></div></section></main></div>${div('vulnerability-inspector')}<script>window.t=(key,opts={})=>{const v=key.split('.').reduce((o,k)=>o&&o[k],${locale});return String(v||key).replace(/{{(\\w+)}}/g,(_,k)=>String(opts[k]??''))};window.loadConversation=async id=>{window.visitedConversation=id};window.initializeChatUI=()=>{};window.refreshAppData=async()=>{};</script><script src="/static/vendor/cytoscape.min.js"></script>${scripts}<script>document.removeEventListener('DOMContentLoaded',initializeApp);saveAuth('fixture-token',new Date(Date.now()+3600000),{user:{id:'fixture',username:'fixture'},permissions:['assessments:read','assessments:write','vulnerability:read','vulnerability:write','chat:read','chat:write','project:read'],scope:'own'});</script></body></html>`;
|
||||
const server=http.createServer(async(req,res)=>{
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ const sample = id => ({ id, name: '隔离样例 ' + id, status: 'draft', revisio
|
|||
async function fixture(t) {
|
||||
const state = { tasks: new Map(Array.from({ length: 24 }, (_, i) => ['t' + i, sample('t' + i)])), requests: [], errors: [], sharedAssets: [], linkedAssets: new Map() };
|
||||
const locale = JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<', '\\u003c');
|
||||
const scripts = ['router', 'auth', 'assessment-node-panel','assessment-exploration-views','deep-assessment-graph', 'deep-assessments'].map(x => `<script src="/static/js/${x}.js"></script>`).join('');
|
||||
const scripts = ['router', 'auth', 'assessment-workbench','assessment-node-panel','assessment-exploration-views','deep-assessment-graph', 'deep-assessments'].map(x => `<script src="/static/js/${x}.js"></script>`).join('');
|
||||
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${['style', 'mobile', 'deep-assessments', 'design-system'].map(x=>`<link rel="stylesheet" href="/static/css/${x}.css">`).join('')}</head><body><div class="container"><main class="main-layout"><section class="content-area">${region}<div class="page" id="page-chat"></div><div class="page" id="page-tasks"></div></section></main></div><script>window.t=k=>k.split('.').reduce((o,p)=>o&&o[p],${locale})||k;window.loadConversation=async id=>{window.visitedConversation=id};window.initializeChatUI=()=>{};window.refreshAppData=async()=>{};</script><script src="/static/vendor/cytoscape.min.js"></script><script>const originalGraph=window.cytoscape;window.cytoscape=(...args)=>{const chart=originalGraph(...args);window.fixtureGraph=chart;return chart};</script>${scripts}<script>document.removeEventListener('DOMContentLoaded',initializeApp);saveAuth('fixture-token',new Date(Date.now()+3600000),{user:{id:'fixture',username:'fixture'},permissions:['assessments:read','assessments:write','assessments:delete','agent:execute','chat:read','chat:write','tasks:read','asset:read'],scope:'own'});</script></body></html>`;
|
||||
const server = http.createServer(async (req,res)=>{
|
||||
const url = new URL(req.url,'http://fixture');
|
||||
|
|
@ -44,8 +44,8 @@ async function fixture(t) {
|
|||
}
|
||||
if(match[2]==='facts'){const facts=(task.facts||[]).filter(f=>!url.searchParams.get('confidence')||f.confidence===url.searchParams.get('confidence'));return send(200,{facts,next_offset:facts.length,has_more:false});}
|
||||
if(match[2]?.startsWith('steps/'))return send(200,{step:task.steps.find(s=>s.id===match[2].slice(6))});
|
||||
if(match[2]==='graph')return send(200,graph);
|
||||
if(match[2]==='graph/node'){const node=graph.nodes.find(n=>n.id===url.searchParams.get('node_id'));if(!node)return send(404,{error:'missing node'});return send(200,{node,next_offset:node.body.length,has_more:false});}
|
||||
if(match[2]==='graph'){const summary=url.searchParams.get('view')==='summary';const nodes=summary?graph.nodes.filter(n=>!['receipt','observation'].includes(n.kind)):graph.nodes;const ids=new Set(nodes.map(n=>n.id));return send(200,{...graph,nodes,edges:graph.edges.filter(e=>ids.has(e.source)&&ids.has(e.target)),primary_count:nodes.filter(n=>!n.boundary).length-1,details_hidden:graph.nodes.length-nodes.length,boundary_total:graph.boundary_total||0});}
|
||||
if(match[2]==='graph/node'){const node=graph.nodes.find(n=>n.id===url.searchParams.get('node_id'));if(!node)return send(404,{error:'missing node'});const refs=graph.edges.flatMap(e=>e.target===node.id?[{direction:'upstream',relation:e.relation,node:graph.nodes.find(n=>n.id===e.source)}]:e.source===node.id?[{direction:'downstream',relation:e.relation,node:graph.nodes.find(n=>n.id===e.target)}]:[]).filter(r=>r.node);return send(200,{node,next_offset:node.body.length,has_more:false,relations:refs,relations_next_offset:refs.length,relations_has_more:false});}
|
||||
if(match[2]==='events')return send(200,{events:[]});
|
||||
if(match[2]==='receipts')return send(200,{receipts:[],next_offset:0,has_more:false});
|
||||
if(match[2]==='report'){res.setHeader('Content-Type','text/markdown');return res.end('# fixture report');}
|
||||
|
|
@ -56,6 +56,10 @@ async function fixture(t) {
|
|||
task.steps.forEach(s=>{if(s.status==='uncertain')s.status='pending';});
|
||||
}
|
||||
const action=match[2].split('/')[1];if(action==='start')task.status='running';if(action==='pause')task.status='paused';if(action==='archive'){task.archived=true;if(!['draft','completed','cancelled'].includes(task.status))task.status='paused';}if(action==='restore')task.archived=false;if(action==='guidance')task.summary=body.message;if(action==='budget')Object.assign(task,body);task.revision++;
|
||||
if(action==='intent-pause'){const st=task.steps.find(s=>s.id===body.step_id);st.status='paused';st.user_paused=true;}
|
||||
if(action==='intent-resume'){const st=task.steps.find(s=>s.id===body.step_id);st.status='pending';st.user_paused=false;}
|
||||
if(action==='intent-priority')task.steps.find(s=>s.id===body.step_id).priority=body.priority;
|
||||
if(action==='intent-guidance'){const st=task.steps.find(s=>s.id===body.step_id);(st.guidance||=[]).push(body.message);}
|
||||
if(action==='retry'){
|
||||
const step=task.steps.find(s=>s.id===body.step_id);if(!step||!body.reconciled)return send(400,{error:'review required'});
|
||||
step.status='pending';task.status=task.steps.some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status))?'needs_review':'paused';
|
||||
|
|
@ -65,7 +69,7 @@ async function fixture(t) {
|
|||
const queue=url.searchParams.get('step_order')==='queue',filter=url.searchParams.get('step_status');
|
||||
const steps=(task.steps||[]).filter(s=>!queue||!filter||s.status===filter||filter==='needs_review'&&['uncertain','cleanup_unconfirmed'].includes(s.status));
|
||||
const stepOffset=Number(url.searchParams.get('step_offset')||0),stepLimit=Number(url.searchParams.get('step_limit')||steps.length);
|
||||
return send(200,{task:{...task,steps:steps.slice(stepOffset,stepOffset+stepLimit)},intent_counts:counts,step_total:steps.length,step_has_more:stepOffset+stepLimit<steps.length});
|
||||
return send(200,{runtime:{live:{active:task.status==='running',planning:false,workers:counts.running||0},counts,intents:(task.steps||[]).filter(s=>s.status==='running'),tools:[],recent:[],facts:0,findings:0,findings_visible:true,asset_names:{},...task.runtime},guidance_delivered:match[2]==='control/intent-guidance'&&task.status==='running'&&task.steps.find(s=>s.id===body?.step_id)?.status==='running',task:{...task,steps:steps.slice(stepOffset,stepOffset+stepLimit)},intent_counts:counts,step_total:steps.length,step_has_more:stepOffset+stepLimit<steps.length});
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const executablePath=process.env.CHROME_PATH||(process.platform==='darwin'?'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome':undefined);
|
||||
|
|
@ -161,6 +165,7 @@ test('continuous assessment workspace shows graph memories and returns to the li
|
|||
const pager=await page.locator('.da-pagination').boundingBox();assert.ok(pager.y+pager.height<=1000);
|
||||
await page.locator('[data-da-action="select"][data-id="t0"]').click();
|
||||
const inspector=page.locator('#da-workspace');await inspector.waitFor({state:'visible'});
|
||||
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
|
||||
await page.locator('#da-graph-select option[value="memory:pi1"]').waitFor({state:'attached'});
|
||||
assert.ok(await page.locator('#da-graph-canvas canvas').count()>0);
|
||||
await page.locator('#da-graph-select').selectOption('memory:pi1');
|
||||
|
|
@ -278,6 +283,7 @@ test('detail is a full page and browser back restores the filtered task list',as
|
|||
assert.ok(Math.abs(detail.width-root.width)<2);assert.equal(await page.locator('dialog[open]').count(),0);
|
||||
assert.equal(await page.locator('#da-list-view').isVisible(),false);
|
||||
assert.equal(await page.locator('#da-guidance').isVisible(),false);
|
||||
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
|
||||
const canvas=await page.locator('#da-graph-canvas').boundingBox();assert.ok(canvas.width>1000&&canvas.height>=400);
|
||||
await page.goBack();await page.locator('#da-list-view').waitFor();
|
||||
assert.equal(await page.locator('#da-search').inputValue(),'隔离样例 t0');
|
||||
|
|
@ -294,6 +300,7 @@ test('graph preserves the viewport through polling, side panel resize and tab ch
|
|||
// A review/proof cycle must not flatten the entire graph into one column.
|
||||
task.graph.edges.push({source:'step:s6',target:'step:s3',relation:'supports'});
|
||||
await page.locator('[data-da-action="details"][data-id="t0"]').click();
|
||||
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
|
||||
await page.locator('#da-graph-select option[value="step:s3"]').waitFor({state:'attached'});
|
||||
const before=await page.locator('#da-graph-canvas').boundingBox();
|
||||
const navigator=page.locator('.da-graph-minimap');await navigator.waitFor({state:'visible'});
|
||||
|
|
@ -303,7 +310,7 @@ test('graph preserves the viewport through polling, side panel resize and tab ch
|
|||
const positions=await page.evaluate(()=>Object.fromEntries(fixtureGraph.nodes().map(n=>[n.id(),n.position()])));
|
||||
assert.ok(new Set(Object.values(positions).map(p=>p.x)).size>2);
|
||||
await page.locator('#da-graph-select').selectOption('step:s3');
|
||||
await page.locator('#da-graph-node h4').waitFor();
|
||||
await page.locator('#da-graph-node .da-node-heading h3').waitFor();
|
||||
await page.waitForFunction(width=>document.getElementById('da-graph-canvas').clientWidth<width-200,before.width);
|
||||
assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),.8);
|
||||
await page.locator('[data-da-action="graph-details"]').click();
|
||||
|
|
@ -336,6 +343,7 @@ test('long node details have an adjustable reader and keep their position throug
|
|||
{id:'receipt:sample',kind:'receipt',step_id:'read',title:'本地样例回执',state:'completed',body:Array.from({length:120},(_,i)=>`record ${i}: example.test /fixture — verified fixture`).join('\n'),source:{tool:'fixture'}}
|
||||
],edges:[{source:'goal',target:'step:read',relation:'plans'},{source:'step:read',target:'receipt:sample',relation:'executes'}],total:2,folded:0,has_more:false};
|
||||
await page.locator('[data-da-action="details"][data-id="t0"]').click();
|
||||
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();await page.locator('[data-da-action="graph-view"][data-view="full"]').click();
|
||||
await page.locator('#da-graph-select').selectOption('step:read');
|
||||
await page.locator('.da-node-heading h3').waitFor();
|
||||
const panel=page.locator('#da-graph-node'),content=panel.locator('.da-node-content'),bar=page.getByRole('separator');
|
||||
|
|
@ -439,7 +447,9 @@ test('large cyclic evidence graphs keep lineage and focus a selected node at rea
|
|||
}
|
||||
task.graph={nodes,edges,total:nodes.length-1,folded:0,has_more:false};
|
||||
await page.locator('[data-da-action="details"][data-id="t0"]').click();
|
||||
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
|
||||
await page.locator('#da-graph-select option[value="step:5"]').waitFor({state:'attached'});
|
||||
await page.locator('[data-da-action="graph-view"][data-view="full"]').click();await page.waitForFunction(()=>fixtureGraph.nodes().length===73);
|
||||
const graphState=await page.evaluate(()=>({nodes:fixtureGraph.nodes().length,edges:fixtureGraph.edges().length,columns:new Set(fixtureGraph.nodes().map(n=>n.position().x)).size}));
|
||||
assert.equal(graphState.nodes,nodes.length);assert.equal(graphState.edges,edges.length);assert.ok(graphState.columns>5);
|
||||
await page.locator('#da-graph-select').selectOption('step:5');
|
||||
|
|
@ -529,3 +539,61 @@ test('start resumes confirmed cancellations and pause also stops scheduled retri
|
|||
assert.equal(task.status,'paused');assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')).length,1);
|
||||
assert.deepEqual(state.errors,[]);
|
||||
});
|
||||
|
||||
test('live overview and intent controls keep sibling work and scoped guidance independent',async t=>{
|
||||
const {page,state}=await fixture(t),task=state.tasks.get('t0');
|
||||
task.name='持续测评工作台样例';task.status='running';task.steps=[{id:'one',title:'核对应用入口',status:'running',instruction:'本地样例步骤',priority:100,asset_ids:['asset-one'],conversation_id:'conv-one'},{id:'two',title:'整理服务证据',status:'running',instruction:'另一条本地样例步骤',priority:100,asset_ids:['asset-two'],conversation_id:'conv-two'}];
|
||||
task.runtime={sessions:{two:{stage:'compacting',updated_at:new Date().toISOString()}},tools:[{id:'exec-one',step_id:'one',tool:'fixture_read',status:'running',started_at:new Date(Date.now()-90000).toISOString(),output_bytes:2048}],recent:[{id:1,step_id:'one',kind:'checkpoint',message:'已保存样例观察,等待原始回执。',created_at:new Date().toISOString()}],facts:3,findings:1,findings_visible:true,asset_names:{'asset-one':'app.example.test','asset-two':'service.example.test'}};
|
||||
await page.locator('[data-da-action="details"][data-id="t0"]').click();
|
||||
await page.locator('.da-live-board').waitFor();
|
||||
assert.match(await page.locator('.da-live-board').innerText(),/fixture_read/);assert.match(await page.locator('.da-live-board').innerText(),/app.example.test/);
|
||||
assert.equal(await page.locator('.da-live-intent').count(),2);assert.match(await page.locator('.da-live-intent').nth(1).innerText(),/Pi 正在压缩上下文/);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
|
||||
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'workbench-live-overview.png'),fullPage:true});
|
||||
task.runtime.recent=Array.from({length:8},(_,i)=>({id:i+1,step_id:'one',kind:'checkpoint',message:'较早的进展记录。'.repeat(20),created_at:new Date().toISOString()}));await page.evaluate(()=>DeepAssessments.refresh());
|
||||
await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop=240);
|
||||
const reading=await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop);
|
||||
task.runtime.recent.unshift({id:9,step_id:'one',kind:'checkpoint',message:'NEW_PROGRESS_FOR_READER',created_at:new Date().toISOString()});await page.evaluate(()=>DeepAssessments.refresh());
|
||||
assert.equal(await page.locator('#da-overview-updates').isVisible(),true);assert.doesNotMatch(await page.locator('.da-live-events').innerText(),/NEW_PROGRESS_FOR_READER/);assert.equal(await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop),reading);
|
||||
await page.locator('#da-overview-updates').click();assert.match(await page.locator('.da-live-events').innerText(),/NEW_PROGRESS_FOR_READER/);
|
||||
await page.locator('.da-live-intent').first().getByRole('button',{name:'查看此意图',exact:true}).click();
|
||||
const step=page.locator('.da-step[data-step="one"]');await step.waitFor();
|
||||
await step.getByRole('button',{name:'暂停此意图',exact:true}).click();await step.getByRole('button',{name:'继续此意图',exact:true}).waitFor();
|
||||
assert.equal(task.status,'running');assert.equal(task.steps[0].status,'paused');assert.equal(task.steps[1].status,'running');
|
||||
await step.getByRole('combobox',{name:'意图优先级',exact:true}).selectOption('10');await page.waitForFunction(()=>document.querySelector('[data-da-intent-priority="one"]').value==='10');
|
||||
await step.locator('details[data-da-detail="intent-guidance:one"] > summary').click();
|
||||
let input=step.getByRole('textbox',{name:'给此意图补充方向',exact:true});await input.fill('只调整这一条意图的方向');
|
||||
await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await input.inputValue(),'只调整这一条意图的方向');
|
||||
await input.evaluate(el=>{el.dataset.fixture='same';el.focus();el.setSelectionRange(3,3);});await page.evaluate(()=>DeepAssessments.refresh());
|
||||
assert.equal(await input.getAttribute('data-fixture'),'same');
|
||||
task.steps[1].summary='Sibling progress changed';await page.evaluate(()=>DeepAssessments.refresh());
|
||||
assert.equal(await input.inputValue(),'只调整这一条意图的方向');assert.equal(await input.evaluate(el=>el===document.activeElement&&el.selectionStart===3),true);
|
||||
await step.getByRole('button',{name:'提交给此意图',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-da-intent-guidance="one"] textarea').value==='');
|
||||
assert.deepEqual(task.steps[0].guidance,['只调整这一条意图的方向']);assert.equal(task.steps[1].guidance,undefined);assert.deepEqual(task.guidance||[],[]);
|
||||
const sent=state.requests.find(r=>r.path.endsWith('/control/intent-guidance'));assert.equal(sent.body.step_id,'one');
|
||||
assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')||r.path.endsWith('/control/pause')).length,0);
|
||||
await step.getByRole('button',{name:'继续此意图',exact:true}).click();await step.getByRole('button',{name:'暂停此意图',exact:true}).waitFor();
|
||||
assert.equal(task.steps[0].status,'pending');assert.equal(task.steps[1].status,'running');
|
||||
await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
|
||||
await page.locator('#page-deep-assessments').evaluate(async el=>{await Promise.all(el.getAnimations({subtree:true}).filter(a=>a.effect?.getComputedTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})));});
|
||||
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'workbench-intent-mobile.png'),fullPage:true});
|
||||
assert.deepEqual(state.errors,[]);
|
||||
});
|
||||
|
||||
test('main graph exposes cross-page references and drills into original execution records',async t=>{
|
||||
const {page,state}=await fixture(t),task=state.tasks.get('t0');
|
||||
task.graph={nodes:[{id:'goal',kind:'goal',title:'样例目标',body:'goal',source:{}},{id:'step:one',kind:'step',step_id:'one',title:'当前意图',body:'current intent',source:{}},{id:'step:outside',kind:'step',step_id:'outside',title:'其他页面的上游意图',body:'upstream original',boundary:true,source:{}},{id:'receipt:one',kind:'receipt',step_id:'one',title:'原始执行回执',body:'original fixture output',source:{}}],edges:[{source:'goal',target:'step:outside',relation:'plans'},{source:'step:outside',target:'step:one',relation:'depends_on'},{source:'step:one',target:'receipt:one',relation:'executes'}],total:2,boundary_total:1,folded:0,has_more:false};
|
||||
await page.locator('[data-da-action="details"][data-id="t0"]').click();await page.getByRole('tab',{name:'探索图',exact:true}).click();
|
||||
await page.locator('#da-graph-select').selectOption('step:one');await page.locator('.da-node-relations').first().waitFor();
|
||||
assert.equal(await page.evaluate(()=>fixtureGraph.getElementById('receipt:one').length),0);
|
||||
assert.match(await page.locator('#da-graph-meta').innerText(),/跨页引用/);
|
||||
await page.locator('#da-graph-node [data-da-action="graph-open"][data-node="step:outside"]').click();
|
||||
await page.waitForFunction(()=>location.hash.includes('graph_scope=step%3Aoutside'));
|
||||
await page.waitForFunction(()=>document.querySelector('#da-graph-node').textContent.includes('upstream original'));
|
||||
await page.locator('#da-graph-select').selectOption('step:one');
|
||||
await page.locator('#da-graph-node [data-da-action="graph-open"][data-node="receipt:one"]').click();
|
||||
await page.waitForFunction(()=>document.querySelector('#da-graph-node').textContent.includes('original fixture output'));
|
||||
assert.match(page.url(),/graph_view=full/);assert.equal(await page.evaluate(()=>fixtureGraph.getElementById('receipt:one').length),1);
|
||||
await page.reload();await page.locator('#da-graph-select').waitFor();
|
||||
assert.ok(state.requests.some(r=>r.path.endsWith('/graph')&&r.query.scope==='receipt:one'&&r.query.view==='full'));
|
||||
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);assert.deepEqual(state.errors,[]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ module.exports = async function ({ page, width, height, theme, out }) {
|
|||
for (const script of [
|
||||
"tasks",
|
||||
"skills",
|
||||
"assessment-workbench",
|
||||
"assessment-node-panel",
|
||||
"assessment-exploration-views",
|
||||
"deep-assessment-graph",
|
||||
|
|
|
|||
|
|
@ -346,3 +346,18 @@ body.da-drawer-open { overflow: hidden; }
|
|||
|
||||
.da-review-status { border:0; padding:0; background:transparent; cursor:pointer; }
|
||||
.da-review-status:hover .da-badge { text-decoration:underline; }
|
||||
.da-live-board { margin:18px 0; }.da-live-heading { display:flex; align-items:center; gap:16px; flex-wrap:wrap; }.da-live-heading h3 { margin:0; font-size:18px; }.da-live-heading > span { margin-left:auto; color:var(--text-secondary); font-size:13px; }
|
||||
.da-live-counts { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin:14px 0 20px; }.da-live-counts > span { color:var(--text-secondary); font-size:13px; padding:6px; }
|
||||
.da-live-intents { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr)); gap:12px; }.da-live-intent { padding:16px; min-width:0; border:1px solid var(--border-color); border-radius:8px; background:var(--bg-secondary); }.da-live-intent-head { display:flex; gap:10px; justify-content:space-between; align-items:flex-start; }.da-live-intent-head strong { overflow-wrap:anywhere; }.da-live-tools { font-size:13px; line-height:1.7; }.da-live-tools code { overflow-wrap:anywhere; }.da-live-summary { color:var(--text-secondary); font-size:13px; line-height:1.7; overflow-wrap:anywhere; }
|
||||
.da-live-events { display:grid; gap:8px; }.da-live-events article { padding:12px; border-left:3px solid var(--border-color); font-size:13px; }.da-live-events small { color:var(--text-secondary); }.da-live-events p { margin:6px 0; white-space:pre-wrap; overflow-wrap:anywhere; line-height:1.7; }
|
||||
.da-task-brief { border-top:1px solid var(--border-color); padding-top:14px; margin-top:18px; }.da-task-brief > summary { cursor:pointer; font-weight:600; }.da-task-brief .da-section { margin-top:18px; }
|
||||
.da-intent-controls { padding-top:14px; margin-top:14px; border-top:1px solid var(--border-color); }.da-intent-controls .da-controls label { display:flex; align-items:center; gap:8px; font-size:13px; }.da-intent-controls select { width:130px; }.da-intent-controls details { margin-top:12px; }.da-intent-controls summary { cursor:pointer; }.da-intent-controls p { overflow-wrap:anywhere; }.da-intent-controls form { display:grid; gap:10px; }.da-intent-controls form button { justify-self:start; }
|
||||
.da-node-relations { margin:18px 0; }.da-node-relations button { display:block; width:100%; text-align:left; margin:6px 0; white-space:normal; overflow-wrap:anywhere; font-size:13px; }
|
||||
.da-graph-toolbar [aria-pressed="true"] { color:var(--accent-color); border-color:var(--accent-color); }
|
||||
@media(max-width:650px){.da-live-heading > span{margin-left:0;}.da-intent-controls .da-controls{align-items:stretch;}.da-intent-controls .da-controls label{flex-wrap:wrap;}}
|
||||
|
||||
.da-live-native { font-size:12px; color:var(--text-secondary); line-height:1.7; overflow-wrap:anywhere; }
|
||||
|
||||
#da-workspace { position:relative; }
|
||||
#da-overview-updates { position:absolute; z-index:4; right:28px; bottom:62px; border-color:var(--accent-color); color:var(--accent-color); box-shadow:0 3px 12px #0002; }
|
||||
#da-overview-updates[hidden] { display:none; }
|
||||
|
|
|
|||
|
|
@ -5383,7 +5383,8 @@
|
|||
"summary": "Compaction summary",
|
||||
"note": "Recorded observation",
|
||||
"user": "User supplied",
|
||||
"folded": "Folded"
|
||||
"folded": "Folded",
|
||||
"superseded": "Superseded archive"
|
||||
},
|
||||
"findings": "Findings",
|
||||
"noFindings": "No registered findings yet.",
|
||||
|
|
@ -5466,7 +5467,9 @@
|
|||
"guides": "guides",
|
||||
"exposes": "exposes",
|
||||
"associated_with": "associated with",
|
||||
"serves": "serves"
|
||||
"serves": "serves",
|
||||
"via_archive": "via archive",
|
||||
"via_details": "via execution records"
|
||||
},
|
||||
"scopeOptional": "Additional restrictions and exclusions (optional)",
|
||||
"criteriaOptional": "Acceptance criteria (optional)",
|
||||
|
|
@ -5513,7 +5516,91 @@
|
|||
"autoResumeState": "Resume after service restart",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"autoResumeHint": "Opening the page does not start work. Automatic recovery applies to work running before restart, not drafts, manually paused assessments, or pending reviews."
|
||||
"autoResumeHint": "Opening the page does not start work. Automatic recovery applies to work running before restart, not drafts, manually paused assessments, or pending reviews.",
|
||||
"mainGraph": "Main lineage",
|
||||
"fullGraph": "Execution records",
|
||||
"graphRefs": "Page references",
|
||||
"graphHidden": "Collapsed execution records",
|
||||
"graphOverflow": "More cross-page relations are available in node details",
|
||||
"upstream": "Upstream sources",
|
||||
"downstream": "Downstream outputs",
|
||||
"moreRelations": "More relations",
|
||||
"openBranch": "Locate related branch",
|
||||
"guidanceDelivered": "Sent to this intent",
|
||||
"guidanceQueued": "Saved for this intent to continue",
|
||||
"workbench": {
|
||||
"live": "Live activity",
|
||||
"planning": "Planning",
|
||||
"reviewing": "Independent review",
|
||||
"executing": "Executing",
|
||||
"scheduling": "Scheduling",
|
||||
"draining": "Stopping and cleaning up",
|
||||
"waiting": "Waiting for new progress",
|
||||
"retrying": "Waiting for model recovery",
|
||||
"nextWake": "Next wake-up",
|
||||
"recent": "Recent progress",
|
||||
"noRecent": "No recent progress recorded",
|
||||
"active": "Current intents",
|
||||
"noActive": "No intents are executing",
|
||||
"tools": "Tool activity",
|
||||
"noTools": "Waiting for the model or next tool call",
|
||||
"facts": "Facts",
|
||||
"findings": "Linked findings",
|
||||
"queue": "Intent queue",
|
||||
"openStep": "View intent",
|
||||
"conversation": "Execution session",
|
||||
"pause": "Pause intent",
|
||||
"resume": "Continue intent",
|
||||
"priority": "Intent priority",
|
||||
"urgent": "Urgent",
|
||||
"high": "High",
|
||||
"normal": "Normal",
|
||||
"low": "Low",
|
||||
"guidance": "Add direction to this intent",
|
||||
"targetHint": "Sent only to this intent. Paused intents keep it for their next continuation.",
|
||||
"send": "Send to this intent",
|
||||
"lastDirection": "Latest direction",
|
||||
"manualPause": "This intent was manually paused",
|
||||
"brief": "Objective and assessment requirements",
|
||||
"route": "Last planned approach",
|
||||
"summary": "Current conclusions / gaps",
|
||||
"output": "Output received",
|
||||
"linkedAssets": "Linked assets",
|
||||
"elapsed": "Elapsed",
|
||||
"min": "min",
|
||||
"sec": "sec",
|
||||
"emptyReview": "No steps need review",
|
||||
"events": {
|
||||
"started": "Assessment started / continued",
|
||||
"step_started": "Intent started",
|
||||
"planning": "Updating plan",
|
||||
"plan_updated": "Plan updated",
|
||||
"checkpoint": "Progress saved",
|
||||
"step_result": "Intent result",
|
||||
"settled": "Scheduling settled",
|
||||
"stop_requested": "Pause / stop requested",
|
||||
"intent_pause": "Intent pause requested",
|
||||
"intent_resume": "Intent returned to queue",
|
||||
"intent_priority": "Priority changed",
|
||||
"intent_guidance": "Targeted direction received",
|
||||
"waiting_progress": "Waiting for new progress",
|
||||
"waiting_retry": "Waiting for model recovery",
|
||||
"waiting_input": "Waiting for an answer",
|
||||
"blocked": "Execution blocked",
|
||||
"guidance": "Direction received",
|
||||
"retry_scheduled": "Model retry scheduled",
|
||||
"review_gap": "Acceptance gaps remain",
|
||||
"shutdown": "Saving progress and shutting down",
|
||||
"retry": "Step requeued"
|
||||
},
|
||||
"native_model": "Model processing",
|
||||
"native_tool": "Processing tool call",
|
||||
"native_compacting": "Pi compacting context",
|
||||
"native_retrying": "Pi retrying model request",
|
||||
"native_idle": "Waiting for next turn",
|
||||
"lastNative": "Last activity"
|
||||
},
|
||||
"liveUpdates": "Updates available — view latest"
|
||||
},
|
||||
"assessmentFindingLinks": {
|
||||
"source": "Source assessment",
|
||||
|
|
|
|||
|
|
@ -5396,7 +5396,8 @@
|
|||
"summary": "Сводка сжатия",
|
||||
"note": "Наблюдение",
|
||||
"user": "От пользователя",
|
||||
"folded": "Свернуто"
|
||||
"folded": "Свернуто",
|
||||
"superseded": "Заменённый архив"
|
||||
},
|
||||
"findings": "Уязвимости",
|
||||
"noFindings": "Уязвимости пока не зарегистрированы.",
|
||||
|
|
@ -5479,7 +5480,9 @@
|
|||
"guides": "направляет",
|
||||
"exposes": "предоставляет",
|
||||
"associated_with": "связан с",
|
||||
"serves": "обслуживает"
|
||||
"serves": "обслуживает",
|
||||
"via_archive": "через архив",
|
||||
"via_details": "через записи выполнения"
|
||||
},
|
||||
"scopeOptional": "Дополнительные ограничения и исключения (необязательно)",
|
||||
"criteriaOptional": "Критерии приёмки (необязательно)",
|
||||
|
|
@ -5526,7 +5529,91 @@
|
|||
"autoResumeState": "Возобновление после перезапуска сервиса",
|
||||
"enabled": "Включено",
|
||||
"disabled": "Выключено",
|
||||
"autoResumeHint": "Открытие страницы не запускает работу. Автовосстановление применяется к работе до перезапуска, но не к черновикам, ручной паузе или ожидающим проверки задачам."
|
||||
"autoResumeHint": "Открытие страницы не запускает работу. Автовосстановление применяется к работе до перезапуска, но не к черновикам, ручной паузе или ожидающим проверки задачам.",
|
||||
"mainGraph": "Основные связи",
|
||||
"fullGraph": "Записи выполнения",
|
||||
"graphRefs": "Ссылки на другие страницы",
|
||||
"graphHidden": "Свёрнутые записи выполнения",
|
||||
"graphOverflow": "Другие связи доступны в деталях узла",
|
||||
"upstream": "Источники",
|
||||
"downstream": "Результаты",
|
||||
"moreRelations": "Другие связи",
|
||||
"openBranch": "Найти связанную ветвь",
|
||||
"guidanceDelivered": "Отправлено этому намерению",
|
||||
"guidanceQueued": "Сохранено для продолжения намерения",
|
||||
"workbench": {
|
||||
"live": "Текущая активность",
|
||||
"planning": "Планирование",
|
||||
"reviewing": "Независимая проверка",
|
||||
"executing": "Выполнение",
|
||||
"scheduling": "Планирование запуска",
|
||||
"draining": "Остановка и очистка",
|
||||
"waiting": "Ожидание новых результатов",
|
||||
"retrying": "Ожидание восстановления модели",
|
||||
"nextWake": "Следующее пробуждение",
|
||||
"recent": "Последние изменения",
|
||||
"noRecent": "Новых записей пока нет",
|
||||
"active": "Текущие намерения",
|
||||
"noActive": "Выполняемых намерений нет",
|
||||
"tools": "Активность инструментов",
|
||||
"noTools": "Ожидание модели или следующего вызова",
|
||||
"facts": "Факты",
|
||||
"findings": "Связанные уязвимости",
|
||||
"queue": "Очередь намерений",
|
||||
"openStep": "Открыть намерение",
|
||||
"conversation": "Сеанс выполнения",
|
||||
"pause": "Приостановить намерение",
|
||||
"resume": "Продолжить намерение",
|
||||
"priority": "Приоритет намерения",
|
||||
"urgent": "Срочный",
|
||||
"high": "Высокий",
|
||||
"normal": "Обычный",
|
||||
"low": "Низкий",
|
||||
"guidance": "Уточнить направление намерения",
|
||||
"targetHint": "Только для этого намерения. При паузе сохраняется до продолжения.",
|
||||
"send": "Отправить намерению",
|
||||
"lastDirection": "Последнее уточнение",
|
||||
"manualPause": "Намерение приостановлено вручную",
|
||||
"brief": "Цель и требования оценки",
|
||||
"route": "Последний план",
|
||||
"summary": "Текущие выводы / пробелы",
|
||||
"output": "Получено данных",
|
||||
"linkedAssets": "Связанные активы",
|
||||
"elapsed": "Прошло",
|
||||
"min": "мин",
|
||||
"sec": "с",
|
||||
"emptyReview": "Проверка не требуется",
|
||||
"events": {
|
||||
"started": "Оценка запущена / продолжена",
|
||||
"step_started": "Намерение запущено",
|
||||
"planning": "Обновление плана",
|
||||
"plan_updated": "План обновлён",
|
||||
"checkpoint": "Прогресс сохранён",
|
||||
"step_result": "Результат намерения",
|
||||
"settled": "Планирование завершено",
|
||||
"stop_requested": "Запрошена пауза / остановка",
|
||||
"intent_pause": "Запрошена пауза намерения",
|
||||
"intent_resume": "Намерение возвращено в очередь",
|
||||
"intent_priority": "Приоритет изменён",
|
||||
"intent_guidance": "Получено уточнение намерения",
|
||||
"waiting_progress": "Ожидание новых результатов",
|
||||
"waiting_retry": "Ожидание восстановления модели",
|
||||
"waiting_input": "Ожидание ответа",
|
||||
"blocked": "Выполнение заблокировано",
|
||||
"guidance": "Получено направление",
|
||||
"retry_scheduled": "Повтор модели запланирован",
|
||||
"review_gap": "Есть пробелы приёмки",
|
||||
"shutdown": "Сохранение и завершение",
|
||||
"retry": "Шаг возвращён в очередь"
|
||||
},
|
||||
"native_model": "Обработка моделью",
|
||||
"native_tool": "Выполнение инструмента",
|
||||
"native_compacting": "Pi сжимает контекст",
|
||||
"native_retrying": "Pi повторяет запрос модели",
|
||||
"native_idle": "Ожидание следующего хода",
|
||||
"lastNative": "Последняя активность"
|
||||
},
|
||||
"liveUpdates": "Есть обновления — показать последние"
|
||||
},
|
||||
"assessmentFindingLinks": {
|
||||
"source": "Исходная оценка",
|
||||
|
|
|
|||
|
|
@ -5371,7 +5371,8 @@
|
|||
"summary": "压缩摘要",
|
||||
"note": "观察记录",
|
||||
"user": "用户提供",
|
||||
"folded": "已折叠"
|
||||
"folded": "已折叠",
|
||||
"superseded": "已替代的归档"
|
||||
},
|
||||
"findings": "关联漏洞",
|
||||
"noFindings": "暂未登记漏洞。",
|
||||
|
|
@ -5455,7 +5456,95 @@
|
|||
"autoResumeState": "服务重启后自动续跑",
|
||||
"enabled": "已开启",
|
||||
"disabled": "已关闭",
|
||||
"autoResumeHint": "打开页面不会启动任务;自动续跑只针对重启前的执行,草稿、手动暂停和待核对任务不会自动开始。"
|
||||
"autoResumeHint": "打开页面不会启动任务;自动续跑只针对重启前的执行,草稿、手动暂停和待核对任务不会自动开始。",
|
||||
"mainGraph": "主链路",
|
||||
"fullGraph": "执行记录",
|
||||
"graphRefs": "跨页引用",
|
||||
"graphHidden": "已收起执行记录",
|
||||
"graphOverflow": "还有跨页关联,可在节点详情中继续查看",
|
||||
"upstream": "上游来源",
|
||||
"downstream": "下游产出",
|
||||
"moreRelations": "继续查看关联",
|
||||
"openBranch": "定位关联分支",
|
||||
"guidanceDelivered": "已发送给此意图",
|
||||
"guidanceQueued": "已保存,将在此意图继续时生效",
|
||||
"workbench": {
|
||||
"live": "运行态势",
|
||||
"planning": "规划中",
|
||||
"reviewing": "独立验收中",
|
||||
"executing": "执行中",
|
||||
"scheduling": "正在调度",
|
||||
"draining": "正在停止并收尾",
|
||||
"waiting": "等待新进展",
|
||||
"retrying": "等待模型恢复",
|
||||
"nextWake": "下次唤醒",
|
||||
"recent": "最近进展",
|
||||
"noRecent": "暂无新进展记录",
|
||||
"active": "当前意图",
|
||||
"noActive": "当前没有在执行的意图",
|
||||
"tools": "工具活动",
|
||||
"noTools": "等待模型或下一次工具调用",
|
||||
"facts": "事实",
|
||||
"findings": "关联漏洞",
|
||||
"queue": "意图队列",
|
||||
"openStep": "查看此意图",
|
||||
"conversation": "执行会话",
|
||||
"pause": "暂停此意图",
|
||||
"resume": "继续此意图",
|
||||
"priority": "意图优先级",
|
||||
"urgent": "优先",
|
||||
"high": "较高",
|
||||
"normal": "普通",
|
||||
"low": "较低",
|
||||
"guidance": "给此意图补充方向",
|
||||
"targetHint": "只发送给此意图;意图暂停时保存,继续后生效。",
|
||||
"send": "提交给此意图",
|
||||
"lastDirection": "最近补充",
|
||||
"manualPause": "此意图已手动暂停",
|
||||
"brief": "目标与测评要求",
|
||||
"route": "最近规划路线",
|
||||
"summary": "当前结论 / 缺口",
|
||||
"output": "已有输出",
|
||||
"linkedAssets": "关联资产",
|
||||
"elapsed": "已持续",
|
||||
"min": "分钟",
|
||||
"sec": "秒",
|
||||
"emptyReview": "无待核对步骤",
|
||||
"events": {
|
||||
"started": "开始/继续测评",
|
||||
"step_started": "意图开始执行",
|
||||
"planning": "更新计划",
|
||||
"plan_updated": "计划已更新",
|
||||
"checkpoint": "已保存进展",
|
||||
"step_result": "意图执行结果",
|
||||
"settled": "调度已结束",
|
||||
"stop_requested": "暂停/停止请求",
|
||||
"intent_pause": "暂停此意图",
|
||||
"intent_resume": "意图已恢复排队",
|
||||
"intent_priority": "优先级已调整",
|
||||
"intent_guidance": "收到定向补充",
|
||||
"waiting_progress": "等待新进展",
|
||||
"waiting_retry": "等待模型恢复",
|
||||
"waiting_input": "等待答复",
|
||||
"blocked": "执行受阻",
|
||||
"guidance": "收到补充方向",
|
||||
"retry_scheduled": "稍后重试模型",
|
||||
"review_gap": "验收仍有缺口",
|
||||
"shutdown": "保存进度并关闭",
|
||||
"retry": "步骤已重新排队"
|
||||
},
|
||||
"native_model": "模型处理中",
|
||||
"native_tool": "工具处理中",
|
||||
"native_compacting": "Pi 正在压缩上下文",
|
||||
"native_retrying": "Pi 正在重试模型请求",
|
||||
"native_idle": "等待下一轮",
|
||||
"lastNative": "最近活动"
|
||||
},
|
||||
"graphRelations": {
|
||||
"via_archive": "经归档",
|
||||
"via_details": "经执行记录"
|
||||
},
|
||||
"liveUpdates": "有更新,查看最新"
|
||||
},
|
||||
"assessmentFindingLinks": {
|
||||
"source": "来源深度测评",
|
||||
|
|
|
|||
|
|
@ -4,12 +4,16 @@
|
|||
const labels = { reader: '展开阅读', back: '返回图', close: '关闭节点详情', source: '证据与来源', summary: '结果摘要', instruction: '执行说明', content: '节点内容', output: '执行回执' };
|
||||
const text = key => { const path='deepAssessments.nodeReader.'+key, value=window.t?.(path); return value && value!==path ? value : labels[key] || key; };
|
||||
const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]);
|
||||
const rendered=new WeakMap();
|
||||
function sections(node) {
|
||||
const body=String(node.body||''), delimiter='\n\nInstruction: ', split=node.kind==='step'?body.indexOf(delimiter):-1;
|
||||
if(split>=0) return [{label:text('summary'),body:body.slice(0,split)},{label:text('instruction'),body:body.slice(split+delimiter.length)}].filter(section=>section.body.trim());
|
||||
return [{label:text(node.kind==='receipt'?'output':'content'),body,code:node.kind==='receipt'}];
|
||||
}
|
||||
function render(panel, options) {
|
||||
const signature=JSON.stringify(options);
|
||||
if(rendered.get(panel)===signature){window.DeepAssessments?.syncDetailPanels();return;}
|
||||
rendered.set(panel,signature);
|
||||
const key=options.key||options.id||'';
|
||||
const same=panel.dataset.nodeKey===key;
|
||||
const scroll=same?(panel.querySelector('.da-node-content')?.scrollTop||0):0;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
/* Live task presentation and per-intent controls. Execution stays in the host/Pi. */
|
||||
(function(){
|
||||
'use strict';
|
||||
const labels={native_model:'模型处理中',native_tool:'工具处理中',native_compacting:'Pi 正在压缩上下文',native_retrying:'Pi 正在重试模型请求',native_idle:'等待下一轮',lastNative:'最近活动',live:'运行态势',planning:'规划中',reviewing:'独立验收中',executing:'执行中',scheduling:'正在调度',draining:'正在停止并收尾',waiting:'等待新进展',retrying:'等待模型恢复',nextWake:'下次唤醒',recent:'最近进展',noRecent:'暂无新进展记录',active:'当前意图',noActive:'当前没有在执行的意图',tools:'工具活动',noTools:'等待模型或下一次工具调用',facts:'事实',findings:'关联漏洞',queue:'意图队列',openStep:'查看此意图',conversation:'执行会话',pause:'暂停此意图',resume:'继续此意图',priority:'意图优先级',urgent:'优先',high:'较高',normal:'普通',low:'较低',guidance:'给此意图补充方向',targetHint:'只发送给此意图;意图暂停时保存,继续后生效。',send:'提交给此意图',lastDirection:'最近补充',manualPause:'此意图已手动暂停',brief:'目标与测评要求',route:'最近规划路线',summary:'当前结论 / 缺口',output:'已有输出',linkedAssets:'关联资产',elapsed:'已持续',min:'分钟',sec:'秒',emptyReview:'无待核对步骤'};
|
||||
const L=k=>{const path='deepAssessments.workbench.'+k,v=window.t?.(path);return v&&v!==path?v:labels[k]||k;};
|
||||
const eventLabels={started:'开始/继续测评',step_started:'意图开始执行',planning:'更新计划',plan_updated:'计划已更新',checkpoint:'已保存进展',step_result:'意图执行结果',settled:'调度已结束',stop_requested:'暂停/停止请求',intent_pause:'暂停此意图',intent_resume:'意图已恢复排队',intent_priority:'优先级已调整',intent_guidance:'收到定向补充',waiting_progress:'等待新进展',waiting_retry:'等待模型恢复',waiting_input:'等待答复',blocked:'执行受阻',guidance:'收到补充方向',retry_scheduled:'稍后重试模型',review_gap:'验收仍有缺口',shutdown:'保存进度并关闭',retry:'步骤已重新排队'};
|
||||
const eventLabel=kind=>{const key='deepAssessments.workbench.events.'+kind,v=window.t?.(key);return v&&v!==key?v:eventLabels[kind]||L('recent');};
|
||||
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]);
|
||||
const button=(action,label,attrs='')=>`<button type="button" class="btn-secondary" data-da-action="${action}" ${attrs}>${esc(label)}</button>`;
|
||||
const time=v=>v?new Date(v).toLocaleString():'—';
|
||||
const elapsed=v=>{const n=Math.max(0,Math.floor((Date.now()-Date.parse(v))/1000));return Number.isFinite(n)?(n>=60?Math.floor(n/60)+' '+L('min'):n+' '+L('sec')):'—';};
|
||||
function overview(task,data,status){
|
||||
if(!data)return '';
|
||||
const live=data.live||{},counts=data.counts||{},tools=data.tools||[];
|
||||
let phase=status(task.status);
|
||||
if(['pausing','cancelling'].includes(task.status))phase=L('draining');else if(task.status==='running')phase=[live.planning?L('planning'):'',live.reviewing?L('reviewing'):'',live.workers?L('executing'):''].filter(Boolean).join(' · ')||L('scheduling');
|
||||
else if(task.status==='waiting_progress')phase=L('waiting');else if(task.status==='waiting_retry')phase=L('retrying');
|
||||
const cards=(data.intents||[]).map(st=>{
|
||||
const activity=tools.filter(t=>t.step_id===st.id),native=data.sessions?.[st.id];
|
||||
const names=(st.asset_ids||[]).filter(id=>data.asset_names?.[id]);
|
||||
return `<article class="da-live-intent"><div class="da-live-intent-head"><strong>${esc(st.title)}</strong><span class="da-badge da-${esc(st.status)}">${esc(status(st.status))}</span></div>${names.length?`<p>${names.map(id=>button('intent-asset',data.asset_names[id],`data-asset="${esc(id)}"`)).join(' ')}</p>`:(st.asset_ids||[]).length?`<p class="da-muted">${L('linkedAssets')} · ${st.asset_ids.length}</p>`:''}${native?.stage?`<p class="da-live-native">${esc(L('native_'+native.stage))}${native.tool?' · '+esc(native.tool):''} · ${esc(L('lastNative'))} ${esc(time(native.updated_at))}</p>`:''}<div class="da-live-tools">${activity.length?activity.map(call=>`<p><code>${esc(call.tool)}</code> · ${esc(status(call.status==='queued'?'pending':call.status))} · ${esc(L('elapsed'))} <span class="da-live-age" data-started="${esc(call.started_at)}">${esc(elapsed(call.started_at))}</span>${call.output_bytes?` · ${esc(L('output'))} ${Math.ceil(call.output_bytes/1024)} KB`:''}</p>`).join(''):native?.stage?'':`<p class="da-muted">${esc(L('noTools'))}</p>`}</div>${st.summary?`<p class="da-live-summary">${esc(st.summary)}</p>`:''}<div class="da-controls">${button('show-step',L('openStep'),`data-step="${esc(st.id)}"`)}${st.conversation_id?button('conversation',L('conversation'),`data-conversation="${esc(st.conversation_id)}"`):''}</div></article>`;
|
||||
}).join('');
|
||||
return `<section class="da-live-board"><div class="da-live-heading"><h3>${esc(L('live'))}</h3><strong>${esc(phase)}</strong>${task.next_wake?`<span>${esc(L('nextWake'))}:${esc(time(task.next_wake))}</span>`:''}</div><div class="da-live-counts">${['running','pending','paused','completed','blocked','uncertain'].map(k=>button('queue-status',status(k)+' '+(counts[k]||0),`data-status="${k}"`)).join('')}<span>${esc(L('facts'))} ${data.facts||0}</span>${data.findings_visible?button('tab',L('findings')+' '+(data.findings||0),'data-tab="findings"'):''}</div><h4>${esc(L('active'))}</h4><div class="da-live-intents">${cards||`<p class="da-muted">${esc(L('noActive'))}</p>`}</div><h4>${esc(L('recent'))}</h4><div class="da-live-events">${(data.recent||[]).map(event=>`<article><small>${esc(time(event.created_at))} · ${esc(eventLabel(event.kind))}</small><p>${esc(event.message)}</p>${event.step_id?button('show-step',L('openStep'),`data-step="${esc(event.step_id)}"`):''}</article>`).join('')||`<p class="da-muted">${esc(L('noRecent'))}</p>`}</div></section>`;
|
||||
}
|
||||
function controls(step,task,write,draft){
|
||||
if(!write||task.archived||['completed','cancelled'].includes(task.status)||['completed','retired'].includes(step.status))return '';
|
||||
const attr=`data-step="${esc(step.id)}"`,busy=['pausing','cancelling'].includes(task.status);
|
||||
let actions='';
|
||||
if(['running','pending','failed','blocked'].includes(step.status))actions+=button('intent-pause',L('pause'),attr+(busy?' disabled':''));
|
||||
if(step.status==='paused')actions+=button('intent-resume',L('resume'),attr+(busy?' disabled':''));
|
||||
const priority=step.priority||100,options=[1,10,100,500];if(!options.includes(priority))options.push(priority);
|
||||
actions+=`<label>${esc(L('priority'))}<select class="form-control" data-da-intent-priority="${esc(step.id)}" aria-label="${esc(L('priority'))}" ${busy?'disabled':''}>${options.sort((a,b)=>a-b).map(p=>`<option value="${p}" ${p===priority?'selected':''}>${p} · ${esc(({1:L('urgent'),10:L('high'),100:L('normal'),500:L('low')})[p]||p)}</option>`).join('')}</select></label>`;
|
||||
return `<section class="da-intent-controls"><div class="da-controls">${actions}</div>${step.user_paused?`<p class="da-muted">${esc(L('manualPause'))}</p>`:''}<details data-da-detail="intent-guidance:${esc(step.id)}"><summary>${esc(L('guidance'))}</summary><p class="da-muted">${esc(L('targetHint'))}</p>${step.guidance?.length?`<p>${esc(L('lastDirection'))}:${esc(step.guidance.at(-1))}</p>`:''}<form data-da-intent-guidance="${esc(step.id)}"><textarea class="form-control" aria-label="${esc(L('guidance'))}" rows="3" maxlength="8000" required>${esc(draft||'')}</textarea><button type="submit" class="btn-secondary" ${busy?'disabled':''}>${esc(L('send'))}</button></form></details></section>`;
|
||||
}
|
||||
window.AssessmentWorkbench={overview,controls,text:L,refreshClocks(root){root.querySelectorAll('.da-live-age').forEach(el=>el.textContent=elapsed(el.dataset.started));}};
|
||||
})();
|
||||
|
|
@ -28,7 +28,7 @@
|
|||
}
|
||||
function relationLabel(key) {
|
||||
const path='deepAssessments.graphRelations.'+key,value=window.t?.(path);
|
||||
return value && value!==path ? value : ({plans:'规划',depends_on:'依赖',informs:'派生',derives:'推导',produces:'产出',supports:'支持',reviews:'复核',executes:'执行',records:'记录',summarizes:'摘要',archives:'归档',contains:'包含',guides:'指导',exposes:'提供',associated_with:'关联',serves:'承载'})[key] || key;
|
||||
return value && value!==path ? value : ({via_archive:'经归档',via_details:'经执行记录',plans:'规划',depends_on:'依赖',informs:'派生',derives:'推导',produces:'产出',supports:'支持',reviews:'复核',executes:'执行',records:'记录',summarizes:'摘要',archives:'归档',contains:'包含',guides:'指导',exposes:'提供',associated_with:'关联',serves:'承载'})[key] || key;
|
||||
}
|
||||
function styles() {
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
|
|
@ -37,11 +37,13 @@
|
|||
return [
|
||||
{ selector: 'node', style: { shape: 'round-rectangle', label: 'data(label)', width: 224, height: 88, 'background-color': surface, 'border-width': 2, 'border-color': 'data(color)', color: text, 'font-size': 14, 'text-wrap': 'wrap', 'text-max-width': 208, 'text-overflow-wrap':'anywhere', 'text-valign': 'center', 'text-halign': 'center', padding: 9 } },
|
||||
{ selector: 'node[kind = "goal"]', style: { 'border-width': 3 } },
|
||||
{selector:'node[?boundary]',style:{'border-style':'dashed','background-opacity':.6}},
|
||||
{ selector: 'node[kind = "digest"]', style: { 'border-style': 'dashed' } },
|
||||
{ selector: 'node[state = "running"]', style: { 'background-color': '#dbeafe', color: '#172033' } },
|
||||
{ selector: 'node:selected', style: { 'border-width': 4, 'overlay-opacity': .08, 'overlay-color': '#3b82f6' } },
|
||||
{ selector: 'edge', style: { width: 1.5, 'line-color': 'data(relationColor)', 'target-arrow-color': 'data(relationColor)', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', label: '', opacity:.65, 'font-size': 10, color: text, 'text-background-color': surface, 'text-background-opacity': .9 } },
|
||||
{ selector: 'edge.da-connected', style: { label:'data(relationLabel)',width:2.5,opacity:1 } },
|
||||
{selector:'edge[projection]',style:{'line-style':'dashed'}},
|
||||
{ selector: 'edge[relation = "supports"], edge[relation = "informs"]', style: { 'line-style': 'dashed' } },
|
||||
];
|
||||
}
|
||||
|
|
@ -157,11 +159,11 @@
|
|||
}
|
||||
return;
|
||||
}
|
||||
const elements = nodes.map(node => ({ data: { id: node.id, kind: node.kind, state: node.state, label: label(node.kind) + (node.state?' · '+stateLabel(node.state):'') + '\n' + (Array.from(node.title).length > 42 ? Array.from(node.title).slice(0, 42).join('') + '…' : node.title), color: colors[node.kind] || colors.step } }));
|
||||
const elements = nodes.map(node => ({ data: { id: node.id, kind: node.kind, state: node.state, boundary:!!node.boundary,label: label(node.kind) + (node.state&&stateLabel(node.state)?' · '+stateLabel(node.state):'') + '\n' + (Array.from(node.title).length > 42 ? Array.from(node.title).slice(0, 42).join('') + '…' : node.title), color: colors[node.kind] || colors.step } }));
|
||||
const ids = new Set(nodes.map(n => n.id));
|
||||
for (const edge of graph.edges || []) if (ids.has(edge.source) && ids.has(edge.target)) {
|
||||
const relationColor=({plans:'#6366f1',depends_on:'#6366f1',informs:'#059669',derives:'#059669',produces:'#d97706',supports:'#e11d48',reviews:'#e11d48',summarizes:'#a855f7',archives:'#a855f7'})[edge.relation]||'#94a3b8';
|
||||
elements.push({ data: { id: 'edge:' + JSON.stringify([edge.source, edge.relation, edge.target]), ...edge, relationLabel: relationLabel(edge.relation),relationColor } });
|
||||
elements.push({ data: { id: 'edge:' + JSON.stringify([edge.source, edge.relation, edge.target,edge.projection||'']), ...edge, relationLabel: relationLabel(edge.relation)+(edge.projection?' · '+relationLabel('via_'+edge.projection):'')+(edge.references>1?' ×'+edge.references:''),relationColor } });
|
||||
}
|
||||
if (!chart) {
|
||||
chart = window.cytoscape({ container: host, elements, style: styles(), layout: { name: 'preset' }, minZoom: .12, maxZoom: 2.2, wheelSensitivity: .25 });
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -50,7 +50,7 @@
|
|||
<link rel="stylesheet" href="/static/css/vulnerability-workspace.css?v=20261115-stable-height">
|
||||
<link rel="stylesheet" href="/static/css/vulnerability-list.css?v=20261115-timestamps">
|
||||
<script src="/static/js/router.js?v=20261114-assessment-links"></script>
|
||||
<link rel="stylesheet" href="/static/css/deep-assessments.css?v=20261115-review-controls">
|
||||
<link rel="stylesheet" href="/static/css/deep-assessments.css?v=20261115-workbench">
|
||||
<link rel="stylesheet" href="/static/css/design-system.css?v=20261115-extra-drawers">
|
||||
</head>
|
||||
<body>
|
||||
|
|
@ -7141,10 +7141,11 @@
|
|||
<script src="/static/js/vulnerability-download.js?v=20261030-2"></script>
|
||||
<script src="/static/js/webshell.js?v=20261011-token-usage-tool-title"></script>
|
||||
<script src="/static/js/chat-files.js?v=20261103-personal-integration"></script>
|
||||
<script src="/static/js/assessment-workbench.js?v=20261115-workbench"></script>
|
||||
<script src="/static/js/assessment-node-panel.js?v=20261115-graph-live-fixes"></script>
|
||||
<script src="/static/js/assessment-exploration-views.js?v=20261115-graph-live-fixes"></script>
|
||||
<script src="/static/js/deep-assessment-graph.js?v=20261115-graph-live-fixes"></script>
|
||||
<script src="/static/js/deep-assessments.js?v=20261115-review-controls"></script>
|
||||
<script src="/static/js/deep-assessment-graph.js?v=20261115-workbench"></script>
|
||||
<script src="/static/js/deep-assessments.js?v=20261115-workbench"></script>
|
||||
<script src="/static/js/tasks.js?v=20261115-queue-label-contrast"></script>
|
||||
<script src="/static/js/workflow-package-client.js"></script>
|
||||
<script src="/static/js/workflows.js"></script>
|
||||
|
|
|
|||
Loading…
Reference in New Issue