File size: 27,739 Bytes
2a9dc4c
 
 
 
 
f4952b6
2a9dc4c
 
 
 
f4952b6
2a9dc4c
 
 
 
 
 
f628309
2a9dc4c
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
f628309
 
 
 
 
 
2a9dc4c
 
48f2b75
 
 
f4952b6
 
 
48f2b75
c35ac38
f4952b6
 
 
 
 
48f2b75
2a9dc4c
48f2b75
2a9dc4c
 
 
 
 
48f2b75
2a9dc4c
 
f628309
 
 
 
2a9dc4c
f4952b6
2a9dc4c
 
 
48f2b75
2a9dc4c
 
 
 
f4952b6
2a9dc4c
 
8947d88
 
 
48f2b75
8947d88
 
 
 
 
f4952b6
8947d88
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
2a9dc4c
 
 
 
 
 
 
f4952b6
2a9dc4c
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
f628309
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
f4952b6
 
 
 
 
 
 
2a9dc4c
f4952b6
 
2a9dc4c
f4952b6
2a9dc4c
 
 
 
 
f4952b6
2a9dc4c
 
 
f4952b6
f628309
 
 
 
 
f4952b6
 
2a9dc4c
 
f628309
 
2a9dc4c
 
 
 
 
 
 
 
 
e1de134
 
f4952b6
 
2a9dc4c
 
 
f4952b6
 
 
1ed2d7f
 
 
 
 
2a9dc4c
 
 
 
 
 
 
e1de134
 
f4952b6
e1de134
2a9dc4c
8947d88
f4952b6
 
 
 
 
8947d88
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
8947d88
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62eac4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
62eac4a
 
 
 
 
 
 
 
2a9dc4c
f4952b6
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
e1de134
 
f4952b6
e1de134
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
"""Command-line interface for the external LingoLOGOS Python programming package."""

from __future__ import annotations

import argparse
import difflib
import json
import sys
from dataclasses import asdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

from lingologos_python._codex_bridge import ensure_codex_on_path

ensure_codex_on_path()

from lingologos_codex.adapter_contract import check_adapter_contract  # noqa: E402
from lingologos_codex.envelope import ENVELOPE_KIND  # noqa: E402
from lingologos_codex.graph import compute_symbol_pagerank, top_symbols  # noqa: E402

from lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter  # noqa: E402
from lingologos_python.ast_graph import (  # noqa: E402
    build_reverse_index,
    discover_python_files,
    extract_python_graph,
    importers_from_index,
)
from lingologos_python.patterns import (  # noqa: E402
    PATTERNS,
    pattern_card,
    plan_pattern,
    render_card,
    scan_pattern,
)
from lingologos_python.session import (  # noqa: E402
    DEFAULT_PROTECTED_PATTERNS,
    SESSION_LOCK_NAME,
    PythonWorkspaceSession,
    workspace_lock_status,
)
from lingologos_python.test_selector import select_python_tests  # noqa: E402


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="lingologos_python",
        description="Python programming workbench and language adapter powered by LingoLOGOS codex.",
    )
    parser.add_argument(
        "--version",
        action="version",
        version="lingologos_python, codex envelope %s" % ENVELOPE_KIND,
        help="Print the envelope this bundle speaks and exit.",
    )
    sub = parser.add_subparsers(dest="command", required=True)

    # Flags shared by every verb that opens a session: the same tools, the same
    # topology, and the same budgets answer from verify to delete.
    session_flags = argparse.ArgumentParser(add_help=False)
    session_flags.add_argument("--strict-tools", action="store_const", const=True, default=None, help="Demand mypy and ruff; abstain when absent.")
    session_flags.add_argument("--subprocesses", action="store_const", const=True, default=None, help="Run the six topology nodes as separate subprocesses.")
    session_flags.add_argument("--node-timeout", type=float, default=None, metavar="SEC", help="Per-node budget when nodes run as subprocesses; an exhausted budget answers UNKNOWN.")
    session_flags.add_argument("--total-timeout", type=float, default=None, metavar="SEC", help="Cap the sum of the six node waits; each node gets the smaller of its budget and the remaining time.")
    session_flags.add_argument("--gate-timeout", type=float, default=None, metavar="SEC", help="Wall-clock budget for each gate command (test runner, static checker); a runner that exhausts it abstains.")
    session_flags.add_argument("--lock-wait", type=float, default=None, metavar="SEC", help="Wait up to SEC seconds for a workspace lock another session holds; 0 answers the refusal at once.")
    session_flags.add_argument("--protect", action="append", default=None, metavar="PATTERN", help="Add one protected pattern on top of the defaults; repeatable.")
    session_flags.add_argument("--config", default=None, metavar="FILE", help="JSON file holding these session defaults; a flag on the command line wins over the file.")
    session_flags.add_argument("--print-diff", action="store_const", const=True, default=None, help="Print a unified diff of the pair before the verdict line.")
    session_flags.add_argument("--audit", default=None, metavar="FILE", help="Append one JSON line describing this run to FILE.")

    # verify
    p_verify = sub.add_parser("verify", parents=[session_flags], help="Verify a Python workspace through the six-node codex pipeline.")
    p_verify.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_verify.add_argument("--file", default=None, help="Optional relative Python file to focus on.")
    p_verify.add_argument("--json", action="store_true", help="Print JSON output.")

    # edit
    p_edit = sub.add_parser("edit", parents=[session_flags], help="Propose, verify, and atomically commit a Python search-replace edit.")
    p_edit.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_edit.add_argument("--file", required=True, help="Relative Python file to edit.")
    p_edit.add_argument("--search", default=None, help="Search text block.")
    p_edit.add_argument("--search-file", default=None, help="Path to a file holding the search text block.")
    p_edit.add_argument("--replace", default=None, help="Replacement text block.")
    p_edit.add_argument("--replace-file", default=None, help="Path to a file holding the replacement text block.")
    p_edit.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.")
    p_edit.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Allow commit at assurance 2.")
    p_edit.add_argument("--json", action="store_true", help="Print JSON output.")

    # create
    p_create = sub.add_parser("create", parents=[session_flags], help="Create a new Python file after full codex verification.")
    p_create.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_create.add_argument("--file", required=True, help="Relative Python file path to create.")
    p_create.add_argument("--content-file", required=True, help="Path to file holding Python source content.")
    p_create.add_argument("--dry-run", action="store_true", help="Verify without committing to disk.")
    p_create.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Commit at assurance 2 when the two trusted roles do not both agree.")
    p_create.add_argument("--json", action="store_true", help="Print JSON output.")

    # delete
    p_delete = sub.add_parser(
        "delete",
        parents=[session_flags],
        help="Delete a Python file only when the full regression after its removal verifies.",
    )
    p_delete.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_delete.add_argument("--file", required=True, help="Relative Python file to delete.")
    p_delete.add_argument("--dry-run", action="store_true", help="Verify the removal without deleting from disk.")
    p_delete.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Commit at assurance 2 when the two trusted roles do not both agree.")
    p_delete.add_argument("--json", action="store_true", help="Print JSON output.")

    # symbols
    p_sym = sub.add_parser("symbols", help="Extract Python AST symbols, edges, and PageRank.")
    p_sym.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_sym.add_argument("--files", nargs="*", default=None, help="Optional relative Python files.")
    p_sym.add_argument("--limit", type=int, default=10, help="Maximum top symbols to display.")
    p_sym.add_argument("--json", action="store_true", help="Print JSON output.")

    # select-tests
    p_tests = sub.add_parser("select-tests", help="Select Python test files impacted by changed files.")
    p_tests.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_tests.add_argument("--files", nargs="+", required=True, help="Changed relative Python files.")
    p_tests.add_argument("--json", action="store_true", help="Print JSON output.")

    # patterns
    p_pat = sub.add_parser(
        "patterns",
        parents=[session_flags],
        help="List, show, scan or apply the verified Python pattern catalog.",
    )
    p_pat.add_argument("action", choices=("list", "show", "scan", "apply"))
    p_pat.add_argument("--pattern", default=None, help="Pattern id from the catalog.")
    p_pat.add_argument("--workspace", default=None, help="Target Python workspace for scan and apply.")
    p_pat.add_argument("--target", default=None, help="Target as path/to/file.py::function_name.")
    p_pat.add_argument("--dry-run", action="store_true", help="Verify the pair without committing.")
    p_pat.add_argument("--allow-single-prover", action="store_const", const=True, default=None, help="Commit at assurance 2 when the two trusted roles do not both agree; a card that states its own bar keeps it.")
    p_pat.add_argument("--json", action="store_true", help="Print JSON output.")

    # check-adapter
    p_check = sub.add_parser("check-adapter", help="Validate PythonLanguageAdapter against the codex contract.")
    p_check.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_check.add_argument("--strict-tools", action="store_true", help="Check StrictPythonLanguageAdapter.")
    p_check.add_argument("--json", action="store_true", help="Print JSON output.")

    # graph
    p_graph = sub.add_parser(
        "graph",
        help="Print which files import which, forward and backward, and prove the two answers mirror.",
    )
    p_graph.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_graph.add_argument("--json", action="store_true", help="Print JSON output.")

    # lock-status
    p_lock = sub.add_parser(
        "lock-status",
        help="Read who holds the workspace session lock, touching nothing.",
    )
    p_lock.add_argument("--workspace", required=True, help="Target Python workspace directory.")
    p_lock.add_argument("--json", action="store_true", help="Print JSON output.")

    return parser


def _side_text(value: Optional[str], path: Optional[str], side: str) -> Optional[str]:
    """One side of the edit pair, from the command line or from a file, never from both."""

    if value is not None and path is not None:
        print("give --%s or --%s-file, not both" % (side, side), file=sys.stderr)
        return None
    if path is not None:
        return Path(path).read_text(encoding="utf-8", newline="")
    return value


CONFIG_KEYS = (
    "strict_tools",
    "subprocesses",
    "allow_single_prover",
    "node_timeout",
    "total_timeout",
    "gate_timeout",
    "lock_wait",
    "protect",
)


def _load_config(path: str) -> Dict[str, Any]:
    """The JSON defaults of one config file, checked key by key before anything runs."""
    try:
        data = json.loads(Path(path).read_text(encoding="utf-8"))
    except OSError as exc:
        raise ValueError("cannot read config file '%s': %s" % (path, exc.strerror or exc))
    except json.JSONDecodeError as exc:
        raise ValueError("config file '%s' is not JSON: %s" % (path, exc))
    if not isinstance(data, dict):
        raise ValueError("config file '%s' must hold one JSON object" % path)
    for key, value in sorted(data.items()):
        if key not in CONFIG_KEYS:
            raise ValueError("config file names unknown key '%s'" % key)
        if key == "protect":
            if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value):
                raise ValueError("config key 'protect' must hold a list of pattern strings")
        elif key in ("strict_tools", "subprocesses", "allow_single_prover"):
            if not isinstance(value, bool):
                raise ValueError("config key '%s' must hold true or false" % key)
        elif isinstance(value, bool) or not isinstance(value, (int, float)):
            raise ValueError("config key '%s' must hold a number of seconds" % key)
    return data


def _session_options(args: argparse.Namespace) -> argparse.Namespace:
    """Merge three sources in one honest order: the flag, then the config file, then the built-in default."""
    config: Dict[str, Any] = {}
    if getattr(args, "config", None) is not None:
        config = _load_config(args.config)

    def pick(flag_value: Any, key: str, default: Any) -> Any:
        if flag_value is not None:
            return flag_value
        if key in config:
            return config[key]
        return default

    opts = argparse.Namespace()
    opts.strict_tools = bool(pick(getattr(args, "strict_tools", None), "strict_tools", False))
    opts.use_subprocesses = bool(pick(getattr(args, "subprocesses", None), "subprocesses", False))
    opts.min_assurance = 2 if pick(getattr(args, "allow_single_prover", None), "allow_single_prover", False) else 3
    opts.node_timeout_sec = pick(getattr(args, "node_timeout", None), "node_timeout", 120.0)
    opts.total_budget_sec = pick(getattr(args, "total_timeout", None), "total_timeout", None)
    opts.gate_timeout_sec = pick(getattr(args, "gate_timeout", None), "gate_timeout", None)
    opts.lock_wait_sec = pick(getattr(args, "lock_wait", None), "lock_wait", 0.0)
    protect = pick(getattr(args, "protect", None), "protect", None)
    opts.protected_patterns = DEFAULT_PROTECTED_PATTERNS + tuple(protect or ())
    return opts


def _open_session(args: argparse.Namespace) -> Tuple[PythonWorkspaceSession, argparse.Namespace]:
    opts = _session_options(args)
    session = PythonWorkspaceSession(
        args.workspace,
        protected_patterns=opts.protected_patterns,
        strict_tools=opts.strict_tools,
        use_subprocesses=opts.use_subprocesses,
        min_assurance=opts.min_assurance,
        node_timeout_sec=opts.node_timeout_sec,
        total_budget_sec=opts.total_budget_sec,
        gate_timeout_sec=opts.gate_timeout_sec,
        lock_wait_sec=opts.lock_wait_sec,
    )
    return session, opts


def _print_diff(old_label: str, new_label: str, before: str, after: str) -> None:
    """The pair as a unified diff, the same shape any git reader already knows."""
    for line in difflib.unified_diff(
        before.splitlines(),
        after.splitlines(),
        fromfile=old_label,
        tofile=new_label,
        lineterm="",
    ):
        print(line)


def _append_audit(args: argparse.Namespace, res: Any) -> None:
    """One JSONL line per session run, wherever the reader asked the ledger to sit."""
    if getattr(args, "audit", None) is None:
        return
    row = {"command": args.command, "workspace": str(Path(args.workspace).resolve())}
    row.update(res.to_dict())
    with open(args.audit, "a", encoding="utf-8", newline="\n") as handle:
        handle.write(json.dumps(row, sort_keys=True) + "\n")


def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = _build_parser()
    args = parser.parse_args(argv)
    try:
        return _run(args)
    except ValueError as exc:
        # A bad config file, an unknown key, or a budget the session refuses:
        # the command shape is fine, the values are not, and exit 2 says so.
        print("REFUSED: %s" % exc, file=sys.stderr)
        return 2


def _run(args: argparse.Namespace) -> int:
    if args.command == "verify":
        session, _opts = _open_session(args)
        res = session.verify(target_file=args.file)
        if args.json:
            print(json.dumps(res.to_dict(), indent=2, sort_keys=True))
        else:
            print(f"{res.verdict} (assurance {res.assurance}) {res.reason}: {res.detail}")
        _append_audit(args, res)
        return 0 if res.accepted else 1

    if args.command == "edit":
        session, opts = _open_session(args)
        search_text = _side_text(args.search, args.search_file, "search")
        replace_text = _side_text(args.replace, args.replace_file, "replace")
        if search_text is None or replace_text is None:
            print("edit needs exactly one source of text on each side of the pair", file=sys.stderr)
            return 2
        if args.print_diff and not args.json:
            _print_diff("a/" + args.file, "b/" + args.file, search_text, replace_text)
        res = session.edit_file(
            args.file,
            search_text,
            replace_text,
            commit=not args.dry_run,
        )
        if args.json:
            print(json.dumps(res.to_dict(), indent=2, sort_keys=True))
        else:
            print(
                f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) "
                f"{res.reason}: {res.detail}"
            )
        # Exit 0 only when the edit landed on disk, or a dry run cleared the bar.
        # An accepted verdict whose commit never landed is a failure to report.
        _append_audit(args, res)
        return 0 if res.committed or (args.dry_run and res.assurance >= opts.min_assurance) else 1

    if args.command == "create":
        content = Path(args.content_file).read_text(encoding="utf-8", newline="")
        session, _opts = _open_session(args)
        if args.print_diff and not args.json:
            _print_diff("/dev/null", "b/" + args.file, "", content)
        try:
            res = session.create_file(args.file, content, commit=not args.dry_run)
        except FileExistsError as exc:
            print("REFUSED: %s" % exc, file=sys.stderr)
            return 1
        if args.json:
            print(json.dumps(res.to_dict(), indent=2, sort_keys=True))
        else:
            print(
                f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) "
                f"{res.reason}: {res.detail}"
            )
        # Exit 0 only when the file landed, or a dry run was accepted; a verdict
        # that never wrote anything is a failure, whatever its assurance says.
        _append_audit(args, res)
        return 0 if res.committed or (args.dry_run and res.accepted) else 1

    if args.command == "delete":
        session, _opts = _open_session(args)
        source = Path(args.workspace) / Path(*args.file.split("/"))
        if args.print_diff and not args.json:
            original = source.read_text(encoding="utf-8", newline="") if source.is_file() else ""
            _print_diff("a/" + args.file, "/dev/null", original, "")
        try:
            res = session.delete_file(args.file, commit=not args.dry_run)
        except FileNotFoundError as exc:
            print("REFUSED: %s" % exc, file=sys.stderr)
            return 1
        if args.json:
            print(json.dumps(res.to_dict(), indent=2, sort_keys=True))
        else:
            print(
                f"{res.verdict} (assurance {res.assurance}, committed={res.committed}) "
                f"{res.reason}: {res.detail}"
            )
        # A removal lands or it does not: exit 0 only when the file is gone,
        # or when a dry run verified the removal without touching the disk.
        _append_audit(args, res)
        return 0 if res.committed or (args.dry_run and res.accepted) else 1

    if args.command == "symbols":
        root = Path(args.workspace).resolve()
        files: List[str] = args.files if args.files else discover_python_files(root)
        symbols, edges = extract_python_graph(root, files)
        ranks = compute_symbol_pagerank(symbols, edges)
        top = top_symbols(ranks, limit=args.limit)
        if args.json:
            print(
                json.dumps(
                    {
                        "files": files,
                        "symbols": symbols,
                        "edges": [list(e) for e in edges],
                        "top": [[name, score] for name, score in top],
                    },
                    indent=2,
                )
            )
        else:
            print(f"files={len(files)} symbols={len(symbols)} edges={len(edges)}")
            for name, score in top:
                print(f"  {score:.4f}  {name}")
        return 0

    if args.command == "select-tests":
        root = Path(args.workspace).resolve()
        selected = select_python_tests(root, args.files)
        if args.json:
            print(json.dumps({"selected_tests": selected}, indent=2))
        else:
            for item in selected:
                print(item)
        return 0

    if args.command == "patterns":
        if args.action in ("scan", "apply") and not args.workspace:
            print("scan and apply need --workspace", file=sys.stderr)
            return 2
        if args.action in ("show", "apply", "scan") and not args.pattern:
            print("this action needs --pattern", file=sys.stderr)
            return 2
        if args.action == "list":
            specs = [PATTERNS[name] for name in sorted(PATTERNS)]
            rows = [
                {
                    "pattern_id": spec.pattern_id,
                    "family": spec.family,
                    "intent_tags": list(spec.intent_tags),
                    "min_assurance": spec.min_assurance,
                    "rule": spec.rule,
                    "companions": list(spec.companions),
                }
                for spec in specs
            ]
            if args.json:
                print(json.dumps({"patterns": rows}, indent=2, sort_keys=True))
            else:
                for spec in specs:
                    print(
                        "%-28s %-10s %s"
                        % (spec.pattern_id, spec.family, ", ".join(spec.intent_tags))
                    )
            return 0
        if args.action == "show":
            try:
                spec = pattern_card(args.pattern)
            except KeyError as exc:
                print(str(exc).strip("'"), file=sys.stderr)
                return 2
            if args.json:
                print(json.dumps(asdict(spec), indent=2, sort_keys=True))
            else:
                print(render_card(spec))
            return 0
        root = Path(args.workspace).resolve()
        if args.action == "scan":
            found = scan_pattern(root, args.pattern)
            if args.json:
                print(
                    json.dumps(
                        {
                            "pattern": args.pattern,
                            "hits": [
                                {
                                    "target": target,
                                    "rule": hit.rule,
                                    "edits": [asdict(edit) for edit in hit.edits],
                                    "evidence": list(hit.evidence),
                                    "reason_code": hit.reason_code,
                                }
                                for target, hit in found
                            ],
                        },
                        indent=2,
                        sort_keys=True,
                    )
                )
            else:
                if not found:
                    print("no function in this workspace has the shape of this card")
                else:
                    print("%s: %d hit(s) in this workspace" % (args.pattern, len(found)))
                    for target, hit in found:
                        print("  %s" % target)
                        for edit in hit.edits:
                            print("    %-26s %s" % (edit.file, edit.label))
                        for line in hit.evidence:
                            print("      why: %s" % line)
            return 0
        session, _opts = _open_session(args)
        if args.print_diff and not args.json:
            plan = plan_pattern(root, args.pattern, args.target)
            if plan.refused:
                print(
                    "the card refuses %s with %s, so there is no diff to show"
                    % (args.target or "every function in this workspace", plan.reason_code)
                )
            else:
                for edit in plan.edits:
                    _print_diff("a/" + edit.file, "b/" + edit.file, edit.search, edit.replace)
        res = session.apply_pattern(args.pattern, target=args.target, commit=not args.dry_run)
        if args.json:
            print(json.dumps(res.to_dict(), indent=2, sort_keys=True))
        else:
            print(
                "%s (assurance %s, committed=%s) %s: %s"
                % (res.verdict, res.assurance, res.committed, res.reason, res.detail)
            )
            if res.verdict == "REFUSED" and not args.json:
                print("nothing was written; the card named this reason before any node ran")
        # Exit 0 only when the pair landed, or a dry run was accepted: a card can
        # be verified in staging and still lose the commit to the disk.
        _append_audit(args, res)
        return 0 if res.committed or (args.dry_run and res.accepted) else 1

    if args.command == "check-adapter":
        root = Path(args.workspace).resolve()
        adapter = (
            StrictPythonLanguageAdapter(root)
            if args.strict_tools
            else PythonLanguageAdapter(root)
        )
        sample_files = discover_python_files(root)[:3]
        violations = check_adapter_contract(adapter, str(root), sample_files)
        if args.json:
            print(
                json.dumps(
                    {"adapter": adapter.meta().name, "violations": violations},
                    indent=2,
                )
            )
        else:
            if violations:
                for v in violations:
                    print(f"VIOLATION: {v}")
            else:
                print(f"ADAPTER OK: {adapter.meta().name}")
        return 1 if violations else 0

    if args.command == "graph":
        root = Path(args.workspace).resolve()
        if not root.is_dir():
            print("REFUSED: workspace does not exist: %s" % root, file=sys.stderr)
            return 1
        files = discover_python_files(root)
        _symbols, edges = extract_python_graph(root, files)
        file_edges = sorted(
            {
                (edge[0], edge[1])
                for edge in edges
                if "::" not in edge[0] and "::" not in edge[1]
            }
        )
        index = build_reverse_index(root, files)
        importers = {rel: importers_from_index(index, rel) for rel in files}
        if any(source not in importers.get(target, []) for source, target in file_edges):
            print(
                "REFUSED: the forward walk and the reverse index disagree about an import edge",
                file=sys.stderr,
            )
            return 1
        if args.json:
            print(
                json.dumps(
                    {
                        "files": files,
                        "import_edges": [list(edge) for edge in file_edges],
                        "importers": importers,
                    },
                    indent=2,
                    sort_keys=True,
                )
            )
        else:
            print("files=%d import_edges=%d" % (len(files), len(file_edges)))
            for rel in files:
                if importers[rel]:
                    print("  %s <- %s" % (rel, ", ".join(importers[rel])))
        return 0

    if args.command == "lock-status":
        root = Path(args.workspace)
        if not root.is_dir():
            print("REFUSED: workspace does not exist: %s" % root, file=sys.stderr)
            return 1
        status = workspace_lock_status(root)
        if args.json:
            print(json.dumps(status, indent=2, sort_keys=True))
        elif not status["present"]:
            print("free: no lock file named %s in this workspace" % SESSION_LOCK_NAME)
        elif status["unreadable"]:
            print("held: a lock file sits there and its owner cannot be read")
        elif status["held"]:
            print("held: process %d holds the workspace" % status["holder_pid"])
        else:
            print("free: the leftover lock names process %d, which no longer runs" % status["holder_pid"])
        return 1 if status["held"] else 0

    return 2


if __name__ == "__main__":
    raise SystemExit(main())