econtone-studio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,815 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """studio_bridge.py — EconTone Studio 的 Python 入口。
4
+
5
+ 它不实现任何写作规则:只负责把 5 个私有脚本的 JSON 合成一份 RunResult,
6
+ 并补上引擎本身不提供的东西——字符区间、严重度、指纹、错误归一化。
7
+
8
+ python studio_bridge.py health --engine <skills-root>
9
+ python studio_bridge.py measure --file draft.md --profile body --engine <root> --out run.json
10
+
11
+ 只用标准库;不联网;读写都按 UTF-8(读 utf-8-sig,写无 BOM)。
12
+ """
13
+ import argparse
14
+ import datetime
15
+ import difflib
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import sys
22
+ import time
23
+
24
+ # Windows 下 stdout 默认是 GBK:强制 UTF-8,否则输出中文 JSON 时直接崩。
25
+ for _stream in (sys.stdout, sys.stderr):
26
+ if hasattr(_stream, "reconfigure"):
27
+ _stream.reconfigure(encoding="utf-8", errors="replace")
28
+ del _stream
29
+
30
+ SKILLS = [
31
+ "econtone-score",
32
+ "econtone-polish",
33
+ "econtone-ai-trace",
34
+ "econtone-prosody",
35
+ "econtone-equilibrium",
36
+ ]
37
+
38
+ SCRIPTS = {
39
+ "score": ("econtone-score", "score.py"),
40
+ "terminology": ("econtone-polish", "terminology_check.py"),
41
+ "mechanical": ("econtone-polish", "mechanical_check.py"),
42
+ "register": ("econtone-ai-trace", "scan_register.py"),
43
+ "detect": ("econtone-ai-trace", "scan_detectability.py"),
44
+ "prosody": ("econtone-prosody", "prosody_check.py"),
45
+ }
46
+
47
+ SEVERITY = {
48
+ "BANNED": "error",
49
+ "MIXED": "error",
50
+ "ACRONYM": "warn",
51
+ "TIER_HIGH": "warn",
52
+ }
53
+
54
+
55
+ def default_engine():
56
+ home = os.path.expanduser("~")
57
+ return os.path.join(home, ".dsh", "skills")
58
+
59
+
60
+ def read_text(path):
61
+ with open(path, encoding="utf-8-sig", errors="replace") as fh:
62
+ return fh.read()
63
+
64
+
65
+ def normalize(text):
66
+ return text.replace("\r\n", "\n").replace("\r", "\n")
67
+
68
+
69
+ def sha256(text):
70
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
71
+
72
+
73
+ def script_path(engine, key):
74
+ skill, name = SCRIPTS[key]
75
+ return os.path.join(engine, skill, "scripts", name)
76
+
77
+
78
+ def fingerprint(engine):
79
+ h = hashlib.sha256()
80
+ for key in sorted(SCRIPTS):
81
+ p = script_path(engine, key)
82
+ try:
83
+ st = os.stat(p)
84
+ h.update(("%s:%d:%d;" % (key, st.st_size, int(st.st_mtime))).encode())
85
+ except OSError:
86
+ h.update(("%s:missing;" % key).encode())
87
+ return h.hexdigest()[:16]
88
+
89
+
90
+ def call_json(engine, key, args, timeout=120):
91
+ """Run one scanner with --json and return its parsed stdout."""
92
+ p = script_path(engine, key)
93
+ if not os.path.exists(p):
94
+ raise BridgeError("SCANNER_MISSING", "%s 不存在" % p)
95
+ started = time.time()
96
+ try:
97
+ proc = subprocess.run(
98
+ [sys.executable, p] + args + ["--json"],
99
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
100
+ timeout=timeout,
101
+ )
102
+ except subprocess.TimeoutExpired:
103
+ raise BridgeError("TIMEOUT", "%s 超过 %ds" % (key, timeout))
104
+ if proc.returncode not in (0, 2):
105
+ tail = (proc.stderr or proc.stdout or "")[-600:]
106
+ raise BridgeError("SCANNER_FAILED", "%s 退出码 %d: %s" % (key, proc.returncode, tail))
107
+ out = (proc.stdout or "").strip()
108
+ if not out:
109
+ raise BridgeError("SCANNER_FAILED", "%s 没有输出" % key)
110
+ try:
111
+ data = json.loads(out)
112
+ except ValueError as exc:
113
+ raise BridgeError("SCANNER_FAILED", "%s 输出不是 JSON: %s" % (key, exc))
114
+ return data, round(time.time() - started, 3)
115
+
116
+
117
+ class BridgeError(Exception):
118
+ def __init__(self, code, message):
119
+ super().__init__(message)
120
+ self.code = code
121
+ self.message = message
122
+
123
+
124
+ def line_starts(text):
125
+ starts = [0]
126
+ for m in re.finditer("\n", text):
127
+ starts.append(m.end())
128
+ return starts
129
+
130
+
131
+ def paragraphs(text):
132
+ """Return [(start, end)] for blank-line separated paragraphs."""
133
+ out, pos = [], 0
134
+ for block in re.split(r"\n[ \t]*\n", text):
135
+ if block:
136
+ start = text.find(block, pos)
137
+ out.append((start, start + len(block)))
138
+ pos = start + len(block)
139
+ return out
140
+
141
+
142
+ def locate(text, needle, line_no=None, starts=None):
143
+ """Best-effort character range for a needle, preferring the given line."""
144
+ if not needle:
145
+ return None
146
+ if line_no and starts and 0 < line_no <= len(starts):
147
+ s = starts[line_no - 1]
148
+ e = starts[line_no] if line_no < len(starts) else len(text)
149
+ i = text.find(needle, s, e)
150
+ if i >= 0:
151
+ return i, i + len(needle)
152
+ i = text.find(needle)
153
+ if i >= 0:
154
+ return i, i + len(needle)
155
+ # 大小写不同很常见(句首大写),回退到不区分大小写
156
+ m = re.search(re.escape(needle), text, re.IGNORECASE)
157
+ if m:
158
+ return m.start(), m.end()
159
+ return None
160
+
161
+
162
+ def para_of(text, offset, paras):
163
+ for idx, (s, e) in enumerate(paras, 1):
164
+ if s <= offset <= e:
165
+ return idx
166
+ return None
167
+
168
+
169
+ def make_finding(fid, text, paras, starts, original, revised, player, kind,
170
+ severity, evidence, locate_mode="exact", span=None):
171
+ if span:
172
+ s, e = span
173
+ else:
174
+ s = e = 0
175
+ locate_mode = "none"
176
+ return {
177
+ "id": fid,
178
+ "op": "none",
179
+ "base_range": {"start": s, "end": e},
180
+ "after_range": {"start": s, "end": e},
181
+ "original": original,
182
+ "revised": revised,
183
+ "paragraph": para_of(text, s, paras),
184
+ "player": player,
185
+ "kind": kind,
186
+ "severity": severity,
187
+ "decision": "pending",
188
+ "reason": evidence.get("message", "") if evidence else "",
189
+ "evidence": [evidence] if evidence else [],
190
+ "locate": locate_mode,
191
+ }
192
+
193
+
194
+ def collect_findings(text, data):
195
+ paras = paragraphs(text)
196
+ starts = line_starts(text)
197
+ findings = []
198
+ n = [0]
199
+
200
+ def nid():
201
+ n[0] += 1
202
+ return "f-%03d" % n[0]
203
+
204
+ term = data.get("terminology") or {}
205
+ for hit in (term.get("hits") or [])[:40]:
206
+ word = hit.get("term") or ""
207
+ span = locate(text, word, hit.get("line"), starts)
208
+ kind = hit.get("kind", "BANNED")
209
+ findings.append(make_finding(
210
+ nid(), text, paras, starts, word, word, "polish", "wording",
211
+ SEVERITY.get(kind, "warn"),
212
+ {"source": "terminology", "code": kind, "term": word,
213
+ "message": hit.get("why", "")},
214
+ "exact" if span else "paragraph", span,
215
+ ))
216
+
217
+ pros = data.get("prosody") or {}
218
+ for idx, para in enumerate(pros.get("paragraphs") or []):
219
+ for marker in (para.get("red_line_markers") or [])[:6]:
220
+ sentence = (marker.get("sentence") or "").strip()
221
+ span = locate(text, sentence[:80]) if sentence else None
222
+ findings.append(make_finding(
223
+ nid(), text, paras, starts, sentence, sentence, "prosody", "boundary",
224
+ "warn",
225
+ {"source": "prosody", "code": marker.get("name", "MARKER"),
226
+ "message": marker.get("message", "")},
227
+ "exact" if span else "paragraph", span,
228
+ ))
229
+
230
+ det = data.get("detect") or {}
231
+ risk = det.get("risk") or {}
232
+ tier = str(risk.get("tier") or "")
233
+ if risk.get("risk_index") is not None:
234
+ sev = "warn" if ("ELEVATED" in tier or "HIGH" in tier) else "info"
235
+ findings.append(make_finding(
236
+ nid(), text, paras, starts, "", "", "trace", "wording", sev,
237
+ {"source": "trace", "code": "TIER", "value": risk.get("risk_index"),
238
+ "message": "risk_index %.1f / %s" % (risk.get("risk_index"), tier or "?")},
239
+ "none", None,
240
+ ))
241
+
242
+ reg = data.get("register") or {}
243
+ for item in (reg.get("findings") or [])[:10]:
244
+ tokens = item.get("tokens") or {}
245
+ phrase = next(iter(tokens), "")
246
+ span = locate(text, phrase) if phrase else None
247
+ findings.append(make_finding(
248
+ nid(), text, paras, starts, phrase, phrase, "trace", "wording", "warn",
249
+ {"source": "register", "code": "REGISTER",
250
+ "message": "%s · %s" % (item.get("band", ""), phrase)},
251
+ "exact" if span else "paragraph", span,
252
+ ))
253
+
254
+ return findings
255
+
256
+
257
+ def cmd_health(args):
258
+ engine = os.path.abspath(args.engine)
259
+ scripts = {}
260
+ for key in SCRIPTS:
261
+ p = script_path(engine, key)
262
+ scripts[key] = {"path": p, "exists": os.path.exists(p)}
263
+ found = all(v["exists"] for v in scripts.values())
264
+ info = {
265
+ "python": {"version": "%d.%d.%d" % sys.version_info[:3], "executable": sys.executable},
266
+ "engine": {
267
+ "root": engine,
268
+ "found": found,
269
+ "fingerprint": fingerprint(engine),
270
+ "skills": {s: os.path.isdir(os.path.join(engine, s)) for s in SKILLS},
271
+ "scripts": scripts,
272
+ },
273
+ "bridgeVersion": "0.1.0",
274
+ }
275
+ if args.json:
276
+ print(json.dumps({"ok": True, "data": info}, ensure_ascii=False, indent=2))
277
+ else:
278
+ print("python %s" % info["python"]["version"])
279
+ print("engine %s found=%s fp=%s" % (engine, found, info["engine"]["fingerprint"]))
280
+ for key, v in scripts.items():
281
+ print(" %-12s %s" % (key, "ok" if v["exists"] else "MISSING"))
282
+ return 0 if found else 3
283
+
284
+
285
+ def cmd_measure(args):
286
+ engine = os.path.abspath(args.engine)
287
+ text = normalize(read_text(args.file))
288
+ if len(text) > args.max_chars:
289
+ raise BridgeError("DOC_TOO_LARGE", "文本 %d 字符,上限 %d" % (len(text), args.max_chars))
290
+
291
+ data, timings, warnings = {}, {}, []
292
+ jobs = [("score", [args.file, "--profile", args.profile])]
293
+ for key in ("terminology", "register", "detect"):
294
+ jobs.append((key, [args.file]))
295
+ jobs.append(("prosody", [args.file, "--profile", args.profile]))
296
+
297
+ for key, argv in jobs:
298
+ try:
299
+ data[key], timings[key] = call_json(engine, key, argv)
300
+ except BridgeError as exc:
301
+ if key == "score":
302
+ raise
303
+ warnings.append("%s: %s" % (exc.code, exc.message))
304
+ timings[key] = 0.0
305
+
306
+ score = data["score"]
307
+ findings = collect_findings(text, data)
308
+
309
+ result = {
310
+ "runId": args.run_id,
311
+ "createdAt": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
312
+ "profile": args.profile,
313
+ "mode": "measure",
314
+ "document": {
315
+ "path": os.path.abspath(args.file),
316
+ "sha256": sha256(text),
317
+ "chars": len(text),
318
+ },
319
+ "engine": {"root": engine, "fingerprint": fingerprint(engine)},
320
+ "score": {
321
+ "rows": score.get("rows", []),
322
+ "total": score.get("total"),
323
+ "editing_latitude": score.get("editing_latitude"),
324
+ "band": score.get("band"),
325
+ "advice": score.get("advice", ""),
326
+ },
327
+ "findings": findings,
328
+ "edits": [],
329
+ "certificate": None,
330
+ "warnings": warnings,
331
+ "timings": timings,
332
+ }
333
+
334
+ out = args.out or os.path.join(os.path.dirname(os.path.abspath(args.file)), "run.json")
335
+ with open(out, "w", encoding="utf-8", newline="\n") as fh:
336
+ json.dump(result, fh, ensure_ascii=False, indent=2)
337
+
338
+ if args.json:
339
+ print(json.dumps({"ok": True, "data": result}, ensure_ascii=False))
340
+ else:
341
+ print("total %s/100 latitude %s%% band %s findings %d" % (
342
+ result["score"]["total"], result["score"]["editing_latitude"],
343
+ result["score"]["band"], len(findings)))
344
+ print("-> %s" % out)
345
+ return 0
346
+
347
+
348
+ def run_mechanical(engine, path, timeout=60):
349
+ """mechanical_check.py 输出的是裸数组,退出码 2 表示「有发现」。"""
350
+ p = script_path(engine, "mechanical")
351
+ if not os.path.exists(p):
352
+ raise BridgeError("SCANNER_MISSING", p)
353
+ try:
354
+ proc = subprocess.run([sys.executable, p, path, "--json"],
355
+ capture_output=True, text=True, encoding="utf-8",
356
+ errors="replace", timeout=timeout)
357
+ except subprocess.TimeoutExpired:
358
+ raise BridgeError("TIMEOUT", "mechanical_check 超时")
359
+ if proc.returncode not in (0, 2):
360
+ raise BridgeError("SCANNER_FAILED", (proc.stderr or proc.stdout)[-400:])
361
+ try:
362
+ return json.loads(proc.stdout or "[]")
363
+ except ValueError:
364
+ raise BridgeError("SCANNER_FAILED", "mechanical_check 输出不是 JSON")
365
+
366
+
367
+ def apply_suggestions(text, findings, limit=200):
368
+ """把 token→suggest 就地替换,返回 (新文本, 实际替换列表)。"""
369
+ hits = []
370
+ used = set()
371
+ for item in findings[:limit]:
372
+ token = item.get("token") or ""
373
+ repl = item.get("suggest")
374
+ if not token or repl is None:
375
+ continue
376
+ start = 0
377
+ while True:
378
+ i = text.find(token, start)
379
+ if i < 0:
380
+ break
381
+ if i not in used:
382
+ hits.append((i, i + len(token), repl))
383
+ used.add(i)
384
+ break
385
+ start = i + 1
386
+ hits.sort(key=lambda h: h[0], reverse=True)
387
+ out = text
388
+ for s, e, repl in hits:
389
+ out = out[:s] + repl + out[e:]
390
+ applied = [{"from": text[s:e], "to": repl, "at": s} for s, e, repl in reversed(hits)]
391
+ return out, applied
392
+
393
+
394
+ def derive(base, after, source="mechanical", reason=""):
395
+ """字符级 diff → EditUnit 列表(合并相邻、跳过等价段)。source/reason 用于说明改动依据。"""
396
+ sm = difflib.SequenceMatcher(None, base, after, autojunk=False)
397
+ raw = []
398
+ for tag, i1, i2, j1, j2 in sm.get_opcodes():
399
+ if tag == "equal" or (i1 == i2 and j1 == j2):
400
+ continue
401
+ op = "replace" if (i1 < i2 and j1 < j2) else ("delete" if i1 < i2 else "insert")
402
+ raw.append([op, i1, i2, j1, j2])
403
+ merged = []
404
+ for unit in raw:
405
+ if merged and unit[1] - merged[-1][2] <= 2:
406
+ last = merged[-1]
407
+ last[2] = unit[2]
408
+ last[4] = unit[4]
409
+ last[0] = "replace" if (last[2] > last[1] and last[4] > last[3]) else last[0]
410
+ else:
411
+ merged.append(unit)
412
+ paras = paragraphs(base)
413
+ out = []
414
+ for idx, (op, i1, i2, j1, j2) in enumerate(merged, 1):
415
+ out.append({
416
+ "id": "eu-%04d" % idx,
417
+ "op": op,
418
+ "base_range": {"start": i1, "end": i2},
419
+ "after_range": {"start": j1, "end": j2},
420
+ "original": base[i1:i2],
421
+ "revised": after[j1:j2],
422
+ "paragraph": para_of(base, i1, paras),
423
+ "player": "polish",
424
+ "kind": "wording",
425
+ "severity": "info",
426
+ "decision": "accepted",
427
+ "reason": reason,
428
+ "evidence": [{"source": source,
429
+ "code": "MODEL" if source == "model" else "MECHANICAL",
430
+ "message": reason}],
431
+ "locate": "exact",
432
+ })
433
+ return out
434
+
435
+
436
+ def attach_reasons(edits, reasons):
437
+ """把模型给的逐条理由对到 diff 条目上。"""
438
+ if not reasons:
439
+ return edits
440
+ used = set()
441
+ for e in edits:
442
+ hit = None
443
+ for i, r in enumerate(reasons):
444
+ if i in used:
445
+ continue
446
+ o = str(r.get("original") or "").strip()
447
+ v = str(r.get("revised") or "").strip()
448
+ if (o and o == e["original"].strip()) or (v and v == e["revised"].strip()):
449
+ hit = i
450
+ break
451
+ if hit is None:
452
+ for i, r in enumerate(reasons):
453
+ if i in used:
454
+ continue
455
+ o = str(r.get("original") or "").strip()
456
+ if o and (o in e["original"] or e["original"] in o):
457
+ hit = i
458
+ break
459
+ if hit is None:
460
+ continue
461
+ used.add(hit)
462
+ why = str(reasons[hit].get("why") or "").strip()
463
+ if why:
464
+ e["reason"] = why
465
+ if e.get("evidence"):
466
+ e["evidence"][0]["message"] = why
467
+ return edits
468
+
469
+
470
+ def _load_json(path):
471
+ if not path or not os.path.exists(path):
472
+ return None
473
+ try:
474
+ with open(path, encoding="utf-8-sig") as fh:
475
+ return json.load(fh)
476
+ except (OSError, ValueError):
477
+ return None
478
+
479
+
480
+ def cmd_agent_result(args):
481
+ """Agent 已经跑完脚本:这里只读结果,不再执行任何扫描器。"""
482
+ engine = os.path.abspath(args.engine)
483
+ file_abs = os.path.abspath(args.file)
484
+ run_dir = os.path.abspath(args.run_dir or os.path.dirname(file_abs))
485
+ os.makedirs(run_dir, exist_ok=True)
486
+
487
+ base_text = normalize(read_text(file_abs))
488
+ final_text = normalize(read_text(args.final))
489
+ cert = _load_json(args.cert)
490
+ score = _load_json(args.score)
491
+ baseline = _load_json(args.baseline)
492
+ reasons = _load_json(args.reasons)
493
+ if not isinstance(reasons, list):
494
+ reasons = []
495
+
496
+ edits = attach_reasons(derive(base_text, final_text, "model", ""), reasons)
497
+ findings = []
498
+ for i, ch in enumerate(reasons, 1):
499
+ why = str(ch.get("why") or "").strip()
500
+ orig = str(ch.get("original") or "").strip()
501
+ if not orig and not why:
502
+ continue
503
+ findings.append({
504
+ "id": "f-%03d" % i, "op": "none",
505
+ "base_range": {"start": 0, "end": 0},
506
+ "after_range": {"start": 0, "end": 0},
507
+ "original": orig, "revised": str(ch.get("revised") or ""),
508
+ "paragraph": 1, "player": "polish", "kind": "wording",
509
+ "severity": "info", "decision": "accepted", "reason": why,
510
+ "evidence": [{"source": "model", "code": "MODEL", "message": why}],
511
+ "locate": "exact" if orig else "none",
512
+ })
513
+
514
+ result = {
515
+ "runId": args.run_id,
516
+ "createdAt": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
517
+ "profile": args.profile,
518
+ "mode": "agent-arbitrate",
519
+ "document": {"path": file_abs,
520
+ "sha256": hashlib.sha256(base_text.encode("utf-8")).hexdigest(),
521
+ "chars": len(base_text)},
522
+ "engine": {"root": engine, "fingerprint": fingerprint(engine)},
523
+ "score": baseline,
524
+ "findings": findings,
525
+ "edits": edits,
526
+ "certificate": cert,
527
+ "candidateDecision": {"id": "m-agent", "accepted": True,
528
+ "reason": str((cert or {}).get("stopped_because") or "agent")},
529
+ "mechanical": {"applied": 0, "candidate": None, "skipped": "agent mode"},
530
+ "finalText": final_text,
531
+ "baseText": base_text,
532
+ "finalScore": score,
533
+ "warnings": [],
534
+ "timings": {},
535
+ }
536
+
537
+ out = args.out or os.path.join(run_dir, "run.json")
538
+ with open(out, "w", encoding="utf-8", newline="\n") as fh:
539
+ json.dump(result, fh, ensure_ascii=False, indent=2)
540
+ if args.json:
541
+ print(json.dumps({"ok": True, "data": result}, ensure_ascii=False))
542
+ else:
543
+ print("agent result (no scripts run) -> %s" % out)
544
+ return 0
545
+
546
+
547
+ def cmd_arbitrate(args):
548
+ if args.final:
549
+ return cmd_agent_result(args)
550
+ """先测量,再让 play.py 在候选动作上求解均衡。
551
+
552
+ 候选动作为空时仍然走完整链路:play.py 会测量基线并立即停止,
553
+ 证书里写明「无可用动作」。等 P4/P6 产出 cand/*.md 后,这里只换 moves.json。
554
+ """
555
+ engine = os.path.abspath(args.engine)
556
+ file_abs = os.path.abspath(args.file)
557
+ run_dir = os.path.abspath(args.run_dir or os.path.dirname(file_abs))
558
+ os.makedirs(run_dir, exist_ok=True)
559
+
560
+ measure_args = [sys.executable, os.path.abspath(__file__), "measure",
561
+ "--file", file_abs, "--profile", args.profile,
562
+ "--engine", engine, "--run-id", args.run_id, "--json"]
563
+ proc = subprocess.run(measure_args, capture_output=True, text=True,
564
+ encoding="utf-8", errors="replace", timeout=args.timeout)
565
+ if proc.returncode != 0:
566
+ raise BridgeError("MEASURE_FAILED", (proc.stderr or proc.stdout)[-600:])
567
+ payload = json.loads(proc.stdout)
568
+ if not payload.get("ok"):
569
+ err = payload.get("error") or {}
570
+ raise BridgeError(err.get("code", "MEASURE_FAILED"), err.get("message", "measure failed"))
571
+ result = payload["data"]
572
+
573
+ base_text = normalize(read_text(file_abs))
574
+ cand_dir = os.path.join(run_dir, "cand")
575
+ os.makedirs(cand_dir, exist_ok=True)
576
+
577
+ # Agent 路径:均衡由 skill 在子 Agent 里跑,这里只做评分与差分。
578
+ if args.final:
579
+ final_text = normalize(read_text(args.final))
580
+ cert = None
581
+ if args.cert and os.path.exists(args.cert):
582
+ try:
583
+ with open(args.cert, encoding="utf-8-sig") as fh:
584
+ cert = json.load(fh)
585
+ except ValueError:
586
+ cert = None
587
+ if not isinstance(cert, dict):
588
+ cert = {"source": "agent", "game": {}, "rounds": [],
589
+ "stopped_because": "agent-equilibrium"}
590
+ reasons = []
591
+ if args.reasons and os.path.exists(args.reasons):
592
+ try:
593
+ with open(args.reasons, encoding="utf-8-sig") as fh:
594
+ reasons = json.load(fh)
595
+ if not isinstance(reasons, list):
596
+ reasons = []
597
+ except (OSError, ValueError):
598
+ reasons = []
599
+ result["mode"] = "agent-arbitrate"
600
+ result["certificate"] = cert
601
+ result["candidateDecision"] = {"id": "m-agent", "accepted": True,
602
+ "reason": str(cert.get("stopped_because") or "agent")}
603
+ result["mechanical"] = {"applied": 0, "candidate": None, "skipped": "agent mode"}
604
+ result["finalText"] = final_text
605
+ result["edits"] = attach_reasons(derive(base_text, final_text, "model", ""), reasons)
606
+
607
+ final_score = None
608
+ if final_text and final_text != base_text:
609
+ scored = os.path.join(run_dir, "final.md")
610
+ with open(scored, "w", encoding="utf-8", newline="\n") as fh:
611
+ fh.write(final_text)
612
+ proc2 = subprocess.run([sys.executable, os.path.abspath(__file__), "measure",
613
+ "--file", scored, "--profile", args.profile,
614
+ "--engine", engine, "--json"],
615
+ capture_output=True, text=True, encoding="utf-8",
616
+ errors="replace", timeout=args.timeout)
617
+ if proc2.returncode == 0:
618
+ try:
619
+ payload2 = json.loads(proc2.stdout)
620
+ if payload2.get("ok"):
621
+ fs = payload2["data"]["score"]
622
+ final_score = {"rows": fs.get("rows"), "total": fs.get("total"),
623
+ "editing_latitude": fs.get("editing_latitude"),
624
+ "band": fs.get("band")}
625
+ except ValueError:
626
+ final_score = None
627
+ result["finalScore"] = final_score
628
+ out = args.out or os.path.join(run_dir, "run.json")
629
+ with open(out, "w", encoding="utf-8", newline="\n") as fh:
630
+ json.dump(result, fh, ensure_ascii=False, indent=2)
631
+ if args.json:
632
+ print(json.dumps({"ok": True, "data": result}, ensure_ascii=False))
633
+ else:
634
+ print("agent equilibrium: %s" % (cert.get("stopped_because") or ""))
635
+ print("-> %s" % out)
636
+ return 0
637
+
638
+ os.makedirs(cand_dir, exist_ok=True)
639
+ mech_info = {"applied": 0, "candidate": None, "skipped": None}
640
+
641
+ # 机械修正是「赛前动作」:play.py 的 gate:"mechanical" 分支有 bug,
642
+ # 所以按引擎的设计意图,在我们这一层先应用到 current.md,再交给博弈。
643
+ after_text, applied = base_text, []
644
+ try:
645
+ findings = run_mechanical(engine, file_abs)
646
+ after_text, applied = apply_suggestions(base_text, findings)
647
+ except BridgeError as exc:
648
+ mech_info["skipped"] = "%s: %s" % (exc.code, exc.message)
649
+
650
+ current_text = after_text if (applied and after_text != base_text) else base_text
651
+ current_path = os.path.join(run_dir, "current.md")
652
+ with open(current_path, "w", encoding="utf-8", newline="\n") as fh:
653
+ fh.write(current_text)
654
+
655
+ if applied and current_text != base_text:
656
+ cand_path = os.path.join(cand_dir, "mechanical.md")
657
+ with open(cand_path, "w", encoding="utf-8", newline="\n") as fh:
658
+ fh.write(current_text)
659
+ mech_info = {"applied": len(applied), "candidate": cand_path, "skipped": None}
660
+ elif not mech_info["skipped"]:
661
+ mech_info["skipped"] = "no mechanical findings"
662
+
663
+ moves_path = args.candidates or os.path.join(run_dir, "moves.json")
664
+ if args.candidates:
665
+ with open(args.candidates, encoding="utf-8-sig") as fh:
666
+ raw_moves = json.load(fh)
667
+ for mv in raw_moves:
668
+ mv["base"] = "current.md"
669
+ mv.setdefault("player", "polish")
670
+ mv.setdefault("kind", "wording")
671
+ with open(moves_path, "w", encoding="utf-8", newline="\n") as fh:
672
+ json.dump(raw_moves, fh, ensure_ascii=False, indent=2)
673
+ elif not os.path.exists(moves_path):
674
+ with open(moves_path, "w", encoding="utf-8", newline="\n") as fh:
675
+ json.dump([], fh)
676
+
677
+ play = os.path.join(engine, "econtone-equilibrium", "scripts", "play.py")
678
+ if not os.path.exists(play):
679
+ raise BridgeError("SCANNER_MISSING", play)
680
+ cert_path = os.path.join(run_dir, "certificate.json")
681
+ started = time.time()
682
+ proc = subprocess.run([sys.executable, play, "--current", current_path,
683
+ "--moves", moves_path, "--profile", args.profile,
684
+ "--rounds", str(args.rounds), "--iteration-cost", "0",
685
+ "--coalition", args.coalition, "--mode", args.mode,
686
+ "--out", cert_path],
687
+ capture_output=True, text=True, encoding="utf-8",
688
+ errors="replace", timeout=args.timeout)
689
+ if proc.returncode != 0:
690
+ raise BridgeError("ARBITRATE_FAILED", (proc.stderr or proc.stdout)[-800:])
691
+ with open(cert_path, encoding="utf-8-sig") as fh:
692
+ cert = json.load(fh)
693
+
694
+ result["mode"] = "arbitrate"
695
+ result["certificate"] = cert
696
+ decision = None
697
+ for rd in cert.get("rounds") or []:
698
+ for mv in rd.get("moves") or []:
699
+ if mv.get("id") == "m-model":
700
+ decision = {"id": "m-model", "accepted": bool(mv.get("accepted")),
701
+ "reason": mv.get("reason", "")}
702
+ result["candidateDecision"] = decision
703
+ result["timings"]["play"] = round(time.time() - started, 3)
704
+ result["mechanical"] = mech_info
705
+
706
+ final_path = cert.get("final_text_path") or file_abs
707
+ try:
708
+ final_text = normalize(read_text(final_path))
709
+ except OSError:
710
+ final_text = base_text
711
+ result["finalText"] = final_text
712
+ result["baseText"] = base_text
713
+ if decision and decision.get("accepted"):
714
+ dsrc, dreason = "model", decision.get("reason", "")
715
+ elif mech_info.get("applied"):
716
+ dsrc, dreason = "mechanical", "\u62fc\u5199 / \u51a0\u8bcd / \u7a7a\u683c\u4fee\u6b63"
717
+ else:
718
+ dsrc, dreason = "model", ""
719
+ reasons = []
720
+ if args.reasons and os.path.exists(args.reasons):
721
+ try:
722
+ with open(args.reasons, encoding="utf-8-sig") as fh:
723
+ reasons = json.load(fh)
724
+ if not isinstance(reasons, list):
725
+ reasons = []
726
+ except (OSError, ValueError):
727
+ reasons = []
728
+ result["edits"] = attach_reasons(derive(base_text, final_text, dsrc, dreason), reasons)
729
+
730
+ # 改写后的评分:对 final.md 再跑一次 measure(只取 score 部分)
731
+ final_score = None
732
+ if final_text and final_text != base_text:
733
+ scored_path = os.path.join(run_dir, "final.md")
734
+ with open(scored_path, "w", encoding="utf-8", newline="\n") as fh:
735
+ fh.write(final_text)
736
+ proc2 = subprocess.run([sys.executable, os.path.abspath(__file__), "measure",
737
+ "--file", scored_path, "--profile", args.profile,
738
+ "--engine", engine, "--json"],
739
+ capture_output=True, text=True, encoding="utf-8",
740
+ errors="replace", timeout=args.timeout)
741
+ if proc2.returncode == 0:
742
+ try:
743
+ payload2 = json.loads(proc2.stdout)
744
+ if payload2.get("ok"):
745
+ fs = payload2["data"]["score"]
746
+ final_score = {"rows": fs.get("rows"), "total": fs.get("total"),
747
+ "editing_latitude": fs.get("editing_latitude"),
748
+ "band": fs.get("band")}
749
+ except ValueError:
750
+ final_score = None
751
+ result["finalScore"] = final_score
752
+
753
+ out = args.out or os.path.join(run_dir, "run.json")
754
+ with open(out, "w", encoding="utf-8", newline="\n") as fh:
755
+ json.dump(result, fh, ensure_ascii=False, indent=2)
756
+ if args.json:
757
+ print(json.dumps({"ok": True, "data": result}, ensure_ascii=False))
758
+ else:
759
+ print("equilibrium: %s" % (cert.get("stopped_because") or ""))
760
+ print("-> %s" % out)
761
+ return 0
762
+
763
+
764
+ def main(argv=None):
765
+ ap = argparse.ArgumentParser(description="EconTone Studio bridge")
766
+ sub = ap.add_subparsers(dest="cmd", required=True)
767
+
768
+ h = sub.add_parser("health")
769
+ h.add_argument("--engine", default=default_engine())
770
+ h.add_argument("--json", action="store_true")
771
+ h.set_defaults(func=cmd_health)
772
+
773
+ m = sub.add_parser("measure")
774
+ m.add_argument("--file", required=True)
775
+ m.add_argument("--profile", choices=["body", "abstract", "intro"], default="body")
776
+ m.add_argument("--engine", default=default_engine())
777
+ m.add_argument("--out", default=None)
778
+ m.add_argument("--run-id", default="local")
779
+ m.add_argument("--max-chars", type=int, default=200000)
780
+ m.add_argument("--json", action="store_true")
781
+ m.set_defaults(func=cmd_measure)
782
+
783
+ a = sub.add_parser("arbitrate")
784
+ a.add_argument("--file", required=True)
785
+ a.add_argument("--profile", choices=["body", "abstract", "intro"], default="body")
786
+ a.add_argument("--engine", default=default_engine())
787
+ a.add_argument("--out", default=None)
788
+ a.add_argument("--run-id", default="local")
789
+ a.add_argument("--run-dir", default=None)
790
+ a.add_argument("--candidates", default=None)
791
+ a.add_argument("--reasons", default=None)
792
+ a.add_argument("--final", default=None)
793
+ a.add_argument("--cert", default=None)
794
+ a.add_argument("--score", default=None)
795
+ a.add_argument("--baseline", default=None)
796
+ a.add_argument("--rounds", type=int, default=3)
797
+ a.add_argument("--coalition", "--cooperation", dest="coalition",
798
+ choices=["none", "maxsum", "nash"], default="none")
799
+ a.add_argument("--mode", choices=["constrained", "free"], default="constrained")
800
+ a.add_argument("--game", choices=["stackelberg", "nash", "bayes", "correlated"], default="stackelberg")
801
+ a.add_argument("--timeout", type=int, default=900)
802
+ a.add_argument("--json", action="store_true")
803
+ a.set_defaults(func=cmd_arbitrate)
804
+
805
+ args = ap.parse_args(argv)
806
+ try:
807
+ return args.func(args)
808
+ except BridgeError as exc:
809
+ print(json.dumps({"ok": False, "error": {"code": exc.code, "message": exc.message}},
810
+ ensure_ascii=False))
811
+ return 1
812
+
813
+
814
+ if __name__ == "__main__":
815
+ sys.exit(main())