feat(stability): add risk tiers, audit trail, and safer restore with dry-run
This commit is contained in:
@@ -60,3 +60,12 @@ Telegram commands:
|
||||
- `mode autonomous on|off`
|
||||
- `goals show`
|
||||
- `goals add <text>`
|
||||
|
||||
## 8) Stability Sprint v1
|
||||
Added:
|
||||
- Risk classification tiers (`prime_core/risk.py`)
|
||||
- Audit trail (`logs/audit.jsonl`)
|
||||
- Safer restore:
|
||||
- `prime restore --dry-run <commit>`
|
||||
- preflight + rollback on failure
|
||||
- Telegram control guardrails for high-risk direct commands
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
AUDIT_FILE = Path('/srv/prime-core/logs/audit.jsonl')
|
||||
|
||||
|
||||
def log_event(event: dict) -> None:
|
||||
AUDIT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
event = dict(event)
|
||||
event.setdefault('ts', int(time.time()))
|
||||
with AUDIT_FILE.open('a') as f:
|
||||
f.write(json.dumps(event, separators=(',', ':')) + '\n')
|
||||
+11
-1
@@ -5,6 +5,8 @@ import subprocess
|
||||
from .router import dispatch
|
||||
from .queue import enqueue, list_items, approve, deny
|
||||
from .worker import run_once
|
||||
from .audit import log_event
|
||||
from .risk import classify as risk_classify
|
||||
from .vault import load_tokens, VaultError
|
||||
|
||||
|
||||
@@ -37,7 +39,13 @@ def cmd_backup_now(_: argparse.Namespace) -> int:
|
||||
|
||||
|
||||
def cmd_restore(args: argparse.Namespace) -> int:
|
||||
return subprocess.run(['/srv/prime-core/scripts/restore.sh', args.commit]).returncode
|
||||
cmd = ['/srv/prime-core/scripts/restore.sh']
|
||||
if args.dry_run:
|
||||
cmd.append('--dry-run')
|
||||
cmd.append(args.commit)
|
||||
rc = subprocess.run(cmd).returncode
|
||||
log_event({'event':'restore', 'commit': args.commit, 'dry_run': bool(args.dry_run), 'rc': rc})
|
||||
return rc
|
||||
|
||||
|
||||
def cmd_dispatch(args: argparse.Namespace) -> int:
|
||||
@@ -63,6 +71,7 @@ def cmd_auth(args: argparse.Namespace) -> int:
|
||||
|
||||
def cmd_queue_add(args: argparse.Namespace) -> int:
|
||||
it = enqueue(args.task_type, args.task, args.max_retries)
|
||||
log_event({'event':'queue_add','task_id':it['id'],'task_type':args.task_type,'risk':risk_classify(args.task),'task':args.task})
|
||||
print(json.dumps(it, indent=2))
|
||||
return 0
|
||||
|
||||
@@ -101,6 +110,7 @@ def main() -> int:
|
||||
b.set_defaults(fn=cmd_backup_now)
|
||||
|
||||
r = sub.add_parser('restore')
|
||||
r.add_argument('--dry-run', action='store_true')
|
||||
r.add_argument('commit')
|
||||
r.set_defaults(fn=cmd_restore)
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
TIERS = {
|
||||
'tier1_read': ['status', 'queue list', 'goals show'],
|
||||
'tier2_safe_write': ['queue add', 'queue approve', 'queue deny', 'goals add', 'mode autonomous'],
|
||||
}
|
||||
|
||||
HIGH_RISK_KEYWORDS = [
|
||||
'delete', 'destroy', 'drop', 'shutdown', 'reboot', 'rm -rf',
|
||||
'passwd', 'userdel', 'mkfs', 'iptables', 'ufw deny', 'curl http', 'wget http'
|
||||
]
|
||||
|
||||
|
||||
def classify(text: str) -> str:
|
||||
t = text.lower().strip()
|
||||
if any(t.startswith(cmd) for cmd in TIERS['tier1_read']):
|
||||
return 'tier1_read'
|
||||
if any(t.startswith(cmd) for cmd in TIERS['tier2_safe_write']):
|
||||
return 'tier2_safe_write'
|
||||
if any(k in t for k in HIGH_RISK_KEYWORDS):
|
||||
return 'tier4_destructive_or_external'
|
||||
return 'tier3_modify'
|
||||
|
||||
|
||||
def needs_approval(command_text: str) -> bool:
|
||||
return classify(command_text) in {'tier3_modify', 'tier4_destructive_or_external'}
|
||||
@@ -7,6 +7,8 @@ import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from .risk import classify, needs_approval
|
||||
from .audit import log_event
|
||||
|
||||
OFFSET_FILE = Path('/srv/prime-core/state/telegram-offset.txt')
|
||||
|
||||
@@ -109,6 +111,10 @@ def set_autonomous(enabled: bool):
|
||||
|
||||
def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str:
|
||||
raw = text.strip()
|
||||
risk = classify(raw.lstrip('/'))
|
||||
log_event({'event':'telegram_command','chat_id':chat_id,'msg_id':msg_id,'text':raw,'risk':risk})
|
||||
if needs_approval(raw.lstrip('/')) and not raw.lower().startswith(('queue add','/queue add')):
|
||||
return f"Command blocked pending explicit queue workflow. Risk={risk}. Use queue add ... then approve."
|
||||
if raw.startswith('/start'):
|
||||
return "Prime online. " + help_text()
|
||||
if raw.startswith('/help') or raw == 'help':
|
||||
|
||||
+25
-2
@@ -1,11 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
BASE=/srv/prime-core
|
||||
DRY_RUN=0
|
||||
if [[ "${1:-}" == "--dry-run" ]]; then
|
||||
DRY_RUN=1
|
||||
shift
|
||||
fi
|
||||
COMMIT="${1:-}"
|
||||
[[ -n "$COMMIT" ]] || { echo "Usage: restore.sh <commit-id>"; exit 1; }
|
||||
[[ -n "$COMMIT" ]] || { echo "Usage: restore.sh [--dry-run] <commit-id>"; exit 1; }
|
||||
cd "$BASE"
|
||||
|
||||
git rev-parse --verify "$COMMIT^{commit}" >/dev/null
|
||||
SNAP="pre-restore-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
git tag "$SNAP" HEAD
|
||||
CURRENT_HEAD="$(git rev-parse HEAD)"
|
||||
|
||||
echo "[preflight] target=$COMMIT current=$CURRENT_HEAD"
|
||||
if [[ "$DRY_RUN" -eq 1 ]]; then
|
||||
echo "[dry-run] restore checks passed; no changes made"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git tag "$SNAP" "$CURRENT_HEAD"
|
||||
set +e
|
||||
git checkout -f "$COMMIT"
|
||||
rc=$?
|
||||
set -e
|
||||
if [[ "$rc" -ne 0 ]]; then
|
||||
echo "[rollback] checkout failed; restoring $CURRENT_HEAD"
|
||||
git checkout -f "$CURRENT_HEAD"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Restored workspace to $COMMIT (saved $SNAP)"
|
||||
|
||||
Reference in New Issue
Block a user