2.1.1 — MCP Phase 0: every high-level op returns an envelope (return-not-print)
Internal refactor per docs/MCP-SERVER-SPEC.md §4; CLI output and exit codes unchanged (wrappers reproduce them from the envelopes): - echo_ops: capture_op/resolve_op/link_op — duplicate gate and offline queueing are data (action: duplicate-gate + candidates; queued: true); the --json stdout-swallow hack is deleted (helper chatter -> stderr inside the cores); capture_op takes body_text= directly (the MCP path, no temp file). - echo_recall.recall_op — one structured result backs prose and --json. - echo_triage.list_op/route_op, echo_reflect.apply_op, echo_session.session_end_op — call capture_op internally, count gate outcomes from envelopes. - echo.scope_show_op/scope_set_op/load_op (+ shared _load_gather), and echo_doctor.run_op (checks as data). New eval/test_ops_api.py asserts the contract for every core: envelope shape AND stdout purity (a stray print would corrupt an MCP response stream). All six suites green. The 2.2 server build now starts directly at the app layer. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -55,19 +55,25 @@ def parse_inbox(text: str) -> list[dict]:
|
||||
return items
|
||||
|
||||
|
||||
def list_inbox(as_json: bool = False) -> int:
|
||||
def list_op() -> dict:
|
||||
"""Core inbox listing (Phase 0): structured captures envelope, no printing."""
|
||||
import echo_output
|
||||
status, body = echo.request("GET", echo.vault_url(INBOX_PATH))
|
||||
if status == 404:
|
||||
items = []
|
||||
else:
|
||||
echo.check(status, body, f"triage list {INBOX_PATH}")
|
||||
items = parse_inbox(body.decode(errors="replace"))
|
||||
return echo_output.envelope("triage-list", {"path": INBOX_PATH, "items": items,
|
||||
"count": len(items)})
|
||||
|
||||
|
||||
def list_inbox(as_json: bool = False) -> int:
|
||||
env = list_op()
|
||||
if as_json:
|
||||
import echo_output
|
||||
env = echo_output.envelope("triage-list", {"path": INBOX_PATH, "items": items,
|
||||
"count": len(items)})
|
||||
print(json.dumps(env, ensure_ascii=False))
|
||||
return 0
|
||||
items = env["items"]
|
||||
if not items:
|
||||
print("triage: inbox is empty — nothing to route.")
|
||||
return 0
|
||||
@@ -80,53 +86,76 @@ def list_inbox(as_json: bool = False) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def apply(proposals: list[dict], confirm: bool = False) -> int:
|
||||
"""Validate -> classify -> preview; with confirm, route each via capture AND write
|
||||
the processing-log audit line. Mirrors echo_reflect.apply's contract exactly."""
|
||||
def route_op(proposals: list[dict], confirm: bool = False) -> dict:
|
||||
"""Core triage routing (Phase 0): reflect pipeline + processing-log audit lines.
|
||||
Returns an envelope (rows = classified preview; results = per-item outcomes);
|
||||
never prints to stdout (audit-append chatter routes to stderr)."""
|
||||
import contextlib
|
||||
import echo_output
|
||||
import echo_reflect
|
||||
valid, errors = echo_reflect.validate(proposals)
|
||||
for e in errors:
|
||||
print(f"skip: {e}", file=sys.stderr)
|
||||
if not valid:
|
||||
print("triage: no valid proposals to route.")
|
||||
return 0
|
||||
|
||||
echo_reflect.classify(valid)
|
||||
counts = {a: sum(1 for p in valid if p.get("_action") == a)
|
||||
for a in ("create", "update", "inbox", "error")}
|
||||
print(f"triage: {len(valid)} proposal(s) — "
|
||||
f"{counts['create']} new, {counts['update']} update, {counts['inbox']} stay-in-inbox"
|
||||
+ (f", {counts['error']} error" if counts["error"] else ""))
|
||||
print(echo_reflect.preview(valid))
|
||||
|
||||
if not confirm:
|
||||
print("\ntriage: dry-run — re-run with --apply to route these and log the moves.")
|
||||
return 0
|
||||
rows: list[dict] = []
|
||||
counts: dict[str, int] = {}
|
||||
if valid:
|
||||
echo_reflect.classify(valid)
|
||||
counts = {a: sum(1 for p in valid if p.get("_action") == a)
|
||||
for a in ("create", "update", "inbox", "error")}
|
||||
rows = [{"action": p.get("_action"), "kind": p.get("kind"),
|
||||
"title": p["title"], "path": p.get("_path")} for p in valid]
|
||||
data = {"proposals": len(proposals or []), "valid": len(valid), "errors": errors,
|
||||
"counts": counts, "rows": rows, "dry_run": not confirm,
|
||||
"routed": 0, "gated": 0, "log": f"{LOG_DIR}/{echo.today()}.md", "results": []}
|
||||
if not valid or not confirm:
|
||||
return echo_output.envelope("triage", data)
|
||||
|
||||
import echo_ops
|
||||
today_s = echo.today()
|
||||
applied = gated = 0
|
||||
routed = gated = 0
|
||||
results = []
|
||||
for p in valid:
|
||||
if p.get("_action") == "error":
|
||||
continue
|
||||
if p.get("_action") == "inbox":
|
||||
if p.get("_action") in ("error", "inbox"):
|
||||
continue # routing an inbox line back to the inbox is a no-op, not a move
|
||||
bodyfile = echo.temp_file((p.get("body") or "").encode()) if p.get("body") else None
|
||||
rc = echo_ops.capture(
|
||||
p.get("kind"), p["title"], bodyfile,
|
||||
env = echo_ops.capture_op(
|
||||
p.get("kind"), p["title"], body_text=p.get("body") or "",
|
||||
aliases=p.get("aliases") or [], sources=p.get("sources") or [],
|
||||
tags=p.get("tags") or [],
|
||||
date=p.get("date"), domain=p.get("domain", "business"))
|
||||
if rc == 76:
|
||||
act = env.get("action", "")
|
||||
results.append({"title": p["title"], "action": act,
|
||||
"path": env.get("path"), "ok": bool(env.get("ok"))})
|
||||
if act == "duplicate-gate":
|
||||
gated += 1
|
||||
continue
|
||||
if rc != 0:
|
||||
if not env.get("ok"):
|
||||
continue
|
||||
applied += 1
|
||||
routed += 1
|
||||
original = (p.get("line") or p["title"]).strip()
|
||||
echo.cmd_append(f"{LOG_DIR}/{today_s}.md",
|
||||
f"- {original} → {p.get('_path', '?')}")
|
||||
print(f"triage: routed {applied}/{len(valid)} item(s); audit in {LOG_DIR}/{today_s}.md. "
|
||||
with contextlib.redirect_stdout(sys.stderr):
|
||||
echo.cmd_append(f"{LOG_DIR}/{today_s}.md",
|
||||
f"- {original} → {p.get('_path', '?')}")
|
||||
data.update(routed=routed, gated=gated, results=results)
|
||||
return echo_output.envelope("triage", data)
|
||||
|
||||
|
||||
def apply(proposals: list[dict], confirm: bool = False) -> int:
|
||||
"""CLI wrapper: same preview/summary text as pre-Phase-0. Mirrors reflect's contract."""
|
||||
env = route_op(proposals, confirm=confirm)
|
||||
for e in env["errors"]:
|
||||
print(f"skip: {e}", file=sys.stderr)
|
||||
if not env["valid"]:
|
||||
print("triage: no valid proposals to route.")
|
||||
return 0
|
||||
counts = env["counts"]
|
||||
print(f"triage: {env['valid']} proposal(s) — "
|
||||
f"{counts['create']} new, {counts['update']} update, {counts['inbox']} stay-in-inbox"
|
||||
+ (f", {counts['error']} error" if counts["error"] else ""))
|
||||
print("\n".join(f" {r['action'] or '?':7} | {('-' if r['action'] == 'inbox' else r['kind'] or '?'):9} "
|
||||
f"| {r['title']} -> {r['path'] or '?'}" for r in env["rows"]))
|
||||
if env["dry_run"]:
|
||||
print("\ntriage: dry-run — re-run with --apply to route these and log the moves.")
|
||||
return 0
|
||||
gated = env["gated"]
|
||||
print(f"triage: routed {env['routed']}/{env['valid']} item(s); audit in {env['log']}. "
|
||||
"Originals kept in the inbox (deletion is explicit-only)."
|
||||
+ (f" {gated} stopped at the duplicate gate — re-propose with the existing "
|
||||
f"entity's title or use capture --merge-into." if gated else ""))
|
||||
|
||||
Reference in New Issue
Block a user