release: Themiz на Gitea

This commit is contained in:
public-repo-gate
2026-10-19 11:10:53 +03:00
parent e52e76d4ea
commit 067c6c2414
225 changed files with 240125 additions and 26157 deletions
+582
View File
@@ -0,0 +1,582 @@
#!/usr/bin/env python3
"""COIS: local append-only observations, snapshots and owner-driven batches."""
from __future__ import annotations
import argparse
import contextlib
import difflib
import hashlib
import io
import json
import os
from pathlib import Path
import re
import secrets
import sqlite3
import tempfile
from datetime import datetime, timezone
import zipfile
from xml.etree import ElementTree as ET
STATES = {'новый', 'проверен', 'исправлен и проверен', 'отложен с причиной', 'не подтвердился'}
TERMINAL = STATES - {'новый', 'проверен'}
SENSITIVE_KEY = re.compile(r'(?i)secret|password|passwd|token|authorization|cookie|credential|api.?key|private.?key|system|developer|reasoning|thought')
SECRET = re.compile(rb'''(?ix)(?:["']?(?:api[_-]?key|secret|password|passwd|access[_-]?token|token|authorization|private[_-]?key|cookie)["']?\s*[:=])|-----BEGIN\ [A-Z\ ]*PRIVATE\ KEY-----|\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,})''')
INTERNAL = re.compile(rb'(?i)<(?:thinking|analysis|system|developer)>|"role"\s*:\s*"(?:system|developer)"|chain[ ._-]*of[ ._-]*thought|internal reasoning|base_instructions|encrypted_content')
DENIED_NAME = re.compile(r'(?i)(?:^|/)(?:\.env(?:\..*)?|auth(?:\..*)?|credentials?(?:\..*)?|.*(?:secret|password|private[-_]?key).*|AGENTS\.md|CLAUDE\.md|SKILL\.md|rollout-.*|.*transcript.*)$')
TEXT_EXT = {'.md', '.txt', '.json', '.jsonl', '.csv', '.tsv', '.yaml', '.yml'}
MAX_BLOB = 32 * 1024 * 1024
def now():
return datetime.now(timezone.utc).isoformat(timespec='microseconds')
def js(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
def digest(value):
return hashlib.sha256(value.encode() if isinstance(value, str) else value).hexdigest()
def safe(value):
"""Sanitize before any durable write; metadata bodies remain opt-in."""
if value is None or isinstance(value, (bool, int, float)):
return value
if isinstance(value, dict):
return {str(k): safe(v) for k, v in value.items() if not SENSITIVE_KEY.search(str(k))}
if isinstance(value, (list, tuple)):
return [safe(v) for v in value]
text = str(value)
raw = text.encode()
return '[FILTERED]' if SECRET.search(raw) or INTERNAL.search(raw) else text[:16000]
def snapshot_allowed(data, rel):
if data is None or DENIED_NAME.search(rel) or rel.startswith('00_intake/'):
return False
suffix = Path(rel).suffix.lower()
if suffix not in TEXT_EXT and suffix != '.docx':
return False
if SECRET.search(data) or INTERNAL.search(data):
return False
if suffix in TEXT_EXT:
try:
data.decode('utf-8')
except UnicodeError:
return False
return True
if suffix == '.docx':
try:
with zipfile.ZipFile(io.BytesIO(data)) as doc:
if sum(x.file_size for x in doc.infolist()) > MAX_BLOB:
return False
for part in doc.infolist():
if part.filename.endswith('.bin'):
return False
if part.filename.endswith(('.xml', '.rels', '.txt')):
body = doc.read(part)
if SECRET.search(body) or INTERNAL.search(body):
return False
return True
except (OSError, zipfile.BadZipFile):
return False
return False
def atomic_write(path, data):
path = Path(path)
fd, temp = tempfile.mkstemp(prefix='.pending-', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as out:
out.write(data)
out.flush()
os.fsync(out.fileno())
os.replace(temp, path)
descriptor = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
finally:
if os.path.exists(temp):
os.unlink(temp)
class Store:
def __init__(self, data_root, code_root):
self.data_root = Path(data_root).resolve()
self.code_root = Path(code_root).resolve()
self.root = self.data_root / 'cases/_logs/session-audits/cois'
self.root.mkdir(parents=True, exist_ok=True)
self.blobs = self.root / 'blobs'
self.snapshots = self.root / 'snapshots'
self.blobs.mkdir(exist_ok=True)
self.snapshots.mkdir(exist_ok=True)
for path in (self.root, self.blobs, self.snapshots):
os.chmod(path, 0o700)
self.db_path = self.root / 'cois.sqlite3'
self.db = sqlite3.connect(self.db_path, timeout=2, isolation_level=None)
self.db.row_factory = sqlite3.Row
self.db.execute('PRAGMA journal_mode=WAL')
self.db.execute('PRAGMA synchronous=FULL')
self.db.execute('PRAGMA foreign_keys=ON')
self.db.executescript('''
CREATE TABLE IF NOT EXISTS sessions(case_path TEXT, session TEXT, started TEXT,
finalized TEXT, PRIMARY KEY(case_path,session));
CREATE TABLE IF NOT EXISTS events(seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT UNIQUE NOT NULL, time TEXT NOT NULL, project TEXT NOT NULL,
case_path TEXT NOT NULL, session TEXT NOT NULL, stream TEXT, event_type TEXT NOT NULL,
source TEXT NOT NULL, action TEXT, path TEXT, workdir TEXT, before_sha TEXT,
after_sha TEXT, result TEXT, evidence TEXT, actor TEXT NOT NULL, payload TEXT);
CREATE INDEX IF NOT EXISTS events_case_time ON events(case_path,time);
CREATE TABLE IF NOT EXISTS file_state(case_path TEXT, relpath TEXT, sha TEXT,
size INTEGER, mtime_ns INTEGER, ino INTEGER, mode INTEGER, blob TEXT,
PRIMARY KEY(case_path,relpath));
CREATE TABLE IF NOT EXISTS batches(batch_id TEXT PRIMARY KEY, created TEXT, status TEXT,
reason TEXT, event_ids TEXT, code_change TEXT);
CREATE TABLE IF NOT EXISTS batch_events(batch_id TEXT, event_id TEXT, status TEXT,
reason TEXT, evidence TEXT, PRIMARY KEY(batch_id,event_id));
CREATE TABLE IF NOT EXISTS batch_history(batch_id TEXT, at TEXT, status TEXT,
reason TEXT, evidence TEXT, code_change TEXT);
CREATE TRIGGER IF NOT EXISTS events_no_update BEFORE UPDATE ON events
BEGIN SELECT RAISE(ABORT,'events append-only'); END;
CREATE TRIGGER IF NOT EXISTS events_no_delete BEFORE DELETE ON events
BEGIN SELECT RAISE(ABORT,'events append-only'); END;
CREATE TRIGGER IF NOT EXISTS history_no_update BEFORE UPDATE ON batch_history
BEGIN SELECT RAISE(ABORT,'history append-only'); END;
CREATE TRIGGER IF NOT EXISTS history_no_delete BEFORE DELETE ON batch_history
BEGIN SELECT RAISE(ABORT,'history append-only'); END;
''')
os.chmod(self.db_path, 0o600)
def close(self):
self.db.close()
@contextlib.contextmanager
def transaction(self):
self.db.execute('BEGIN IMMEDIATE')
try:
yield
self.db.commit()
except BaseException:
self.db.rollback()
raise
def _case(self, case):
path = Path(case)
if not path.is_absolute():
raise ValueError('case must be absolute')
path = path.resolve()
try:
relative = path.relative_to(self.data_root / 'cases')
except ValueError:
raise ValueError('case outside data_root/cases')
if len(relative.parts) != 2 or any(p.startswith(('_', '.')) for p in relative.parts) or not path.is_dir():
raise ValueError('expected cases/client/case directory')
return path, relative.as_posix()
def _open_session(self, case, session):
if not isinstance(session, str) or not session or safe(session) != session:
raise ValueError('invalid session identifier')
row = self.db.execute('SELECT finalized FROM sessions WHERE case_path=? AND session=?', (case, session)).fetchone()
if row and row[0]:
raise ValueError('session already finalized; begin a new segment')
self.db.execute('INSERT OR IGNORE INTO sessions VALUES(?,?,?,NULL)', (case, session, now()))
def begin(self, case, session):
_, relative = self._case(case)
with self.transaction():
self._open_session(relative, session)
return {'case': relative, 'session': session}
def session_closed(self, case, session):
_, relative = self._case(case)
row = self.db.execute('SELECT finalized FROM sessions WHERE case_path=? AND session=?', (relative, session)).fetchone()
return bool(row and row[0])
def _insert(self, case, session, event_type, source, **fields):
_, relative = self._case(case)
identity = fields.pop('event_id', None)
before = fields.pop('before_sha256', fields.pop('before', None))
after = fields.pop('after_sha256', fields.pop('after', None))
target = fields.pop('target', fields.pop('path', None))
payload = fields.pop('payload', None)
# Raw tool output is never accepted as a payload, even through the direct API.
if event_type in ('tool', 'tool_call', 'tool_result', 'agent_report'):
payload = {k: v for k, v in (payload or {}).items()
if k in ('exit_code', 'is_error', 'tool', 'call_id', 'duration_ms')} if isinstance(payload, dict) else None
values = dict(project=str(self.code_root), case_path=relative, session=session,
stream=fields.pop('stream', 'main'), event_type=event_type, source=source,
action=fields.pop('action', None), path=target, workdir=fields.pop('workdir', None),
before_sha=before, after_sha=after, result=fields.pop('result', None),
evidence=fields.pop('evidence', None), actor=fields.pop('actor', 'не установлен'),
payload=payload)
if fields:
raise TypeError('unknown event metadata: ' + ','.join(fields))
values = {k: safe(v) for k, v in values.items()}
values['payload'] = js(values['payload']) if values['payload'] is not None else None
identity = identity or digest(js(values))[:32]
existing = self.db.execute('SELECT * FROM events WHERE id=?', (identity,)).fetchone()
if existing:
if any(existing[k] != v for k, v in values.items()):
raise ValueError('event ID collision with different content; append a correction')
return identity
self._open_session(relative, session)
columns = ['id', 'time', *values]
self.db.execute('INSERT INTO events(' + ','.join(columns) + ') VALUES(' + ','.join('?' for _ in columns) + ')',
(identity, now(), *values.values()))
return identity
def emit(self, case, session, event_type, source, **fields):
with self.transaction():
return self._insert(case, session, event_type, source, **fields)
def _read(self, path, capture=True):
hashed = hashlib.sha256()
chunks = []
size = 0
with path.open('rb') as source:
for chunk in iter(lambda: source.read(1024 * 1024), b''):
hashed.update(chunk)
size += len(chunk)
if capture and size <= MAX_BLOB:
chunks.append(chunk)
return hashed.hexdigest(), b''.join(chunks) if capture and size <= MAX_BLOB else None
def _blob(self, data, rel=''):
if not snapshot_allowed(data, rel):
return None
hashed = digest(data)
target = self.blobs / hashed
if not target.exists():
atomic_write(target, data)
return hashed
def _diff(self, old, new, rel):
if old is None or new is None:
return {'delta': 'unavailable', 'before_available': old is not None}
if not snapshot_allowed(new, rel) or not snapshot_allowed(old, rel):
return {'delta': 'filtered'}
if rel.lower().endswith('.docx'):
try:
try:
from .redline_diff import diff
except ImportError:
from redline_diff import diff
# Reuse the existing human-readable text/margins/fonts comparison;
# additionally track run styles, tables, sections, headers and numbering.
def structure(data):
out = {}
ET.register_namespace('w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main')
with zipfile.ZipFile(io.BytesIO(data)) as package:
for name in sorted(package.namelist()):
if not name.startswith('word/') or not name.endswith('.xml'):
continue
tree = ET.fromstring(package.read(name))
for element in tree.iter():
for key in list(element.attrib):
if 'rsid' in key or key.endswith('paraId') or key.endswith('textId'):
del element.attrib[key]
out[name] = ET.tostring(tree, encoding='unicode').replace('><', '>\n<')
return out
with tempfile.TemporaryDirectory(dir=self.root, prefix='diff-') as td:
a, b = Path(td) / 'before.docx', Path(td) / 'after.docx'
a.write_bytes(old)
b.write_bytes(new)
human = diff(str(a), str(b))
a, b = structure(old), structure(new)
changed = [n for n in sorted(set(a) | set(b)) if a.get(n) != b.get(n)]
return {'redline': human, 'changed_word_parts': changed,
'structural_diff': '\n'.join(line for name in changed for line in
difflib.unified_diff(a.get(name, '').splitlines(), b.get(name, '').splitlines(),
fromfile='before/' + name, tofile='after/' + name, n=2))[:16000]}
except (ImportError, ValueError, OSError, zipfile.BadZipFile, ET.ParseError):
return {'docx_diff': 'unavailable'}
return {'text_diff': '\n'.join(difflib.unified_diff(old.decode().splitlines(), new.decode().splitlines(), n=2))[:16000]}
def scan(self, case, session):
root, relative = self._case(case)
with self.transaction():
self._open_session(relative, session)
previous = {r['relpath']: r for r in self.db.execute('SELECT * FROM file_state WHERE case_path=?', (relative,))}
current, bodies = {}, {}
for directory, dirs, files in os.walk(root, followlinks=False):
dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', '__pycache__') and not (Path(directory) / d).is_symlink()]
for name in files:
path = Path(directory) / name
rel = path.relative_to(root).as_posix()
if path.is_symlink() or name.startswith(('~$', '.pending-')) or path.suffix.lower() in ('.tmp', '.temp'):
continue
try:
stat = path.stat()
old = previous.get(rel)
stamp = (stat.st_size, stat.st_mtime_ns, stat.st_ino, stat.st_mode)
if old and stamp == tuple(old[k] for k in ('size', 'mtime_ns', 'ino', 'mode')):
current[rel] = (old['sha'], *stamp, old['blob'])
continue
capture = (path.suffix.lower() in TEXT_EXT or path.suffix.lower() == '.docx') and not rel.startswith('00_intake/') and not DENIED_NAME.search(rel)
sha, body = self._read(path, capture=capture)
after = path.stat()
if (after.st_size, after.st_mtime_ns, after.st_ino) != (stat.st_size, stat.st_mtime_ns, stat.st_ino):
raise OSError('file changed during snapshot; retry')
except FileNotFoundError:
continue # atomic replacement is picked up in the next native/poll pass
blob = self._blob(body, rel)
current[rel] = (sha, *stamp, blob)
bodies[rel] = body if blob else None
sequence = self.db.execute('SELECT COALESCE(MAX(seq),0) FROM events').fetchone()[0]
ids = []
def event(action, rel, before=None, after=None, payload=None):
eid = digest(js([relative, sequence, len(ids), action, rel, before, after]))[:32]
ids.append(self._insert(case, session, 'file', 'scanner', action=action, path=rel,
before=before, after=after, payload=payload, event_id=eid))
removed, added = set(previous) - set(current), set(current) - set(previous)
for old in sorted(removed.copy()):
matches = [n for n in added if previous[old]['sha'] == current[n][0]]
# Ambiguous identical copies do not establish a rename.
if len(matches) == 1 and sum(previous[o]['sha'] == previous[old]['sha'] for o in removed) == 1:
new = matches[0]
event('rename', new, previous[old]['sha'], current[new][0], {'from': old, 'to': new, 'inference': 'unique_equal_sha'})
removed.remove(old)
added.remove(new)
for rel in sorted(removed):
event('delete', rel, before=previous[rel]['sha'], payload={'before_blob': previous[rel]['blob']})
for rel in sorted(added | (set(previous) & set(current))):
old = previous.get(rel)
sha, size, _mtime, _ino, _mode, blob = current[rel]
if old and old['sha'] == sha:
continue
old_body = None
old_blob = old['blob'] if old else None
if old_blob and (self.blobs / old_blob).is_file():
old_body = (self.blobs / old_blob).read_bytes()
payload = {'size': size, 'blob': blob, 'before_blob': old_blob,
'before_available': old_body is not None, 'snapshot': 'stored' if blob else 'metadata_only',
**self._diff(old_body, bodies.get(rel), rel)}
if rel.lower().endswith('.docx') and not rel.startswith('.agent/drafts/_baselines/'):
baseline = root / '.agent/drafts/_baselines' / Path(rel).name
if baseline.is_file() and not baseline.is_symlink():
base_sha, base_body = self._read(baseline)
if base_sha != sha:
payload['baseline_sha'] = base_sha
payload['baseline_blob'] = self._blob(base_body, '.agent/drafts/_baselines/' + baseline.name)
payload['client_edit_candidate'] = True
payload['baseline_diff'] = self._diff(base_body, bodies.get(rel), rel)
event('change' if old else 'create', rel, old['sha'] if old else None, sha, payload)
self.db.execute('DELETE FROM file_state WHERE case_path=?', (relative,))
self.db.executemany('INSERT INTO file_state VALUES(?,?,?,?,?,?,?,?)', ((relative, rel, *row) for rel, row in current.items()))
return {'case': relative, 'session': session, 'events': len(ids), 'event_ids': ids, 'degraded': False}
def finalize(self, case, session):
_, relative = self._case(case)
out = self.snapshots / digest(relative + '\0' + session)[:32]
with self.transaction():
row = self.db.execute('SELECT finalized FROM sessions WHERE case_path=? AND session=?', (relative, session)).fetchone()
if not row or not row[0]:
self._open_session(relative, session)
self.db.execute('UPDATE sessions SET finalized=? WHERE case_path=? AND session=?', (now(), relative, session))
rows = self.db.execute('SELECT * FROM events WHERE case_path=? AND session=? ORDER BY seq', (relative, session)).fetchall()
# Seal the journal first. A failed/partial export is safely retried from
# these same sealed rows; no late event can change the package meanwhile.
out.mkdir(exist_ok=True)
artifacts = {'events.jsonl': ('\n'.join(js(dict(r)) for r in rows) + '\n').encode(),
'report.md': (f'# COIS session\n\nCase: `{relative}`\n\nSession: `{session}`\n\nEvents: {len(rows)}\n\n'
+ '\n'.join(f"- {r['time']} · {r['event_type']} · {r['action'] or r['result']} · {r['id']}" for r in rows) + '\n').encode()}
for name, content in artifacts.items():
path = out / name
if not path.exists():
atomic_write(path, content)
elif path.read_bytes() != content:
raise ValueError('immutable snapshot differs from journal')
return {'case': relative, 'session': session, 'events': len(rows), 'snapshot': str(out)}
def health(self):
return {'ok': True, 'db': str(self.db_path), 'events': self.db.execute('SELECT COUNT(*) FROM events').fetchone()[0], 'journal': 'WAL'}
def has_event(self, event_id):
return self.db.execute('SELECT 1 FROM events WHERE id=?', (event_id,)).fetchone() is not None
def write_index(self):
sessions = [dict(r) for r in self.db.execute('''SELECT s.*, COUNT(e.id) AS events FROM sessions s
LEFT JOIN events e ON s.case_path=e.case_path AND s.session=e.session
GROUP BY s.case_path,s.session ORDER BY s.started DESC''')]
batches = [dict(r) for r in self.db.execute('SELECT * FROM batches ORDER BY created DESC')]
incidents = [dict(r) for r in self.db.execute("SELECT id,case_path,payload FROM events WHERE event_type='historical_incident' ORDER BY seq")]
text = '# COIS: индекс наблюдения\n\nАктивные сессии доступны в SQLite; завершенные — по ссылкам ниже.\n\n'
for row in sessions:
folder = 'snapshots/' + digest(row['case_path'] + '\0' + row['session'])[:32]
state = 'завершена' if row['finalized'] else 'наблюдение / незавершена'
link = f'[{row["session"]}]({folder}/report.md)' if row['finalized'] else row['session']
text += f'- `{row["case_path"]}` · {link} · {state} · {row["events"]} событий\n'
text += '\nПартии:\n\n' + '\n'.join(f'- `{b["batch_id"]}` · {b["status"]}' for b in batches) + '\n'
atomic_write(self.root / 'INDEX.md', text.encode())
atomic_write(self.root / 'queue.json', js({'sessions': sessions, 'batches': batches, 'incidents': incidents}).encode())
return {'sessions': len(sessions), 'batches': len(batches), 'incidents': len(incidents)}
def select_batch(self, since=None, until=None, limit=100, event_ids=None):
def timestamp(raw):
if raw is None:
return None
date = datetime.fromisoformat(raw)
if date.tzinfo is None:
raise ValueError('period timestamps require timezone')
return date.astimezone(timezone.utc).isoformat(timespec='microseconds')
since, until = timestamp(since), timestamp(until)
if since and until and since >= until:
raise ValueError('empty or reversed period')
if limit < 1:
raise ValueError('positive limit required')
with self.transaction():
for row in self.db.execute("SELECT * FROM batches WHERE status IN ('новый','проверен') ORDER BY created"):
ids = json.loads(row['event_ids'])
if event_ids is not None and set(ids) != set(event_ids):
continue
if since or until:
dates = [r[0] for r in self.db.execute('SELECT time FROM events WHERE id IN (' + ','.join('?' for _ in ids) + ')', ids)]
if not all((not since or d >= since) and (not until or d < until) for d in dates):
continue
return {'batch_id': row['batch_id'], 'event_ids': ids, 'status': row['status']}
query = 'SELECT e.id FROM events e WHERE NOT EXISTS(SELECT 1 FROM batch_events b WHERE b.event_id=e.id)'
args = []
if since:
query += ' AND e.time>=?'
args.append(since)
if until:
query += ' AND e.time<?'
args.append(until)
if event_ids is not None:
if not event_ids:
return {'batch_id': None, 'event_ids': [], 'status': 'empty'}
query += ' AND e.id IN (' + ','.join('?' for _ in event_ids) + ')'
args.extend(event_ids)
ids = [r[0] for r in self.db.execute(query + ' ORDER BY e.seq LIMIT ?', (*args, limit))]
if not ids:
return {'batch_id': None, 'event_ids': [], 'status': 'empty'}
batch = 'b_' + digest(js(ids))[:24]
self.db.execute('INSERT INTO batches VALUES(?,?,?,?,?,?)', (batch, now(), 'новый', None, js(ids), None))
self.db.executemany('INSERT INTO batch_events VALUES(?,?,?,?,?)', ((batch, i, 'новый', None, None) for i in ids))
self.db.execute('INSERT INTO batch_history VALUES(?,?,?,?,?,?)', (batch, now(), 'новый', None, None, None))
return {'batch_id': batch, 'event_ids': ids, 'status': 'новый'}
def batch_status(self, batch_id, status, reason=None, *, code_change=None, evidence=None, event_statuses=None):
if status not in STATES:
raise ValueError('invalid status')
with self.transaction():
row = self.db.execute('SELECT * FROM batches WHERE batch_id=?', (batch_id,)).fetchone()
if row is None:
raise KeyError(batch_id)
members = {r['event_id']: r['status'] for r in self.db.execute('SELECT * FROM batch_events WHERE batch_id=?', (batch_id,))}
changes = event_statuses if event_statuses is not None else {i: status for i in members}
if not changes or set(changes) - set(members) or any(s not in STATES for s in changes.values()):
raise ValueError('invalid batch event transition')
if any(s == 'исправлен и проверен' for s in changes.values()) and (not code_change or not evidence):
raise ValueError('fixed requires code_change and executed test evidence')
if any(s in TERMINAL for s in changes.values()) and not reason:
raise ValueError('terminal status requires reason')
for event_id, state in changes.items():
if members[event_id] in TERMINAL and state != members[event_id]:
raise ValueError('terminal event is immutable; append a new correction event')
self.db.execute('UPDATE batch_events SET status=?,reason=?,evidence=? WHERE batch_id=? AND event_id=?',
(state, safe(reason), safe(evidence), batch_id, event_id))
self.db.execute('INSERT INTO batch_history VALUES(?,?,?,?,?,?)',
(batch_id, now(), state, js({'event_id': event_id, 'reason': safe(reason)}), safe(evidence), safe(code_change)))
members[event_id] = state
aggregate = ('проверен' if any(s not in TERMINAL for s in members.values()) else
'исправлен и проверен' if 'исправлен и проверен' in members.values() else 'отложен с причиной')
if all(s in TERMINAL for s in members.values()):
reason = '; '.join(f'{state}: {sum(v == state for v in members.values())}'
for state in sorted(set(members.values())))
changes = [r[0] for r in self.db.execute('''SELECT DISTINCT code_change FROM batch_history
WHERE batch_id=? AND status='исправлен и проверен' AND code_change IS NOT NULL''', (batch_id,))]
code_change = '\n'.join(changes) or 'Системная правка не вносилась; см. причины по событиям.'
self.db.execute('UPDATE batches SET status=?,reason=?,code_change=? WHERE batch_id=?',
(aggregate, safe(reason), safe(code_change), batch_id))
return dict(self.db.execute('SELECT * FROM batches WHERE batch_id=?', (batch_id,)).fetchone())
batch = select_batch
def import_candidates(self, path, record_decisions=False):
path = Path(path).resolve()
path.relative_to(self.root.parent)
document = json.loads(path.read_text())
candidates = document['candidates']
ids, sessions = [], set()
for candidate in candidates:
case = candidate['case_path']
self._case(case)
identity = digest(js(['historical', case, candidate['id'], candidate['source']]))[:32]
session = 'historical-' + digest(str(path) + candidate['id'].split('-')[1])[:24]
if not self.has_event(identity):
self.emit(case, session, 'historical_incident', 'verified-audit-package',
event_id=identity, evidence=str(path),
result='candidate_not_machine_failure',
payload={k: candidate.get(k) for k in ('id', 'source', 'source_id', 'category', 'group', 'evidence', 'note')})
ids.append(identity)
sessions.add((case, session))
for case, session in sessions:
self.finalize(case, session)
batch = self.select_batch(limit=max(len(ids), 1), event_ids=ids)
if record_decisions and batch['batch_id']:
for candidate, event_id in zip(candidates, ids):
status = candidate['status']
self.batch_status(batch['batch_id'], status,
reason=candidate.get('reason') or candidate.get('note'),
evidence=candidate.get('verification_evidence') or str(path),
code_change=candidate.get('code_change'),
event_statuses={event_id: status})
batch = dict(self.db.execute('SELECT * FROM batches WHERE batch_id=?', (batch['batch_id'],)).fetchone())
self.write_index()
return batch
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--data-root', required=True)
parser.add_argument('--code-root', required=True)
sub = parser.add_subparsers(dest='cmd', required=True)
for name in ('begin', 'scan', 'finalize'):
command = sub.add_parser(name)
command.add_argument('case')
command.add_argument('session')
sub.add_parser('health')
command = sub.add_parser('batch')
command.add_argument('--since')
command.add_argument('--until')
command.add_argument('--limit', type=int, default=100)
command = sub.add_parser('status')
command.add_argument('batch_id')
command.add_argument('status', choices=sorted(STATES))
command.add_argument('--reason')
command.add_argument('--code-change')
command.add_argument('--evidence')
command = sub.add_parser('import-candidates')
command.add_argument('path')
command.add_argument('--record-decisions', action='store_true')
args = parser.parse_args(argv)
try:
store = Store(args.data_root, args.code_root)
except (OSError, sqlite3.Error) as exc:
print(js({'ok': False, 'status': 'degraded', 'gap_since': now(), 'error': type(exc).__name__}))
return 1
try:
if args.cmd == 'health':
result = store.health()
elif args.cmd == 'batch':
result = store.select_batch(args.since, args.until, args.limit)
elif args.cmd == 'status':
result = store.batch_status(args.batch_id, args.status, args.reason, code_change=args.code_change, evidence=args.evidence)
elif args.cmd == 'import-candidates':
result = store.import_candidates(args.path, args.record_decisions)
else:
result = getattr(store, args.cmd)(args.case, args.session)
print(js(result))
finally:
store.close()
return 0
if __name__ == '__main__':
raise SystemExit(main())