初始化:质量数据分析平台源码
This commit is contained in:
@@ -0,0 +1,172 @@
|
||||
"""Install the quality investigation context into the existing local nao runtime.
|
||||
|
||||
Uses upstream nao extension points: project rules, system prompt, model settings,
|
||||
and a stdio MCP. The packaged engine, source workbooks and business DB stay intact.
|
||||
"""
|
||||
import argparse
|
||||
import ast
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
|
||||
import nao_trial
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TEMPLATES = ROOT / "ai/nao-quality"
|
||||
ACTIVE = nao_trial.PROJECT
|
||||
STATE = nao_trial.TRIAL / "quality-context.json"
|
||||
OUT = ROOT / "output/nao-quality"
|
||||
|
||||
|
||||
def _digest(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def configure():
|
||||
for name in ("nao_quality_tools.py", "nao_quality_mcp.py"):
|
||||
path = ROOT / "scripts" / name
|
||||
ast.parse(path.read_text())
|
||||
_, _, model = nao_trial.model_settings()
|
||||
stamp = datetime.now().astimezone().strftime("%Y%m%d-%H%M%S-%f")
|
||||
backup = nao_trial.TRIAL / "context-backups" / stamp
|
||||
backup.mkdir(parents=True, mode=0o700)
|
||||
ACTIVE.mkdir(parents=True, exist_ok=True)
|
||||
files = ["RULES.md", "nao_config.yaml", "agent/prompts/system.md", "agent/mcps/mcp.json"]
|
||||
for relative in files:
|
||||
old = ACTIVE / relative
|
||||
if old.exists():
|
||||
target = backup / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(old, target)
|
||||
# Old baseline warehouse context is preserved outside the active project.
|
||||
# Deep investigation uses the live, version-bound quality API MCP instead.
|
||||
old_databases = ACTIVE / "databases"
|
||||
if old_databases.exists():
|
||||
shutil.move(str(old_databases), str(backup / "databases"))
|
||||
# Upstream deliberately reuses discovered specs across restarts. Move only
|
||||
# our generated server directory aside so startup discovers the live schema.
|
||||
old_quality_specs = ACTIVE / "agent/mcps/quality"
|
||||
if old_quality_specs.exists():
|
||||
target = backup / "agent/mcps/quality"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(old_quality_specs), str(target))
|
||||
for relative in ("RULES.md", "agent/prompts/system.md"):
|
||||
target = ACTIVE / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(TEMPLATES / relative, target)
|
||||
(ACTIVE / "nao_config.yaml").write_text(
|
||||
"project_name: quality-investigation\n"
|
||||
"databases: []\n"
|
||||
"llm:\n"
|
||||
f" annotation_model: openaiCompatible:{model}\n"
|
||||
" providers:\n"
|
||||
" - provider: openaiCompatible\n"
|
||||
" api_key: \"{{ env('NAO_MODEL_KEY') }}\"\n"
|
||||
" base_url: \"{{ env('NAO_MODEL_BASE') }}\"\n"
|
||||
" models:\n"
|
||||
f" - id: {json.dumps(model)}\n"
|
||||
" default: true\n"
|
||||
" settings:\n"
|
||||
" maxOutputTokens: 8192\n"
|
||||
" temperature: 0.2\n"
|
||||
" reasoningEffort: low\n"
|
||||
)
|
||||
old_mcp = backup / "agent/mcps/mcp.json"
|
||||
mcps = json.loads(old_mcp.read_text()) if old_mcp.exists() else {"mcpServers": {}}
|
||||
mcps.setdefault("mcpServers", {})["quality"] = {
|
||||
"transport": "stdio",
|
||||
"command": sys.executable,
|
||||
"args": [str(ROOT / "scripts/nao_quality_mcp.py")],
|
||||
}
|
||||
mcp_path = ACTIVE / "agent/mcps/mcp.json"
|
||||
mcp_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
mcp_path.write_text(json.dumps(mcps, ensure_ascii=False, indent=2))
|
||||
mcp_path.chmod(0o600)
|
||||
state = {
|
||||
"mode": "QUALITY_API_MCP",
|
||||
"model": model,
|
||||
"backup": str(backup),
|
||||
"configuredAt": datetime.now().astimezone().isoformat(),
|
||||
"sourceHashes": {relative: _digest(TEMPLATES / relative)
|
||||
for relative in ("RULES.md", "agent/prompts/system.md")},
|
||||
"upstreamCoreModified": False,
|
||||
"qualityApi": "http://127.0.0.1:5281",
|
||||
"naoUi": "http://127.0.0.1:5674",
|
||||
"accessBoundary": "Local maintenance-account project only, not a shared multi-user integration",
|
||||
}
|
||||
STATE.write_text(json.dumps(state, ensure_ascii=False, indent=2))
|
||||
STATE.chmod(0o600)
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / "environment.json").write_text(json.dumps(state, ensure_ascii=False, indent=2))
|
||||
print("Quality investigation context installed; prior context backed up")
|
||||
|
||||
|
||||
def stop():
|
||||
state_path = nao_trial.TRIAL / "pids.json"
|
||||
previous = json.loads(state_path.read_text()) if state_path.exists() else {}
|
||||
nao_trial.stop()
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
alive = []
|
||||
for pid in previous.values():
|
||||
result = subprocess.run(["ps", "-p", str(pid), "-o", "stat="], capture_output=True, text=True)
|
||||
if result.returncode == 0 and not result.stdout.strip().startswith("Z"):
|
||||
alive.append(pid)
|
||||
if not alive:
|
||||
return
|
||||
time.sleep(0.1)
|
||||
for pid in alive:
|
||||
result = subprocess.run(["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
continue
|
||||
if str(nao_trial.TRIAL) not in result.stdout or os.getpgid(pid) != pid:
|
||||
raise RuntimeError("Local nao process identity changed; force stop refused")
|
||||
os.killpg(pid, signal.SIGKILL)
|
||||
print("Stopped verified local nao process groups after graceful shutdown timeout")
|
||||
|
||||
|
||||
def activate():
|
||||
# Validate first so a missing adapter never takes the working trial offline.
|
||||
for name in ("nao_quality_tools.py", "nao_quality_mcp.py"):
|
||||
ast.parse((ROOT / "scripts" / name).read_text())
|
||||
stop()
|
||||
deadline = time.monotonic() + 15
|
||||
for port in (5674, 5675):
|
||||
while True:
|
||||
with socket.socket() as connection:
|
||||
connection.settimeout(0.3)
|
||||
occupied = connection.connect_ex(("127.0.0.1", port)) == 0
|
||||
if not occupied:
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError(f"Prior local nao port {port} is still occupied; restart was not attempted")
|
||||
time.sleep(0.15)
|
||||
configure()
|
||||
nao_trial.start()
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urlopen("http://127.0.0.1:5674", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
print("Quality investigation ready at http://127.0.0.1:5674")
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(0.3)
|
||||
raise RuntimeError("nao did not become ready; preserved backup is recorded in quality-context.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("configure", "activate", "start", "stop"))
|
||||
args = parser.parse_args()
|
||||
{"configure": configure, "activate": activate, "start": nao_trial.start,
|
||||
"stop": stop}[args.action]()
|
||||
Reference in New Issue
Block a user