mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-11-24 13:20:55 +01:00
feat(assessment): add acceptance review, specialist workers and resilient recovery
This commit is contained in:
1 parent
ef89d9e464
commit
261d2cd0ad
26 files changed
+1987
-272
No files matched your search
@@ -43,12 +43,14 @@ const server = http.createServer(async (req, res) => {
|
||||
if (url.pathname.endsWith('/events')) { send({ events: url.searchParams.get('after') === '0' ? [{ id: 1, kind: 'fixture', message: '<img src=x onerror="window.XSS=1">', data: {}, created_at: now() }] : [] }); return; }
|
||||
if (url.pathname.includes('/control/')) {
|
||||
const action = url.pathname.split('/').at(-1);
|
||||
if (action === 'steer') current.material += '\n' + input.message;
|
||||
if (action === 'budget') { current.token_budget=input.token_budget;current.remaining_seconds=input.remaining_seconds;current.max_rounds=input.max_rounds;current.status='paused'; }
|
||||
else if (action === 'steer') current.material += '\n' + input.message;
|
||||
else if (action === 'start') { current.status = 'awaiting_approval'; current.steps = [{ ...task.steps[0], id: 'review-step', status: 'awaiting_approval', approval_id: 'fixture-request', pending: { id: 'call1', function: { name: 'inspect', arguments: { target: 'local-fixture' } } } }]; }
|
||||
else current.status = action === 'pause' ? 'paused' : 'stopped';
|
||||
current.updated_at = now(); send({ ok: true }); return;
|
||||
}
|
||||
if (url.pathname.endsWith('/decision')) { if(input.approval_id !== current.steps[0].approval_id) {res.statusCode=409;send({error:'stale approval'});return;} current.status = input.approved ? 'completed' : 'blocked'; current.steps[0].status = current.status; current.steps[0].pending = null; current.updated_at = now(); send({ ok: true }); return; }
|
||||
if (url.pathname.endsWith('/metrics')) {send({task_id:current.id,status:current.status,tokens:current.tokens});return;}
|
||||
if (url.pathname.endsWith('/publish')) { if(input.revision !== 'fixture-version'){res.statusCode=409;send({error:'stale evidence'});return;} send({ result: { id: 'published' } }); return; }
|
||||
if(holdDetail && req.method === "GET") await new Promise(resolve => detailWaiters.push(resolve));
|
||||
send({ assessment: current });
|
||||
@@ -78,13 +80,16 @@ try {
|
||||
assert.equal(await evaluate("document.getElementById('assessment-guidance').value"), 'preserve unsaved guidance', 'poll erased typed guidance');
|
||||
assert.ok(await evaluate("document.getElementById('assessment-tab').textContent.includes('先核验响应,再检查访问控制边界')"));
|
||||
await screenshot('desktop-overview');
|
||||
await click('[data-tab=review]'); await waitFor("document.getElementById('assessment-tab').textContent.includes('验收条件')");
|
||||
await click('[data-assessment-action=budget]'); await waitFor("document.getElementById('assessment-budget')?.open");
|
||||
await evaluate("document.querySelector('#assessment-budget [name=token_budget]').value='250000';document.querySelector('#assessment-budget form').requestSubmit()");await waitFor("!document.getElementById('assessment-budget')");
|
||||
await click('[data-tab=chain]'); await waitFor("!!document.querySelector('#assessment-graph canvas')"); await screenshot('desktop-chain');
|
||||
await evaluate("document.documentElement.dataset.theme='dark'"); await click('[data-tab=chain]'); await screenshot('desktop-dark-chain'); await evaluate("document.documentElement.dataset.theme='light'");
|
||||
await click('[data-tab=evidence]'); assert.equal(await evaluate("document.querySelectorAll('[data-assessment-action=vulnerability]').length"), 1);
|
||||
await click('[data-assessment-action=fact]'); await waitFor("document.getElementById('assessment-message').textContent.includes('已保存')");
|
||||
await click('[data-tab=logs]'); assert.equal(await evaluate('window.XSS || 0'), 0, 'untrusted log rendered as HTML');
|
||||
await click('[data-assessment-action=new]'); await waitFor("document.getElementById('assessment-create')?.open"); assert.equal(await evaluate("document.querySelector('[name=project_id] option:last-child').textContent"), '本地测试项目');
|
||||
await evaluate(`document.querySelector('[name=name]').value='Created in browser';document.querySelector('[name=goal]').value='Inspect fixture';document.querySelector('[name=scope]').value='Local fixture';document.querySelector('[name=tools]').checked=true;document.getElementById('assessment-create-form').requestSubmit()`);
|
||||
await evaluate(`document.querySelector('[name=name]').value='Created in browser';document.querySelector('[name=goal]').value='Inspect fixture';document.querySelector('[name=scope]').value='Local fixture';document.querySelector('[name=criteria]').value='Record a fixture response';document.querySelector('[name=tools]').checked=true;document.getElementById('assessment-create-form').requestSubmit()`);
|
||||
await waitFor("document.querySelector('#assessment-detail h2')?.textContent==='Created in browser'");
|
||||
assert.ok((await evaluate('location.hash')).startsWith('#assessments?task=created-'), 'created task deep link missing');
|
||||
await click('[data-assessment-action=start]'); await waitFor("document.querySelector('#assessment-detail .assessment-status')?.dataset.status==='awaiting_approval'");
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare downloaded assessment metric cohorts; no model/network calls.
|
||||
|
||||
Usage: python3 scripts/assessment-evaluate.py --baseline /path/a --candidate /path/b
|
||||
Input: one metrics JSON per run, as exported by /api/assessments/:id/metrics.
|
||||
Rates describe system-recorded outcomes, not ground-truth vulnerability recall.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
FIELDS = ("criteria_total", "criteria_satisfied", "findings", "confirmed_findings",
|
||||
"needs_retest", "tool_calls", "unique_actions", "suppressed_repeats",
|
||||
"model_calls", "model_retries", "tokens")
|
||||
|
||||
|
||||
def summarize(directory):
|
||||
files = sorted(Path(directory).glob("*.json"))
|
||||
if not files:
|
||||
raise ValueError(f"No metric JSON files in {directory}")
|
||||
totals = dict.fromkeys(FIELDS, 0)
|
||||
completed = 0
|
||||
seen = set()
|
||||
settings = set()
|
||||
scenarios = set()
|
||||
for file in files:
|
||||
row = json.loads(file.read_text(encoding="utf-8"))
|
||||
if not isinstance(row.get("task_id"), str) or row["task_id"] in seen:
|
||||
raise ValueError(f"Missing or duplicate task_id: {file}")
|
||||
seen.add(row["task_id"])
|
||||
settings.add(json.dumps({k: row.get(k) for k in ("model_channel", "reviewer_channel", "worker_channels", "token_budget", "max_rounds")}, sort_keys=True))
|
||||
scenarios.add(row.get("name", ""))
|
||||
completed += row.get("status") == "completed"
|
||||
for key in FIELDS:
|
||||
value = row.get(key)
|
||||
if type(value) is not int or value < 0:
|
||||
raise ValueError(f"Invalid nonnegative integer {key}: {file}")
|
||||
totals[key] += value
|
||||
if row["criteria_satisfied"] > row["criteria_total"] or row["confirmed_findings"] + row["needs_retest"] > row["findings"] or row["unique_actions"] > row["tool_calls"]:
|
||||
raise ValueError(f"Inconsistent metric counters: {file}")
|
||||
return {"configurations": [json.loads(s) for s in sorted(settings)], "scenarios": sorted(scenarios), "runs": len(files), "completed_runs": completed, **totals,
|
||||
"completion_rate": completed / len(files),
|
||||
"criteria_satisfied_rate": (totals["criteria_satisfied"] / totals["criteria_total"]
|
||||
if totals["criteria_total"] else None),
|
||||
"tokens_per_run": totals["tokens"] / len(files)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--baseline", required=True)
|
||||
parser.add_argument("--candidate", required=True)
|
||||
parser.add_argument("--output")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
baseline, candidate = summarize(args.baseline), summarize(args.candidate)
|
||||
except (ValueError, OSError) as error:
|
||||
parser.error(str(error))
|
||||
output = {"baseline": baseline, "candidate": candidate,
|
||||
"same_configurations": baseline["configurations"] == candidate["configurations"],
|
||||
"same_scenarios": baseline["scenarios"] == candidate["scenarios"],
|
||||
"delta": {key: candidate[key] - baseline[key]
|
||||
for key in (*FIELDS, "completion_rate", "tokens_per_run")},
|
||||
"interpretation": "Use identical authorized scenarios, model channels and budgets. "
|
||||
"These are system-reviewed outcomes, not ground-truth accuracy. "
|
||||
"Tokens include conservative charges when provider usage is missing."}
|
||||
text = json.dumps(output, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + "\n", encoding="utf-8")
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user