mindmap.actions module

mindmap.actions.build_parser() ArgumentParser

Build the CLI argument parser.

mindmap.actions.create_mindmap_from_mermaid(mermaid: str, turbo_mode: bool = False, charttype: str = 'auto', macos_access: str = 'applescript') str | int | float | bool | None | Dict[str, JsonValue] | List[JsonValue]

Create a MindManager mindmap from Mermaid syntax (full or simplified).

Parameters:
  • mermaid (str) – Mermaid mindmap text (full with metadata or simplified).

  • turbo_mode (bool) – Enable turbo mode (text-only operations).

  • charttype (str) – Mindmap chart type (auto/orgchart/radial).

  • macos_access (str) – macOS MindManager access method.

Returns:

Status dict or error payload.

Return type:

JsonValue

mindmap.actions.get_grounding_information(mode: str = 'full', turbo_mode: bool = False, charttype: str = 'auto', macos_access: str = 'applescript') str | int | float | bool | None | Dict[str, JsonValue] | List[JsonValue]

Extract grounding information from the current mindmap.

Parameters:
  • mode (str) – Detail level (“full”, “content”, “text”).

  • turbo_mode (bool) – Enable turbo mode (text-only operations).

  • charttype (str) – Mindmap chart type (auto/orgchart/radial).

  • macos_access (str) – macOS MindManager access method.

Returns:

Dict with grounding information or error payload.

Return type:

JsonValue

mindmap.actions.get_library_folder(charttype: str = 'auto', macos_access: str = 'applescript') str | int | float | bool | None | Dict[str, JsonValue] | List[JsonValue]

Get the path to the MindManager library folder.

Parameters:
  • charttype (str) – Mindmap chart type (auto/orgchart/radial).

  • macos_access (str) – macOS MindManager access method.

Returns:

Folder path or error payload.

Return type:

JsonValue

mindmap.actions.get_mindmap(mode: str = 'full', turbo_mode: bool = False, charttype: str = 'auto', macos_access: str = 'applescript') str | int | float | bool | None | Dict[str, JsonValue] | List[JsonValue]

Retrieve the current mindmap and serialize it.

Parameters:
  • mode (str) – Detail level (“full”, “content”, “text”). (Unused for selection.)

  • turbo_mode (bool) – Enable turbo mode (text-only operations).

  • charttype (str) – Mindmap chart type (auto/orgchart/radial).

  • macos_access (str) – macOS MindManager access method.

Returns:

Serialized mindmap or error payload.

Return type:

JsonValue

mindmap.actions.get_selection(mode: str = 'full', turbo_mode: bool = False, charttype: str = 'auto', macos_access: str = 'applescript') str | int | float | bool | None | Dict[str, JsonValue] | List[JsonValue]

Retrieve the currently selected topics in MindManager.

Parameters:
  • mode (str) – Detail level (“full”, “content”, “text”).

  • turbo_mode (bool) – Enable turbo mode (text-only operations).

  • charttype (str) – Mindmap chart type (auto/orgchart/radial).

  • macos_access (str) – macOS MindManager access method.

Returns:

List of serialized topics or error payload.

Return type:

JsonValue

mindmap.actions.main(argv: Sequence[str] | None = None) int
mindmap.actions.serialize_current_mindmap_to_mermaid(id_only: bool = False, mode: str = 'content', turbo_mode: bool = False, charttype: str = 'auto', macos_access: str = 'applescript') str | Dict[str, str]

Serialize the current mindmap to Mermaid format.

Parameters:
  • id_only (bool) – If True, include only IDs without attributes (full mode only).

  • mode (str) – Detail level (“full”, “content”, “text”). Full mode emits Mermaid with metadata comments; other modes emit simplified Mermaid.

  • turbo_mode (bool) – Enable turbo mode (text-only operations).

  • charttype (str) – Mindmap chart type (auto/orgchart/radial).

  • macos_access (str) – macOS MindManager access method.

Returns:

Mermaid string or error payload.

Return type:

Union[str, Dict[str, str]]

Source code for actions.py
  1from __future__ import annotations
  2
  3import argparse
  4import json
  5import sys
  6from typing import Any, Dict, List, Optional, Sequence, Union
  7
  8import mindm
  9import mindmap.mindmap as mm
 10from mindmap import serialization
 11
 12JsonValue = Union[str, int, float, bool, None, Dict[str, "JsonValue"], List["JsonValue"]]
 13
 14DEFAULT_MACOS_ACCESS = "applescript"
 15DEFAULT_CHARTTYPE = "auto"
 16VALID_MODES = ("full", "content", "text")
 17VALID_MACOS_ACCESS = ("applescript", "appscript")
 18VALID_CHARTTYPES = ("auto", "orgchart", "radial")
 19
 20
 21def _serialize_result(data: Any) -> JsonValue:
 22    """Serialize MindmapTopic structures into JSON-friendly values.
 23
 24    Args:
 25        data (Any): The data to serialize.
 26
 27    Returns:
 28        JsonValue: JSON-serializable representation of the input.
 29    """
 30    if isinstance(data, (mm.MindmapTopic, list)):
 31        return serialization.serialize_object_simple(data)
 32    if isinstance(data, tuple):
 33        return list(data)
 34    if isinstance(data, (dict, str, int, float, bool)) or data is None:
 35        return data
 36    return str(data)
 37
 38
 39def _handle_mindmanager_error(func_name: str, exc: Exception) -> Dict[str, str]:
 40    """Format MindManager errors for CLI or skill consumers.
 41
 42    Args:
 43        func_name (str): Function name where the error occurred.
 44        exc (Exception): The exception that was raised.
 45
 46    Returns:
 47        Dict[str, str]: Standardized error payload.
 48    """
 49    if "No document found" in str(exc):
 50        return {
 51            "error": "MindManager Error",
 52            "message": "No document found or MindManager not running.",
 53        }
 54    return {
 55        "error": "MindManager Error",
 56        "message": f"Error during MindManager operation '{func_name}': {exc}",
 57    }
 58
 59
 60def _get_document_instance(
 61    charttype: str = DEFAULT_CHARTTYPE,
 62    turbo_mode: bool = False,
 63    macos_access: str = DEFAULT_MACOS_ACCESS,
 64) -> mm.MindmapDocument:
 65    """Create a configured MindmapDocument instance."""
 66    return mm.MindmapDocument(
 67        charttype=charttype,
 68        turbo_mode=turbo_mode,
 69        inline_editing_mode=False,
 70        mermaid_mode=True,
 71        macos_access=macos_access,
 72    )
 73
 74
 75def _get_document_with_mindmap(
 76    mode: str = "full",
 77    turbo_mode: bool = False,
 78    charttype: str = DEFAULT_CHARTTYPE,
 79    macos_access: str = DEFAULT_MACOS_ACCESS,
 80) -> Optional[mm.MindmapDocument]:
 81    document = _get_document_instance(
 82        charttype=charttype,
 83        turbo_mode=turbo_mode,
 84        macos_access=macos_access,
 85    )
 86    if document.get_mindmap(mode=mode):
 87        return document
 88    return None
 89
 90
 91def get_mindmap(
 92    mode: str = "full",
 93    turbo_mode: bool = False,
 94    charttype: str = DEFAULT_CHARTTYPE,
 95    macos_access: str = DEFAULT_MACOS_ACCESS,
 96) -> JsonValue:
 97    """Retrieve the current mindmap and serialize it.
 98
 99    Args:
100        mode (str): Detail level ("full", "content", "text"). (Unused for selection.)
101        turbo_mode (bool): Enable turbo mode (text-only operations).
102        charttype (str): Mindmap chart type (auto/orgchart/radial).
103        macos_access (str): macOS MindManager access method.
104
105    Returns:
106        JsonValue: Serialized mindmap or error payload.
107    """
108    try:
109        document = _get_document_with_mindmap(
110            mode=mode,
111            turbo_mode=turbo_mode,
112            charttype=charttype,
113            macos_access=macos_access,
114        )
115        if document is None:
116            return {
117                "error": "MindManager Error",
118                "message": "No document found or MindManager not running.",
119            }
120        return _serialize_result(document.mindmap)
121    except Exception as exc:
122        return _handle_mindmanager_error("get_mindmap", exc)
123
124
125def get_selection(
126    mode: str = "full",
127    turbo_mode: bool = False,
128    charttype: str = DEFAULT_CHARTTYPE,
129    macos_access: str = DEFAULT_MACOS_ACCESS,
130) -> JsonValue:
131    """Retrieve the currently selected topics in MindManager.
132
133    Args:
134        mode (str): Detail level ("full", "content", "text").
135        turbo_mode (bool): Enable turbo mode (text-only operations).
136        charttype (str): Mindmap chart type (auto/orgchart/radial).
137        macos_access (str): macOS MindManager access method.
138
139    Returns:
140        JsonValue: List of serialized topics or error payload.
141    """
142    try:
143        document = _get_document_instance(
144            charttype=charttype,
145            turbo_mode=turbo_mode,
146            macos_access=macos_access,
147        )
148        selection = document.get_selection()
149        return _serialize_result(selection)
150    except Exception as exc:
151        return _handle_mindmanager_error("get_selection", exc)
152
153
154def get_grounding_information(
155    mode: str = "full",
156    turbo_mode: bool = False,
157    charttype: str = DEFAULT_CHARTTYPE,
158    macos_access: str = DEFAULT_MACOS_ACCESS,
159) -> JsonValue:
160    """Extract grounding information from the current mindmap.
161
162    Args:
163        mode (str): Detail level ("full", "content", "text").
164        turbo_mode (bool): Enable turbo mode (text-only operations).
165        charttype (str): Mindmap chart type (auto/orgchart/radial).
166        macos_access (str): macOS MindManager access method.
167
168    Returns:
169        JsonValue: Dict with grounding information or error payload.
170    """
171    try:
172        document = _get_document_with_mindmap(
173            mode=mode,
174            turbo_mode=turbo_mode,
175            charttype=charttype,
176            macos_access=macos_access,
177        )
178        if document is None:
179            return {
180                "error": "MindManager Error",
181                "message": "No document found or MindManager not running.",
182            }
183        document.get_selection()
184        top_most, subtopics = document.get_grounding_information()
185        return {"top_most": top_most, "subtopics": subtopics}
186    except Exception as exc:
187        return {
188            "error": "Internal Error",
189            "message": f"Failed to get grounding information: {exc}",
190        }
191
192
193def get_library_folder(
194    charttype: str = DEFAULT_CHARTTYPE,
195    macos_access: str = DEFAULT_MACOS_ACCESS,
196) -> JsonValue:
197    """Get the path to the MindManager library folder.
198
199    Args:
200        charttype (str): Mindmap chart type (auto/orgchart/radial).
201        macos_access (str): macOS MindManager access method.
202
203    Returns:
204        JsonValue: Folder path or error payload.
205    """
206    try:
207        mindmanager_obj = mindm.mindmanager.Mindmanager(
208            charttype=charttype, macos_access=macos_access
209        )
210        return mindmanager_obj.get_library_folder()
211    except Exception as exc:
212        return _handle_mindmanager_error("get_library_folder", exc)
213
214
215def serialize_current_mindmap_to_mermaid(
216    id_only: bool = False,
217    mode: str = "content",
218    turbo_mode: bool = False,
219    charttype: str = DEFAULT_CHARTTYPE,
220    macos_access: str = DEFAULT_MACOS_ACCESS,
221) -> Union[str, Dict[str, str]]:
222    """Serialize the current mindmap to Mermaid format.
223
224    Args:
225        id_only (bool): If True, include only IDs without attributes (full mode only).
226        mode (str): Detail level ("full", "content", "text"). Full mode emits
227            Mermaid with metadata comments; other modes emit simplified Mermaid.
228        turbo_mode (bool): Enable turbo mode (text-only operations).
229        charttype (str): Mindmap chart type (auto/orgchart/radial).
230        macos_access (str): macOS MindManager access method.
231
232    Returns:
233        Union[str, Dict[str, str]]: Mermaid string or error payload.
234    """
235    try:
236        document = _get_document_with_mindmap(
237            mode=mode,
238            turbo_mode=turbo_mode,
239            charttype=charttype,
240            macos_access=macos_access,
241        )
242        if document is None:
243            return {
244                "error": "MindManager Error",
245                "message": "No document found or MindManager not running.",
246            }
247        if mode == "full":
248            guid_mapping: Dict[str, int] = {}
249            serialization.build_mapping(document.mindmap, guid_mapping)
250            return serialization.serialize_mindmap(
251                document.mindmap, guid_mapping, id_only=id_only
252            )
253        return serialization.serialize_mindmap_simple(document.mindmap)
254    except Exception as exc:
255        return _handle_mindmanager_error("serialize_current_mindmap_to_mermaid", exc)
256
257
258def _is_full_mermaid(mermaid: str) -> bool:
259    return "%%" in mermaid
260
261
262def create_mindmap_from_mermaid(
263    mermaid: str,
264    turbo_mode: bool = False,
265    charttype: str = DEFAULT_CHARTTYPE,
266    macos_access: str = DEFAULT_MACOS_ACCESS,
267) -> JsonValue:
268    """Create a MindManager mindmap from Mermaid syntax (full or simplified).
269
270    Args:
271        mermaid (str): Mermaid mindmap text (full with metadata or simplified).
272        turbo_mode (bool): Enable turbo mode (text-only operations).
273        charttype (str): Mindmap chart type (auto/orgchart/radial).
274        macos_access (str): macOS MindManager access method.
275
276    Returns:
277        JsonValue: Status dict or error payload.
278    """
279    if not mermaid or not mermaid.strip():
280        return {"error": "Invalid Input", "message": "Mermaid content is required."}
281    try:
282        if _is_full_mermaid(mermaid):
283            guid_mapping: Dict[str, int] = {}
284            deserialized = serialization.deserialize_mermaid_full(mermaid, guid_mapping)
285            message = "Mindmap created from Mermaid diagram."
286        else:
287            deserialized = serialization.deserialize_mermaid_simple(mermaid)
288            message = "Mindmap created from Mermaid diagram (simple)."
289        document = _get_document_instance(
290            charttype=charttype,
291            turbo_mode=turbo_mode,
292            macos_access=macos_access,
293        )
294        document.mindmap = deserialized
295        document.create_mindmap()
296        return {"status": "success", "message": message}
297    except Exception as exc:
298        return _handle_mindmanager_error("create_mindmap_from_mermaid", exc)
299
300
301def _json_dumps(payload: JsonValue, pretty: bool = False) -> str:
302    if pretty:
303        return json.dumps(payload, indent=2)
304    return json.dumps(payload)
305
306
307def _add_turbo_flag(parser: argparse.ArgumentParser, default: bool = False) -> None:
308    if default:
309        parser.add_argument(
310            "--no-turbo-mode",
311            dest="turbo_mode",
312            action="store_false",
313            help="Disable turbo mode for this command.",
314        )
315        parser.set_defaults(turbo_mode=True)
316    else:
317        parser.add_argument(
318            "--turbo-mode",
319            dest="turbo_mode",
320            action="store_true",
321            help="Enable turbo mode (text-only operations).",
322        )
323
324
325def _add_common_args(
326    parser: argparse.ArgumentParser,
327    *,
328    include_mode: bool = True,
329    default_mode: str = "full",
330    turbo_default: bool = False,
331    include_turbo: bool = True,
332) -> None:
333    if include_mode:
334        parser.add_argument(
335            "--mode",
336            default=default_mode,
337            choices=VALID_MODES,
338            help="Detail level for mindmap extraction.",
339        )
340    if include_turbo:
341        _add_turbo_flag(parser, default=turbo_default)
342    parser.add_argument(
343        "--charttype",
344        default=DEFAULT_CHARTTYPE,
345        choices=VALID_CHARTTYPES,
346        help="Chart type for MindManager templates.",
347    )
348    parser.add_argument(
349        "--macos-access",
350        default=DEFAULT_MACOS_ACCESS,
351        choices=VALID_MACOS_ACCESS,
352        help="macOS MindManager access method.",
353    )
354
355
356def build_parser() -> argparse.ArgumentParser:
357    """Build the CLI argument parser."""
358    parser = argparse.ArgumentParser(
359        description="High-level MindManager mindmap operations."
360    )
361    parser.add_argument(
362        "--json",
363        action="store_true",
364        help="Force JSON output for text responses.",
365    )
366    parser.add_argument(
367        "--pretty",
368        action="store_true",
369        help="Pretty-print JSON output.",
370    )
371    subparsers = parser.add_subparsers(dest="command", required=True)
372
373    parser_get = subparsers.add_parser("get-mindmap", help="Get the mindmap.")
374    _add_common_args(parser_get)
375
376    parser_selection = subparsers.add_parser(
377        "get-selection", help="Get selected topics."
378    )
379    _add_common_args(parser_selection)
380
381    parser_grounding = subparsers.add_parser(
382        "get-grounding-information", help="Get grounding information."
383    )
384    _add_common_args(parser_grounding)
385
386    parser_library = subparsers.add_parser(
387        "get-library-folder", help="Get the library folder path."
388    )
389    _add_common_args(parser_library, include_mode=False)
390
391    parser_mermaid = subparsers.add_parser(
392        "serialize-mermaid", help="Serialize to Mermaid format."
393    )
394    parser_mermaid.add_argument(
395        "--id-only",
396        action="store_true",
397        help="Serialize Mermaid with IDs only.",
398    )
399    _add_common_args(parser_mermaid, default_mode="content")
400
401    parser_create = subparsers.add_parser(
402        "create-from-mermaid",
403        help="Create mindmap from Mermaid (auto-detect full vs simplified).",
404    )
405    input_group = parser_create.add_mutually_exclusive_group()
406    input_group.add_argument("--input", help="Path to Mermaid text file.")
407    input_group.add_argument("--text", help="Mermaid text payload.")
408    _add_common_args(parser_create, include_mode=False, include_turbo=False)
409    _add_turbo_flag(parser_create, default=False)
410
411    return parser
412
413
414def _read_mermaid_input(text: Optional[str], path: Optional[str]) -> str:
415    if text is not None:
416        return text
417    if path is not None:
418        with open(path, "r", encoding="utf-8") as handle:
419            return handle.read()
420    if sys.stdin.isatty():
421        raise ValueError("Provide --text, --input, or pipe Mermaid via stdin.")
422    return sys.stdin.read()
423
424
425def main(argv: Optional[Sequence[str]] = None) -> int:
426    parser = build_parser()
427    args = parser.parse_args(argv)
428
429    result: JsonValue
430    output_kind = "json"
431    exit_code: Optional[int] = None
432
433    if args.command == "get-mindmap":
434        result = get_mindmap(
435            mode=args.mode,
436            turbo_mode=args.turbo_mode,
437            charttype=args.charttype,
438            macos_access=args.macos_access,
439        )
440    elif args.command == "get-selection":
441        result = get_selection(
442            mode=args.mode,
443            turbo_mode=args.turbo_mode,
444            charttype=args.charttype,
445            macos_access=args.macos_access,
446        )
447    elif args.command == "get-grounding-information":
448        result = get_grounding_information(
449            mode=args.mode,
450            turbo_mode=args.turbo_mode,
451            charttype=args.charttype,
452            macos_access=args.macos_access,
453        )
454    elif args.command == "get-library-folder":
455        result = get_library_folder(
456            charttype=args.charttype, macos_access=args.macos_access
457        )
458        output_kind = "text"
459    elif args.command == "serialize-mermaid":
460        result = serialize_current_mindmap_to_mermaid(
461            id_only=args.id_only,
462            mode=args.mode,
463            turbo_mode=args.turbo_mode,
464            charttype=args.charttype,
465            macos_access=args.macos_access,
466        )
467        output_kind = "text"
468    elif args.command == "create-from-mermaid":
469        try:
470            mermaid_text = _read_mermaid_input(args.text, args.input)
471        except ValueError as exc:
472            result = {"error": "Invalid Input", "message": str(exc)}
473            exit_code = 2
474        else:
475            result = create_mindmap_from_mermaid(
476                mermaid=mermaid_text,
477                turbo_mode=args.turbo_mode,
478                charttype=args.charttype,
479                macos_access=args.macos_access,
480            )
481    else:
482        parser.print_help()
483        return 2
484
485    is_error = isinstance(result, dict) and "error" in result
486    if output_kind == "text" and not args.json and isinstance(result, str):
487        sys.stdout.write(result)
488    else:
489        print(_json_dumps(result, pretty=args.pretty))
490
491    if exit_code is not None:
492        return exit_code
493    return 1 if is_error else 0
494
495
496if __name__ == "__main__":
497    raise SystemExit(main())