release: Евномия, новая версия, линейка юристов
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{ "name": "femida-lineup", "version": "0.1.0", "description": "Линейка юристов Фемиды над полем ввода: какой этап прогона идет и кто работает", "author": { "name": "Филипп Зарубин" }, "types": "./types/index.d.ts" }
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{ "modules": ["./register.tsx"] }
|
||||
@@ -0,0 +1,34 @@
|
||||
import { expect, test } from 'claude-code/testing'
|
||||
|
||||
import type { Snapshot } from '../types'
|
||||
import { FACES } from './faces'
|
||||
import { headline, lineupSvg } from './register'
|
||||
|
||||
const st = (id: string, title: string, status: string, face: string, who: string) => ({ id, title, status, face, who })
|
||||
const run: Snapshot = {
|
||||
run: '/r', kase: 'client/case', status: 'running', label: 'идет', track: 'FAST', doc: 'иск',
|
||||
phase: 'karta', who: 'Александр Гольмстен', action: '', done: 1, total: 3, since: '10:34', elapsed: 125, mtime: 0,
|
||||
stations: [st('priem', 'Прием', 'ok', 'gruzenberg', 'Грузенберг'), st('karta', 'Карта', 'start', 'holmsten', 'Гольмстен'), st('sborka', 'Сборка', '', 'femida', 'Фемида')],
|
||||
}
|
||||
|
||||
test('идущий этап пульсирует, готовый отмечен, будущий серый', async () => {
|
||||
const svg = lineupSvg(run, { gruzenberg: ['#000000', [['#111111', 'M0 0.5h1']]], holmsten: ['#000000', [['#222222', 'M1 1.5h2']]], femida: ['#000000', [['#333333', 'M2 2.5h1']]] })
|
||||
expect(svg.match(/<animate /g)?.length).toBe(2)
|
||||
expect(svg).toContain('✓')
|
||||
expect(svg).toContain('<path stroke="#222222" d="M1 1.5h2"/>')
|
||||
expect(svg).not.toContain('<image')
|
||||
expect(svg).toContain('url(#gray)')
|
||||
expect(svg.length < 131072).toBe(true)
|
||||
})
|
||||
|
||||
test('строка называет этап, юриста и счет этапов', async () => {
|
||||
expect(headline(run)).toBe('Фемида · client/case · FAST · иск — Карта · Александр Гольмстен · этапов 1 из 3 · с 10:34')
|
||||
expect(headline({ ...run, status: 'stopped', label: 'остановлен' })).toContain('— остановлен · этапов 1 из 3 · шел 2 мин')
|
||||
})
|
||||
|
||||
test('восемь настоящих портретов укладываются в предел Svg', async () => {
|
||||
const all = FACES
|
||||
const big = Object.keys(all).sort((a, b) => JSON.stringify(all[b]).length - JSON.stringify(all[a]).length)
|
||||
const stations = Array.from({ length: 8 }, (_, i) => st(`p${i}`, 'Приложения', 'ok', big[i], 'Шершеневич'))
|
||||
expect(lineupSvg({ ...run, stations }, all).length < 131072).toBe(true)
|
||||
})
|
||||
@@ -0,0 +1,162 @@
|
||||
import { atom, read, update } from 'claude-code'
|
||||
import type { Engine, Register } from 'claude-code'
|
||||
|
||||
import type { Snapshot, Station } from '../types'
|
||||
import { FACE_PX, FACES } from './faces'
|
||||
|
||||
// Линейка прогона Фемиды над полем ввода: портреты юристов по этапам core.PHASES.
|
||||
// Данные - state.json и events.jsonl последнего прогона, читает hooks/snapshot.py.
|
||||
// Мод живет в репозитории Фемиды (plugins/femida-lineup): корень Фемиды - корень сессии.
|
||||
const PYTHON = ['/usr/bin/env', 'python3']
|
||||
// Портрет - штрихи по цветам (hooks/faces.ts, собирает hooks/vectorize.py из портретов кокпита):
|
||||
// приложение вырезает из Svg вложенные картинки <image>, а контуры рисует.
|
||||
type Face = [string, Array<[string, string]>]
|
||||
const POLL_MS = 3_000 // как board.py
|
||||
const SHOW_MIN = 20 // законченный прогон висит 20 минут после последней записи
|
||||
|
||||
const snap = atom({ plugin: 'femida-lineup', key: 'snap' } as const, null)
|
||||
const hidden = atom({ plugin: 'femida-lineup', key: 'hidden' } as const, '')
|
||||
const problem = atom({ plugin: 'femida-lineup', key: 'problem' } as const, null)
|
||||
const pinned = atom({ plugin: 'femida-lineup', key: 'pinned' } as const, false)
|
||||
|
||||
const COLOR: Record<string, string> = {
|
||||
ok: '#3a8f5c', running: '#c9a227', start: '#c9a227', fail: '#b3261e', stopped: '#b3261e', failed: '#b3261e',
|
||||
}
|
||||
const MARK: Record<string, string> = { ok: '✓', fail: '✕', stopped: '✕', failed: '✕' }
|
||||
const W = 96
|
||||
const H = 118
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!)
|
||||
const clock = (s: number) => (s < 3600 ? `${Math.max(1, Math.round(s / 60))} мин` : `${Math.floor(s / 3600)} ч ${Math.floor((s % 3600) / 60)} мин`)
|
||||
|
||||
// Этап, который сейчас идет: фаза из state.json, пока прогон жив.
|
||||
export const isLive = (s: Snapshot, st: Station) => s.status === 'running' && st.id === s.phase && st.status !== 'ok'
|
||||
|
||||
export function lineupSvg(s: Snapshot, pics: Record<string, Face> = FACES): string {
|
||||
const cells = s.stations.map((st, i) => {
|
||||
const x = i * W + W / 2
|
||||
const live = isLive(s, st)
|
||||
const color = live ? COLOR.running : COLOR[st.status] ?? '#8a8a8a'
|
||||
const idle = !live && !st.status
|
||||
const pic = pics[st.face]
|
||||
const ring = live
|
||||
? `<circle cx="${x}" cy="36" r="31" fill="none" stroke="${color}" stroke-width="3"><animate attributeName="r" values="30;34;30" dur="1.6s" repeatCount="indefinite"/><animate attributeName="stroke-opacity" values="1;.35;1" dur="1.6s" repeatCount="indefinite"/></circle>`
|
||||
: `<circle cx="${x}" cy="36" r="30" fill="none" stroke="${color}" stroke-width="${idle ? 1 : 3}"/>`
|
||||
const mark = MARK[st.status]
|
||||
? `<circle cx="${x + 21}" cy="57" r="9" fill="${color}"/><text x="${x + 21}" y="61" font-size="12" fill="#fff" text-anchor="middle">${MARK[st.status]}</text>`
|
||||
: ''
|
||||
const link = i < s.stations.length - 1
|
||||
? `<line x1="${x + 32}" y1="36" x2="${x + W - 32}" y2="36" stroke="${st.status === 'ok' ? COLOR.ok : '#8a8a8a'}" stroke-width="2" stroke-opacity="${st.status === 'ok' ? 1 : 0.35}"/>`
|
||||
: ''
|
||||
const face = pic
|
||||
? `<g clip-path="url(#c${i})" opacity="${idle ? 0.35 : 1}"${idle ? ' filter="url(#gray)"' : ''}>`
|
||||
+ `<g transform="translate(${x - 28} 8) scale(${56 / FACE_PX})" fill="none" shape-rendering="crispEdges">`
|
||||
+ `<rect width="${FACE_PX}" height="${FACE_PX}" fill="${pic[0]}"/>`
|
||||
+ pic[1].map(([stroke, d]) => `<path stroke="${stroke}" d="${d}"/>`).join('') + '</g></g>'
|
||||
: `<circle cx="${x}" cy="36" r="28" fill="#8a8a8a" fill-opacity=".2"/>`
|
||||
return `<clipPath id="c${i}"><circle cx="${x}" cy="36" r="28"/></clipPath>${link}${face}${ring}${mark}`
|
||||
+ `<text x="${x}" y="88" font-size="12" font-weight="${live ? 700 : 500}" fill="${idle ? '#8a8a8a' : 'currentColor'}" text-anchor="middle">${esc(st.title)}</text>`
|
||||
+ `<text x="${x}" y="104" font-size="10.5" fill="#8a8a8a" text-anchor="middle">${esc(st.who)}</text>`
|
||||
+ `<title>${esc(`${st.title}: ${st.who}`)}</title>`
|
||||
})
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W * s.stations.length} ${H}" font-family="-apple-system, system-ui, sans-serif" style="color:#999">`
|
||||
+ `<defs><filter id="gray"><feColorMatrix type="saturate" values="0"/></filter></defs>${cells.join('')}</svg>`
|
||||
}
|
||||
|
||||
export function headline(s: Snapshot): string {
|
||||
const live = s.stations.find(st => isLive(s, st))
|
||||
const now = live ? `${live.title} · ${s.who || live.who}` : s.label
|
||||
// время не тикает: строка меняется только с новым событием прогона, иначе линейка перерисовывается и мерцает
|
||||
const time = s.status === 'running' ? `с ${s.since}` : `шел ${clock(s.elapsed)}`
|
||||
return `Фемида · ${s.kase} · ${s.track} · ${s.doc} — ${now} · этапов ${s.done} из ${s.total} · ${time}`
|
||||
}
|
||||
|
||||
let busy = false
|
||||
let last = ''
|
||||
let themiz = ''
|
||||
|
||||
async function poll($: Engine) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
try {
|
||||
const out = await $.process.run([...PYTHON, `${$.plugin.root}/hooks/snapshot.py`, themiz], { timeoutMs: 10_000 })
|
||||
if (out.exitCode !== 0) throw new Error(out.stderr.trim().split('\n').pop() || `код ${out.exitCode}`)
|
||||
const value = JSON.parse(out.stdout) as Snapshot | null
|
||||
const fresh = value ? { ...value, fresh: value.status === 'running' || Date.now() / 1000 - value.mtime < SHOW_MIN * 60 } : null
|
||||
const key = JSON.stringify(fresh)
|
||||
if (key !== last) {
|
||||
last = key
|
||||
await update($, snap, () => fresh)
|
||||
}
|
||||
if ((await read($, problem)) !== null) await update($, problem, () => null)
|
||||
} catch (error) {
|
||||
const text = error instanceof Error ? error.message : String(error)
|
||||
await update($, problem, () => text)
|
||||
} finally {
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
export const register: Register = on => {
|
||||
on('session.start', async ($, e, next) => {
|
||||
const root = await $.session.root()
|
||||
if (!(await $.fs.exists(`${root}/themiz-next/core.py`))) return next(e)
|
||||
themiz = root
|
||||
await $.command.register({ name: 'lineup', description: 'Линейка юристов Фемиды: показать последний прогон или скрыть' })
|
||||
void poll($)
|
||||
$.clock.every(POLL_MS, () => void poll($))
|
||||
|
||||
return next(e)
|
||||
})
|
||||
|
||||
on('command.run', { command: 'lineup' }, async $ => {
|
||||
const show = !(await read($, pinned))
|
||||
await update($, pinned, () => show)
|
||||
await update($, hidden, () => '')
|
||||
void poll($)
|
||||
|
||||
return { text: show ? 'Линейка Фемиды открыта.' : 'Линейка Фемиды показывается только во время прогона.' }
|
||||
})
|
||||
|
||||
on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
|
||||
const s = await read($, snap)
|
||||
if (e.props.hasSurvey || s === null) return next(e)
|
||||
if (!s.fresh && !(await read($, pinned))) return next(e)
|
||||
if ((await read($, hidden)) === s.run) return next(e)
|
||||
|
||||
const trouble = await read($, problem)
|
||||
const line = headline(s) + (trouble ? ` · табло: ${trouble}` : '')
|
||||
const hide = { key: 'hide', label: 'Скрыть', onPress: () => update($, hidden, () => s.run) }
|
||||
|
||||
if (e.surface === 'terminal') {
|
||||
const { Box, Text, Button } = $.ui.resolve(e)
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
{s.stations.map(st => (
|
||||
<Text key={st.id} color={isLive(s, st) ? 'yellow' : st.status === 'ok' ? 'green' : MARK[st.status] ? 'red' : undefined} dimColor={!st.status && !isLive(s, st)}>
|
||||
{isLive(s, st) ? '● ' : MARK[st.status] ? `${MARK[st.status]} ` : '○ '}{st.title} ({st.who}){' '}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{line} </Text>
|
||||
<Button {...hide} />
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const { Box, Text, Button, Svg } = $.ui.resolve(e)
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{/* живой кадр (пульс) - только когда кто-то реально работает; иначе неподвижная картинка */}
|
||||
{Svg ? <Svg source={lineupSvg(s)} alt={line} isInteractive={s.stations.some(st => isLive(s, st))} /> : null}
|
||||
<Box>
|
||||
<Text dimColor>{line} </Text>
|
||||
<Button {...hide} />
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Снимок последнего прогона Фемиды для линейки: snapshot.py КОРЕНЬ_ФЕМИДЫ."""
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(sys.argv[1])
|
||||
sys.path.insert(0, str(ROOT / "themiz-next"))
|
||||
import board # noqa: E402
|
||||
import core # noqa: E402
|
||||
|
||||
# роль -> портрет из кокпита; роли без своего портрета показывают ведущего фазы
|
||||
ROLE_FACE = {
|
||||
"themiz": "femida", "inbox-triage": "gruzenberg", "case-mapper": "meyer", "case-reconciler": "shershenevich",
|
||||
"pdf-reader": "holmsten", "image-reader": "burinsky", "docx-reader": "pokrovsky",
|
||||
"practice-hunter-classic": "spasovich", "practice-hunter-skeptic": "karabchevsky", "practice-hunter-tactical": "plevako",
|
||||
"position-council/prokuror": "muravyov", "position-council/advokat-dyavola": "maklakov",
|
||||
"position-council/processualist": "foynitsky", "position-council/dokazatelstvennik": "vladimirov",
|
||||
"position-council/taktik": "urusov", "doc-drafter": "speransky", "doc-vychitka": "speransky",
|
||||
"doc-reviewer": "koni", "koni-normy": "koni", "koni-list": "koni",
|
||||
}
|
||||
LEAD = {"priem": "inbox-triage", "karta": "case-mapper", "praktika": "practice-hunter-tactical",
|
||||
"pozitsiya": "position-council/taktik", "chernovik": "doc-drafter", "koni": "doc-reviewer"}
|
||||
FACE_NAME = {"femida": "Фемида", "readers": "Читатели"}
|
||||
|
||||
|
||||
# роли без своей персоны (листы Кони, вычитка) показываются именем того, чью работу делят
|
||||
ALIAS = {"koni-list": "doc-reviewer", "koni-normy": "doc-reviewer", "doc-vychitka": "doc-drafter"}
|
||||
|
||||
|
||||
def person(role: str) -> str:
|
||||
return "Фемида" if role in ("themiz", "") else core.name(ALIAS.get(role, role))
|
||||
|
||||
|
||||
def surname(role: str) -> str:
|
||||
return person(role).split()[-1]
|
||||
|
||||
|
||||
def ts(event: dict) -> float:
|
||||
try:
|
||||
return datetime.fromisoformat(event["ts"]).timestamp()
|
||||
except (KeyError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def snapshot():
|
||||
runs = sorted(ROOT.glob("cases/*/*/.agent/next/*/state.json"), key=lambda p: p.stat().st_mtime)
|
||||
if not runs:
|
||||
return None
|
||||
path = runs[-1]
|
||||
run_dir = path.parent
|
||||
state = json.loads(path.read_text(encoding="utf-8"))
|
||||
case = run_dir.parents[2]
|
||||
if board.is_dead(case, state):
|
||||
state = {**state, "status": "dead"}
|
||||
events = board.read_events(run_dir / "events.jsonl")
|
||||
current = state.get("phase", "")
|
||||
mine = [e for e in events if e.get("phase") == current and e.get("who") in ROLE_FACE]
|
||||
worker = next((e for e in reversed(mine) if e.get("who") != "themiz"), mine[-1] if mine else {})
|
||||
said = next((e for e in reversed(mine)), {})
|
||||
stations = []
|
||||
for pid, title, _ in core.PHASES:
|
||||
info = state.get("phases", {}).get(pid)
|
||||
status = info.get("status", "") if isinstance(info, dict) else (info or "")
|
||||
role = worker.get("who") if pid == current and worker else LEAD.get(pid, "themiz")
|
||||
stations.append({"id": pid, "title": title, "status": status, "face": ROLE_FACE[role], "who": surname(role)})
|
||||
start = ts(events[0]) if events else path.stat().st_mtime
|
||||
end = ts(events[-1]) if events else start
|
||||
done, total = board.done(state)
|
||||
return {
|
||||
"run": str(run_dir), "kase": f"{case.parent.name}/{case.name}", "status": state.get("status", ""),
|
||||
"label": board._label(state.get("status", "")), "track": state.get("track", ""), "doc": state.get("doc", ""),
|
||||
"phase": current, "who": person(worker["who"]) if worker else "", "action": (said.get("action") or "").replace(f"{case}/", "")[:140],
|
||||
"done": done, "total": total, "since": datetime.fromtimestamp(start).strftime("%H:%M"),
|
||||
"elapsed": max(0, round(end - start)), "mtime": round(path.stat().st_mtime), "stations": stations,
|
||||
}
|
||||
|
||||
|
||||
print(json.dumps(snapshot(), ensure_ascii=False))
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Портреты кокпита -> hooks/faces.ts: растр в штрихи SVG по цветам (приложение вырезает <image> из Svg).
|
||||
|
||||
vectorize.py ПАПКА_ПОРТРЕТОВ hooks/faces.ts 64 13
|
||||
Размер и число цветов - наибольшие, при которых восемь самых тяжелых лиц линейки держат предел Svg
|
||||
в 131 072 знака (проверяет hooks/lineup.test.ts).
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
src, out, size, colors = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])
|
||||
|
||||
|
||||
def encode(path: Path) -> list:
|
||||
img = Image.open(path).convert('RGB')
|
||||
w, h = img.size
|
||||
side = int(min(w, h) * 0.62) # круг держит лицо, не бюст
|
||||
left, top = (w - side) // 2, int(h * 0.06)
|
||||
img = img.crop((left, top, left + side, top + side)).resize((size, size), Image.LANCZOS)
|
||||
img = img.quantize(colors, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
|
||||
pal, px = img.getpalette(), img.load()
|
||||
counts: dict[int, int] = {}
|
||||
for y in range(size):
|
||||
for x in range(size):
|
||||
counts[px[x, y]] = counts.get(px[x, y], 0) + 1
|
||||
bg = max(counts, key=counts.get) # самый частый цвет - подложкой, его штрихи не пишутся
|
||||
runs: dict[int, list[str]] = {}
|
||||
for y in range(size):
|
||||
x = 0
|
||||
while x < size:
|
||||
c, s = px[x, y], x
|
||||
while x < size and px[x, y] == c:
|
||||
x += 1
|
||||
if c != bg:
|
||||
runs.setdefault(c, []).append(f'M{s} {y}.5h{x - s}')
|
||||
hexed = lambda c: '#%02x%02x%02x' % tuple(pal[c * 3:c * 3 + 3])
|
||||
return [hexed(bg), [[hexed(c), ''.join(d)] for c, d in runs.items()]]
|
||||
|
||||
|
||||
faces = {f.stem: encode(f) for f in sorted(src.glob('*.png'))}
|
||||
out.write_text(
|
||||
'// Собрано hooks/vectorize.py из cockpit/static/faces, руками не править.\n'
|
||||
f'export const FACE_PX = {size}\n'
|
||||
'export const FACES: Record<string, [string, Array<[string, string]>]> = '
|
||||
+ json.dumps(faces, separators=(',', ':')) + '\n'
|
||||
)
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
export type Station = { id: string; title: string; status: string; face: string; who: string }
|
||||
|
||||
export type Snapshot = {
|
||||
run: string
|
||||
kase: string
|
||||
status: string
|
||||
label: string
|
||||
track: string
|
||||
doc: string
|
||||
phase: string
|
||||
who: string
|
||||
action: string
|
||||
done: number
|
||||
total: number
|
||||
since: string
|
||||
elapsed: number
|
||||
mtime: number
|
||||
fresh?: boolean
|
||||
stations: Station[]
|
||||
}
|
||||
|
||||
declare module 'claude-code' {
|
||||
interface PluginState {
|
||||
'femida-lineup': { snap: Snapshot | null; hidden: string; problem: string | null; pinned: boolean }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user