-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcli.py
More file actions
7542 lines (6780 loc) · 270 KB
/
Copy pathcli.py
File metadata and controls
7542 lines (6780 loc) · 270 KB
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Sponsio CLI entry point."""
from __future__ import annotations
import contextlib
import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
import click
from sponsio import __version__
from sponsio.constants import DASHBOARD_DEFAULT_PORT
@click.group()
@click.version_option(version=__version__, prog_name="sponsio")
def cli():
"""Sponsio. the contract layer for LLM agent systems."""
def _contract_guarantee(entry):
"""Read the guarantee block out of a YAML/dict contract entry.
Reads the canonical ``G`` (short) / ``guarantee`` (long) keys. No
legacy alias support. the rename is hard.
"""
if not isinstance(entry, dict):
return None
return entry.get("G") or entry.get("guarantee")
# ---------------------------------------------------------------------------
# demo
# ---------------------------------------------------------------------------
@cli.command()
@click.option(
"--scenario",
default="cleanup",
type=click.Choice(["cleanup", "backup", "wire", "freeze"], case_sensitive=False),
help="Demo scenario: cleanup (default), backup, wire, freeze",
)
@click.option(
"--mode",
default="mock",
type=click.Choice(["mock", "integration"], case_sensitive=False),
show_default=True,
help="mock uses no optional SDKs; integration runs repo example scripts.",
)
@click.option("--no-guard", is_flag=True, help="Replay the unsafe trajectory.")
@click.option("--fast", is_flag=True, help="Skip typing delays.")
def demo(scenario: str, mode: str, no_guard: bool, fast: bool):
"""Run a Sponsio demo in your terminal.
Four trajectory replays showing unsafe agent behavior and the
contracts that block it. The default mock mode works from a plain
PyPI install with no API key and no optional framework SDKs.
\b
cleanup . Claude Code cleanup agent deletes `.env` & `.git/`
backup . SRE cost-optimizer deletes prod DR backups (OWASP ASI-10)
wire . AP copilot wires $847k to an unverified vendor (OWASP ASI-09)
freeze . Replit-style agent violates code freeze + hides it (OWASP ASI-10)
Examples:\n
sponsio demo\n
sponsio demo --scenario freeze --fast\n
sponsio demo --scenario wire --no-guard\n
sponsio demo --mode integration --scenario freeze
"""
scenario_map = {
"cleanup": ("demo_coding_cleanup.py", "Coding Agent \u2014 Cleanup gone rogue"),
"backup": (
"demo_backup_delete.py",
"SRE Cost-Optimizer \u2014 Prod DR backups deleted",
),
"wire": (
"demo_wire_transfer.py",
"AP Copilot \u2014 Fraudulent wire transfer",
),
"freeze": (
"demo_freeze_violation.py",
"Coding Agent \u2014 Code-freeze violation + coverup",
),
}
script_name, label = scenario_map[scenario]
click.echo()
click.echo(click.style("Sponsio Demo", bold=True))
click.echo(click.style(f" {label}", fg="cyan"))
click.echo()
if mode == "mock":
from sponsio.demos.replay import run_demo
run_demo(scenario, no_guard=no_guard, fast=fast)
return
repo_root = Path(__file__).resolve().parent.parent
script_path = repo_root / "examples" / "demo" / script_name
if not script_path.exists():
click.echo(
click.style(
"Error: integration demo scripts are only available from a "
"source checkout. Use the default mock mode from PyPI: "
f"{click.style('sponsio demo', bold=True)}",
fg="red",
)
)
sys.exit(1)
try:
cmd = [sys.executable, str(script_path)]
if no_guard:
cmd.append("--no-guard")
if fast:
cmd.append("--fast")
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
sys.exit(e.returncode)
except KeyboardInterrupt:
click.echo("\nInterrupted.")
# ---------------------------------------------------------------------------
# patterns
# ---------------------------------------------------------------------------
@cli.command()
def patterns():
"""List all available contract patterns with examples."""
def _section(title, items, color):
click.echo(click.style(title, bold=True))
click.echo()
for name, example, meaning in items:
click.echo(click.style(f" {name}", fg=color, bold=True))
click.echo(f" Example : {example}")
click.echo(click.style(f" Meaning : {meaning}", dim=True))
click.echo()
# --- Core temporal (14) ---
click.echo()
_section(
"Core Temporal Patterns (14 det)",
[
("must_precede", "tool `A` must precede `B`", "A must happen before B"),
(
"always_followed_by",
"tool `A` must always be followed by `B`",
"whenever A, eventually B",
),
("no_reversal", "cannot `B` after `A`", "A commits; B forbidden after"),
(
"requires_permission",
"tool `X` requires permission `perm`",
"tool needs authorization",
),
("no_data_leak", "no data leak from `src` to `ext`", "data containment"),
(
"mutual_exclusion",
"`A` and `B` are mutually exclusive",
"at most one per session",
),
("rate_limit", "tool `X` at most N times", "frequency cap"),
("idempotent", "tool `X` must execute at most once", "single execution"),
(
"deadline",
"`action` within N steps of `trigger`",
"time-bounded obligation",
),
("must_confirm", "tool `X` requires confirmation", "human-in-the-loop"),
("cooldown", "N steps between consecutive `X`", "minimum interval"),
(
"segregation_of_duty",
"review and approve by different agents",
"separation of concerns",
),
("bounded_retry", "tool `X` limited to N retries", "retry cap"),
(
"loop_detection",
"tool `X` at most N consecutive calls",
"runaway loop prevention",
),
],
"cyan",
)
# --- Argument / path / length (5) ---
_section(
"Argument & Path Constraints (5 det)",
[
(
"arg_blacklist",
"tool `bash` arg `command` must not match `rm -rf`",
"forbid patterns in args",
),
(
"arg_allowlist",
"tool `send_money` arg `recipient` must be one of `US-internal-001`, `US-internal-002`",
"arg must match one of the allowed patterns",
),
(
"scope_limit",
"tool `file_write` restricted to `/app/data`",
"restrict tool to allowed paths",
),
(
"arg_length_limit",
"tool `bash` arg `command` max 500 chars",
"block code-injection via long args",
),
(
"data_intact",
"`grep` must use only original data files",
"tool must use unmodified data",
),
],
"cyan",
)
# --- OWASP Agentic Top 10 (8) ---
_section(
"OWASP Agentic Security Patterns (8 det)",
[
(
"destructive_action_gate",
"`delete_db` requires approval from `approver`",
"human approval + role for destructive ops",
),
(
"untrusted_source_gate",
"after `web_fetch`, `send_email` requires re-confirmation",
"re-confirm after untrusted input (A,E pair)",
),
(
"required_steps_completion",
"every `start_task` must be followed by all of [`log`, `notify`]",
"all steps must follow trigger",
),
(
"tool_allowlist",
"only [`read_file`, `write_file`] may be called",
"first-line defense against injected tools",
),
(
"dangerous_bash_commands",
"ban `rm -rf`, `sudo`, `chmod` in bash",
"preset: dangerous shell commands",
),
(
"dangerous_sql_verbs",
"ban `DROP`, `TRUNCATE` in `execute_sql`",
"preset: dangerous SQL verbs",
),
(
"irreversible_once",
"`deploy_production` at most once per session",
"irreversible action protection",
),
(
"confirm_after_source",
"after `fetch_url`, `file_write` requires confirmation",
"narrow source→action gate (A,E pair)",
),
],
"cyan",
)
# --- Atom extensions (3) ---
_section(
"Resource & Delegation Constraints (3 det)",
[
(
"token_budget",
"session total tokens must not exceed 100000",
"limit token consumption",
),
(
"arg_value_range",
"tool `set_price` field `amount` in [0, 1000]",
"constrain numeric arguments",
),
(
"delegation_depth_limit",
"delegation chain max depth 3",
"limit agent-to-agent delegation",
),
],
"cyan",
)
# --- Workflow hygiene (6) ---
_section(
"Workflow Hygiene Patterns (6 det)",
[
(
"dry_run_before_commit",
"`plan_migration` dry-run before `apply_migration`",
"require dry-run before committing changes",
),
(
"backup_before_destructive",
"`snapshot_db` before destructive `drop_table`",
"require backup before destructive action",
),
(
"audit_after",
"`transfer_funds` must be followed by `audit_transfer`",
"require audit/log after sensitive action",
),
(
"approval_freshness",
"`approve_deploy` authorizes `deploy` for 3 steps",
"expire old approvals after N steps",
),
(
"sanitized_before_sink",
"`web_fetch` then `sanitize_input` before `send_email`",
"sanitize untrusted source before sink",
),
(
"duplicate_call_limit",
"`search` args matching `invoice-42` at most 2 times",
"cap repeated same-argument calls",
),
],
"cyan",
)
# This build ships only deterministic patterns. Stochastic /
# LLM-judged evaluators (tone, relevance, generic LLM judge, ...)
# are an extension point with no implementation included;
# ``sponsio patterns`` shows det only.
# ---------------------------------------------------------------------------
# packs. list the contract packs that ship inside the distribution
# ---------------------------------------------------------------------------
@cli.command()
def packs():
"""List shipped contract packs with rule counts + include syntax.
Useful right after ``sponsio scan`` / ``sponsio onboard``: the
generated :file:`sponsio.yaml` references packs by ``include:``
spec, and this command prints the full inventory plus one-line
summaries so users can see what's been pulled in without opening
five YAML files.
"""
# We walk the shipped contracts directory rather than hardcoding
# a table so new packs become visible the moment they're added.
from collections import Counter
from importlib.resources import files
import yaml as _yaml
try:
contracts_root = files("sponsio") / "contracts"
except (ModuleNotFoundError, FileNotFoundError):
click.echo("error: sponsio package not found on import path", err=True)
raise SystemExit(1) from None
rows = [] # (spec, desc_line, n_contracts, kinds_summary, needs_workspace)
for category_dir in sorted(contracts_root.iterdir()):
if not category_dir.is_dir():
continue
for pack_file in sorted(category_dir.iterdir()):
if not pack_file.is_file() or pack_file.suffix not in (".yaml", ".yml"):
continue
spec = f"sponsio:{category_dir.name}/{pack_file.stem}"
try:
text = pack_file.read_text(encoding="utf-8")
doc = _yaml.safe_load(text) or {}
# Header comment's first meaningful sentence gives the
# summary. Fallback to "(no summary)" if the pack didn't
# follow the convention.
summary = "(no summary)"
for line in text.splitlines():
stripped = line.lstrip("#").strip()
if not stripped or stripped.startswith("="):
continue
if stripped.startswith("sponsio/contracts/"):
continue
summary = stripped
break
agents = doc.get("agents") or {}
template = agents.get("*") or next(iter(agents.values()), {})
contracts = (template or {}).get("contracts") or []
n = len(contracts)
# Rough kind count. det patterns vs raw LTL. OSS ships
# no sto pipeline; the third bucket is gone.
kinds = Counter()
for c in contracts:
es = _contract_guarantee(c)
if isinstance(es, dict):
es_list = [es]
elif isinstance(es, list):
es_list = es
else:
es_list = []
for e in es_list:
if not isinstance(e, dict):
continue
if "ltl" in e and "pattern" not in e:
kinds["raw"] += 1
elif e.get("pattern"):
kinds["det"] += 1
needs_ws = "<workspace>/" in text
rows.append((spec, summary, n, dict(kinds), needs_ws))
except Exception as exc: # noqa: BLE001
rows.append((spec, f"(unreadable: {exc})", 0, {}, False))
click.echo()
click.echo(click.style("Shipped contract packs", bold=True))
click.echo()
for spec, summary, n, kinds, needs_ws in rows:
badge = " [needs workspace:]" if needs_ws else ""
click.echo(click.style(f" {spec}{badge}", fg="cyan", bold=True))
k = ", ".join(f"{v} {k}" for k, v in kinds.items()) or f"{n} contracts"
click.echo(f" {n} contracts ({k})")
click.echo(click.style(f" {summary}", dim=True))
click.echo()
click.echo("Use in sponsio.yaml:")
click.echo(" agents:")
click.echo(" your_agent:")
click.echo(" include:")
for spec, *_ in rows:
click.echo(f" - {spec}")
# ---------------------------------------------------------------------------
# skill. install the bundled Agent Skill into Cursor / Claude Code / Codex
# ---------------------------------------------------------------------------
@cli.group()
def skill():
"""Install / manage the bundled Sponsio Agent Skill.
Sponsio ships an Agent Skill (``SKILL.md``) that teaches Cursor,
Claude Code, and Codex how to run the ``onboard``/``scan``/``report``
lifecycle end-to-end. The source file lives inside the installed
package at ``sponsio/skills/sponsio/SKILL.md``; this subcommand
puts it where the respective coding agent will discover it.
The canonical source is packaged, not developer-local, so:
* ``pip install sponsio`` → ``sponsio skill install`` works.
* Upgrading Sponsio refreshes the skill via pip; re-run
``sponsio skill install`` (or use ``--link`` once) to propagate.
"""
# Per-tool discovery paths. Keep the mapping in one place so
# ``--tool both`` / ``auto`` can iterate over it without duplicating
# knowledge about where each tool looks.
_SKILL_TOOL_DIRS: dict[str, Path] = {
"cursor": Path("~/.cursor/skills").expanduser(),
"claude": Path("~/.claude/skills").expanduser(),
"codex": Path("~/.codex/skills").expanduser(),
}
def _packaged_skill_source() -> Path:
"""Return the absolute path to the packaged ``sponsio/skills/sponsio/``
directory. Raises ``FileNotFoundError`` if the install is missing
the skill. which means a broken wheel or a dev checkout without
``pip install -e`` (common footgun)."""
from importlib.resources import files
try:
src = Path(str(files("sponsio") / "skills" / "sponsio"))
except (ModuleNotFoundError, FileNotFoundError) as exc: # pragma: no cover
raise FileNotFoundError(
"sponsio/skills/sponsio/ not found in the installed package. "
"If you're running from a source checkout, `pip install -e .` "
"first so package-data is registered."
) from exc
if not src.is_dir() or not (src / "SKILL.md").is_file():
raise FileNotFoundError(
f"Expected {src / 'SKILL.md'} to exist but it doesn't. "
"The sponsio wheel may be incomplete. re-install sponsio."
)
return src
def _detect_installed_tools() -> list[str]:
"""Return the list of tools whose personal-skills dir already exists.
Used by ``--tool auto``. We prefer "dir already exists" over
"tool is installed" because the dir is a stronger signal of "the
user actually uses this tool's skill system". Cursor / Claude
Code both create it on first skill install.
"""
return [name for name, path in _SKILL_TOOL_DIRS.items() if path.is_dir()]
# ---------------------------------------------------------------------------
# Shared skill-install verification
# ---------------------------------------------------------------------------
#
# Both ``sponsio skill install`` (post-write footer) and
# ``sponsio doctor`` (skill health check) need to answer the same
# question: "is the skill installed at ``<parent>/sponsio/`` such that
# a coding-agent can actually discover it?". A positive answer
# requires all of:
#
# 1. The subdir ``<parent>/sponsio/`` exists.
# 2. It contains ``SKILL.md``, non-empty.
# 3. That file starts with ``---`` (YAML frontmatter delimiter).
# 4. Frontmatter contains ``name: sponsio``. the discovery key the
# agent dispatchers look up.
# 5. For non-symlink installs, content matches the currently-
# packaged skill. otherwise ``pip install -U sponsio`` has
# moved ahead of the copy and the user should re-install.
#
# We encode this once in ``_verify_skill_install_target`` and use it
# from both places. Status is one of:
# - ``ok`` : healthy, up to date
# - ``drift`` : installed but stale (copy lagging packaged src)
# - ``missing`` : nothing at this target (neither installed nor broken)
# - ``broken`` : directory exists but SKILL.md is unusable
SkillInstallStatus = Literal["ok", "drift", "missing", "broken"]
@dataclass
class _SkillInstallHealth:
"""Result of probing one skill-target location."""
tool: str # "cursor" / "claude" / "codex" / "custom:<abs>"
parent: Path # e.g. ~/.cursor/skills
skill_md: Path # e.g. ~/.cursor/skills/sponsio/SKILL.md
mode: Literal["link", "copy", "missing", "broken"]
status: SkillInstallStatus
detail: str # human summary; safe to drop into click.echo()
def _hash_file(p: Path) -> str | None:
"""md5 of ``p``'s bytes, or ``None`` if unreadable.
md5 is fine here. we're checking equality of two local files we
control, not resisting adversarial collisions."""
try:
return hashlib.md5(p.read_bytes()).hexdigest()
except OSError:
return None
def _verify_skill_install_target(
tool: str, parent: Path, packaged_src: Path
) -> _SkillInstallHealth:
"""Probe one install location and classify it.
``packaged_src`` is the directory returned by
:func:`_packaged_skill_source`. typically the ``sponsio/skills/sponsio/``
inside the wheel. We compare the installed ``SKILL.md`` bytes
against ``packaged_src / 'SKILL.md'`` to detect copy-drift.
"""
target = parent / "sponsio"
skill_md = target / "SKILL.md"
if not target.exists() and not target.is_symlink():
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode="missing",
status="missing",
detail=f"not installed at {skill_md}",
)
is_link = target.is_symlink()
mode: Literal["link", "copy", "broken"] = "link" if is_link else "copy"
if not skill_md.is_file():
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode="broken",
status="broken",
detail=f"{target} exists but SKILL.md is missing. re-run with --force",
)
try:
body = skill_md.read_text(errors="replace")
except OSError as exc:
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode=mode,
status="broken",
detail=f"{skill_md}: {exc}",
)
# Fast content-shape checks. catch empty / truncated / wrong-file
# cases before we get into drift comparison. ``name: sponsio`` is
# what the coding-agent dispatchers grep for.
if not body.strip():
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode=mode,
status="broken",
detail=f"{skill_md} is empty",
)
if not body.startswith("---"):
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode=mode,
status="broken",
detail=f"{skill_md} has no YAML frontmatter (agent won't discover it)",
)
if "name: sponsio" not in body:
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode=mode,
status="broken",
detail=f"{skill_md} frontmatter missing `name: sponsio`. agent won't dispatch",
)
# Symlinks are always fresh by definition. no drift check needed.
if is_link:
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode="link",
status="ok",
detail=f"symlink → {packaged_src}",
)
# Copy: compare bytes with packaged source. Hash mismatch means
# the user upgraded sponsio (pip install -U) but didn't re-run
# ``sponsio skill install``. their agent still sees the old skill.
installed_hash = _hash_file(skill_md)
packaged_hash = _hash_file(packaged_src / "SKILL.md")
if (
installed_hash is not None
and packaged_hash is not None
and installed_hash != packaged_hash
):
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode="copy",
status="drift",
detail=(
"installed copy doesn't match packaged SKILL.md. "
"re-run `sponsio skill install --force` after upgrading sponsio"
),
)
size = skill_md.stat().st_size
return _SkillInstallHealth(
tool=tool,
parent=parent,
skill_md=skill_md,
mode="copy",
status="ok",
detail=f"copy ({size:,} bytes, in sync)",
)
def _print_skill_discovery_footer(
results: list[_SkillInstallHealth],
) -> bool:
"""Render the "Discovery:" block after ``sponsio skill install``.
Returns ``True`` iff every result is ``ok``. the caller uses this
to decide the command exit status (healthy installs → 0, any
broken or drift → 1 so CI / scripts notice).
"""
click.echo()
click.echo(click.style("Discovery:", bold=True))
all_ok = True
for r in results:
if r.status == "ok":
icon = click.style("✓", fg="green", bold=True)
elif r.status == "drift":
icon = click.style("⚠", fg="yellow", bold=True)
all_ok = False
elif r.status == "missing":
icon = click.style("·", fg="bright_black", bold=True)
# ``missing`` here means the caller decided to install at
# this target but the target wasn't actually written; this
# shouldn't happen on the happy path, so surface it.
all_ok = False
else: # broken
icon = click.style("✗", fg="red", bold=True)
all_ok = False
click.echo(f" {icon} {r.tool} {r.skill_md} . {r.detail}")
return all_ok
@skill.command("install")
@click.option(
"--tool",
type=click.Choice(["cursor", "claude", "codex", "both", "all", "auto"]),
default="auto",
show_default=True,
help=(
"Which coding agent's skill directory to install into. "
"``auto`` detects which of ``~/.cursor/skills``, "
"``~/.claude/skills``, ``~/.codex/skills`` already exists and "
"installs into every one that does (falls back to cursor+claude "
"when none do). ``both`` = cursor+claude only. ``all`` = all "
"three."
),
)
@click.option(
"--link/--copy",
"use_link",
default=False,
help=(
"``--copy`` (default) makes a standalone copy under "
"``<dest>/sponsio/``; safer cross-platform but requires "
"re-running this command after ``pip install -U sponsio``. "
"``--link`` symlinks back to the bundled skill so upgrades "
"propagate automatically; not reliable on Windows (auto-"
"downgraded to copy)."
),
)
@click.option(
"--dest",
type=click.Path(path_type=Path),
default=None,
help=(
"Install to an explicit directory instead of the per-tool "
"default. The skill is placed under ``<dest>/sponsio/``."
),
)
@click.option(
"--force",
is_flag=True,
help="Overwrite an existing ``<dest>/sponsio/`` entry.",
)
def skill_install(tool: str, use_link: bool, dest: Path | None, force: bool):
mode = "link" if use_link else "copy"
"""Install the bundled Sponsio Agent Skill into a coding-agent's
skills directory.
Examples:\n
sponsio skill install\n
sponsio skill install --tool claude\n
sponsio skill install --tool all --link\n
sponsio skill install --dest /custom/path --force
"""
import shutil
src = _packaged_skill_source()
# Resolve target directories.
if dest is not None:
dest = dest.expanduser().resolve()
targets = [(f"custom:{dest}", dest)]
else:
if tool == "auto":
detected = _detect_installed_tools()
if detected:
names = detected
else:
# Nothing detected. pick a sensible default pair rather
# than erroring. Most Cursor/Claude users will have
# one of these even if the dir hasn't been created yet
# (first-time install case).
names = ["cursor", "claude"]
click.echo(
click.style(
"· no existing skills dir detected. installing "
"into cursor + claude defaults",
fg="bright_black",
dim=True,
),
err=True,
)
elif tool == "both":
names = ["cursor", "claude"]
elif tool == "all":
names = ["cursor", "claude", "codex"]
else:
names = [tool]
targets = [(name, _SKILL_TOOL_DIRS[name]) for name in names]
if mode == "link" and sys.platform.startswith("win"):
click.echo(
click.style(
"warning: --link isn't reliable on Windows; falling back to --copy",
fg="yellow",
),
err=True,
)
mode = "copy"
any_written = False
for label, parent in targets:
target = parent / "sponsio"
parent.mkdir(parents=True, exist_ok=True)
if target.exists() or target.is_symlink():
if not force:
click.echo(
click.style("✗ ", fg="yellow")
+ f"{label}: {target} already exists. pass --force to replace",
err=True,
)
continue
if target.is_symlink() or target.is_file():
target.unlink()
else:
shutil.rmtree(target)
if mode == "link":
try:
target.symlink_to(src, target_is_directory=True)
except OSError as exc:
click.echo(
click.style("✗ ", fg="red")
+ f"{label}: symlink failed ({exc}); retry with --copy",
err=True,
)
continue
click.echo(
click.style("✓ ", fg="green") + f"{label}: linked {target} → {src}"
)
else:
shutil.copytree(src, target)
click.echo(click.style("✓ ", fg="green") + f"{label}: copied to {target}")
any_written = True
if not any_written:
raise SystemExit(1)
# Verify every target we wrote to. catches cases where the copy
# landed at the wrong depth (``<parent>/SKILL.md`` instead of
# ``<parent>/sponsio/SKILL.md``), the source wheel is broken, or a
# filesystem quirk silently ate the write. Also gives the user a
# concrete path to paste into their agent's logs if discovery
# later fails.
probes = [
_verify_skill_install_target(label, parent, src) for label, parent in targets
]
# ``--force`` can leave ``mode == "missing"`` for slots the caller
# explicitly skipped (e.g. the pre-existing target they didn't
# overwrite). don't report those as install failures here since
# the per-target ``already exists`` line already told the story.
probes_to_show = [
p
for p in probes
# drop "missing" entries that correspond to skipped targets;
# keep "missing" that got through an actual write attempt so
# the anomaly is visible
if p.status != "missing" or not (p.parent / "sponsio").exists()
] or probes
all_ok = _print_skill_discovery_footer(probes_to_show)
if not all_ok:
# Non-zero exit so CI / "install then verify" shell scripts
# catch drift / broken installs without having to grep output.
raise SystemExit(1)
# ---------------------------------------------------------------------------
# validate
# ---------------------------------------------------------------------------
def _looks_like_sponsio_config(path: Path) -> bool:
"""Return True if ``path`` is probably a :file:`sponsio.yaml` (not
an arbitrary string the user wanted to parse as a contract).
Kept intentionally narrow so ``sponsio validate interesting.yaml`` only
auto-routes when the file *looks* like a Sponsio config, not every YAML
on disk.
"""
try:
head = path.read_text(encoding="utf-8", errors="replace")[:32768]
except OSError:
return False
# Project configs list agents; ``init`` output uses version+extractor.
if re.search(r"(?m)^\s*agents:\s*", head):
return True
return bool(
re.search(r"(?m)^\s*version:\s*\d", head)
and re.search(r"(?m)^\s*extractor:\s*", head)
)
@cli.command()
@click.argument("contracts", nargs=-1)
@click.option(
"--config",
"-c",
"config_path",
type=click.Path(exists=True),
help="YAML config file (sponsio.yaml)",
)
@click.option("--agent", "-a", "agent_id", help="Agent ID to validate (with --config)")
@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
@click.option(
"--traces",
"trace_paths",
multiple=True,
type=click.Path(exists=True),
help=(
"Replay each parsed contract against the trace file(s) or "
"directory. Adds a per-contract pass/fail/error count so you "
"can see whether a rule would have hit your historical traffic "
"before flipping it to enforce mode. Repeat for multiple paths."
),
)
def validate(contracts, config_path, agent_id, as_json, trace_paths):
"""Validate that contract strings parse into formal patterns.
If you pass a single existing ``.yaml`` / ``.yml`` path that looks like
a Sponsio project file (``agents:`` or ``version:`` + ``extractor:``),
it is treated as ``--config`` automatically so ``sponsio validate
./sponsio.yaml`` does the right thing.
With ``--traces``, each successfully-parsed deterministic contract is
replayed against the supplied trace files / directories and a
pass / fail / error count is reported alongside the parse result.
Counts only. for per-failure attribution and repair suggestions
see the proprietary ``sponsio-pro`` validation pipeline.
Examples:\n
sponsio validate "tool `A` must precede `B`"\n
sponsio validate --config sponsio.yaml\n
sponsio validate --config sponsio.yaml --agent customer_bot\n
sponsio validate --config sponsio.yaml --traces traces/\n
sponsio validate ./sponsio.yaml # same as --config when file looks like a project config
"""
from sponsio.generation.dsl_to_contract import (
ContractSyntaxError,
parse_nl_unified,
)
if config_path and contracts:
click.echo(
click.style(
"Error: cannot use both --config and positional contracts", fg="red"
)
)
sys.exit(1)
# ``sponsio validate ./sponsio.yaml`` (forgot --config) used to try to
# parse the *path string* as a contract. When the path exists and the
# head of the file looks like a project config, treat it as --config.
if not config_path and len(contracts) == 1:
raw = contracts[0]
p = Path(os.path.expanduser(str(raw)))
if not p.is_absolute():
p = Path.cwd() / p
try:
p = p.resolve()
except OSError:
p = Path(raw)
if p.is_file() and p.suffix.lower() in (".yaml", ".yml"):
if _looks_like_sponsio_config(p):
if not as_json:
click.echo(
click.style(" note: ", fg="cyan", dim=True)
+ (
f"treating {p} as a Sponsio config (equivalent to "
f"`--config {p.name}`). "
f"If you meant a one-line contract that looks like a path, "
f"quote it or use `sponsio validate --config` explicitly."
),
err=True,