From e587dd832a12571bfebdc0de5e94a417ff8f0e8b Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:07:29 +0800 Subject: [PATCH 1/2] refactor(lark): slim kanban into cohesive Zero-Any modules Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/lark_kanban.py | 26 +- loopx/extensions/lark/presentation/kanban.py | 1306 +++-------------- .../lark/presentation/kanban_config.py | 591 ++++++++ .../lark/presentation/kanban_records.py | 350 +++++ .../lark/presentation/kanban_sync.py | 458 ++++++ .../extensions/lark/presentation/record_io.py | 47 +- .../lark/presentation/sync_receipt.py | 76 +- tests/extensions/test_lark_kanban_contract.py | 164 +++ 8 files changed, 1829 insertions(+), 1189 deletions(-) create mode 100644 loopx/extensions/lark/presentation/kanban_config.py create mode 100644 loopx/extensions/lark/presentation/kanban_records.py create mode 100644 loopx/extensions/lark/presentation/kanban_sync.py create mode 100644 tests/extensions/test_lark_kanban_contract.py diff --git a/loopx/cli_commands/lark_kanban.py b/loopx/cli_commands/lark_kanban.py index 2875696883..fe5fe3be25 100644 --- a/loopx/cli_commands/lark_kanban.py +++ b/loopx/cli_commands/lark_kanban.py @@ -493,18 +493,20 @@ def handle_lark_kanban_command( payload["operator_card_fields"] = lark_kanban_operator_card_fields() elif args.lark_kanban_command == "sync-loopx-todos": target_config = _target_config(args, config_path=config_path) - payload = sync_loopx_todos_to_lark_kanban( - target_config, - registry_path=registry_path, - goal_id=args.goal_id, - agent_id=args.agent_id, - config_path=config_path, - project=Path(args.project).expanduser() if args.project else None, - state_file=Path(args.state_file).expanduser() if args.state_file else None, - include_done=bool(args.include_done), - limit=args.limit, - sink_visibility=args.sink_visibility, - execute=bool(args.execute), + payload = dict( + sync_loopx_todos_to_lark_kanban( + target_config, + registry_path=registry_path, + goal_id=args.goal_id, + agent_id=args.agent_id, + config_path=config_path, + project=Path(args.project).expanduser() if args.project else None, + state_file=Path(args.state_file).expanduser() if args.state_file else None, + include_done=bool(args.include_done), + limit=args.limit, + sink_visibility=args.sink_visibility, + execute=bool(args.execute), + ) ) try: if not payload.get("ok"): diff --git a/loopx/extensions/lark/presentation/kanban.py b/loopx/extensions/lark/presentation/kanban.py index 188b80aa6f..2e7ff5fcd6 100644 --- a/loopx/extensions/lark/presentation/kanban.py +++ b/loopx/extensions/lark/presentation/kanban.py @@ -1,38 +1,13 @@ +"""Public Lark Kanban facade, seeding workflows, and heartbeat execution.""" + from __future__ import annotations -import json -import re import shlex -from collections.abc import Callable, Mapping -from dataclasses import dataclass +from collections.abc import Mapping, Sequence from datetime import datetime from pathlib import Path -from typing import Any -from urllib.parse import parse_qs, urlparse -from ....control_plane.todos.contract import ( - TODO_STATUS_BLOCKED, - TODO_STATUS_DEFERRED, - TODO_STATUS_DONE, - TODO_STATUS_OPEN, - TODO_TASK_CLASS_ADVANCEMENT, - TODO_TASK_CLASS_BLOCKER, - TODO_TASK_CLASS_USER_GATE, - normalize_explicit_todo_task_class, - normalize_todo_status, -) -from ....presentation.projection_source_reconcile import ( - plan_projection_source_reconcile, - validate_projection_source_reconcile_request, -) -from ....public_safe_text import ( - HOME_RELATIVE_PATH_PATTERN, - PRESENTATION_LOCAL_PATH_PATTERNS, - SECRET_LIKE_SURFACE_PATTERN, - SINK_COMPOUND_CREDENTIAL_ASSIGNMENT_PATTERN, -) from .. import cli_transport as cli_transport -from ..private_json import write_private_json_atomic from . import issue_fix_surface as issue_fix_surface from .kanban_board import ( CLAIM_AGENT as CLAIM_AGENT, @@ -49,7 +24,7 @@ STATUS_RUNNING as STATUS_RUNNING, STATUS_TODO as STATUS_TODO, STATUS_USER_GATE as STATUS_USER_GATE, - _base_cmd, + _base_cmd as _base_cmd, _board_payload as _board_payload, _extract_base_token as _extract_base_token, _extract_created_record_id as _extract_created_record_id, @@ -81,1078 +56,102 @@ setup_lark_kanban_board as setup_lark_kanban_board, use_lark_kanban_board as use_lark_kanban_board, ) -from .projection_rows import ( - projection_lifecycle_parts as _projection_lifecycle_parts, - projection_lifecycle_state as _projection_lifecycle_state, - projection_lifecycle_value as _projection_lifecycle_value, - projection_namespace as _projection_namespace, - projection_rows_from_payload as _projection_rows_from_payload, - projection_text_list as _as_text_list, - todo_matches_agent_scope, +from .kanban_config import ( + DEFAULT_AGENT_ID as DEFAULT_AGENT_ID, + LARK_KANBAN_HEARTBEAT_VERSION as LARK_KANBAN_HEARTBEAT_VERSION, + LARK_KANBAN_LOCAL_CONFIG_VERSION as LARK_KANBAN_LOCAL_CONFIG_VERSION, + LARK_KANBAN_SYNC_PROJECTION_VERSION as LARK_KANBAN_SYNC_PROJECTION_VERSION, + TEXT_LIMIT as TEXT_LIMIT, + LarkKanbanConfig as LarkKanbanConfig, + _ANSI_CONTROL_SEQUENCE_PATTERN as _ANSI_CONTROL_SEQUENCE_PATTERN, + _FEASIBILITY_CASE_SPECS as _FEASIBILITY_CASE_SPECS, + _SHARED_REDACTION_PATTERNS as _SHARED_REDACTION_PATTERNS, + _STRUCTURAL_ID_KEYS as _STRUCTURAL_ID_KEYS, + _STRUCTURAL_RECORD_ID_PATTERN as _STRUCTURAL_RECORD_ID_PATTERN, + _compact_text as _compact_text, + _credential_safe_lark_values as _credential_safe_lark_values, + _credential_safe_text as _credential_safe_text, + _credential_safe_value as _credential_safe_value, + _first_query_value as _first_query_value, + _local_config_stub as _local_config_stub, + _next_lark_kanban_commands as _next_lark_kanban_commands, + _public_safe_lark_values as _public_safe_lark_values, + _public_safe_text as _public_safe_text, + _public_safe_value as _public_safe_value, + _record_json_args as _record_json_args, + _redact_credential_shapes as _redact_credential_shapes, + _redact_non_credential_shapes as _redact_non_credential_shapes, + _redact_public_safe_shapes as _redact_public_safe_shapes, + _sink_safe_lark_values as _sink_safe_lark_values, + _task_record as _task_record, + _transform_lark_value as _transform_lark_value, + _validate_sink_visibility as _validate_sink_visibility, + allowed_worker_command as allowed_worker_command, + append_history as append_history, + build_record_list_command as build_record_list_command, + build_record_upsert_command as build_record_upsert_command, + choose_heartbeat_task as choose_heartbeat_task, + default_lark_kanban_config_path as default_lark_kanban_config_path, + lark_kanban_config_from_payload as lark_kanban_config_from_payload, + lark_kanban_feasibility_cases as lark_kanban_feasibility_cases, + lark_kanban_ux_task as lark_kanban_ux_task, + normalize_select_value as normalize_select_value, + now_lark_datetime as now_lark_datetime, + parse_lark_base_url as parse_lark_base_url, + read_lark_kanban_local_config as read_lark_kanban_local_config, + sample_lark_kanban_task as sample_lark_kanban_task, + save_lark_kanban_board_config as save_lark_kanban_board_config, + write_lark_kanban_local_config as write_lark_kanban_local_config, +) +from .kanban_records import ( + _lark_record_from_projection_block as _lark_record_from_projection_block, + _lark_record_from_todo_block as _lark_record_from_todo_block, + _load_lark_todo_record_map as _load_lark_todo_record_map, + _persist_lark_todo_record_map as _persist_lark_todo_record_map, + _projection_upsert_items as _projection_upsert_items, + _todo_record_map_from_local_config as _todo_record_map_from_local_config, +) +from .kanban_sync import ( + LarkKanbanTodoSyncResult as LarkKanbanTodoSyncResult, + _upsert_record_batch as _upsert_record_batch, + sync_loopx_projection_to_lark_kanban as sync_loopx_projection_to_lark_kanban, + sync_loopx_todos_to_lark_kanban as sync_loopx_todos_to_lark_kanban, ) from .record_io import ( - build_record_delete_command, + RecordTarget as RecordTarget, + build_record_delete_command as build_record_delete_command, lark_record_rows as lark_record_rows, - record_list_is_complete, - todo_record_entries, - todo_record_list_is_authoritative, + record_list_is_complete as record_list_is_complete, + todo_record_entries as todo_record_entries, + todo_record_list_is_authoritative as todo_record_list_is_authoritative, ) from .sink_visibility import ( - SINK_VISIBILITIES, - SINK_VISIBILITY_OWNER_ONLY, - SINK_VISIBILITY_SHARED, + SINK_VISIBILITIES as SINK_VISIBILITIES, + SINK_VISIBILITY_OWNER_ONLY as SINK_VISIBILITY_OWNER_ONLY, + SINK_VISIBILITY_SHARED as SINK_VISIBILITY_SHARED, ) from .sync_receipt import ( compact_lark_kanban_sync_receipt as compact_lark_kanban_sync_receipt, render_lark_kanban_markdown as render_lark_kanban_markdown, ) -LARK_KANBAN_HEARTBEAT_VERSION = "loopx_lark_kanban_heartbeat_v0" -LARK_KANBAN_LOCAL_CONFIG_VERSION = "loopx_lark_kanban_local_config_v0" -LARK_KANBAN_SYNC_PROJECTION_VERSION = "loopx_lark_kanban_sync_projection_v0" -DEFAULT_AGENT_ID = "codex-kanban-worker" -TEXT_LIMIT = 4000 - - -def _task_record(overrides: Mapping[str, object]) -> dict[str, Any]: - base: dict[str, Any] = { - "Task": "", - "Status": STATUS_TODO, - "Claim": CLAIM_UNCLAIMED, - "Claimed By": "", - "Priority": "P1", - "Task Class": "advancement_task", - "Action Kind": "", - "LoopX Goal ID": "", - "LoopX Todo ID": "", - "Scope": "", - "User Gate": "", - "Handoff": "", - "Evidence": "", - "Run History": "", - "Worker Command": "", - "Workdir": "", - "Last Error": "", - "Last Result Code": None, - } - base.update(overrides) - return base - - -def sample_lark_kanban_task( - *, - goal_id: str = "loopx-lark-kanban-poc", - worker_command: str = "", - workdir: str = "", -) -> dict[str, Any]: - return _task_record( - { - "Task": "POC: triage a public issue and produce a reviewable handoff", - "Action Kind": "analyze", - "LoopX Goal ID": goal_id, - "LoopX Todo ID": "todo_lark_kanban_poc", - "Scope": "public repo read/write prototype; no credentials, no private logs", - "Handoff": "Start from the Worker Command. Return compact evidence and next review step.", - "Worker Command": worker_command, - "Workdir": workdir, - } - ) - - -def lark_kanban_ux_task( - *, - goal_id: str = "loopx-lark-kanban-ux", - worker_command: str = "", - workdir: str = "", -) -> dict[str, Any]: - return _task_record( - { - "Task": "Optimize LoopX Kanban control-plane UX", - "Status": STATUS_USER_GATE, - "Claim": CLAIM_HUMAN, - "Task Class": "user_gate", - "Action Kind": "decide", - "LoopX Goal ID": goal_id, - "LoopX Todo ID": "todo_lark_kanban_ux", - "Scope": ( - "Use LoopX itself to reduce operator attention cost while preserving " - "complete structured context in Lark Base." - ), - "User Gate": ( - "Approve the simplified Kanban card profile and heartbeat/subagent " - "worker model for this prototype." - ), - "Handoff": ( - "After approval, move this row to Todo/Unclaimed and let an agent " - "claim it, produce evidence, and leave the row in Review." - ), - "Evidence": "Awaiting human gate pass.", - "Worker Command": worker_command, - "Workdir": workdir, - } - ) - - -_FEASIBILITY_CASE_SPECS = ( - ( - "Case: notes.zaynjarvis.com LoopX architecture decision", - "advancement_task", - "publish_decision_note", - "todo_case_notes_arch_decision", - "Publish a public-safe decision note describing LoopX axioms, control-plane shape, and Lark Kanban adapter tradeoffs.", - "Human approves final wording before publishing.", - "Draft the architecture/decision note, keep source-of-truth fields in the board, and publish only a concise public version.", - "Feasible: the board row captures task, gate, scope, handoff, and public evidence pointer for a notes.zaynjarvis.com publish lane.", - "case seeded: public decision note lane is representable", - ), - ( - "Case: P1/P2 human gate timeout with default fallback", - "user_gate", - "decide_with_timeout", - "todo_case_gate_timeout_fallback", - "Model a human decision that should not block the loop forever; P1/P2 gates can fall back to a default after timeout.", - "Choose explicit decision, or allow the default fallback to fire after the configured timeout.", - "Record the gate question in User Gate; record fallback policy in Handoff; apply only via loop state transition.", - "Feasible: User Gate plus Handoff can separate human choice from the structured state transition that actually changes memory.", - "case seeded: gate timeout/fallback lane is representable", - ), - ( - "Case: cross-session compact memory through OV", - "continuous_monitor", - "memory_handoff", - "todo_case_ov_compact_memory", - "Carry loop context across sessions through an external compact memory surface instead of relying on raw transcript recall.", - "Confirm which facts are durable enough to enter compact memory.", - "Store concise decisions and state deltas externally; keep raw session details out of the Kanban card.", - "Feasible: the Kanban row can point to compact memory writes while remaining a simple operator control surface.", - "case seeded: OV compact-memory lane is representable", - ), - ( - "Case: output quality vs token and attention cost eval", - "advancement_task", - "define_eval", - "todo_case_quality_cost_eval", - "Define a loop benchmark that scores delivered output against token spend and human attention cost.", - "Approve the cost dimensions before using the eval as a gate.", - "Use Evidence for results, Run History for compact attempts, and Priority to decide whether a rerun is worth more attention.", - "Feasible: Base fields support an eval lane that keeps quality, token cost, and attention cost visible without bloating the card.", - "case seeded: quality/cost eval lane is representable", - ), -) - - -def lark_kanban_feasibility_cases( - *, - goal_id: str = "loopx-lark-kanban-feasibility", - workdir: str = "", -) -> list[dict[str, Any]]: - return [ - _task_record( - { - "Status": STATUS_REVIEW, - "Claim": CLAIM_AGENT, - "Claimed By": DEFAULT_AGENT_ID, - "LoopX Goal ID": goal_id, - "Workdir": workdir, - "Last Result Code": 0, - "Task": task, - "Task Class": task_class, - "Action Kind": action_kind, - "LoopX Todo ID": todo_id, - "Scope": scope, - "User Gate": user_gate, - "Handoff": handoff, - "Evidence": evidence, - "Run History": run_history, - } - ) - for task, task_class, action_kind, todo_id, scope, user_gate, handoff, evidence, run_history in _FEASIBILITY_CASE_SPECS - ] - - -def _compact_text(value: object, *, limit: int = TEXT_LIMIT) -> str: - text = " ".join(str(value or "").split()) - return text if len(text) <= limit else text[: max(0, limit - 1)].rstrip() + "..." - - -_ANSI_CONTROL_SEQUENCE_PATTERN = re.compile( - r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)?)" -) - - -def _redact_credential_shapes(value: object) -> str: - text = _ANSI_CONTROL_SEQUENCE_PATTERN.sub("", str(value or "")) - text = SECRET_LIKE_SURFACE_PATTERN.sub("[credential-redacted]", text) - return SINK_COMPOUND_CREDENTIAL_ASSIGNMENT_PATTERN.sub("[credential-redacted]", text) - - -_SHARED_REDACTION_PATTERNS = ( - (re.compile(r"file://[^\s,;)]+", re.IGNORECASE), "[local-path-redacted]"), - *((pattern, "[local-path-redacted]") for pattern in PRESENTATION_LOCAL_PATH_PATTERNS), - (HOME_RELATIVE_PATH_PATTERN, "[local-path-redacted]"), - ( - re.compile( - r"https?://[^\s,;)]*(?:feishu|larksuite|internal|corp|localhost|127\.0\.0\.1)[^\s,;)]*", - re.IGNORECASE, - ), - "[private-link-redacted]", - ), - (re.compile(r"\b(?:base|tbl|vew|rec)[A-Za-z0-9_-]{6,}\b"), "[external-id-redacted]"), - ( - re.compile( - r"\b(?:PRIVATE_MATERIAL|PRIVATE_REF|SECRET_REF|CREDENTIAL_REF)[A-Za-z0-9_.:-]*\b", - re.IGNORECASE, - ), - "[private-ref-redacted]", - ), -) - - -def _redact_non_credential_shapes(text: str) -> str: - for pattern, replacement in _SHARED_REDACTION_PATTERNS: - text = pattern.sub(replacement, text) - return text - - -def _redact_public_safe_shapes(value: object) -> str: - """Apply the shared boundary without collapsing whitespace or truncating.""" - - return _redact_non_credential_shapes(_redact_credential_shapes(value)) - - -def _credential_safe_text(value: object, *, limit: int = TEXT_LIMIT) -> str: - return _compact_text(_redact_credential_shapes(value), limit=limit) - - -def _public_safe_text(value: object, *, limit: int = TEXT_LIMIT) -> str: - text = _compact_text(_redact_credential_shapes(value), limit=limit) - return _compact_text(_redact_non_credential_shapes(text), limit=limit) - - -_STRUCTURAL_ID_KEYS = frozenset({"id", "record_id", "record_ids"}) -_STRUCTURAL_RECORD_ID_PATTERN = re.compile(r"^rec[A-Za-z0-9_-]{6,}$") - - -def _transform_lark_value( - value: object, - *, - text_fn: Callable[[object], str], - key_fn: Callable[[object], str], - check_structural_id: bool = False, - preserve_external_id: bool = False, -) -> object: - if isinstance(value, str): - if check_structural_id and preserve_external_id and _STRUCTURAL_RECORD_ID_PATTERN.fullmatch(value): - return value - return text_fn(value) - if isinstance(value, dict): - return { - key_fn(key): _transform_lark_value( - item, - text_fn=text_fn, - key_fn=key_fn, - check_structural_id=check_structural_id, - preserve_external_id=str(key).lower() in _STRUCTURAL_ID_KEYS, - ) - for key, item in value.items() - } - if isinstance(value, (list, tuple)): - items = [ - _transform_lark_value( - item, - text_fn=text_fn, - key_fn=key_fn, - check_structural_id=check_structural_id, - preserve_external_id=preserve_external_id, - ) - for item in value - ] - return tuple(items) if isinstance(value, tuple) else items - return value - - -def _public_safe_value(value: object, *, preserve_external_id: bool = False) -> object: - return _transform_lark_value( - value, text_fn=_public_safe_text, key_fn=lambda k: _public_safe_text(str(k)), - check_structural_id=True, preserve_external_id=preserve_external_id, - ) - - -def _public_safe_lark_values(values: dict[str, Any]) -> dict[str, Any]: - credential_safe = _credential_safe_lark_values(values) - return {key: _public_safe_value(value) for key, value in credential_safe.items()} - - -def _credential_safe_value(value: object) -> object: - return _transform_lark_value( - value, text_fn=_redact_credential_shapes, key_fn=_redact_credential_shapes - ) - - -def _credential_safe_lark_values(values: dict[str, Any]) -> dict[str, Any]: - return {key: _credential_safe_value(value) for key, value in values.items()} - - -def _sink_safe_lark_values(values: dict[str, Any], *, public_safe: bool) -> dict[str, Any]: - values = _credential_safe_lark_values(values) - return _public_safe_lark_values(values) if public_safe else values - - -def _validate_sink_visibility(sink_visibility: str) -> bool: - if sink_visibility not in SINK_VISIBILITIES: - raise ValueError(f"sink_visibility must be one of {sorted(SINK_VISIBILITIES)}") - return sink_visibility == SINK_VISIBILITY_SHARED - - -def now_lark_datetime(now: datetime | None = None) -> str: - return (now or datetime.now()).strftime("%Y-%m-%d %H:%M:%S") - - -def append_history(existing: object, entry: str, *, limit: int = TEXT_LIMIT) -> str: - prior = str(existing or "").strip() - combined = f"{prior}\n{entry}".strip() if prior else entry - return combined if len(combined) <= limit else combined[-limit:] - - -def normalize_select_value(value: object) -> str: - return str(value[0] or "") if isinstance(value, list) and value else str(value or "") - - -def choose_heartbeat_task( - records: list[dict[str, Any]], *, agent_id: str -) -> dict[str, Any] | None: - own_claim: dict[str, Any] | None = None - unclaimed: dict[str, Any] | None = None - for record in records: - status = normalize_select_value(record.get("Status")) - claim = normalize_select_value(record.get("Claim")) - claimed_by = str(record.get("Claimed By") or "").strip() - if status in {STATUS_DONE, STATUS_BLOCKED, STATUS_REVIEW, STATUS_USER_GATE}: - continue - if claimed_by == agent_id and status in {STATUS_CLAIMED, STATUS_RUNNING, STATUS_TODO}: - own_claim = own_claim or record - continue - if status == STATUS_TODO and claim in {"", CLAIM_UNCLAIMED} and not claimed_by: - unclaimed = unclaimed or record - return own_claim or unclaimed - - -def allowed_worker_command(command: str, prefixes: list[str]) -> bool: - stripped = command.strip() - return bool(stripped and prefixes) and any( - stripped == prefix or stripped.startswith(prefix + " ") for prefix in prefixes - ) - - -def _record_json_args(values: Mapping[str, object]) -> str: - return json.dumps(values, ensure_ascii=False, separators=(",", ":")) - - -@dataclass(frozen=True) -class LarkKanbanConfig: - base_token: str - table_id: str - view_id: str | None = DEFAULT_STATUS_QUEUE_VIEW - cli_bin: str = cli_transport.DEFAULT_CLI_BIN - identity: str = "user" - - -def default_lark_kanban_config_path(registry_path: Path | None = None) -> Path: - if registry_path is not None: - expanded = registry_path.expanduser() - if expanded.parent.name == ".loopx": - return expanded.parent / "lark-kanban.json" - return Path.cwd() / ".loopx" / "lark-kanban.json" - - -def _local_config_stub( - config_path: Path, *, exists: bool, error: str | None = None -) -> dict[str, Any]: - payload: dict[str, Any] = { - "ok": error is None, - "exists": exists, - "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, - "path": str(config_path), - "board": None, - } - if error is not None: - payload["error"] = error - return payload - - -def read_lark_kanban_local_config(path: Path) -> dict[str, Any]: - config_path = path.expanduser() - if not config_path.exists(): - return _local_config_stub(config_path, exists=False) - try: - payload = json.loads(config_path.read_text(encoding="utf-8")) - except json.JSONDecodeError as exc: - return _local_config_stub(config_path, exists=True, error=f"invalid JSON: {exc}") - if not isinstance(payload, dict): - return _local_config_stub(config_path, exists=True, error="config root must be a JSON object") - payload.setdefault("schema_version", LARK_KANBAN_LOCAL_CONFIG_VERSION) - payload["ok"] = True - payload["exists"] = True - payload["path"] = str(config_path) - return payload - - -def write_lark_kanban_local_config(path: Path, payload: Mapping[str, object]) -> None: - config_path = path.expanduser() - config_path.parent.mkdir(parents=True, exist_ok=True) - to_write = dict(payload) - to_write.pop("ok", None) - to_write.pop("exists", None) - to_write["schema_version"] = LARK_KANBAN_LOCAL_CONFIG_VERSION - to_write["updated_at"] = now_lark_datetime() - write_private_json_atomic(config_path, to_write) - - -def parse_lark_base_url(base_url: str) -> dict[str, str]: - parsed = urlparse(base_url.strip()) - query = parse_qs(parsed.query) - parts = [part for part in parsed.path.strip("/").split("/") if part] - base_token = "" - for index, part in enumerate(parts): - if part in {"base", "bitable"} and index + 1 < len(parts): - base_token = parts[index + 1] - break - if not base_token and parts: - base_token = parts[-1] - return { - "base_token": base_token, - "table_id": _first_query_value(query, "table") or _first_query_value(query, "table_id"), - "view_id": _first_query_value(query, "view") or _first_query_value(query, "view_id"), - } - - -def _first_query_value(query: dict[str, list[str]], key: str) -> str: - values = query.get(key) or [] - return str(values[0]).strip() if values else "" - - -def save_lark_kanban_board_config( - path: Path, - *, - base_token: str, - table_id: str, - view_id: str | None = None, - base_url: str | None = None, - base_name: str | None = None, - table_name: str | None = None, - cli_bin: str = cli_transport.DEFAULT_CLI_BIN, - identity: str = "user", - view_ids: dict[str, str] | None = None, - merge_existing: bool = True, -) -> dict[str, Any]: - if not base_token: - raise ValueError("base token is required") - if not table_id: - raise ValueError("table id is required") - config_path = path.expanduser() - existing = read_lark_kanban_local_config(config_path) if merge_existing else {} - payload = existing if isinstance(existing, dict) and existing.get("ok") else {} - raw_board = payload.get("board") - board: dict[str, Any] = dict(raw_board) if isinstance(raw_board, dict) else {} - existing_views = board.get("view_ids") - board.update( - { - "base_token": base_token, - "table_id": table_id, - "view_id": view_id or board.get("view_id") or DEFAULT_STATUS_QUEUE_VIEW, - "base_url": base_url or board.get("base_url") or "", - "base_name": base_name or board.get("base_name") or "", - "table_name": table_name or board.get("table_name") or table_id, - "cli_bin": cli_bin, - "identity": identity, - "view_ids": { - **(existing_views if isinstance(existing_views, dict) else {}), - **(view_ids or {}), - }, - } - ) - raw_records = payload.get("todo_records") - write_lark_kanban_local_config( - config_path, - { - "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, - "board": board, - "todo_records": raw_records if isinstance(raw_records, dict) else {}, - }, - ) - return { - "ok": True, - "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, - "path": str(config_path), - "board": board, - "next_commands": _next_lark_kanban_commands(board), - } - - -def lark_kanban_config_from_payload(payload: Mapping[str, object]) -> LarkKanbanConfig | None: - board = payload.get("board") - if not isinstance(board, dict): - return None - base_token = str(board.get("base_token") or "").strip() - table_id = str(board.get("table_id") or "").strip() - if not base_token or not table_id: - return None - return LarkKanbanConfig( - base_token=base_token, - table_id=table_id, - view_id=str(board.get("view_id") or DEFAULT_STATUS_QUEUE_VIEW), - cli_bin=str(board.get("cli_bin") or cli_transport.DEFAULT_CLI_BIN), - identity=str(board.get("identity") or "user"), - ) - - -def _next_lark_kanban_commands(board: Mapping[str, object]) -> list[str]: - return [ - "loopx lark-kanban doctor", - "loopx lark-kanban sync-loopx-todos --goal-id --execute", - ( - "loopx lark-kanban heartbeat --execute-lark --agent-id " - f"{DEFAULT_AGENT_ID} --allow-command-prefix 'codex exec'" - ), - ] - - -def build_record_upsert_command( - config: LarkKanbanConfig, *, record_id: str | None, values: dict[str, Any] -) -> list[str]: - safe_values = _credential_safe_lark_values(values) - extra = (["--record-id", record_id] if record_id else []) + [ - "--json", _record_json_args(safe_values) - ] - return _base_cmd( - config.cli_bin, "+record-upsert", config.identity, *extra, - base_token=config.base_token, table_id=config.table_id, - ) - - -def build_record_list_command(config: LarkKanbanConfig) -> list[str]: - extra = ["--format", "json", "--offset", "0", "--limit", "200"] - if config.view_id: - extra.extend(["--view-id", config.view_id]) - return _base_cmd( - config.cli_bin, "+record-list", config.identity, *extra, - base_token=config.base_token, table_id=config.table_id, - ) - - -def _lark_record_from_projection_block( - block: dict[str, Any], *, goal_id: str, source_id: str, public_safe: bool = False -) -> dict[str, Any]: - values = _lark_record_from_todo_block( - block, goal_id=goal_id, state_file=Path(f"{source_id}.projection"), - priority=str(block.get("priority") or "P2"), - ) - original_id = str(block.get("original_todo_id") or "") - evidence_parts = [ - str(block.get("evidence") or block.get("reason") or block.get("note") or "").strip(), - f"source_id={source_id}", - ] - if original_id: - evidence_parts.append(f"original_todo_id={original_id}") - evidence_parts.extend(_projection_lifecycle_parts(block, source_id=source_id)) - evidence_parts = list(dict.fromkeys(part for part in evidence_parts if part)) - lifecycle_state = _projection_lifecycle_state(block) - default_handoff = f"Synced from LoopX projection source={source_id}" - if lifecycle_state in {"superseded", "migrated", "retired"}: - superseded_by = ( - ", ".join(_as_text_list(_projection_lifecycle_value(block, "superseded_by"))) - or "current projection row" - ) - default_handoff = f"Row lifecycle {lifecycle_state}; continue with {superseded_by}." - values.update( - { - "LoopX Goal ID": goal_id, - "LoopX Todo ID": str(block.get("todo_id") or ""), - "Scope": _compact_text( - block.get("scope") or block.get("source_section") or f"projection_source={source_id}" - ), - "Handoff": _compact_text(block.get("handoff") or default_handoff), - "Evidence": _compact_text("; ".join(evidence_parts)), - "Run History": _compact_text( - "; ".join( - part - for part in ( - f"synced from LoopX projection source={source_id} status={block.get('status') or 'open'}", - f"row_lifecycle={lifecycle_state}" if lifecycle_state else "", - ) - if part - ) - ), - } - ) - values.update(issue_fix_surface.issue_fix_record_values(block, compact_text=_compact_text)) - return _sink_safe_lark_values(values, public_safe=public_safe) - - -def _projection_upsert_items( - rows: list[dict[str, Any]], *, default_goal_id: str, source_id: str, public_safe: bool -) -> list[tuple[str, str, dict[str, Any]]]: - items: list[tuple[str, str, dict[str, Any]]] = [] - for row in rows: - row_goal_id = str(row.get("goal_id") or default_goal_id) - todo_id = str(row.get("todo_id") or "").strip() - values = _lark_record_from_projection_block( - row, goal_id=row_goal_id, source_id=source_id, public_safe=public_safe - ) - items.append((f"{row_goal_id}:{todo_id}", todo_id, values)) - return items - - -def _upsert_record_batch( - config: LarkKanbanConfig, - items: list[tuple[str, str, dict[str, Any]]], - *, - record_map: dict[str, str], - commands: list[dict[str, Any]], - results: list[dict[str, Any]], - execute: bool, - runner: cli_transport.CommandRunner, -) -> tuple[bool, int]: - ok = True - successful_write_count = 0 - for key, todo_id, values in items: - result = cli_transport.run_command( - build_record_upsert_command(config, record_id=record_map.get(key), values=values), - execute=execute, runner=runner, - ) - commands.append(result) - record_id = _extract_created_record_id(result.get("json")) or record_map.get(key) - if execute and result.get("executed") and result.get("ok"): - successful_write_count += 1 - if execute and result.get("ok") and record_id: - record_map[key] = record_id - results.append({"todo_id": todo_id, "record_id": record_id, "command": result, "values": values}) - ok = ok and bool(result.get("ok")) - if execute and not result.get("ok"): - break - return ok, successful_write_count - - -def sync_loopx_projection_to_lark_kanban( - config: LarkKanbanConfig, - *, - projection: dict[str, Any], - goal_id: str | None = None, - agent_id: str | None = None, - source_id: str | None = None, - config_path: Path | None = None, - include_done: bool = False, - limit: int = 50, - sink_visibility: str = SINK_VISIBILITY_OWNER_ONLY, - reconcile_source: bool = False, - source_snapshot_complete: bool = False, - execute: bool = False, - runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, -) -> dict[str, Any]: - if not isinstance(projection, dict): - raise ValueError("projection must be a JSON object") - public_safe = _validate_sink_visibility(sink_visibility) - resolved_source_id, namespace_warnings = _projection_namespace(projection, source_id) - resolved_goal_id, rows, warnings = _projection_rows_from_payload( - projection, goal_id=goal_id, agent_id=agent_id, - source_id=resolved_source_id, include_done=include_done, limit=limit, - ) - warnings = [*namespace_warnings, *warnings] - - complete_rows = rows - complete_warnings: list[str] = [] - if reconcile_source: - _, complete_rows, complete_warnings = _projection_rows_from_payload( - projection, goal_id=goal_id, agent_id=None, - source_id=resolved_source_id, include_done=True, limit=2**31 - 1, - ) - validate_projection_source_reconcile_request( - requested=reconcile_source, source_snapshot_complete=source_snapshot_complete, - agent_id=agent_id, include_done=include_done, namespace_warnings=namespace_warnings, - selected_row_count=len(rows), complete_row_count=len(complete_rows), - complete_warnings=complete_warnings, - ) - - commands: list[dict[str, Any]] = [] - schema_check: dict[str, Any] | None = None - base_payload: dict[str, Any] = { - "schema_version": LARK_KANBAN_SYNC_PROJECTION_VERSION, - "execute": execute, - "goal_id": resolved_goal_id, - "agent_id": agent_id, - "source_id": resolved_source_id, - "sink_visibility": sink_visibility, - "public_safe_redaction": public_safe, - "projection_schema_version": projection.get("schema_version"), - "row_count": len(rows), - "warnings": warnings, - "config_path": str(config_path) if config_path else None, - } - if execute: - schema_check = _inspect_lark_kanban_schema(config, commands=commands, runner=runner) - if not schema_check.get("ok"): - return { - **base_payload, "ok": False, "records": [], "commands": commands, - "schema_check": schema_check, "error": _schema_check_error(schema_check), - } - - local, record_map, remote_records, remote_list_complete = _load_lark_todo_record_map( - config, config_path=config_path, execute=execute, - inspect_remote=reconcile_source, commands=commands, runner=runner, - ) - if reconcile_source and not remote_list_complete: - raise ValueError("source reconcile requires a complete remote record list") - - desired_keys = { - f"{str(row.get('goal_id') or resolved_goal_id)}:{str(row.get('todo_id') or '').strip()}" - for row in rows - } - reconcile_plan = ( - plan_projection_source_reconcile( - goal_id=resolved_goal_id, source_id=resolved_source_id, - desired_keys=sorted(desired_keys), local_record_map=record_map, - remote_records=remote_records, - ) - if reconcile_source - else { - "schema_version": "projection_source_reconcile_plan_v0", - "goal_id": resolved_goal_id, - "source_id": resolved_source_id, - "remote_orphan_record_ids": [], - "remote_duplicate_record_ids": [], - "remote_delete_record_ids": [], - "local_mapping_keys_to_remove": [], - "remote_delete_count": 0, - "local_mapping_delete_count": 0, - } - ) - - results: list[dict[str, Any]] = [] - ok, _ = _upsert_record_batch( - config, - _projection_upsert_items( - rows, default_goal_id=resolved_goal_id, source_id=resolved_source_id, public_safe=public_safe - ), - record_map=record_map, commands=commands, results=results, execute=execute, runner=runner, - ) - - executed_remote_delete_count = 0 - delete_ids = reconcile_plan.get("remote_delete_record_ids") - if ok and reconcile_source and isinstance(delete_ids, list) and delete_ids: - delete_result = cli_transport.run_command( - build_record_delete_command(config, record_ids=[str(item) for item in delete_ids]), # type: ignore[arg-type] - execute=execute, runner=runner, - ) - commands.append(delete_result) - ok = ok and bool(delete_result.get("ok")) - if execute and delete_result.get("ok"): - raw_delete_count = reconcile_plan.get("remote_delete_count") - executed_remote_delete_count = raw_delete_count if isinstance(raw_delete_count, int) else 0 - - removed_local_mapping_count = 0 - local_keys = reconcile_plan.get("local_mapping_keys_to_remove") - if execute and ok and reconcile_source and isinstance(local_keys, list): - for key in local_keys: - if str(key) in record_map: - removed_local_mapping_count += 1 - record_map.pop(str(key), None) - - if execute and ok: - _persist_lark_todo_record_map(config, config_path=config_path, local=local, record_map=record_map) - - return { - **base_payload, - "ok": ok, - "schema_check": schema_check, - "source_reconcile": { - **reconcile_plan, - "requested": reconcile_source, - "source_snapshot_complete": source_snapshot_complete, - "mode": "execute" if reconcile_source and execute else ("preview" if reconcile_source else "disabled"), - "executed_remote_delete_count": executed_remote_delete_count, - "removed_local_mapping_count": removed_local_mapping_count, - }, - "records": results, - "commands": commands, - } - - -def sync_loopx_todos_to_lark_kanban( - config: LarkKanbanConfig, - *, - registry_path: Path, - goal_id: str, - agent_id: str | None = None, - config_path: Path | None = None, - project: Path | None = None, - state_file: Path | None = None, - include_done: bool = False, - limit: int = 50, - sink_visibility: str = SINK_VISIBILITY_SHARED, - execute: bool = False, - runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, -) -> dict[str, Any]: - from ....capabilities.issue_fix.outcome_projection import ( - build_issue_fix_outcome_collection_from_domain_state, - ) - from ....control_plane.todos.active_state_editing import section_bounds, todo_blocks - from ....control_plane.todos.path_resolution import resolve_todo_state_path - from ....control_plane.todos.todo_semantics import todo_priority_label - - public_safe = _validate_sink_visibility(sink_visibility) - resolved_project, resolved_state_file = resolve_todo_state_path( - registry_path=registry_path, goal_id=goal_id, project=project, state_file=state_file - ) - lines = resolved_state_file.read_text(encoding="utf-8").splitlines() - todos: list[dict[str, Any]] = [] - for role in ("user", "agent"): - bounds = section_bounds(lines, role) - if not bounds: - continue - start, end, heading = bounds - for block in todo_blocks(lines, start, end, role=role, source_section=heading): - status = normalize_todo_status(str(block.get("status") or "").strip()) - if (block.get("done") or status == TODO_STATUS_DONE) and not include_done: - continue - candidate = {**block, "role": role, "source_section": heading} - if todo_matches_agent_scope(candidate, agent_id): - todos.append(candidate) - todos = todos[:limit] - - outcome_projection = build_issue_fix_outcome_collection_from_domain_state( - goal_id=goal_id, project=resolved_project or project or Path(".") - ) - outcome_source_id, outcome_namespace_warnings = _projection_namespace(outcome_projection, None) - outcome_source_count = len(outcome_projection.get("issue_fix_outcomes") or []) - _, outcome_rows, outcome_row_warnings = _projection_rows_from_payload( - outcome_projection, goal_id=goal_id, agent_id=agent_id, - source_id=outcome_source_id, include_done=True, limit=outcome_source_count, - ) - outcome_warnings = [ - *outcome_namespace_warnings, - *list(outcome_projection.get("warnings") or []), - *outcome_row_warnings, - ] - - commands: list[dict[str, Any]] = [] - schema_check: dict[str, Any] | None = None - base_payload: dict[str, Any] = { - "schema_version": "loopx_lark_kanban_sync_todos_v0", - "execute": execute, - "goal_id": goal_id, - "agent_id": agent_id, - "sink_visibility": sink_visibility, - "public_safe_redaction": public_safe, - "base_token": config.base_token, - "table_id": config.table_id, - "view_id": config.view_id, - "project": str(resolved_project) if resolved_project else None, - "state_file": str(resolved_state_file), - "todo_count": len(todos), - "issue_fix_outcome_count": len(outcome_rows), - "limit_policy": {"todo_rows": limit, "issue_fix_outcomes": "complete_source_projection"}, - "issue_fix_source_counts": outcome_projection.get("source_counts"), - "warnings": outcome_warnings, - "config_path": str(config_path) if config_path else None, - } - if execute: - schema_check = _inspect_lark_kanban_schema(config, commands=commands, runner=runner) - if not schema_check.get("ok"): - return { - **base_payload, "ok": False, "records": [], "commands": commands, - "schema_check": schema_check, "successful_write_count": 0, - "external_write_performed": False, "error": _schema_check_error(schema_check), - } - - local, record_map, _, _ = _load_lark_todo_record_map( - config, config_path=config_path, execute=execute, - inspect_remote=False, commands=commands, runner=runner, - ) - - todo_items: list[tuple[str, str, dict[str, Any]]] = [] - for block in todos: - todo_id = str(block.get("todo_id") or "").strip() - values = _lark_record_from_todo_block( - block, goal_id=goal_id, state_file=resolved_state_file, - priority=todo_priority_label(block, text_mode="prefix") or "P2", - ) - if public_safe: - values = _public_safe_lark_values(values) - todo_items.append((f"{goal_id}:{todo_id}", todo_id, values)) - - results: list[dict[str, Any]] = [] - ok, successful_write_count = _upsert_record_batch( - config, todo_items, record_map=record_map, commands=commands, - results=results, execute=execute, runner=runner, - ) - if ok and outcome_rows: - ok, outcome_writes = _upsert_record_batch( - config, - _projection_upsert_items( - outcome_rows, default_goal_id=goal_id, source_id=outcome_source_id, public_safe=public_safe - ), - record_map=record_map, commands=commands, results=results, execute=execute, runner=runner, - ) - successful_write_count += outcome_writes - - if execute and successful_write_count: - _persist_lark_todo_record_map(config, config_path=config_path, local=local, record_map=record_map) - - return { - **base_payload, - "ok": ok, - "schema_check": schema_check, - "records": results, - "commands": commands, - "successful_write_count": successful_write_count, - "external_write_performed": bool(successful_write_count), - } - - -def _load_lark_todo_record_map( - config: LarkKanbanConfig, - *, - config_path: Path | None, - execute: bool, - inspect_remote: bool, - commands: list[dict[str, Any]], - runner: cli_transport.CommandRunner, -) -> tuple[dict[str, Any], dict[str, str], list[dict[str, str]], bool | None]: - local = read_lark_kanban_local_config(config_path) if config_path else {} - record_map = _todo_record_map_from_local_config(local) - if not execute and not inspect_remote: - return local, record_map, [], None - - list_config = LarkKanbanConfig( - base_token=config.base_token, table_id=config.table_id, view_id=None, - cli_bin=config.cli_bin, identity=config.identity, - ) - list_result = cli_transport.run_command( - build_record_list_command(list_config), execute=True, runner=runner - ) - commands.append(list_result) - remote_records: list[dict[str, str]] = [] - remote_complete = False - if list_result.get("ok"): - parsed_records = list_result.get("json") - remote_records = todo_record_entries(parsed_records) - remote_by_key: dict[str, list[str]] = {} - for item in remote_records: - remote_by_key.setdefault(item["key"], []).append(item["record_id"]) - if todo_record_list_is_authoritative(parsed_records): - record_map = { - key: record_id - for key, record_id in record_map.items() - if record_id in remote_by_key.get(key, []) - } - for key, record_ids in remote_by_key.items(): - preferred = record_map.get(key) - record_map[key] = preferred if preferred in record_ids else sorted(record_ids)[0] - remote_complete = record_list_is_complete(parsed_records) - return local, record_map, remote_records, remote_complete - - -def _todo_record_map_from_local_config(local: Mapping[str, object]) -> dict[str, str]: - records = local.get("todo_records") if isinstance(local, Mapping) else None - if not isinstance(records, dict): - return {} - return { - str(key): str(value) - for key, value in records.items() - if str(key).strip() and str(value).strip() - } - - -def _persist_lark_todo_record_map( - config: LarkKanbanConfig, - *, - config_path: Path | None, - local: Mapping[str, object], - record_map: dict[str, str], -) -> None: - if not config_path: - return - raw_board = local.get("board") - board = raw_board if isinstance(raw_board, dict) and raw_board else { - "base_token": config.base_token, - "table_id": config.table_id, - "view_id": config.view_id, - "cli_bin": config.cli_bin, - "identity": config.identity, - } - write_lark_kanban_local_config( - config_path, - { - "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, - "board": board, - "todo_records": record_map, - }, - ) - - -def _lark_record_from_todo_block( - block: dict[str, Any], *, goal_id: str, state_file: Path, priority: str -) -> dict[str, Any]: - role = str(block.get("role") or "agent") - status = normalize_todo_status(str(block.get("status") or "").strip()) or TODO_STATUS_OPEN - task_class = normalize_explicit_todo_task_class(block.get("task_class")) or ( - TODO_TASK_CLASS_USER_GATE if role == "user" else TODO_TASK_CLASS_ADVANCEMENT - ) - claimed_by = str(block.get("claimed_by") or "").strip() - lark_status = STATUS_TODO - if block.get("done") or status == TODO_STATUS_DONE: - lark_status = STATUS_DONE - elif status == TODO_STATUS_BLOCKED or task_class == TODO_TASK_CLASS_BLOCKER: - lark_status = STATUS_BLOCKED - elif role == "user" or task_class == TODO_TASK_CLASS_USER_GATE or status == TODO_STATUS_DEFERRED: - lark_status = STATUS_USER_GATE - elif claimed_by: - lark_status = STATUS_CLAIMED - claim = ( - CLAIM_HUMAN - if lark_status == STATUS_USER_GATE - else (CLAIM_AGENT if claimed_by else CLAIM_UNCLAIMED) - ) - scope = block.get("required_write_scopes") - scope_text = ", ".join(str(item) for item in scope) if isinstance(scope, list) else str(scope or "") - text = str(block.get("text") or "") - values = { - "Task": text, - "Status": lark_status, - "Claim": claim, - "Claimed By": claimed_by, - "Priority": priority if priority in {"P0", "P1", "P2", "P3"} else "P2", - "Task Class": task_class, - "Action Kind": str(block.get("action_kind") or "sync_loopx_todo"), - "LoopX Goal ID": goal_id, - "LoopX Todo ID": str(block.get("todo_id") or ""), - **issue_fix_surface.todo_record_values(), - "Scope": scope_text, - "User Gate": text if lark_status == STATUS_USER_GATE else "", - "Handoff": f"Synced from LoopX active state: {state_file.name}", - "Evidence": str(block.get("evidence") or block.get("reason") or block.get("note") or ""), - "Run History": f"synced from LoopX todo status={status}", - "Worker Command": "", - "Workdir": "", - "Last Error": "", - "Last Result Code": None, - } - return _credential_safe_lark_values(values) - def seed_lark_kanban_task( config: LarkKanbanConfig, *, - task: dict[str, Any], + task: Mapping[str, object], sink_visibility: str = SINK_VISIBILITY_SHARED, execute: bool = False, runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, -) -> dict[str, Any]: +) -> dict[str, object]: public_safe = _validate_sink_visibility(sink_visibility) safe_task = _sink_safe_lark_values(task, public_safe=public_safe) - result = cli_transport.run_command( - build_record_upsert_command(config, record_id=None, values=safe_task), - execute=execute, runner=runner, + result = dict( + cli_transport.run_command( + build_record_upsert_command(config, record_id=None, values=safe_task), + execute=execute, + runner=runner, + ) ) return { "ok": bool(result.get("ok")), @@ -1168,17 +167,21 @@ def seed_lark_kanban_task( def seed_lark_kanban_records( config: LarkKanbanConfig, *, - records: list[dict[str, Any]], + records: Sequence[Mapping[str, object]], sink_visibility: str = SINK_VISIBILITY_SHARED, execute: bool = False, runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, -) -> dict[str, Any]: +) -> dict[str, object]: public_safe = _validate_sink_visibility(sink_visibility) - results: list[dict[str, Any]] = [] + results: list[dict[str, object]] = [] ok = True for record in records: result = seed_lark_kanban_task( - config, task=record, sink_visibility=sink_visibility, execute=execute, runner=runner + config, + task=record, + sink_visibility=sink_visibility, + execute=execute, + runner=runner, ) results.append(result) ok = ok and bool(result.get("ok")) @@ -1201,21 +204,33 @@ def _run_heartbeat_worker( command: str, execute_worker: bool, complete_on_success: bool, - allowed_command_prefixes: list[str] | None, + allowed_command_prefixes: Sequence[str] | None, runner: cli_transport.CommandRunner, worker_timeout_seconds: float, -) -> tuple[dict[str, Any], str, str, int | None]: +) -> tuple[dict[str, object], str, str, int | None]: safe_command = _redact_credential_shapes(command) if not command: return ( - {"attempted": False, "executed": False, "ok": False, "reason": "worker_command_missing", "command": ""}, + { + "attempted": False, + "executed": False, + "ok": False, + "reason": "worker_command_missing", + "command": "", + }, STATUS_USER_GATE, "worker command missing; user must provide Worker Command or heartbeat --worker-command", None, ) if not execute_worker: return ( - {"attempted": True, "executed": False, "ok": True, "reason": "execute_worker_not_set", "command": safe_command}, + { + "attempted": True, + "executed": False, + "ok": True, + "reason": "execute_worker_not_set", + "command": safe_command, + }, STATUS_CLAIMED, f"dry-run worker command: {safe_command}", None, @@ -1223,9 +238,12 @@ def _run_heartbeat_worker( if not allowed_worker_command(command, allowed_command_prefixes or []): return ( { - "attempted": True, "executed": False, "ok": False, - "reason": "worker_command_prefix_not_allowed", "command": safe_command, - "allowed_prefixes": allowed_command_prefixes or [], + "attempted": True, + "executed": False, + "ok": False, + "reason": "worker_command_prefix_not_allowed", + "command": safe_command, + "allowed_prefixes": list(allowed_command_prefixes or []), }, STATUS_BLOCKED, "worker command blocked by prefix allowlist", @@ -1239,7 +257,7 @@ def _run_heartbeat_worker( timeout_seconds=worker_timeout_seconds, ) worker_ok = bool(worker_result.get("ok")) - worker: dict[str, Any] = { + worker: dict[str, object] = { "attempted": True, "executed": True, "ok": worker_ok, @@ -1262,27 +280,34 @@ def lark_kanban_heartbeat( config: LarkKanbanConfig, *, agent_id: str = DEFAULT_AGENT_ID, - fixture: dict[str, Any] | None = None, + fixture: Mapping[str, object] | None = None, worker_command: str | None = None, sink_visibility: str = SINK_VISIBILITY_SHARED, execute_lark: bool = False, execute_worker: bool = False, complete_on_success: bool = False, - allowed_command_prefixes: list[str] | None = None, + allowed_command_prefixes: Sequence[str] | None = None, runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, now: datetime | None = None, worker_timeout_seconds: float = 600.0, -) -> dict[str, Any]: +) -> dict[str, object]: public_safe = _validate_sink_visibility(sink_visibility) - commands: list[dict[str, Any]] = [] + commands: list[dict[str, object]] = [] + parsed: object if fixture is None: - list_result = cli_transport.run_command( - build_record_list_command(config), execute=execute_lark, runner=runner + list_result = dict( + cli_transport.run_command( + build_record_list_command(config), execute=execute_lark, runner=runner + ) ) commands.append(list_result) if execute_lark and not list_result.get("ok"): return _heartbeat_payload( - ok=False, decision="record_list_failed", agent_id=agent_id, commands=commands, records=[] + ok=False, + decision="record_list_failed", + agent_id=agent_id, + commands=commands, + records=[], ) parsed = list_result.get("json") if execute_lark else {"data": {"fields": [], "data": []}} else: @@ -1291,13 +316,21 @@ def lark_kanban_heartbeat( task = choose_heartbeat_task(records, agent_id=agent_id) if task is None: return _heartbeat_payload( - ok=True, decision="no_claimable_task", agent_id=agent_id, commands=commands, records=records + ok=True, + decision="no_claimable_task", + agent_id=agent_id, + commands=commands, + records=records, ) record_id = str(task.get("_record_id") or "").strip() if not record_id: return _heartbeat_payload( - ok=False, decision="selected_task_missing_record_id", agent_id=agent_id, - commands=commands, records=records, selected_task=task, + ok=False, + decision="selected_task_missing_record_id", + agent_id=agent_id, + commands=commands, + records=records, + selected_task=task, ) timestamp = now_lark_datetime(now) claim_values = _sink_safe_lark_values( @@ -1310,21 +343,32 @@ def lark_kanban_heartbeat( }, public_safe=public_safe, ) - claim_result = cli_transport.run_command( - build_record_upsert_command(config, record_id=record_id, values=claim_values), - execute=execute_lark, runner=runner, + claim_result = dict( + cli_transport.run_command( + build_record_upsert_command(config, record_id=record_id, values=claim_values), + execute=execute_lark, + runner=runner, + ) ) commands.append(claim_result) if execute_lark and not claim_result.get("ok"): return _heartbeat_payload( - ok=False, decision="claim_failed", agent_id=agent_id, - commands=commands, records=records, selected_task=task, + ok=False, + decision="claim_failed", + agent_id=agent_id, + commands=commands, + records=records, + selected_task=task, ) command = (worker_command if worker_command is not None else str(task.get("Worker Command") or "")).strip() worker, final_status, evidence, result_code = _run_heartbeat_worker( - task, command=command, execute_worker=execute_worker, - complete_on_success=complete_on_success, allowed_command_prefixes=allowed_command_prefixes, - runner=runner, worker_timeout_seconds=worker_timeout_seconds, + task, + command=command, + execute_worker=execute_worker, + complete_on_success=complete_on_success, + allowed_command_prefixes=allowed_command_prefixes, + runner=runner, + worker_timeout_seconds=worker_timeout_seconds, ) finish_values = _sink_safe_lark_values( { @@ -1343,15 +387,25 @@ def lark_kanban_heartbeat( }, public_safe=public_safe, ) - finish_result = cli_transport.run_command( - build_record_upsert_command(config, record_id=record_id, values=finish_values), - execute=execute_lark, runner=runner, + finish_result = dict( + cli_transport.run_command( + build_record_upsert_command(config, record_id=record_id, values=finish_values), + execute=execute_lark, + runner=runner, + ) ) commands.append(finish_result) ok = bool(worker.get("ok")) and (not execute_lark or bool(finish_result.get("ok"))) return _heartbeat_payload( - ok=ok, decision="task_processed", agent_id=agent_id, commands=commands, records=records, - selected_task=task, worker=worker, final_status=final_status, writeback=finish_values, + ok=ok, + decision="task_processed", + agent_id=agent_id, + commands=commands, + records=records, + selected_task=task, + worker=worker, + final_status=final_status, + writeback=finish_values, ) @@ -1370,13 +424,13 @@ def _heartbeat_payload( ok: bool, decision: str, agent_id: str, - commands: list[dict[str, Any]], - records: list[dict[str, Any]], - selected_task: dict[str, Any] | None = None, - worker: dict[str, Any] | None = None, + commands: Sequence[Mapping[str, object]], + records: Sequence[Mapping[str, object]], + selected_task: Mapping[str, object] | None = None, + worker: Mapping[str, object] | None = None, final_status: str | None = None, - writeback: dict[str, Any] | None = None, -) -> dict[str, Any]: + writeback: Mapping[str, object] | None = None, +) -> dict[str, object]: return { "ok": ok, "schema_version": LARK_KANBAN_HEARTBEAT_VERSION, @@ -1384,9 +438,9 @@ def _heartbeat_payload( "decision": decision, "record_count": len(records), "selected_record_id": selected_task.get("_record_id") if selected_task else None, - "selected_task": selected_task, - "worker": worker, + "selected_task": dict(selected_task) if selected_task is not None else None, + "worker": dict(worker) if worker is not None else None, "final_status": final_status, - "writeback": writeback, - "commands": commands, + "writeback": dict(writeback) if writeback is not None else None, + "commands": [dict(cmd) for cmd in commands], } diff --git a/loopx/extensions/lark/presentation/kanban_config.py b/loopx/extensions/lark/presentation/kanban_config.py new file mode 100644 index 0000000000..6a9ada04bf --- /dev/null +++ b/loopx/extensions/lark/presentation/kanban_config.py @@ -0,0 +1,591 @@ +"""Shared Lark Kanban configuration, redaction, fixture, and command helpers.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +from ....public_safe_text import ( + HOME_RELATIVE_PATH_PATTERN, + PRESENTATION_LOCAL_PATH_PATTERNS, + SECRET_LIKE_SURFACE_PATTERN, + SINK_COMPOUND_CREDENTIAL_ASSIGNMENT_PATTERN, +) +from .. import cli_transport as cli_transport +from ..private_json import write_private_json_atomic +from .kanban_board import ( + CLAIM_UNCLAIMED, + DEFAULT_STATUS_QUEUE_VIEW, + CLAIM_HUMAN, + CLAIM_AGENT, + STATUS_BLOCKED, + STATUS_CLAIMED, + STATUS_DONE, + STATUS_REVIEW, + STATUS_RUNNING, + STATUS_TODO, + STATUS_USER_GATE, + _base_cmd, +) +from .sink_visibility import SINK_VISIBILITIES, SINK_VISIBILITY_SHARED + +LARK_KANBAN_HEARTBEAT_VERSION = "loopx_lark_kanban_heartbeat_v0" +LARK_KANBAN_LOCAL_CONFIG_VERSION = "loopx_lark_kanban_local_config_v0" +LARK_KANBAN_SYNC_PROJECTION_VERSION = "loopx_lark_kanban_sync_projection_v0" +DEFAULT_AGENT_ID = "codex-kanban-worker" +TEXT_LIMIT = 4000 + + +def _task_record(overrides: Mapping[str, object]) -> dict[str, object]: + base: dict[str, object] = { + "Task": "", + "Status": STATUS_TODO, + "Claim": CLAIM_UNCLAIMED, + "Claimed By": "", + "Priority": "P1", + "Task Class": "advancement_task", + "Action Kind": "", + "LoopX Goal ID": "", + "LoopX Todo ID": "", + "Scope": "", + "User Gate": "", + "Handoff": "", + "Evidence": "", + "Run History": "", + "Worker Command": "", + "Workdir": "", + "Last Error": "", + "Last Result Code": None, + } + base.update(overrides) + return base + + +def sample_lark_kanban_task( + *, + goal_id: str = "loopx-lark-kanban-poc", + worker_command: str = "", + workdir: str = "", +) -> dict[str, object]: + return _task_record( + { + "Task": "POC: triage a public issue and produce a reviewable handoff", + "Action Kind": "analyze", + "LoopX Goal ID": goal_id, + "LoopX Todo ID": "todo_lark_kanban_poc", + "Scope": "public repo read/write prototype; no credentials, no private logs", + "Handoff": "Start from the Worker Command. Return compact evidence and next review step.", + "Worker Command": worker_command, + "Workdir": workdir, + } + ) + + +def lark_kanban_ux_task( + *, + goal_id: str = "loopx-lark-kanban-ux", + worker_command: str = "", + workdir: str = "", +) -> dict[str, object]: + return _task_record( + { + "Task": "Optimize LoopX Kanban control-plane UX", + "Status": STATUS_USER_GATE, + "Claim": CLAIM_HUMAN, + "Task Class": "user_gate", + "Action Kind": "decide", + "LoopX Goal ID": goal_id, + "LoopX Todo ID": "todo_lark_kanban_ux", + "Scope": ( + "Use LoopX itself to reduce operator attention cost while preserving " + "complete structured context in Lark Base." + ), + "User Gate": ( + "Approve the simplified Kanban card profile and heartbeat/subagent " + "worker model for this prototype." + ), + "Handoff": ( + "After approval, move this row to Todo/Unclaimed and let an agent " + "claim it, produce evidence, and leave the row in Review." + ), + "Evidence": "Awaiting human gate pass.", + "Worker Command": worker_command, + "Workdir": workdir, + } + ) + + +_FEASIBILITY_CASE_SPECS = ( + ( + "Case: notes.zaynjarvis.com LoopX architecture decision", + "advancement_task", + "publish_decision_note", + "todo_case_notes_arch_decision", + "Publish a public-safe decision note describing LoopX axioms, control-plane shape, and Lark Kanban adapter tradeoffs.", + "Human approves final wording before publishing.", + "Draft the architecture/decision note, keep source-of-truth fields in the board, and publish only a concise public version.", + "Feasible: the board row captures task, gate, scope, handoff, and public evidence pointer for a notes.zaynjarvis.com publish lane.", + "case seeded: public decision note lane is representable", + ), + ( + "Case: P1/P2 human gate timeout with default fallback", + "user_gate", + "decide_with_timeout", + "todo_case_gate_timeout_fallback", + "Model a human decision that should not block the loop forever; P1/P2 gates can fall back to a default after timeout.", + "Choose explicit decision, or allow the default fallback to fire after the configured timeout.", + "Record the gate question in User Gate; record fallback policy in Handoff; apply only via loop state transition.", + "Feasible: User Gate plus Handoff can separate human choice from the structured state transition that actually changes memory.", + "case seeded: gate timeout/fallback lane is representable", + ), + ( + "Case: cross-session compact memory through OV", + "continuous_monitor", + "memory_handoff", + "todo_case_ov_compact_memory", + "Carry loop context across sessions through an external compact memory surface instead of relying on raw transcript recall.", + "Confirm which facts are durable enough to enter compact memory.", + "Store concise decisions and state deltas externally; keep raw session details out of the Kanban card.", + "Feasible: the Kanban row can point to compact memory writes while remaining a simple operator control surface.", + "case seeded: OV compact-memory lane is representable", + ), + ( + "Case: output quality vs token and attention cost eval", + "advancement_task", + "define_eval", + "todo_case_quality_cost_eval", + "Define a loop benchmark that scores delivered output against token spend and human attention cost.", + "Approve the cost dimensions before using the eval as a gate.", + "Use Evidence for results, Run History for compact attempts, and Priority to decide whether a rerun is worth more attention.", + "Feasible: Base fields support an eval lane that keeps quality, token cost, and attention cost visible without bloating the card.", + "case seeded: quality/cost eval lane is representable", + ), +) + + +def lark_kanban_feasibility_cases( + *, + goal_id: str = "loopx-lark-kanban-feasibility", + workdir: str = "", +) -> list[dict[str, object]]: + return [ + _task_record( + { + "Status": STATUS_REVIEW, + "Claim": CLAIM_AGENT, + "Claimed By": DEFAULT_AGENT_ID, + "LoopX Goal ID": goal_id, + "Workdir": workdir, + "Last Result Code": 0, + "Task": task, + "Task Class": task_class, + "Action Kind": action_kind, + "LoopX Todo ID": todo_id, + "Scope": scope, + "User Gate": user_gate, + "Handoff": handoff, + "Evidence": evidence, + "Run History": run_history, + } + ) + for task, task_class, action_kind, todo_id, scope, user_gate, handoff, evidence, run_history in _FEASIBILITY_CASE_SPECS + ] + + +def _compact_text(value: object, *, limit: int = TEXT_LIMIT) -> str: + text = " ".join(str(value or "").split()) + return text if len(text) <= limit else text[: max(0, limit - 1)].rstrip() + "..." + + +_ANSI_CONTROL_SEQUENCE_PATTERN = re.compile( + r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)?)" +) + + +def _redact_credential_shapes(value: object) -> str: + text = _ANSI_CONTROL_SEQUENCE_PATTERN.sub("", str(value or "")) + text = SECRET_LIKE_SURFACE_PATTERN.sub("[credential-redacted]", text) + return SINK_COMPOUND_CREDENTIAL_ASSIGNMENT_PATTERN.sub("[credential-redacted]", text) + + +_SHARED_REDACTION_PATTERNS = ( + (re.compile(r"file://[^\s,;)]+", re.IGNORECASE), "[local-path-redacted]"), + *((pattern, "[local-path-redacted]") for pattern in PRESENTATION_LOCAL_PATH_PATTERNS), + (HOME_RELATIVE_PATH_PATTERN, "[local-path-redacted]"), + ( + re.compile( + r"https?://[^\s,;)]*(?:feishu|larksuite|internal|corp|localhost|127\.0\.0\.1)[^\s,;)]*", + re.IGNORECASE, + ), + "[private-link-redacted]", + ), + (re.compile(r"\b(?:base|tbl|vew|rec)[A-Za-z0-9_-]{6,}\b"), "[external-id-redacted]"), + ( + re.compile( + r"\b(?:PRIVATE_MATERIAL|PRIVATE_REF|SECRET_REF|CREDENTIAL_REF)[A-Za-z0-9_.:-]*\b", + re.IGNORECASE, + ), + "[private-ref-redacted]", + ), +) + + +def _redact_non_credential_shapes(text: str) -> str: + for pattern, replacement in _SHARED_REDACTION_PATTERNS: + text = pattern.sub(replacement, text) + return text + + +def _redact_public_safe_shapes(value: object) -> str: + """Apply the shared boundary without collapsing whitespace or truncating.""" + + return _redact_non_credential_shapes(_redact_credential_shapes(value)) + + +def _credential_safe_text(value: object, *, limit: int = TEXT_LIMIT) -> str: + return _compact_text(_redact_credential_shapes(value), limit=limit) + + +def _public_safe_text(value: object, *, limit: int = TEXT_LIMIT) -> str: + text = _compact_text(_redact_credential_shapes(value), limit=limit) + return _compact_text(_redact_non_credential_shapes(text), limit=limit) + + +_STRUCTURAL_ID_KEYS = frozenset({"id", "record_id", "record_ids"}) +_STRUCTURAL_RECORD_ID_PATTERN = re.compile(r"^rec[A-Za-z0-9_-]{6,}$") + + +def _transform_lark_value( + value: object, + *, + text_fn: Callable[[object], str], + key_fn: Callable[[object], str], + check_structural_id: bool = False, + preserve_external_id: bool = False, +) -> object: + if isinstance(value, str): + if check_structural_id and preserve_external_id and _STRUCTURAL_RECORD_ID_PATTERN.fullmatch(value): + return value + return text_fn(value) + if isinstance(value, dict): + return { + key_fn(key): _transform_lark_value( + item, + text_fn=text_fn, + key_fn=key_fn, + check_structural_id=check_structural_id, + preserve_external_id=str(key).lower() in _STRUCTURAL_ID_KEYS, + ) + for key, item in value.items() + } + if isinstance(value, (list, tuple)): + items = [ + _transform_lark_value( + item, + text_fn=text_fn, + key_fn=key_fn, + check_structural_id=check_structural_id, + preserve_external_id=preserve_external_id, + ) + for item in value + ] + return tuple(items) if isinstance(value, tuple) else items + return value + + +def _public_safe_value(value: object, *, preserve_external_id: bool = False) -> object: + return _transform_lark_value( + value, + text_fn=_public_safe_text, + key_fn=lambda k: _public_safe_text(str(k)), + check_structural_id=True, + preserve_external_id=preserve_external_id, + ) + + +def _public_safe_lark_values(values: Mapping[str, object]) -> dict[str, object]: + credential_safe = _credential_safe_lark_values(values) + return {key: _public_safe_value(value) for key, value in credential_safe.items()} + + +def _credential_safe_value(value: object) -> object: + return _transform_lark_value( + value, + text_fn=_redact_credential_shapes, + key_fn=_redact_credential_shapes, + ) + + +def _credential_safe_lark_values(values: Mapping[str, object]) -> dict[str, object]: + return {key: _credential_safe_value(value) for key, value in values.items()} + + +def _sink_safe_lark_values(values: Mapping[str, object], *, public_safe: bool) -> dict[str, object]: + safe_values = _credential_safe_lark_values(values) + return _public_safe_lark_values(safe_values) if public_safe else safe_values + + +def _validate_sink_visibility(sink_visibility: str) -> bool: + if sink_visibility not in SINK_VISIBILITIES: + raise ValueError(f"sink_visibility must be one of {sorted(SINK_VISIBILITIES)}") + return sink_visibility == SINK_VISIBILITY_SHARED + + +def now_lark_datetime(now: datetime | None = None) -> str: + return (now or datetime.now()).strftime("%Y-%m-%d %H:%M:%S") + + +def append_history(existing: object, entry: str, *, limit: int = TEXT_LIMIT) -> str: + prior = str(existing or "").strip() + combined = f"{prior}\n{entry}".strip() if prior else entry + return combined if len(combined) <= limit else combined[-limit:] + + +def normalize_select_value(value: object) -> str: + return str(value[0] or "") if isinstance(value, list) and value else str(value or "") + + +def choose_heartbeat_task( + records: Sequence[Mapping[str, object]], *, agent_id: str +) -> dict[str, object] | None: + own_claim: dict[str, object] | None = None + unclaimed: dict[str, object] | None = None + for record in records: + status = normalize_select_value(record.get("Status")) + claim = normalize_select_value(record.get("Claim")) + claimed_by = str(record.get("Claimed By") or "").strip() + if status in {STATUS_DONE, STATUS_BLOCKED, STATUS_REVIEW, STATUS_USER_GATE}: + continue + if claimed_by == agent_id and status in {STATUS_CLAIMED, STATUS_RUNNING, STATUS_TODO}: + if own_claim is None: + own_claim = record if isinstance(record, dict) else dict(record) + continue + if status == STATUS_TODO and claim in {"", CLAIM_UNCLAIMED} and not claimed_by: + if unclaimed is None: + unclaimed = record if isinstance(record, dict) else dict(record) + return own_claim or unclaimed + + +def allowed_worker_command(command: str, prefixes: Sequence[str]) -> bool: + stripped = command.strip() + return bool(stripped and prefixes) and any( + stripped == prefix or stripped.startswith(prefix + " ") for prefix in prefixes + ) + + +def _record_json_args(values: Mapping[str, object]) -> str: + return json.dumps(dict(values), ensure_ascii=False, separators=(",", ":")) + + +@dataclass(frozen=True) +class LarkKanbanConfig: + base_token: str + table_id: str + view_id: str | None = DEFAULT_STATUS_QUEUE_VIEW + cli_bin: str = cli_transport.DEFAULT_CLI_BIN + identity: str = "user" + + +def default_lark_kanban_config_path(registry_path: Path | None = None) -> Path: + if registry_path is not None: + expanded = registry_path.expanduser() + if expanded.parent.name == ".loopx": + return expanded.parent / "lark-kanban.json" + return Path.cwd() / ".loopx" / "lark-kanban.json" + + +def _local_config_stub( + config_path: Path, *, exists: bool, error: str | None = None +) -> dict[str, object]: + payload: dict[str, object] = { + "ok": error is None, + "exists": exists, + "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, + "path": str(config_path), + "board": None, + } + if error is not None: + payload["error"] = error + return payload + + +def read_lark_kanban_local_config(path: Path) -> dict[str, object]: + config_path = path.expanduser() + if not config_path.exists(): + return _local_config_stub(config_path, exists=False) + try: + raw_payload: object = json.loads(config_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + return _local_config_stub(config_path, exists=True, error=f"invalid JSON: {exc}") + if not isinstance(raw_payload, dict): + return _local_config_stub(config_path, exists=True, error="config root must be a JSON object") + payload: dict[str, object] = {str(key): value for key, value in raw_payload.items()} + payload.setdefault("schema_version", LARK_KANBAN_LOCAL_CONFIG_VERSION) + payload["ok"] = True + payload["exists"] = True + payload["path"] = str(config_path) + return payload + + +def write_lark_kanban_local_config(path: Path, payload: Mapping[str, object]) -> None: + config_path = path.expanduser() + config_path.parent.mkdir(parents=True, exist_ok=True) + to_write: dict[str, object] = dict(payload) + to_write.pop("ok", None) + to_write.pop("exists", None) + to_write["schema_version"] = LARK_KANBAN_LOCAL_CONFIG_VERSION + to_write["updated_at"] = now_lark_datetime() + write_private_json_atomic(config_path, to_write) + + +def parse_lark_base_url(base_url: str) -> dict[str, str]: + parsed = urlparse(base_url.strip()) + query = parse_qs(parsed.query) + parts = [part for part in parsed.path.strip("/").split("/") if part] + base_token = "" + for index, part in enumerate(parts): + if part in {"base", "bitable"} and index + 1 < len(parts): + base_token = parts[index + 1] + break + if not base_token and parts: + base_token = parts[-1] + return { + "base_token": base_token, + "table_id": _first_query_value(query, "table") or _first_query_value(query, "table_id"), + "view_id": _first_query_value(query, "view") or _first_query_value(query, "view_id"), + } + + +def _first_query_value(query: Mapping[str, Sequence[str]], key: str) -> str: + values = query.get(key) or () + return str(values[0]).strip() if values else "" + + +def save_lark_kanban_board_config( + path: Path, + *, + base_token: str, + table_id: str, + view_id: str | None = None, + base_url: str | None = None, + base_name: str | None = None, + table_name: str | None = None, + cli_bin: str = cli_transport.DEFAULT_CLI_BIN, + identity: str = "user", + view_ids: Mapping[str, object] | None = None, + merge_existing: bool = True, +) -> dict[str, object]: + if not base_token: + raise ValueError("base token is required") + if not table_id: + raise ValueError("table id is required") + config_path = path.expanduser() + existing = read_lark_kanban_local_config(config_path) if merge_existing else {} + payload: Mapping[str, object] = existing if existing.get("ok") else {} + raw_board = payload.get("board") + board: dict[str, object] = ( + {str(key): value for key, value in raw_board.items()} if isinstance(raw_board, dict) else {} + ) + existing_views = board.get("view_ids") + merged_views: dict[str, object] = ( + {str(key): value for key, value in existing_views.items()} + if isinstance(existing_views, dict) + else {} + ) + if view_ids: + merged_views.update(view_ids) + board.update( + { + "base_token": base_token, + "table_id": table_id, + "view_id": view_id or board.get("view_id") or DEFAULT_STATUS_QUEUE_VIEW, + "base_url": base_url or board.get("base_url") or "", + "base_name": base_name or board.get("base_name") or "", + "table_name": table_name or board.get("table_name") or table_id, + "cli_bin": cli_bin, + "identity": identity, + "view_ids": merged_views, + } + ) + raw_records = payload.get("todo_records") + write_lark_kanban_local_config( + config_path, + { + "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, + "board": board, + "todo_records": raw_records if isinstance(raw_records, dict) else {}, + }, + ) + return { + "ok": True, + "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, + "path": str(config_path), + "board": board, + "next_commands": _next_lark_kanban_commands(board), + } + + +def lark_kanban_config_from_payload(payload: Mapping[str, object]) -> LarkKanbanConfig | None: + board = payload.get("board") + if not isinstance(board, dict): + return None + base_token = str(board.get("base_token") or "").strip() + table_id = str(board.get("table_id") or "").strip() + if not base_token or not table_id: + return None + return LarkKanbanConfig( + base_token=base_token, + table_id=table_id, + view_id=str(board.get("view_id") or DEFAULT_STATUS_QUEUE_VIEW), + cli_bin=str(board.get("cli_bin") or cli_transport.DEFAULT_CLI_BIN), + identity=str(board.get("identity") or "user"), + ) + + +def _next_lark_kanban_commands(board: Mapping[str, object]) -> list[str]: + del board + return [ + "loopx lark-kanban doctor", + "loopx lark-kanban sync-loopx-todos --goal-id --execute", + ( + "loopx lark-kanban heartbeat --execute-lark --agent-id " + f"{DEFAULT_AGENT_ID} --allow-command-prefix 'codex exec'" + ), + ] + + +def build_record_upsert_command( + config: LarkKanbanConfig, *, record_id: str | None, values: Mapping[str, object] +) -> list[str]: + safe_values = _credential_safe_lark_values(values) + extra = (["--record-id", record_id] if record_id else []) + [ + "--json", + _record_json_args(safe_values), + ] + return _base_cmd( + config.cli_bin, + "+record-upsert", + config.identity, + *extra, + base_token=config.base_token, + table_id=config.table_id, + ) + + +def build_record_list_command(config: LarkKanbanConfig) -> list[str]: + extra = ["--format", "json", "--offset", "0", "--limit", "200"] + if config.view_id: + extra.extend(["--view-id", config.view_id]) + return _base_cmd( + config.cli_bin, + "+record-list", + config.identity, + *extra, + base_token=config.base_token, + table_id=config.table_id, + ) diff --git a/loopx/extensions/lark/presentation/kanban_records.py b/loopx/extensions/lark/presentation/kanban_records.py new file mode 100644 index 0000000000..d4579f9ed0 --- /dev/null +++ b/loopx/extensions/lark/presentation/kanban_records.py @@ -0,0 +1,350 @@ +"""Lark Kanban record mapping and local todo-record cache persistence.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Protocol, cast + +from ....control_plane.todos.contract import ( + TODO_STATUS_BLOCKED, + TODO_STATUS_DEFERRED, + TODO_STATUS_DONE, + TODO_STATUS_OPEN, + TODO_TASK_CLASS_ADVANCEMENT, + TODO_TASK_CLASS_BLOCKER, + TODO_TASK_CLASS_USER_GATE, + normalize_explicit_todo_task_class, + normalize_todo_status, +) +from .. import cli_transport as cli_transport +from . import issue_fix_surface as issue_fix_surface +from . import projection_rows as projection_rows +from .kanban_board import ( + CLAIM_AGENT, + CLAIM_HUMAN, + CLAIM_UNCLAIMED, + STATUS_BLOCKED, + STATUS_CLAIMED, + STATUS_DONE, + STATUS_TODO, + STATUS_USER_GATE, +) +from .kanban_config import ( + LARK_KANBAN_LOCAL_CONFIG_VERSION, + LarkKanbanConfig, + _compact_text, + _credential_safe_lark_values, + _public_safe_lark_values, + _sink_safe_lark_values, + build_record_list_command, + read_lark_kanban_local_config, + write_lark_kanban_local_config, +) +from .record_io import ( + record_list_is_complete, + todo_record_entries, + todo_record_list_is_authoritative, +) + + +class _ProjectionRowsAdapter(Protocol): + def projection_lifecycle_parts( + self, item: Mapping[str, object], *, source_id: str + ) -> list[str]: ... + def projection_lifecycle_state(self, item: Mapping[str, object]) -> str: ... + def projection_lifecycle_value( + self, item: Mapping[str, object], key: str + ) -> object: ... + def projection_namespace( + self, projection: Mapping[str, object], source_id: str | None + ) -> tuple[str, list[str]]: ... + def projection_rows_from_payload( + self, + projection: Mapping[str, object], + *, + goal_id: str | None, + agent_id: str | None, + source_id: str, + include_done: bool, + limit: int, + ) -> tuple[str, list[dict[str, object]], list[str]]: ... + def projection_text_list(self, value: object) -> list[str]: ... + def todo_matches_agent_scope( + self, block: Mapping[str, object], agent_id: str | None + ) -> bool: ... + + +def _projection_rows_api() -> _ProjectionRowsAdapter: + return cast(_ProjectionRowsAdapter, projection_rows) + + +def _json_dict(value: Mapping[str, object]) -> dict[str, object]: + return dict(value) + + +def _lark_record_from_projection_block( + block: Mapping[str, object], + *, + goal_id: str, + source_id: str, + public_safe: bool = False, +) -> dict[str, object]: + rows_api = _projection_rows_api() + values = _lark_record_from_todo_block( + block, + goal_id=goal_id, + state_file=Path(f"{source_id}.projection"), + priority=str(block.get("priority") or "P2"), + ) + original_id = str(block.get("original_todo_id") or "") + evidence_parts = [ + str(block.get("evidence") or block.get("reason") or block.get("note") or "").strip(), + f"source_id={source_id}", + ] + if original_id: + evidence_parts.append(f"original_todo_id={original_id}") + evidence_parts.extend(rows_api.projection_lifecycle_parts(block, source_id=source_id)) + evidence_parts = list(dict.fromkeys(part for part in evidence_parts if part)) + lifecycle_state = rows_api.projection_lifecycle_state(block) + default_handoff = f"Synced from LoopX projection source={source_id}" + if lifecycle_state in {"superseded", "migrated", "retired"}: + superseded_by = ( + ", ".join( + rows_api.projection_text_list( + rows_api.projection_lifecycle_value(block, "superseded_by") + ) + ) + or "current projection row" + ) + default_handoff = f"Row lifecycle {lifecycle_state}; continue with {superseded_by}." + values.update( + { + "LoopX Goal ID": goal_id, + "LoopX Todo ID": str(block.get("todo_id") or ""), + "Scope": _compact_text( + block.get("scope") or block.get("source_section") or f"projection_source={source_id}" + ), + "Handoff": _compact_text(block.get("handoff") or default_handoff), + "Evidence": _compact_text("; ".join(evidence_parts)), + "Run History": _compact_text( + "; ".join( + part + for part in ( + f"synced from LoopX projection source={source_id} status={block.get('status') or 'open'}", + f"row_lifecycle={lifecycle_state}" if lifecycle_state else "", + ) + if part + ) + ), + } + ) + values.update(issue_fix_surface.issue_fix_record_values(block, compact_text=_compact_text)) + return _sink_safe_lark_values(values, public_safe=public_safe) + + +def _projection_upsert_items( + rows: Sequence[Mapping[str, object]], + *, + default_goal_id: str, + source_id: str, + public_safe: bool, +) -> list[tuple[str, str, dict[str, object]]]: + items: list[tuple[str, str, dict[str, object]]] = [] + for row in rows: + row_goal_id = str(row.get("goal_id") or default_goal_id) + todo_id = str(row.get("todo_id") or "").strip() + values = _lark_record_from_projection_block( + row, goal_id=row_goal_id, source_id=source_id, public_safe=public_safe + ) + items.append((f"{row_goal_id}:{todo_id}", todo_id, values)) + return items + + +def _collect_goal_todo_items( + lines: list[str], + *, + goal_id: str, + state_file: Path, + agent_id: str | None, + include_done: bool, + limit: int, + public_safe: bool, +) -> list[tuple[str, str, dict[str, object]]]: + from ....control_plane.todos.active_state_editing import section_bounds, todo_blocks + from ....control_plane.todos.todo_semantics import todo_priority_label + + rows_api = _projection_rows_api() + selected: list[tuple[dict[str, object], str]] = [] + for role in ("user", "agent"): + bounds = section_bounds(lines, role) + if not bounds: + continue + start, end, heading = bounds + for block in todo_blocks(lines, start, end, role=role, source_section=heading): + status = normalize_todo_status(str(block.get("status") or "").strip()) + if (block.get("done") or status == TODO_STATUS_DONE) and not include_done: + continue + candidate: dict[str, object] = { + **{str(k): v for k, v in block.items()}, + "role": role, + "source_section": heading, + } + if rows_api.todo_matches_agent_scope(candidate, agent_id): + priority = todo_priority_label(block, text_mode="prefix") or "P2" + selected.append((candidate, priority)) + selected = selected[:limit] + + todo_items: list[tuple[str, str, dict[str, object]]] = [] + for candidate, priority in selected: + todo_id = str(candidate.get("todo_id") or "").strip() + values = _lark_record_from_todo_block( + candidate, + goal_id=goal_id, + state_file=state_file, + priority=priority, + ) + if public_safe: + values = _public_safe_lark_values(values) + todo_items.append((f"{goal_id}:{todo_id}", todo_id, values)) + return todo_items + + +def _load_lark_todo_record_map( + config: LarkKanbanConfig, + *, + config_path: Path | None, + execute: bool, + inspect_remote: bool, + commands: list[dict[str, object]], + runner: cli_transport.CommandRunner, +) -> tuple[dict[str, object], dict[str, str], list[dict[str, str]], bool | None]: + local: dict[str, object] = read_lark_kanban_local_config(config_path) if config_path else {} + record_map = _todo_record_map_from_local_config(local) + if not execute and not inspect_remote: + return local, record_map, [], None + + list_config = LarkKanbanConfig( + base_token=config.base_token, + table_id=config.table_id, + view_id=None, + cli_bin=config.cli_bin, + identity=config.identity, + ) + list_result = _json_dict( + cli_transport.run_command( + build_record_list_command(list_config), execute=True, runner=runner + ) + ) + commands.append(list_result) + remote_records: list[dict[str, str]] = [] + remote_complete = False + if list_result.get("ok"): + parsed_records = list_result.get("json") + remote_records = todo_record_entries(parsed_records) + remote_by_key: dict[str, list[str]] = {} + for item in remote_records: + remote_by_key.setdefault(item["key"], []).append(item["record_id"]) + if todo_record_list_is_authoritative(parsed_records): + record_map = { + key: record_id + for key, record_id in record_map.items() + if record_id in remote_by_key.get(key, []) + } + for key, record_ids in remote_by_key.items(): + preferred = record_map.get(key) + record_map[key] = preferred if preferred in record_ids else sorted(record_ids)[0] + remote_complete = record_list_is_complete(parsed_records) + return local, record_map, remote_records, remote_complete + + +def _todo_record_map_from_local_config(local: Mapping[str, object]) -> dict[str, str]: + records = local.get("todo_records") if isinstance(local, Mapping) else None + if not isinstance(records, dict): + return {} + return { + str(key): str(value) + for key, value in records.items() + if str(key).strip() and str(value).strip() + } + + +def _persist_lark_todo_record_map( + config: LarkKanbanConfig, + *, + config_path: Path | None, + local: Mapping[str, object], + record_map: Mapping[str, str], +) -> None: + if not config_path: + return + raw_board = local.get("board") + board: Mapping[str, object] = ( + raw_board + if isinstance(raw_board, dict) and raw_board + else { + "base_token": config.base_token, + "table_id": config.table_id, + "view_id": config.view_id, + "cli_bin": config.cli_bin, + "identity": config.identity, + } + ) + write_lark_kanban_local_config( + config_path, + { + "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, + "board": board, + "todo_records": dict(record_map), + }, + ) + + +def _lark_record_from_todo_block( + block: Mapping[str, object], *, goal_id: str, state_file: Path, priority: str +) -> dict[str, object]: + role = str(block.get("role") or "agent") + status = normalize_todo_status(str(block.get("status") or "").strip()) or TODO_STATUS_OPEN + task_class = normalize_explicit_todo_task_class(block.get("task_class")) or ( + TODO_TASK_CLASS_USER_GATE if role == "user" else TODO_TASK_CLASS_ADVANCEMENT + ) + claimed_by = str(block.get("claimed_by") or "").strip() + lark_status = STATUS_TODO + if block.get("done") or status == TODO_STATUS_DONE: + lark_status = STATUS_DONE + elif status == TODO_STATUS_BLOCKED or task_class == TODO_TASK_CLASS_BLOCKER: + lark_status = STATUS_BLOCKED + elif role == "user" or task_class == TODO_TASK_CLASS_USER_GATE or status == TODO_STATUS_DEFERRED: + lark_status = STATUS_USER_GATE + elif claimed_by: + lark_status = STATUS_CLAIMED + claim = ( + CLAIM_HUMAN + if lark_status == STATUS_USER_GATE + else (CLAIM_AGENT if claimed_by else CLAIM_UNCLAIMED) + ) + scope = block.get("required_write_scopes") + scope_text = ", ".join(str(item) for item in scope) if isinstance(scope, list) else str(scope or "") + text = str(block.get("text") or "") + values: dict[str, object] = { + "Task": text, + "Status": lark_status, + "Claim": claim, + "Claimed By": claimed_by, + "Priority": priority if priority in {"P0", "P1", "P2", "P3"} else "P2", + "Task Class": task_class, + "Action Kind": str(block.get("action_kind") or "sync_loopx_todo"), + "LoopX Goal ID": goal_id, + "LoopX Todo ID": str(block.get("todo_id") or ""), + **issue_fix_surface.todo_record_values(), + "Scope": scope_text, + "User Gate": text if lark_status == STATUS_USER_GATE else "", + "Handoff": f"Synced from LoopX active state: {state_file.name}", + "Evidence": str(block.get("evidence") or block.get("reason") or block.get("note") or ""), + "Run History": f"synced from LoopX todo status={status}", + "Worker Command": "", + "Workdir": "", + "Last Error": "", + "Last Result Code": None, + } + return _credential_safe_lark_values(values) diff --git a/loopx/extensions/lark/presentation/kanban_sync.py b/loopx/extensions/lark/presentation/kanban_sync.py new file mode 100644 index 0000000000..8bbb6593ba --- /dev/null +++ b/loopx/extensions/lark/presentation/kanban_sync.py @@ -0,0 +1,458 @@ +"""Lark Kanban projection reconciliation and LoopX Todo synchronization.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import NotRequired, Protocol, TypedDict, cast + +from ....presentation.projection_source_reconcile import ( + plan_projection_source_reconcile, + validate_projection_source_reconcile_request, +) +from .. import cli_transport as cli_transport +from . import kanban_board as kanban_board +from .kanban_board import _extract_created_record_id, _schema_check_error +from .kanban_config import ( + LARK_KANBAN_SYNC_PROJECTION_VERSION, + LarkKanbanConfig, + _validate_sink_visibility, + build_record_upsert_command, +) +from .kanban_records import ( + _collect_goal_todo_items, + _json_dict, + _load_lark_todo_record_map, + _persist_lark_todo_record_map, + _projection_rows_api, + _projection_upsert_items, +) +from .record_io import build_record_delete_command +from .sink_visibility import SINK_VISIBILITY_OWNER_ONLY, SINK_VISIBILITY_SHARED + + +class LarkKanbanTodoSyncResult(TypedDict): + ok: bool + schema_version: str + execute: bool + goal_id: str + agent_id: str | None + sink_visibility: str + public_safe_redaction: bool + base_token: str + table_id: str + view_id: str | None + project: str | None + state_file: str + todo_count: int + issue_fix_outcome_count: int + limit_policy: dict[str, object] + issue_fix_source_counts: object + warnings: list[str] + config_path: str | None + schema_check: dict[str, object] | None + records: list[dict[str, object]] + commands: list[dict[str, object]] + successful_write_count: int + external_write_performed: bool + error: NotRequired[str] + + +class _SchemaInspectorAdapter(Protocol): + def _inspect_lark_kanban_schema( + self, + config: LarkKanbanConfig, + *, + commands: list[dict[str, object]], + runner: cli_transport.CommandRunner, + ) -> dict[str, object]: ... + + +def _inspect_lark_kanban_schema_typed( + config: LarkKanbanConfig, + *, + commands: list[dict[str, object]], + runner: cli_transport.CommandRunner, +) -> dict[str, object]: + board_api = cast(_SchemaInspectorAdapter, kanban_board) + return board_api._inspect_lark_kanban_schema( + config, commands=commands, runner=runner + ) + + +def _upsert_record_batch( + config: LarkKanbanConfig, + items: Sequence[tuple[str, str, Mapping[str, object]]], + *, + record_map: dict[str, str], + commands: list[dict[str, object]], + results: list[dict[str, object]], + execute: bool, + runner: cli_transport.CommandRunner, +) -> tuple[bool, int]: + ok = True + successful_write_count = 0 + for key, todo_id, values in items: + result = _json_dict( + cli_transport.run_command( + build_record_upsert_command(config, record_id=record_map.get(key), values=values), + execute=execute, + runner=runner, + ) + ) + commands.append(result) + record_id = _extract_created_record_id(result.get("json")) or record_map.get(key) + if execute and result.get("executed") and result.get("ok"): + successful_write_count += 1 + if execute and result.get("ok") and record_id: + record_map[key] = record_id + results.append( + {"todo_id": todo_id, "record_id": record_id, "command": result, "values": dict(values)} + ) + ok = ok and bool(result.get("ok")) + if execute and not result.get("ok"): + break + return ok, successful_write_count + + +def sync_loopx_projection_to_lark_kanban( + config: LarkKanbanConfig, + *, + projection: Mapping[str, object], + goal_id: str | None = None, + agent_id: str | None = None, + source_id: str | None = None, + config_path: Path | None = None, + include_done: bool = False, + limit: int = 50, + sink_visibility: str = SINK_VISIBILITY_OWNER_ONLY, + reconcile_source: bool = False, + source_snapshot_complete: bool = False, + execute: bool = False, + runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, +) -> dict[str, object]: + if not isinstance(projection, dict): + raise ValueError("projection must be a JSON object") + rows_api = _projection_rows_api() + public_safe = _validate_sink_visibility(sink_visibility) + resolved_source_id, namespace_warnings = rows_api.projection_namespace(projection, source_id) + resolved_goal_id, rows, warnings = rows_api.projection_rows_from_payload( + projection, + goal_id=goal_id, + agent_id=agent_id, + source_id=resolved_source_id, + include_done=include_done, + limit=limit, + ) + warnings = [*namespace_warnings, *warnings] + + complete_rows = rows + complete_warnings: list[str] = [] + if reconcile_source: + _, complete_rows, complete_warnings = rows_api.projection_rows_from_payload( + projection, + goal_id=goal_id, + agent_id=None, + source_id=resolved_source_id, + include_done=True, + limit=2**31 - 1, + ) + validate_projection_source_reconcile_request( + requested=reconcile_source, + source_snapshot_complete=source_snapshot_complete, + agent_id=agent_id, + include_done=include_done, + namespace_warnings=namespace_warnings, + selected_row_count=len(rows), + complete_row_count=len(complete_rows), + complete_warnings=complete_warnings, + ) + + commands: list[dict[str, object]] = [] + schema_check: dict[str, object] | None = None + base_payload: dict[str, object] = { + "schema_version": LARK_KANBAN_SYNC_PROJECTION_VERSION, + "execute": execute, + "goal_id": resolved_goal_id, + "agent_id": agent_id, + "source_id": resolved_source_id, + "sink_visibility": sink_visibility, + "public_safe_redaction": public_safe, + "projection_schema_version": projection.get("schema_version"), + "row_count": len(rows), + "warnings": warnings, + "config_path": str(config_path) if config_path else None, + } + if execute: + schema_check = _inspect_lark_kanban_schema_typed(config, commands=commands, runner=runner) + if not schema_check.get("ok"): + return { + **base_payload, + "ok": False, + "records": [], + "commands": commands, + "schema_check": schema_check, + "error": _schema_check_error(schema_check), + } + + local, record_map, remote_records, remote_list_complete = _load_lark_todo_record_map( + config, + config_path=config_path, + execute=execute, + inspect_remote=reconcile_source, + commands=commands, + runner=runner, + ) + if reconcile_source and not remote_list_complete: + raise ValueError("source reconcile requires a complete remote record list") + + desired_keys = { + f"{str(row.get('goal_id') or resolved_goal_id)}:{str(row.get('todo_id') or '').strip()}" + for row in rows + } + reconcile_plan = ( + plan_projection_source_reconcile( + goal_id=resolved_goal_id, + source_id=resolved_source_id, + desired_keys=sorted(desired_keys), + local_record_map=record_map, + remote_records=remote_records, + ) + if reconcile_source + else { + "schema_version": "projection_source_reconcile_plan_v0", + "goal_id": resolved_goal_id, + "source_id": resolved_source_id, + "remote_orphan_record_ids": [], + "remote_duplicate_record_ids": [], + "remote_delete_record_ids": [], + "local_mapping_keys_to_remove": [], + "remote_delete_count": 0, + "local_mapping_delete_count": 0, + } + ) + + results: list[dict[str, object]] = [] + ok, _ = _upsert_record_batch( + config, + _projection_upsert_items( + rows, default_goal_id=resolved_goal_id, source_id=resolved_source_id, public_safe=public_safe + ), + record_map=record_map, + commands=commands, + results=results, + execute=execute, + runner=runner, + ) + + executed_remote_delete_count = 0 + delete_ids = reconcile_plan.get("remote_delete_record_ids") + if ok and reconcile_source and isinstance(delete_ids, list) and delete_ids: + delete_result = _json_dict( + cli_transport.run_command( + build_record_delete_command(config, record_ids=[str(item) for item in delete_ids]), + execute=execute, + runner=runner, + ) + ) + commands.append(delete_result) + ok = ok and bool(delete_result.get("ok")) + if execute and delete_result.get("ok"): + raw_delete_count = reconcile_plan.get("remote_delete_count") + executed_remote_delete_count = raw_delete_count if isinstance(raw_delete_count, int) else 0 + + removed_local_mapping_count = 0 + local_keys = reconcile_plan.get("local_mapping_keys_to_remove") + if execute and ok and reconcile_source and isinstance(local_keys, list): + for key in local_keys: + if str(key) in record_map: + removed_local_mapping_count += 1 + record_map.pop(str(key), None) + + if execute and ok: + _persist_lark_todo_record_map(config, config_path=config_path, local=local, record_map=record_map) + + return { + **base_payload, + "ok": ok, + "schema_check": schema_check, + "source_reconcile": { + **reconcile_plan, + "requested": reconcile_source, + "source_snapshot_complete": source_snapshot_complete, + "mode": "execute" if reconcile_source and execute else ("preview" if reconcile_source else "disabled"), + "executed_remote_delete_count": executed_remote_delete_count, + "removed_local_mapping_count": removed_local_mapping_count, + }, + "records": results, + "commands": commands, + } + + +def sync_loopx_todos_to_lark_kanban( + config: LarkKanbanConfig, + *, + registry_path: Path, + goal_id: str, + agent_id: str | None = None, + config_path: Path | None = None, + project: Path | None = None, + state_file: Path | None = None, + include_done: bool = False, + limit: int = 50, + sink_visibility: str = SINK_VISIBILITY_SHARED, + execute: bool = False, + runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, +) -> LarkKanbanTodoSyncResult: + from ....capabilities.issue_fix.outcome_projection import ( + build_issue_fix_outcome_collection_from_domain_state, + ) + from ....control_plane.todos.path_resolution import resolve_todo_state_path + + rows_api = _projection_rows_api() + public_safe = _validate_sink_visibility(sink_visibility) + resolved_project, resolved_state_file = resolve_todo_state_path( + registry_path=registry_path, goal_id=goal_id, project=project, state_file=state_file + ) + lines = resolved_state_file.read_text(encoding="utf-8").splitlines() + todo_items = _collect_goal_todo_items( + lines, + goal_id=goal_id, + state_file=resolved_state_file, + agent_id=agent_id, + include_done=include_done, + limit=limit, + public_safe=public_safe, + ) + + outcome_projection = _json_dict( + build_issue_fix_outcome_collection_from_domain_state( + goal_id=goal_id, project=resolved_project or project or Path(".") + ) + ) + outcome_source_id, outcome_namespace_warnings = rows_api.projection_namespace( + outcome_projection, None + ) + raw_outcomes = outcome_projection.get("issue_fix_outcomes") + outcome_source_count = len(raw_outcomes) if isinstance(raw_outcomes, Sequence) else 0 + _, outcome_rows, outcome_row_warnings = rows_api.projection_rows_from_payload( + outcome_projection, + goal_id=goal_id, + agent_id=agent_id, + source_id=outcome_source_id, + include_done=True, + limit=outcome_source_count, + ) + raw_outcome_warnings = outcome_projection.get("warnings") + outcome_warnings: list[str] = [ + *outcome_namespace_warnings, + *( + [str(item) for item in raw_outcome_warnings] + if isinstance(raw_outcome_warnings, Sequence) + and not isinstance(raw_outcome_warnings, (str, bytes)) + else [] + ), + *outcome_row_warnings, + ] + + commands: list[dict[str, object]] = [] + schema_check: dict[str, object] | None = None + project_str = str(resolved_project) if resolved_project else None + state_file_str = str(resolved_state_file) + config_path_str = str(config_path) if config_path else None + limit_policy: dict[str, object] = { + "todo_rows": limit, + "issue_fix_outcomes": "complete_source_projection", + } + source_counts = outcome_projection.get("source_counts") + if execute: + schema_check = _inspect_lark_kanban_schema_typed(config, commands=commands, runner=runner) + if not schema_check.get("ok"): + return { + "ok": False, + "schema_version": "loopx_lark_kanban_sync_todos_v0", + "execute": execute, + "goal_id": goal_id, + "agent_id": agent_id, + "sink_visibility": sink_visibility, + "public_safe_redaction": public_safe, + "base_token": config.base_token, + "table_id": config.table_id, + "view_id": config.view_id, + "project": project_str, + "state_file": state_file_str, + "todo_count": len(todo_items), + "issue_fix_outcome_count": len(outcome_rows), + "limit_policy": limit_policy, + "issue_fix_source_counts": source_counts, + "warnings": outcome_warnings, + "config_path": config_path_str, + "records": [], + "commands": commands, + "schema_check": schema_check, + "successful_write_count": 0, + "external_write_performed": False, + "error": _schema_check_error(schema_check), + } + + local, record_map, _, _ = _load_lark_todo_record_map( + config, + config_path=config_path, + execute=execute, + inspect_remote=False, + commands=commands, + runner=runner, + ) + + results: list[dict[str, object]] = [] + ok, successful_write_count = _upsert_record_batch( + config, + todo_items, + record_map=record_map, + commands=commands, + results=results, + execute=execute, + runner=runner, + ) + if ok and outcome_rows: + ok, outcome_writes = _upsert_record_batch( + config, + _projection_upsert_items( + outcome_rows, default_goal_id=goal_id, source_id=outcome_source_id, public_safe=public_safe + ), + record_map=record_map, + commands=commands, + results=results, + execute=execute, + runner=runner, + ) + successful_write_count += outcome_writes + + if execute and successful_write_count: + _persist_lark_todo_record_map(config, config_path=config_path, local=local, record_map=record_map) + + return { + "ok": ok, + "schema_version": "loopx_lark_kanban_sync_todos_v0", + "execute": execute, + "goal_id": goal_id, + "agent_id": agent_id, + "sink_visibility": sink_visibility, + "public_safe_redaction": public_safe, + "base_token": config.base_token, + "table_id": config.table_id, + "view_id": config.view_id, + "project": project_str, + "state_file": state_file_str, + "todo_count": len(todo_items), + "issue_fix_outcome_count": len(outcome_rows), + "limit_policy": limit_policy, + "issue_fix_source_counts": source_counts, + "warnings": outcome_warnings, + "config_path": config_path_str, + "schema_check": schema_check, + "records": results, + "commands": commands, + "successful_write_count": successful_write_count, + "external_write_performed": bool(successful_write_count), + } diff --git a/loopx/extensions/lark/presentation/record_io.py b/loopx/extensions/lark/presentation/record_io.py index eb84791611..459a9d3c52 100644 --- a/loopx/extensions/lark/presentation/record_io.py +++ b/loopx/extensions/lark/presentation/record_io.py @@ -1,27 +1,33 @@ from __future__ import annotations -from typing import Any, Protocol +from collections.abc import Mapping, Sequence +from typing import Protocol class RecordTarget(Protocol): - cli_bin: str - identity: str - base_token: str - table_id: str + @property + def cli_bin(self) -> str: ... + @property + def identity(self) -> str: ... + @property + def base_token(self) -> str: ... + @property + def table_id(self) -> str: ... -def lark_record_rows(payload: dict[str, Any]) -> list[dict[str, Any]]: - data = payload.get("data") if isinstance(payload.get("data"), dict) else payload - fields = data.get("fields") if isinstance(data, dict) else None - rows = data.get("data") if isinstance(data, dict) else None - record_ids = data.get("record_id_list") if isinstance(data, dict) else None +def lark_record_rows(payload: Mapping[str, object]) -> list[dict[str, object]]: + raw_data = payload.get("data") + data: Mapping[str, object] = raw_data if isinstance(raw_data, Mapping) else payload + fields = data.get("fields") + rows = data.get("data") + record_ids = data.get("record_id_list") if not isinstance(fields, list) or not isinstance(rows, list): return [] - records: list[dict[str, Any]] = [] + records: list[dict[str, object]] = [] for index, values in enumerate(rows): if not isinstance(values, list): continue - record = { + record: dict[str, object] = { str(field): values[pos] if pos < len(values) else None for pos, field in enumerate(fields) } @@ -31,9 +37,10 @@ def lark_record_rows(payload: dict[str, Any]) -> list[dict[str, Any]]: return records -def todo_record_entries(parsed: Any) -> list[dict[str, str]]: +def todo_record_entries(parsed: object) -> list[dict[str, str]]: result: list[dict[str, str]] = [] - for record in lark_record_rows(parsed if isinstance(parsed, dict) else {}): + payload: Mapping[str, object] = parsed if isinstance(parsed, dict) else {} + for record in lark_record_rows(payload): todo_id = str(record.get("LoopX Todo ID") or "").strip() goal_id = str(record.get("LoopX Goal ID") or "").strip() record_id = str(record.get("_record_id") or "").strip() @@ -42,10 +49,11 @@ def todo_record_entries(parsed: Any) -> list[dict[str, str]]: return result -def record_list_is_complete(parsed: Any) -> bool: +def record_list_is_complete(parsed: object) -> bool: if not isinstance(parsed, dict): return False - data = parsed.get("data") if isinstance(parsed.get("data"), dict) else parsed + raw_data = parsed.get("data") + data: object = raw_data if isinstance(raw_data, dict) else parsed if not isinstance(data, dict): return False return ( @@ -54,10 +62,11 @@ def record_list_is_complete(parsed: Any) -> bool: ) -def todo_record_list_is_authoritative(parsed: Any) -> bool: +def todo_record_list_is_authoritative(parsed: object) -> bool: if not record_list_is_complete(parsed) or not isinstance(parsed, dict): return False - data = parsed.get("data") if isinstance(parsed.get("data"), dict) else parsed + raw_data = parsed.get("data") + data: object = raw_data if isinstance(raw_data, dict) else parsed if not isinstance(data, dict): return False fields = data.get("fields") @@ -77,7 +86,7 @@ def todo_record_list_is_authoritative(parsed: Any) -> bool: def build_record_delete_command( config: RecordTarget, *, - record_ids: list[str], + record_ids: Sequence[str], ) -> list[str]: args = [ config.cli_bin, diff --git a/loopx/extensions/lark/presentation/sync_receipt.py b/loopx/extensions/lark/presentation/sync_receipt.py index ef2aaa7dc7..c6d9caa1a7 100644 --- a/loopx/extensions/lark/presentation/sync_receipt.py +++ b/loopx/extensions/lark/presentation/sync_receipt.py @@ -1,19 +1,19 @@ from __future__ import annotations -from typing import Any +from collections.abc import Mapping OUTPUT_LIMIT = 1800 -def _compact_text(value: Any, *, limit: int) -> str: +def _compact_text(value: object, *, limit: int) -> str: text = " ".join(str(value or "").split()) if len(text) <= limit: return text return text[: max(0, limit - 1)].rstrip() + "..." -def _command_error(command_result: dict[str, Any]) -> str: +def _command_error(command_result: Mapping[str, object]) -> str: parsed = command_result.get("json") if isinstance(parsed, dict): error = parsed.get("error") @@ -31,31 +31,29 @@ def _command_error(command_result: dict[str, Any]) -> str: def compact_lark_kanban_sync_receipt( - payload: dict[str, Any], + payload: Mapping[str, object], *, include_command_details: bool = False, -) -> dict[str, Any]: +) -> dict[str, object]: raw_records = payload.get("records") raw_commands = payload.get("commands") records = [item for item in (raw_records if isinstance(raw_records, list) else []) if isinstance(item, dict)] commands = [item for item in (raw_commands if isinstance(raw_commands, list) else []) if isinstance(item, dict)] - result = dict(payload) + result: dict[str, object] = dict(payload) + record_success_count = 0 + record_failure_count = 0 + for item in records: + item_cmd = item.get("command") + if isinstance(item_cmd, dict) and item_cmd.get("ok") is True: + record_success_count += 1 + else: + record_failure_count += 1 result.update( { "detail_level": "full" if include_command_details else "compact", "record_count": len(records), - "record_success_count": sum( - 1 - for item in records - if isinstance(item.get("command"), dict) - and item["command"].get("ok") is True - ), - "record_failure_count": sum( - 1 - for item in records - if not isinstance(item.get("command"), dict) - or item["command"].get("ok") is not True - ), + "record_success_count": record_success_count, + "record_failure_count": record_failure_count, "command_count": len(commands), "command_failure_count": sum( 1 for item in commands if item.get("ok") is not True @@ -65,20 +63,28 @@ def compact_lark_kanban_sync_receipt( if include_command_details: return result - compact_records: list[dict[str, Any]] = [] + compact_records: list[dict[str, object]] = [] for item in records: raw_command = item.get("command") raw_values = item.get("values") - command = raw_command if isinstance(raw_command, dict) else {} - values = raw_values if isinstance(raw_values, dict) else {} + cmd_dict: dict[str, object] = ( + {str(k): v for k, v in raw_command.items()} + if isinstance(raw_command, dict) + else {} + ) + values: dict[str, object] = ( + {str(k): v for k, v in raw_values.items()} + if isinstance(raw_values, dict) + else {} + ) compact_records.append( { "todo_id": item.get("todo_id"), "record_id": item.get("record_id"), - "ok": command.get("ok") is True, - "executed": bool(command.get("executed")), - "returncode": command.get("returncode"), - "error": _command_error(command) if command.get("ok") is not True else None, + "ok": cmd_dict.get("ok") is True, + "executed": bool(cmd_dict.get("executed")), + "returncode": cmd_dict.get("returncode"), + "error": _command_error(cmd_dict) if cmd_dict.get("ok") is not True else None, "work_item_type": values.get("Work Item Type"), "repository": values.get("Repository"), "issue": values.get("Issue"), @@ -90,7 +96,7 @@ def compact_lark_kanban_sync_receipt( return result -def render_lark_kanban_markdown(payload: dict[str, Any]) -> str: +def render_lark_kanban_markdown(payload: Mapping[str, object]) -> str: lines = [ "# LoopX Lark Kanban", "", @@ -98,6 +104,9 @@ def render_lark_kanban_markdown(payload: dict[str, Any]) -> str: f"- schema_version: `{payload.get('schema_version')}`", ] summary_keys = ( + "execute", + "goal_id", + "source_id", "base_token", "table_id", "view_id", @@ -119,15 +128,17 @@ def render_lark_kanban_markdown(payload: dict[str, Any]) -> str: lines.append(f"- {key}: `{payload.get(key)}`") if payload.get("error"): lines.append(f"- error: {payload.get('error')}") - if isinstance(payload.get("commands"), list): + raw_commands = payload.get("commands") + if isinstance(raw_commands, list): lines.extend(("", "## Commands")) - for item in payload["commands"]: + for item in raw_commands: if isinstance(item, dict): marker = "ran" if item.get("executed") else "dry-run" lines.append(f"- `{marker}` `{item.get('command')}`") - if payload.get("detail_level") == "compact" and isinstance(payload.get("records"), list): + raw_records = payload.get("records") + if payload.get("detail_level") == "compact" and isinstance(raw_records, list): lines.extend(("", "## Records")) - for item in payload["records"]: + for item in raw_records: if not isinstance(item, dict): continue status = "ok" if item.get("ok") else "failed" @@ -142,8 +153,9 @@ def render_lark_kanban_markdown(payload: dict[str, Any]) -> str: if item.get("error"): summary += f" error={_compact_text(item.get('error'), limit=220)}" lines.append(summary) - if isinstance(payload.get("writeback"), dict): + raw_writeback = payload.get("writeback") + if isinstance(raw_writeback, dict): lines.extend(("", "## Writeback")) - for key, value in payload["writeback"].items(): + for key, value in raw_writeback.items(): lines.append(f"- {key}: `{_compact_text(value, limit=220)}`") return "\n".join(lines) diff --git a/tests/extensions/test_lark_kanban_contract.py b/tests/extensions/test_lark_kanban_contract.py new file mode 100644 index 0000000000..7949291d0a --- /dev/null +++ b/tests/extensions/test_lark_kanban_contract.py @@ -0,0 +1,164 @@ +from __future__ import annotations + +import ast +import inspect +from dataclasses import FrozenInstanceError, is_dataclass +from pathlib import Path + +import pytest + +from loopx.extensions.lark.presentation import ( + kanban, + kanban_board, + kanban_config, + kanban_records, + kanban_sync, + record_io, + sink_visibility, + sync_receipt, +) + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +SLIM_MODULES = ( + "loopx/extensions/lark/presentation/record_io.py", + "loopx/extensions/lark/presentation/sync_receipt.py", + "loopx/extensions/lark/presentation/kanban_config.py", + "loopx/extensions/lark/presentation/kanban_records.py", + "loopx/extensions/lark/presentation/kanban_sync.py", + "loopx/extensions/lark/presentation/kanban.py", + "loopx/cli_commands/lark_kanban.py", +) + + +def test_kanban_split_modules_stay_under_budget_with_zero_any() -> None: + for rel_path in SLIM_MODULES: + source = (REPOSITORY_ROOT / rel_path).read_text(encoding="utf-8") + lines = source.splitlines() + assert len(lines) < 700, f"{rel_path} exceeded 700 LOC ({len(lines)})" + assert "type: ignore" not in source, f"{rel_path} must not use type: ignore" + tree = ast.parse(source, filename=rel_path) + any_nodes = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Name) and node.id == "Any" + ] + assert any_nodes == [], f"{rel_path} contains forbidden AST Any nodes" + + +def test_kanban_facade_preserves_canonical_export_identities() -> None: + assert ( + kanban.SINK_VISIBILITY_OWNER_ONLY + is sink_visibility.SINK_VISIBILITY_OWNER_ONLY + ) + assert kanban.SINK_VISIBILITY_SHARED is sink_visibility.SINK_VISIBILITY_SHARED + assert kanban.SINK_VISIBILITIES is sink_visibility.SINK_VISIBILITIES + + proj_default = inspect.signature( + kanban.sync_loopx_projection_to_lark_kanban + ).parameters["sink_visibility"].default + todo_default = inspect.signature( + kanban.sync_loopx_todos_to_lark_kanban + ).parameters["sink_visibility"].default + assert proj_default is sink_visibility.SINK_VISIBILITY_OWNER_ONLY + assert todo_default is sink_visibility.SINK_VISIBILITY_SHARED + + assert kanban.LarkKanbanConfig is kanban_config.LarkKanbanConfig + assert ( + kanban.save_lark_kanban_board_config + is kanban_config.save_lark_kanban_board_config + ) + assert ( + kanban.sync_loopx_projection_to_lark_kanban + is kanban_sync.sync_loopx_projection_to_lark_kanban + ) + assert ( + kanban.sync_loopx_todos_to_lark_kanban + is kanban_sync.sync_loopx_todos_to_lark_kanban + ) + assert ( + kanban._lark_record_from_todo_block + is kanban_records._lark_record_from_todo_block + ) + assert ( + kanban.compact_lark_kanban_sync_receipt + is sync_receipt.compact_lark_kanban_sync_receipt + ) + assert kanban.render_lark_kanban_markdown is sync_receipt.render_lark_kanban_markdown + assert kanban.build_record_delete_command is record_io.build_record_delete_command + assert kanban.use_lark_kanban_board is kanban_board.use_lark_kanban_board + + +def test_kanban_config_is_frozen_and_builds_record_delete_command( + tmp_path: Path, +) -> None: + cfg = kanban.LarkKanbanConfig(base_token="bas123", table_id="tbl456") + assert is_dataclass(cfg) + with pytest.raises(FrozenInstanceError): + setattr(cfg, "table_id", "tbl999") + + delete_cmd = kanban.build_record_delete_command(cfg, record_ids=["recA", "recB"]) + assert delete_cmd == [ + cfg.cli_bin, + "base", + "+record-delete", + "--as", + cfg.identity, + "--base-token", + "bas123", + "--table-id", + "tbl456", + "--record-id", + "recA", + "--record-id", + "recB", + "--yes", + ] + + config_path = tmp_path / "lark-kanban.json" + saved = kanban.save_lark_kanban_board_config( + config_path, + base_token="bas123", + table_id="tbl456", + view_ids={"Worker Queue": "vew1"}, + ) + assert saved["ok"] is True + loaded = kanban.read_lark_kanban_local_config(config_path) + assert loaded["ok"] is True + parsed_cfg = kanban.lark_kanban_config_from_payload(loaded) + assert parsed_cfg is not None + assert parsed_cfg.base_token == "bas123" + assert parsed_cfg.table_id == "tbl456" + + +def test_choose_heartbeat_task_and_fail_closed_reconcile() -> None: + selected = kanban.choose_heartbeat_task( + [ + {"Status": kanban.STATUS_DONE, "Claim": kanban.CLAIM_AGENT, "Claimed By": "worker-a"}, + {"Status": kanban.STATUS_TODO, "Claim": kanban.CLAIM_UNCLAIMED, "Task": "unclaimed"}, + { + "Status": kanban.STATUS_CLAIMED, + "Claim": kanban.CLAIM_AGENT, + "Claimed By": "worker-a", + "Task": "own-claim", + }, + ], + agent_id="worker-a", + ) + assert selected is not None + assert selected["Task"] == "own-claim" + + cfg = kanban.LarkKanbanConfig(base_token="bas123", table_id="tbl456") + with pytest.raises(ValueError, match="sink_visibility must be one of"): + kanban.sync_loopx_projection_to_lark_kanban( + cfg, + projection={"goal_id": "g1", "items": []}, + sink_visibility="invalid-mode", + ) + + with pytest.raises(ValueError, match="complete source snapshot"): + kanban.sync_loopx_projection_to_lark_kanban( + cfg, + projection={"goal_id": "g1", "source_id": "src-1", "items": []}, + reconcile_source=True, + source_snapshot_complete=False, + ) From 909390a69dab41320eab41b6ec4f77ac2de439e2 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:57:04 +0800 Subject: [PATCH 2/2] fix(lark): align Mapping runtime normalization and markdown receipt headers Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/extensions/lark/presentation/kanban.py | 14 +- .../lark/presentation/kanban_config.py | 30 +++- .../lark/presentation/kanban_records.py | 34 ++-- .../lark/presentation/kanban_sync.py | 10 +- .../extensions/lark/presentation/record_io.py | 14 +- .../lark/presentation/sync_receipt.py | 23 ++- tests/extensions/test_lark_kanban_contract.py | 150 +++++++++++++++++- 7 files changed, 221 insertions(+), 54 deletions(-) diff --git a/loopx/extensions/lark/presentation/kanban.py b/loopx/extensions/lark/presentation/kanban.py index 2e7ff5fcd6..9f33827014 100644 --- a/loopx/extensions/lark/presentation/kanban.py +++ b/loopx/extensions/lark/presentation/kanban.py @@ -68,6 +68,8 @@ _SHARED_REDACTION_PATTERNS as _SHARED_REDACTION_PATTERNS, _STRUCTURAL_ID_KEYS as _STRUCTURAL_ID_KEYS, _STRUCTURAL_RECORD_ID_PATTERN as _STRUCTURAL_RECORD_ID_PATTERN, + _coerce_mapping_tree as _coerce_mapping_tree, + _coerce_mapping_value as _coerce_mapping_value, _compact_text as _compact_text, _credential_safe_lark_values as _credential_safe_lark_values, _credential_safe_text as _credential_safe_text, @@ -293,7 +295,7 @@ def lark_kanban_heartbeat( ) -> dict[str, object]: public_safe = _validate_sink_visibility(sink_visibility) commands: list[dict[str, object]] = [] - parsed: object + parsed_mapping: dict[str, object] = {} if fixture is None: list_result = dict( cli_transport.run_command( @@ -309,10 +311,12 @@ def lark_kanban_heartbeat( commands=commands, records=[], ) - parsed = list_result.get("json") if execute_lark else {"data": {"fields": [], "data": []}} - else: - parsed = fixture - records = lark_record_rows(parsed if isinstance(parsed, dict) else {}) + raw_parsed = list_result.get("json") if execute_lark else {"data": {"fields": [], "data": []}} + if isinstance(raw_parsed, Mapping): + parsed_mapping = _coerce_mapping_tree(raw_parsed) + elif isinstance(fixture, Mapping): + parsed_mapping = _coerce_mapping_tree(fixture) + records = lark_record_rows(parsed_mapping) task = choose_heartbeat_task(records, agent_id=agent_id) if task is None: return _heartbeat_payload( diff --git a/loopx/extensions/lark/presentation/kanban_config.py b/loopx/extensions/lark/presentation/kanban_config.py index 6a9ada04bf..014bccf4cc 100644 --- a/loopx/extensions/lark/presentation/kanban_config.py +++ b/loopx/extensions/lark/presentation/kanban_config.py @@ -260,6 +260,20 @@ def _public_safe_text(value: object, *, limit: int = TEXT_LIMIT) -> str: _STRUCTURAL_RECORD_ID_PATTERN = re.compile(r"^rec[A-Za-z0-9_-]{6,}$") +def _coerce_mapping_value(value: object) -> object: + if isinstance(value, Mapping): + return {str(key): _coerce_mapping_value(item) for key, item in value.items()} + if isinstance(value, list): + return [_coerce_mapping_value(item) for item in value] + if isinstance(value, tuple): + return tuple(_coerce_mapping_value(item) for item in value) + return value + + +def _coerce_mapping_tree(mapping: Mapping[str, object]) -> dict[str, object]: + return {str(key): _coerce_mapping_value(item) for key, item in mapping.items()} + + def _transform_lark_value( value: object, *, @@ -272,7 +286,7 @@ def _transform_lark_value( if check_structural_id and preserve_external_id and _STRUCTURAL_RECORD_ID_PATTERN.fullmatch(value): return value return text_fn(value) - if isinstance(value, dict): + if isinstance(value, Mapping): return { key_fn(key): _transform_lark_value( item, @@ -435,7 +449,7 @@ def read_lark_kanban_local_config(path: Path) -> dict[str, object]: def write_lark_kanban_local_config(path: Path, payload: Mapping[str, object]) -> None: config_path = path.expanduser() config_path.parent.mkdir(parents=True, exist_ok=True) - to_write: dict[str, object] = dict(payload) + to_write: dict[str, object] = _coerce_mapping_tree(payload) to_write.pop("ok", None) to_write.pop("exists", None) to_write["schema_version"] = LARK_KANBAN_LOCAL_CONFIG_VERSION @@ -489,16 +503,16 @@ def save_lark_kanban_board_config( payload: Mapping[str, object] = existing if existing.get("ok") else {} raw_board = payload.get("board") board: dict[str, object] = ( - {str(key): value for key, value in raw_board.items()} if isinstance(raw_board, dict) else {} + _coerce_mapping_tree(raw_board) if isinstance(raw_board, Mapping) else {} ) existing_views = board.get("view_ids") merged_views: dict[str, object] = ( - {str(key): value for key, value in existing_views.items()} - if isinstance(existing_views, dict) + _coerce_mapping_tree(existing_views) + if isinstance(existing_views, Mapping) else {} ) if view_ids: - merged_views.update(view_ids) + merged_views.update(_coerce_mapping_tree(view_ids)) board.update( { "base_token": base_token, @@ -518,7 +532,7 @@ def save_lark_kanban_board_config( { "schema_version": LARK_KANBAN_LOCAL_CONFIG_VERSION, "board": board, - "todo_records": raw_records if isinstance(raw_records, dict) else {}, + "todo_records": _coerce_mapping_tree(raw_records) if isinstance(raw_records, Mapping) else {}, }, ) return { @@ -532,7 +546,7 @@ def save_lark_kanban_board_config( def lark_kanban_config_from_payload(payload: Mapping[str, object]) -> LarkKanbanConfig | None: board = payload.get("board") - if not isinstance(board, dict): + if not isinstance(board, Mapping): return None base_token = str(board.get("base_token") or "").strip() table_id = str(board.get("table_id") or "").strip() diff --git a/loopx/extensions/lark/presentation/kanban_records.py b/loopx/extensions/lark/presentation/kanban_records.py index d4579f9ed0..58d5c43966 100644 --- a/loopx/extensions/lark/presentation/kanban_records.py +++ b/loopx/extensions/lark/presentation/kanban_records.py @@ -33,6 +33,7 @@ from .kanban_config import ( LARK_KANBAN_LOCAL_CONFIG_VERSION, LarkKanbanConfig, + _coerce_mapping_tree, _compact_text, _credential_safe_lark_values, _public_safe_lark_values, @@ -91,28 +92,29 @@ def _lark_record_from_projection_block( public_safe: bool = False, ) -> dict[str, object]: rows_api = _projection_rows_api() + block_dict = block if isinstance(block, dict) else _coerce_mapping_tree(block) values = _lark_record_from_todo_block( - block, + block_dict, goal_id=goal_id, state_file=Path(f"{source_id}.projection"), - priority=str(block.get("priority") or "P2"), + priority=str(block_dict.get("priority") or "P2"), ) - original_id = str(block.get("original_todo_id") or "") + original_id = str(block_dict.get("original_todo_id") or "") evidence_parts = [ - str(block.get("evidence") or block.get("reason") or block.get("note") or "").strip(), + str(block_dict.get("evidence") or block_dict.get("reason") or block_dict.get("note") or "").strip(), f"source_id={source_id}", ] if original_id: evidence_parts.append(f"original_todo_id={original_id}") - evidence_parts.extend(rows_api.projection_lifecycle_parts(block, source_id=source_id)) + evidence_parts.extend(rows_api.projection_lifecycle_parts(block_dict, source_id=source_id)) evidence_parts = list(dict.fromkeys(part for part in evidence_parts if part)) - lifecycle_state = rows_api.projection_lifecycle_state(block) + lifecycle_state = rows_api.projection_lifecycle_state(block_dict) default_handoff = f"Synced from LoopX projection source={source_id}" if lifecycle_state in {"superseded", "migrated", "retired"}: superseded_by = ( ", ".join( rows_api.projection_text_list( - rows_api.projection_lifecycle_value(block, "superseded_by") + rows_api.projection_lifecycle_value(block_dict, "superseded_by") ) ) or "current projection row" @@ -121,17 +123,17 @@ def _lark_record_from_projection_block( values.update( { "LoopX Goal ID": goal_id, - "LoopX Todo ID": str(block.get("todo_id") or ""), + "LoopX Todo ID": str(block_dict.get("todo_id") or ""), "Scope": _compact_text( - block.get("scope") or block.get("source_section") or f"projection_source={source_id}" + block_dict.get("scope") or block_dict.get("source_section") or f"projection_source={source_id}" ), - "Handoff": _compact_text(block.get("handoff") or default_handoff), + "Handoff": _compact_text(block_dict.get("handoff") or default_handoff), "Evidence": _compact_text("; ".join(evidence_parts)), "Run History": _compact_text( "; ".join( part for part in ( - f"synced from LoopX projection source={source_id} status={block.get('status') or 'open'}", + f"synced from LoopX projection source={source_id} status={block_dict.get('status') or 'open'}", f"row_lifecycle={lifecycle_state}" if lifecycle_state else "", ) if part @@ -139,7 +141,7 @@ def _lark_record_from_projection_block( ), } ) - values.update(issue_fix_surface.issue_fix_record_values(block, compact_text=_compact_text)) + values.update(issue_fix_surface.issue_fix_record_values(block_dict, compact_text=_compact_text)) return _sink_safe_lark_values(values, public_safe=public_safe) @@ -260,7 +262,7 @@ def _load_lark_todo_record_map( def _todo_record_map_from_local_config(local: Mapping[str, object]) -> dict[str, str]: records = local.get("todo_records") if isinstance(local, Mapping) else None - if not isinstance(records, dict): + if not isinstance(records, Mapping): return {} return { str(key): str(value) @@ -279,9 +281,9 @@ def _persist_lark_todo_record_map( if not config_path: return raw_board = local.get("board") - board: Mapping[str, object] = ( - raw_board - if isinstance(raw_board, dict) and raw_board + board: dict[str, object] = ( + _coerce_mapping_tree(raw_board) + if isinstance(raw_board, Mapping) and raw_board else { "base_token": config.base_token, "table_id": config.table_id, diff --git a/loopx/extensions/lark/presentation/kanban_sync.py b/loopx/extensions/lark/presentation/kanban_sync.py index 8bbb6593ba..088bcc1ffc 100644 --- a/loopx/extensions/lark/presentation/kanban_sync.py +++ b/loopx/extensions/lark/presentation/kanban_sync.py @@ -16,6 +16,7 @@ from .kanban_config import ( LARK_KANBAN_SYNC_PROJECTION_VERSION, LarkKanbanConfig, + _coerce_mapping_tree, _validate_sink_visibility, build_record_upsert_command, ) @@ -131,13 +132,14 @@ def sync_loopx_projection_to_lark_kanban( execute: bool = False, runner: cli_transport.CommandRunner = cli_transport.default_subprocess_runner, ) -> dict[str, object]: - if not isinstance(projection, dict): + if not isinstance(projection, Mapping): raise ValueError("projection must be a JSON object") + projection_dict = _coerce_mapping_tree(projection) rows_api = _projection_rows_api() public_safe = _validate_sink_visibility(sink_visibility) - resolved_source_id, namespace_warnings = rows_api.projection_namespace(projection, source_id) + resolved_source_id, namespace_warnings = rows_api.projection_namespace(projection_dict, source_id) resolved_goal_id, rows, warnings = rows_api.projection_rows_from_payload( - projection, + projection_dict, goal_id=goal_id, agent_id=agent_id, source_id=resolved_source_id, @@ -150,7 +152,7 @@ def sync_loopx_projection_to_lark_kanban( complete_warnings: list[str] = [] if reconcile_source: _, complete_rows, complete_warnings = rows_api.projection_rows_from_payload( - projection, + projection_dict, goal_id=goal_id, agent_id=None, source_id=resolved_source_id, diff --git a/loopx/extensions/lark/presentation/record_io.py b/loopx/extensions/lark/presentation/record_io.py index 459a9d3c52..e0584463ec 100644 --- a/loopx/extensions/lark/presentation/record_io.py +++ b/loopx/extensions/lark/presentation/record_io.py @@ -39,7 +39,7 @@ def lark_record_rows(payload: Mapping[str, object]) -> list[dict[str, object]]: def todo_record_entries(parsed: object) -> list[dict[str, str]]: result: list[dict[str, str]] = [] - payload: Mapping[str, object] = parsed if isinstance(parsed, dict) else {} + payload: Mapping[str, object] = parsed if isinstance(parsed, Mapping) else {} for record in lark_record_rows(payload): todo_id = str(record.get("LoopX Todo ID") or "").strip() goal_id = str(record.get("LoopX Goal ID") or "").strip() @@ -50,11 +50,11 @@ def todo_record_entries(parsed: object) -> list[dict[str, str]]: def record_list_is_complete(parsed: object) -> bool: - if not isinstance(parsed, dict): + if not isinstance(parsed, Mapping): return False raw_data = parsed.get("data") - data: object = raw_data if isinstance(raw_data, dict) else parsed - if not isinstance(data, dict): + data: object = raw_data if isinstance(raw_data, Mapping) else parsed + if not isinstance(data, Mapping): return False return ( data.get("has_more") is False @@ -63,11 +63,11 @@ def record_list_is_complete(parsed: object) -> bool: def todo_record_list_is_authoritative(parsed: object) -> bool: - if not record_list_is_complete(parsed) or not isinstance(parsed, dict): + if not record_list_is_complete(parsed) or not isinstance(parsed, Mapping): return False raw_data = parsed.get("data") - data: object = raw_data if isinstance(raw_data, dict) else parsed - if not isinstance(data, dict): + data: object = raw_data if isinstance(raw_data, Mapping) else parsed + if not isinstance(data, Mapping): return False fields = data.get("fields") rows = data.get("data") diff --git a/loopx/extensions/lark/presentation/sync_receipt.py b/loopx/extensions/lark/presentation/sync_receipt.py index c6d9caa1a7..3daadf261f 100644 --- a/loopx/extensions/lark/presentation/sync_receipt.py +++ b/loopx/extensions/lark/presentation/sync_receipt.py @@ -15,9 +15,9 @@ def _compact_text(value: object, *, limit: int) -> str: def _command_error(command_result: Mapping[str, object]) -> str: parsed = command_result.get("json") - if isinstance(parsed, dict): + if isinstance(parsed, Mapping): error = parsed.get("error") - if isinstance(error, dict): + if isinstance(error, Mapping): return str(error.get("message") or error) if error: return str(error) @@ -37,14 +37,14 @@ def compact_lark_kanban_sync_receipt( ) -> dict[str, object]: raw_records = payload.get("records") raw_commands = payload.get("commands") - records = [item for item in (raw_records if isinstance(raw_records, list) else []) if isinstance(item, dict)] - commands = [item for item in (raw_commands if isinstance(raw_commands, list) else []) if isinstance(item, dict)] + records = [item for item in (raw_records if isinstance(raw_records, list) else []) if isinstance(item, Mapping)] + commands = [item for item in (raw_commands if isinstance(raw_commands, list) else []) if isinstance(item, Mapping)] result: dict[str, object] = dict(payload) record_success_count = 0 record_failure_count = 0 for item in records: item_cmd = item.get("command") - if isinstance(item_cmd, dict) and item_cmd.get("ok") is True: + if isinstance(item_cmd, Mapping) and item_cmd.get("ok") is True: record_success_count += 1 else: record_failure_count += 1 @@ -69,12 +69,12 @@ def compact_lark_kanban_sync_receipt( raw_values = item.get("values") cmd_dict: dict[str, object] = ( {str(k): v for k, v in raw_command.items()} - if isinstance(raw_command, dict) + if isinstance(raw_command, Mapping) else {} ) values: dict[str, object] = ( {str(k): v for k, v in raw_values.items()} - if isinstance(raw_values, dict) + if isinstance(raw_values, Mapping) else {} ) compact_records.append( @@ -104,9 +104,6 @@ def render_lark_kanban_markdown(payload: Mapping[str, object]) -> str: f"- schema_version: `{payload.get('schema_version')}`", ] summary_keys = ( - "execute", - "goal_id", - "source_id", "base_token", "table_id", "view_id", @@ -132,14 +129,14 @@ def render_lark_kanban_markdown(payload: Mapping[str, object]) -> str: if isinstance(raw_commands, list): lines.extend(("", "## Commands")) for item in raw_commands: - if isinstance(item, dict): + if isinstance(item, Mapping): marker = "ran" if item.get("executed") else "dry-run" lines.append(f"- `{marker}` `{item.get('command')}`") raw_records = payload.get("records") if payload.get("detail_level") == "compact" and isinstance(raw_records, list): lines.extend(("", "## Records")) for item in raw_records: - if not isinstance(item, dict): + if not isinstance(item, Mapping): continue status = "ok" if item.get("ok") else "failed" summary = ( @@ -154,7 +151,7 @@ def render_lark_kanban_markdown(payload: Mapping[str, object]) -> str: summary += f" error={_compact_text(item.get('error'), limit=220)}" lines.append(summary) raw_writeback = payload.get("writeback") - if isinstance(raw_writeback, dict): + if isinstance(raw_writeback, Mapping): lines.extend(("", "## Writeback")) for key, value in raw_writeback.items(): lines.append(f"- {key}: `{_compact_text(value, limit=220)}`") diff --git a/tests/extensions/test_lark_kanban_contract.py b/tests/extensions/test_lark_kanban_contract.py index 7949291d0a..6811dff0af 100644 --- a/tests/extensions/test_lark_kanban_contract.py +++ b/tests/extensions/test_lark_kanban_contract.py @@ -4,6 +4,8 @@ import inspect from dataclasses import FrozenInstanceError, is_dataclass from pathlib import Path +from types import MappingProxyType +from typing import cast import pytest @@ -35,7 +37,7 @@ def test_kanban_split_modules_stay_under_budget_with_zero_any() -> None: source = (REPOSITORY_ROOT / rel_path).read_text(encoding="utf-8") lines = source.splitlines() assert len(lines) < 700, f"{rel_path} exceeded 700 LOC ({len(lines)})" - assert "type: ignore" not in source, f"{rel_path} must not use type: ignore" + assert ("type:" + " ignore") not in source, f"{rel_path} contains ignore directive" tree = ast.parse(source, filename=rel_path) any_nodes = [ node @@ -162,3 +164,149 @@ def test_choose_heartbeat_task_and_fail_closed_reconcile() -> None: reconcile_source=True, source_snapshot_complete=False, ) + + +def test_mapping_proxy_inputs_match_dict_behavior(tmp_path: Path) -> None: + cfg = kanban.LarkKanbanConfig(base_token="bas123", table_id="tbl456") + + parsed_from_proxy = kanban.lark_kanban_config_from_payload( + MappingProxyType( + { + "board": MappingProxyType( + {"base_token": "bas123", "table_id": "tbl456", "view_id": "Worker Queue"} + ) + } + ) + ) + assert parsed_from_proxy == cfg + + saved_from_proxy = kanban.save_lark_kanban_board_config( + tmp_path / "proxy-kanban.json", + base_token="bas123", + table_id="tbl456", + view_ids=MappingProxyType({"Worker Queue": "vew1"}), + ) + assert saved_from_proxy["ok"] is True + + proj_dict = { + "goal_id": "goal_proxy", + "source_id": "src-proxy", + "items": [{"todo_id": "todo_proxy", "text": "Sync proxy projection", "status": "open"}], + } + proj_proxy = MappingProxyType( + { + "goal_id": "goal_proxy", + "source_id": "src-proxy", + "items": [ + MappingProxyType( + {"todo_id": "todo_proxy", "text": "Sync proxy projection", "status": "open"} + ) + ], + } + ) + res_dict = kanban.sync_loopx_projection_to_lark_kanban(cfg, projection=proj_dict) + res_proxy = kanban.sync_loopx_projection_to_lark_kanban(cfg, projection=proj_proxy) + assert res_proxy == res_dict + + with pytest.raises(ValueError, match="projection must be a JSON object"): + kanban.sync_loopx_projection_to_lark_kanban( + cfg, + projection=cast(dict[str, object], ["not-a-mapping"]), + ) + + fixture_dict = { + "data": { + "fields": ["Task", "Status", "Claim", "Claimed By", "Run History", "Worker Command"], + "data": [["Check proxy", kanban.STATUS_TODO, kanban.CLAIM_UNCLAIMED, "", "", "echo ok"]], + "record_id_list": ["rec_proxy_1"], + } + } + fixture_proxy = MappingProxyType( + { + "data": MappingProxyType( + { + "fields": ["Task", "Status", "Claim", "Claimed By", "Run History", "Worker Command"], + "data": [["Check proxy", kanban.STATUS_TODO, kanban.CLAIM_UNCLAIMED, "", "", "echo ok"]], + "record_id_list": ["rec_proxy_1"], + } + ) + } + ) + assert kanban.lark_record_rows(fixture_proxy) == kanban.lark_record_rows(fixture_dict) + hb_dict = kanban.lark_kanban_heartbeat(cfg, fixture=fixture_dict) + hb_proxy = kanban.lark_kanban_heartbeat(cfg, fixture=fixture_proxy) + assert hb_proxy["decision"] == hb_dict["decision"] == "task_processed" + assert hb_proxy["selected_record_id"] == hb_dict["selected_record_id"] == "rec_proxy_1" + + task_proxy = MappingProxyType({"Task": "Proxy task", "Status": kanban.STATUS_TODO}) + seeded_one = kanban.seed_lark_kanban_task(cfg, task=task_proxy) + seeded_many = kanban.seed_lark_kanban_records(cfg, records=(task_proxy,)) + assert seeded_one["ok"] is True + assert seeded_many["record_count"] == 1 + + receipt_proxy = MappingProxyType( + { + "ok": True, + "schema_version": "loopx_lark_kanban_sync_todos_v0", + "records": [ + MappingProxyType( + { + "todo_id": "t1", + "record_id": "rec1", + "command": MappingProxyType({"ok": True, "executed": False}), + "values": MappingProxyType({"Work Item Type": "Todo"}), + } + ) + ], + "commands": [MappingProxyType({"ok": True, "executed": False, "command": ["cmd"]})], + } + ) + compact = kanban.compact_lark_kanban_sync_receipt(receipt_proxy) + assert compact["record_success_count"] == 1 + assert "###" not in kanban.render_lark_kanban_markdown(compact) + + +def test_render_lark_kanban_markdown_preserves_summary_headers() -> None: + todos_receipt = { + "ok": True, + "schema_version": "loopx_lark_kanban_sync_todos_v0", + "execute": False, + "goal_id": "g-md-probe", + "base_token": "bas1234567", + "table_id": "tbl1234567", + "view_id": "Worker Queue", + "todo_count": 2, + } + todos_md = kanban.render_lark_kanban_markdown(todos_receipt) + assert todos_md.splitlines()[:6] == [ + "# LoopX Lark Kanban", + "", + "- ok: `True`", + "- schema_version: `loopx_lark_kanban_sync_todos_v0`", + "- base_token: `bas1234567`", + "- table_id: `tbl1234567`", + ] + assert "- execute:" not in todos_md + assert "- goal_id:" not in todos_md + + proj_receipt = { + "ok": True, + "schema_version": kanban.LARK_KANBAN_SYNC_PROJECTION_VERSION, + "execute": True, + "goal_id": "g-md-probe", + "source_id": "src-probe", + "detail_level": "compact", + "record_count": 1, + } + proj_md = kanban.render_lark_kanban_markdown(proj_receipt) + assert proj_md.splitlines()[:6] == [ + "# LoopX Lark Kanban", + "", + "- ok: `True`", + f"- schema_version: `{kanban.LARK_KANBAN_SYNC_PROJECTION_VERSION}`", + "- detail_level: `compact`", + "- record_count: `1`", + ] + assert "- execute:" not in proj_md + assert "- goal_id:" not in proj_md + assert "- source_id:" not in proj_md