testzeus-cli 0.0.35__tar.gz → 0.0.37__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. testzeus_cli-0.0.35/README.md → testzeus_cli-0.0.37/PKG-INFO +57 -0
  2. testzeus_cli-0.0.35/PKG-INFO → testzeus_cli-0.0.37/README.md +26 -30
  3. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/pyproject.toml +3 -2
  4. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/auth.py +5 -2
  5. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/cli.py +22 -14
  6. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/daemon.py +4 -0
  7. testzeus_cli-0.0.37/testzeus_cli/commands/telemetry.py +22 -0
  8. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/tests_authoring.py +4 -0
  9. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/config.py +3 -1
  10. testzeus_cli-0.0.37/testzeus_cli/observability/__init__.py +300 -0
  11. testzeus_cli-0.0.37/testzeus_cli/observability/scrub.py +82 -0
  12. testzeus_cli-0.0.37/testzeus_cli/observability/settings.py +167 -0
  13. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/auth.py +6 -3
  14. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/LICENSE +0 -0
  15. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/__init__.py +0 -0
  16. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/agent-capabilities.json +0 -0
  17. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/agent_capabilities.py +0 -0
  18. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/__init__.py +0 -0
  19. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/agent_harness.py +0 -0
  20. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/capabilities.py +0 -0
  21. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/connected_environments.py +0 -0
  22. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/device_pool.py +0 -0
  23. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/environments.py +0 -0
  24. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/hypermind_code_blocks.py +0 -0
  25. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/knowledge_bases.py +0 -0
  26. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/knowledge_documents.py +0 -0
  27. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/notification_channels.py +0 -0
  28. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/qa.py +0 -0
  29. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/records.py +0 -0
  30. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/tags.py +0 -0
  31. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_blocks.py +0 -0
  32. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_data.py +0 -0
  33. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_report_runs.py +0 -0
  34. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_report_schedules.py +0 -0
  35. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_run_groups.py +0 -0
  36. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_runs.py +0 -0
  37. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_suite_node_runs.py +0 -0
  38. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_suite_runs.py +0 -0
  39. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_suite_schedules.py +0 -0
  40. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/test_suites.py +0 -0
  41. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/tests.py +0 -0
  42. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/tests_ai_generator.py +0 -0
  43. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/commands/user_integrations.py +0 -0
  44. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/record-contract.json +0 -0
  45. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/record_contract.py +0 -0
  46. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/record_query.py +0 -0
  47. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/__init__.py +0 -0
  48. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/client.py +0 -0
  49. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/files.py +0 -0
  50. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/formatters.py +0 -0
  51. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/links.py +0 -0
  52. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/profile.py +0 -0
  53. {testzeus_cli-0.0.35 → testzeus_cli-0.0.37}/testzeus_cli/utils/validators.py +0 -0
@@ -1,3 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: testzeus-cli
3
+ Version: 0.0.37
4
+ Summary: Command-line interface for TestZeus testing platform
5
+ License-File: LICENSE
6
+ Author: Shriyansh Agnihotri
7
+ Author-email: shriyansh@testzeus.com
8
+ Requires-Python: >=3.11,<3.14
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Provides-Extra: daemon
15
+ Requires-Dist: Pygments (==2.20.0)
16
+ Requires-Dist: aiohttp (>=3.14.1,<4.0.0)
17
+ Requires-Dist: click (>=8.1.3,<9.0.0)
18
+ Requires-Dist: cryptography (>=48.0.1,<49.0.0)
19
+ Requires-Dist: ipdb (>=0.13.13,<0.14.0)
20
+ Requires-Dist: keyring (>=24.0.0,<25.0.0)
21
+ Requires-Dist: pocketbase (>=0.15.0,<0.16.0)
22
+ Requires-Dist: pydantic (>=2.0.0,<3.0.0)
23
+ Requires-Dist: pyyaml (>=6.0,<7.0)
24
+ Requires-Dist: rich (>=13.3.1,<14.0.0)
25
+ Requires-Dist: sentry-sdk (>=3.0.2,<4.0.0)
26
+ Requires-Dist: testzeus-sdk (>=0.0.35,<0.1.0)
27
+ Requires-Dist: toml (>=0.10.2,<0.11.0)
28
+ Project-URL: Repository, https://github.com/test-zeus-ai/testzeus-cli
29
+ Description-Content-Type: text/markdown
30
+
1
31
  # TestZeus CLI
2
32
 
3
33
  A powerful command-line interface for the TestZeus testing platform.
@@ -42,6 +72,7 @@ The following options can be used with any command:
42
72
  | `--api-url` | Custom TestZeus API URL |
43
73
  | `--verbose` | Enable verbose output |
44
74
  | `--format` | Output format: json, table, or yaml (default: table) |
75
+ | `--no-telemetry` | Send no usage or error reports for this command |
45
76
 
46
77
  ## Managing Tests
47
78
 
@@ -1101,6 +1132,31 @@ Example GitHub Actions workflow:
1101
1132
  --interval 30
1102
1133
  ```
1103
1134
 
1135
+ ## Telemetry
1136
+
1137
+ The CLI sends anonymous usage metrics and reports of unexpected errors to [Sentry](https://sentry.io) to help us find bugs and see which commands are used. It is on by default. The first command you run prints a notice to stderr once, saying what is sent and how to opt out.
1138
+
1139
+ What is sent:
1140
+
1141
+ - for each command: its name (for example `testzeus tests list`, never its arguments), outcome (`ok`, `expected_error`, `error` or `cancelled`), exit code, duration and error class name;
1142
+ - for unexpected errors only: the exception type, its message and the stack trace, with argument values, home-directory paths, tokens, keys, passwords and emails removed;
1143
+ - the CLI, SDK, Python (major and minor) and OS family (`darwin`, `linux`, `windows` or `other`);
1144
+ - which coding agent ran the CLI, if any: `claude-code`, `codex`, `cursor`, `copilot`, `gemini` or `other`, else `human`;
1145
+ - a random installation id stored in `~/.testzeus/installation_id` and, after you log in, your TestZeus user id and tenant id.
1146
+
1147
+ What is never sent: argument or option values, test content, file contents or paths, emails, tokens, API keys, passwords, local variables or your machine's host name. Expected errors (wrong usage, Ctrl-C, authentication, not found and validation errors from the platform) are counted but not reported.
1148
+
1149
+ Reports are sent only when the profile points at the TestZeus cloud (`pb.prod.testzeus.app` or a TestZeus preprod or dev host). Against `localhost` or any other host, nothing is sent. Sending never slows the CLI down by more than 2 seconds, even offline, and never changes its output or exit code.
1150
+
1151
+ Any of these turns it off:
1152
+
1153
+ ```bash
1154
+ testzeus --no-telemetry tests list # this command only (the flag also works after the command)
1155
+ export TESTZEUS_TELEMETRY=0 # this shell; also accepts false, no, off
1156
+ export DO_NOT_TRACK=1 # the cross-tool convention; TESTZEUS_TELEMETRY wins if both are set
1157
+ testzeus telemetry off # saved in ~/.testzeus/config.yaml; `testzeus telemetry status` shows the state
1158
+ ```
1159
+
1104
1160
  ## Error Handling
1105
1161
 
1106
1162
  When an error occurs, the CLI will display an error message. For more detailed information, run any command with the `--verbose` flag:
@@ -1190,3 +1246,4 @@ their own consent rules. The timestamp check is preflight, not atomic CAS.
1190
1246
  Regenerate the committed discovery snapshot using
1191
1247
  `PYTHONPATH=. python scripts/export-record-contract.py`, then update Hermes' pin
1192
1248
  and its `src/tools/record-contract.json`. Contract tests reject drift.
1249
+
@@ -1,32 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: testzeus-cli
3
- Version: 0.0.35
4
- Summary: Command-line interface for TestZeus testing platform
5
- License-File: LICENSE
6
- Author: Shriyansh Agnihotri
7
- Author-email: shriyansh@testzeus.com
8
- Requires-Python: >=3.11,<3.14
9
- Classifier: License :: OSI Approved :: MIT License
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.11
12
- Classifier: Programming Language :: Python :: 3.12
13
- Classifier: Programming Language :: Python :: 3.13
14
- Provides-Extra: daemon
15
- Requires-Dist: Pygments (==2.20.0)
16
- Requires-Dist: aiohttp (>=3.14.1,<4.0.0)
17
- Requires-Dist: click (>=8.1.3,<9.0.0)
18
- Requires-Dist: cryptography (>=48.0.1,<49.0.0)
19
- Requires-Dist: ipdb (>=0.13.13,<0.14.0)
20
- Requires-Dist: keyring (>=24.0.0,<25.0.0)
21
- Requires-Dist: pocketbase (>=0.15.0,<0.16.0)
22
- Requires-Dist: pydantic (>=2.0.0,<3.0.0)
23
- Requires-Dist: pyyaml (>=6.0,<7.0)
24
- Requires-Dist: rich (>=13.3.1,<14.0.0)
25
- Requires-Dist: testzeus-sdk (>=0.0.34,<0.1.0)
26
- Requires-Dist: toml (>=0.10.2,<0.11.0)
27
- Project-URL: Repository, https://github.com/test-zeus-ai/testzeus-cli
28
- Description-Content-Type: text/markdown
29
-
30
1
  # TestZeus CLI
31
2
 
32
3
  A powerful command-line interface for the TestZeus testing platform.
@@ -71,6 +42,7 @@ The following options can be used with any command:
71
42
  | `--api-url` | Custom TestZeus API URL |
72
43
  | `--verbose` | Enable verbose output |
73
44
  | `--format` | Output format: json, table, or yaml (default: table) |
45
+ | `--no-telemetry` | Send no usage or error reports for this command |
74
46
 
75
47
  ## Managing Tests
76
48
 
@@ -1130,6 +1102,31 @@ Example GitHub Actions workflow:
1130
1102
  --interval 30
1131
1103
  ```
1132
1104
 
1105
+ ## Telemetry
1106
+
1107
+ The CLI sends anonymous usage metrics and reports of unexpected errors to [Sentry](https://sentry.io) to help us find bugs and see which commands are used. It is on by default. The first command you run prints a notice to stderr once, saying what is sent and how to opt out.
1108
+
1109
+ What is sent:
1110
+
1111
+ - for each command: its name (for example `testzeus tests list`, never its arguments), outcome (`ok`, `expected_error`, `error` or `cancelled`), exit code, duration and error class name;
1112
+ - for unexpected errors only: the exception type, its message and the stack trace, with argument values, home-directory paths, tokens, keys, passwords and emails removed;
1113
+ - the CLI, SDK, Python (major and minor) and OS family (`darwin`, `linux`, `windows` or `other`);
1114
+ - which coding agent ran the CLI, if any: `claude-code`, `codex`, `cursor`, `copilot`, `gemini` or `other`, else `human`;
1115
+ - a random installation id stored in `~/.testzeus/installation_id` and, after you log in, your TestZeus user id and tenant id.
1116
+
1117
+ What is never sent: argument or option values, test content, file contents or paths, emails, tokens, API keys, passwords, local variables or your machine's host name. Expected errors (wrong usage, Ctrl-C, authentication, not found and validation errors from the platform) are counted but not reported.
1118
+
1119
+ Reports are sent only when the profile points at the TestZeus cloud (`pb.prod.testzeus.app` or a TestZeus preprod or dev host). Against `localhost` or any other host, nothing is sent. Sending never slows the CLI down by more than 2 seconds, even offline, and never changes its output or exit code.
1120
+
1121
+ Any of these turns it off:
1122
+
1123
+ ```bash
1124
+ testzeus --no-telemetry tests list # this command only (the flag also works after the command)
1125
+ export TESTZEUS_TELEMETRY=0 # this shell; also accepts false, no, off
1126
+ export DO_NOT_TRACK=1 # the cross-tool convention; TESTZEUS_TELEMETRY wins if both are set
1127
+ testzeus telemetry off # saved in ~/.testzeus/config.yaml; `testzeus telemetry status` shows the state
1128
+ ```
1129
+
1133
1130
  ## Error Handling
1134
1131
 
1135
1132
  When an error occurs, the CLI will display an error message. For more detailed information, run any command with the `--verbose` flag:
@@ -1219,4 +1216,3 @@ their own consent rules. The timestamp check is preflight, not atomic CAS.
1219
1216
  Regenerate the committed discovery snapshot using
1220
1217
  `PYTHONPATH=. python scripts/export-record-contract.py`, then update Hermes' pin
1221
1218
  and its `src/tools/record-contract.json`. Contract tests reject drift.
1222
-
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [tool.poetry]
6
6
  name = "testzeus-cli"
7
- version = "0.0.35"
7
+ version = "0.0.37"
8
8
  description = "Command-line interface for TestZeus testing platform"
9
9
  authors = ["Shriyansh Agnihotri <shriyansh@testzeus.com>"]
10
10
  readme = "README.md"
@@ -22,12 +22,13 @@ pydantic = "^2.0.0"
22
22
  pyyaml = "^6.0"
23
23
  keyring = "^24.0.0"
24
24
  ipdb = "^0.13.13"
25
- testzeus-sdk = ">=0.0.34,<0.1.0"
25
+ testzeus-sdk = ">=0.0.35,<0.1.0"
26
26
  pocketbase = "^0.15.0"
27
27
  toml = "^0.10.2"
28
28
  aiohttp = "^3.14.1"
29
29
  Pygments = "2.20.0"
30
30
  cryptography = "^48.0.1"
31
+ sentry-sdk = "^3.0.2"
31
32
 
32
33
  [tool.poetry.extras]
33
34
  daemon = [
@@ -13,6 +13,8 @@ from rich.console import Console
13
13
  from typing import Dict, Any, Optional
14
14
 
15
15
  from testzeus_sdk import TestZeusClient
16
+ from testzeus_cli import observability
17
+ from testzeus_cli.observability import client_identity
16
18
  from testzeus_cli.config import (
17
19
  update_config,
18
20
  get_client_config,
@@ -59,7 +61,7 @@ def login_command(
59
61
  )
60
62
 
61
63
  # Create a clean config without email/password to avoid duplicates
62
- base_config = {"base_url": config.get("base_url")}
64
+ base_config = {"base_url": config.get("base_url"), **client_identity()}
63
65
 
64
66
  # Create client with explicit email/password
65
67
  client = TestZeusClient(email=email, password=password, **base_config)
@@ -72,6 +74,7 @@ def login_command(
72
74
  # Get tenant ID from the authenticated client
73
75
  tenant_id = client.get_tenant_id()
74
76
  user_id = client.get_user_id()
77
+ observability.identify(user_id, tenant_id)
75
78
 
76
79
  if save:
77
80
  update_config(
@@ -198,7 +201,7 @@ def session_exchange_command(
198
201
  _debug(f"session-exchange start profile={profile_name} base_url={base_url}")
199
202
 
200
203
  # Create SDK client
201
- client = TestZeusClient(base_url=base_url)
204
+ client = TestZeusClient(base_url=base_url, **client_identity())
202
205
 
203
206
  async def enrich_from_user_record(
204
207
  session_token: str,
@@ -7,7 +7,7 @@ import sys
7
7
  import click
8
8
  from rich.console import Console
9
9
 
10
- from testzeus_cli import __version__
10
+ from testzeus_cli import __version__, observability
11
11
  from testzeus_cli.auth import login_command, logout_command, session_clear_command, session_exchange_command, session_list_command, session_status_command, whoami_command
12
12
  from testzeus_cli.commands.agent_harness import agent_harness_group
13
13
  from testzeus_cli.commands.capabilities import capabilities_group
@@ -21,6 +21,7 @@ from testzeus_cli.commands.notification_channels import notification_channels_gr
21
21
  from testzeus_cli.commands.qa import qa_group
22
22
  from testzeus_cli.commands.records import records_group
23
23
  from testzeus_cli.commands.tags import tags_group
24
+ from testzeus_cli.commands.telemetry import telemetry_command
24
25
  from testzeus_cli.commands.test_blocks import test_blocks_group
25
26
  from testzeus_cli.commands.test_data import test_data_group
26
27
  from testzeus_cli.commands.test_report_runs import test_report_runs_group
@@ -50,7 +51,7 @@ except ModuleNotFoundError as exc:
50
51
  console = Console()
51
52
 
52
53
 
53
- @click.group()
54
+ @click.group(cls=observability.TrackedGroup)
54
55
  @click.version_option(version=__version__, prog_name="testzeus")
55
56
  @click.option("--profile", default="default", help="Configuration profile to use")
56
57
  @click.option("--api-url", help="TestZeus API URL")
@@ -62,6 +63,7 @@ console = Console()
62
63
  default="table",
63
64
  help="Output format",
64
65
  )
66
+ @click.option("--no-telemetry", is_flag=True, expose_value=False, help="Send no usage or error reports for this command")
65
67
  @click.pass_context
66
68
  def cli(ctx, profile, api_url, verbose, output_format):
67
69
  """TestZeus CLI - Command line interface for TestZeus testing platform"""
@@ -95,6 +97,7 @@ cli.add_command(test_suite_schedules_group)
95
97
  cli.add_command(test_run_groups_group)
96
98
  cli.add_command(test_data_group)
97
99
  cli.add_command(tags_group)
100
+ cli.add_command(telemetry_command)
98
101
  cli.add_command(device_pool_group)
99
102
  cli.add_command(environments_group)
100
103
  cli.add_command(connected_environments_group)
@@ -114,18 +117,23 @@ if daemon_command is not None:
114
117
 
115
118
  def main():
116
119
  """Main entry point for the CLI"""
117
- try:
118
- cli(obj={})
119
- except KeyboardInterrupt:
120
- console.print("\n[yellow]Operation cancelled by user[/yellow]")
121
- sys.exit(1)
122
- except Exception as e:
123
- console.print(f"[bold red]Error:[/bold red] {str(e)}")
124
- if "--verbose" in sys.argv:
125
- console.print_exception(show_locals=True)
126
- else:
127
- console.print("[yellow]Run with --verbose for more details[/yellow]")
128
- sys.exit(1)
120
+ args = observability.start(cli, sys.argv[1:])
121
+ with observability.CommandRun(cli, sys.argv[1:]) as run:
122
+ try:
123
+ cli.main(args=args, obj={})
124
+ except SystemExit as e:
125
+ run.exit(e.code)
126
+ except KeyboardInterrupt as e:
127
+ console.print("\n[yellow]Operation cancelled by user[/yellow]")
128
+ run.exit(1, e)
129
+ except Exception as e:
130
+ console.print(f"[bold red]Error:[/bold red] {str(e)}")
131
+ if "--verbose" in sys.argv:
132
+ console.print_exception(show_locals=True)
133
+ else:
134
+ console.print("[yellow]Run with --verbose for more details[/yellow]")
135
+ run.exit(1, e)
136
+ sys.exit(run.raw_exit_code)
129
137
 
130
138
 
131
139
  if __name__ == "__main__":
@@ -24,6 +24,8 @@ from pocketbase import PocketBase
24
24
  from pocketbase.services.realtime_service import MessageData
25
25
  from sse_starlette.sse import EventSourceResponse
26
26
 
27
+ from testzeus_cli import observability
28
+
27
29
  # Store active clients per generator
28
30
  _active_subscriptions: Dict[str, PocketBase] = {}
29
31
 
@@ -120,6 +122,7 @@ async def subscribe_to_generator(generator_id: str, request: Request):
120
122
  "data": _format_record(event.record) if event.record else None,
121
123
  }
122
124
  except Exception as e:
125
+ observability.capture(e)
123
126
  yield {
124
127
  "event": "error",
125
128
  "data": {"error": str(e)}
@@ -154,6 +157,7 @@ async def get_generator_status(generator_id: str, request: Request):
154
157
  record = await pb.collection("tests_ai_generator").get_one(generator_id)
155
158
  return _format_record(record)
156
159
  except Exception as e:
160
+ observability.capture(e)
157
161
  return {"error": str(e)}
158
162
 
159
163
 
@@ -0,0 +1,22 @@
1
+ """
2
+ Command to turn anonymous usage and error reporting on or off.
3
+ """
4
+
5
+ import os
6
+
7
+ import click
8
+
9
+ from testzeus_cli.observability import settings
10
+
11
+
12
+ @click.command(name="telemetry")
13
+ @click.argument("state", type=click.Choice(["on", "off", "status"]), default="status")
14
+ def telemetry_command(state: str) -> None:
15
+ """Turn usage and error reporting on or off, or show whether it is on"""
16
+ if state != "status":
17
+ settings.set_config_enabled(state == "on")
18
+ configured = settings.config_enabled()
19
+ effective = settings.telemetry_enabled([], os.environ)
20
+ click.echo(f"Telemetry: {'on' if effective else 'off'} (config: {'off' if configured is False else 'on'})")
21
+ if configured is not False and not effective:
22
+ click.echo("Turned off by TESTZEUS_TELEMETRY or DO_NOT_TRACK in this shell.")
@@ -11,6 +11,7 @@ from rich.console import Console
11
11
  from rich.table import Table
12
12
 
13
13
  from testzeus_sdk import TestZeusClient
14
+ from testzeus_cli import observability
14
15
  from testzeus_cli.config import get_client_config
15
16
  from testzeus_cli.utils.formatters import format_output, print_message
16
17
  from testzeus_cli.utils.validators import parse_key_value_pairs
@@ -104,6 +105,7 @@ def _fetch_environments(client: TestZeusClient) -> list:
104
105
  ]
105
106
  return []
106
107
  except Exception as e:
108
+ observability.capture(e)
107
109
  console.print(f"[yellow]Warning: Could not fetch environments: {str(e)}[/yellow]")
108
110
  return []
109
111
 
@@ -127,6 +129,7 @@ def _fetch_test_data(client: TestZeusClient) -> list:
127
129
  ]
128
130
  return []
129
131
  except Exception as e:
132
+ observability.capture(e)
130
133
  console.print(f"[yellow]Warning: Could not fetch test data: {str(e)}[/yellow]")
131
134
  return []
132
135
 
@@ -149,6 +152,7 @@ def _fetch_tags(client: TestZeusClient) -> list:
149
152
  ]
150
153
  return []
151
154
  except Exception as e:
155
+ observability.capture(e)
152
156
  console.print(f"[yellow]Warning: Could not fetch tags: {str(e)}[/yellow]")
153
157
  return []
154
158
 
@@ -95,7 +95,9 @@ def get_client_config(
95
95
  """
96
96
  profile_config = get_profile_config(profile)
97
97
 
98
- client_config: Dict[str, Any] = {}
98
+ from testzeus_cli.observability import client_identity
99
+
100
+ client_config: Dict[str, Any] = dict(client_identity())
99
101
  token = None
100
102
  tenant_id = None
101
103
  user_id = None
@@ -0,0 +1,300 @@
1
+ """Sentry error reporting and usage metrics for the CLI.
2
+
3
+ The rest of the CLI calls only: ``start``, ``CommandRun``, ``TrackedGroup``,
4
+ ``identify``, ``capture`` and ``client_identity``.
5
+ """
6
+
7
+ import os
8
+ import platform
9
+ import sys
10
+ import time
11
+ from importlib.metadata import PackageNotFoundError, version
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ import click
15
+ from testzeus_sdk import TestZeusAuthError, TestZeusNotFoundError, TestZeusValidationError
16
+
17
+ from testzeus_cli import __version__
18
+ from testzeus_cli.observability import scrub, settings
19
+
20
+ EXPECTED_ERRORS = (click.ClickException, TestZeusAuthError, TestZeusNotFoundError, TestZeusValidationError)
21
+ _CONTROL_FLOW = (click.exceptions.Exit, click.Abort, click.ClickException, SystemExit)
22
+ _FLUSH_TIMEOUT_S = 2.0
23
+ DAEMON_DEFAULT_URL = "http://localhost:8090"
24
+
25
+ _state: Dict[str, Any] = {"enabled": False, "agent": "human", "last_exception": None}
26
+
27
+
28
+ def client_identity() -> Dict[str, str]:
29
+ return {"client_name": "cli", "client_version": __version__}
30
+
31
+
32
+ def _sdk_version() -> str:
33
+ try:
34
+ return version("testzeus-sdk")
35
+ except PackageNotFoundError:
36
+ return "unknown"
37
+
38
+
39
+ def _os_family() -> str:
40
+ name = sys.platform
41
+ if name.startswith("linux"):
42
+ return "linux"
43
+ if name == "darwin":
44
+ return "darwin"
45
+ if name.startswith("win"):
46
+ return "windows"
47
+ return "other"
48
+
49
+
50
+ def _argument_values(cli: click.Group, args: List[str]) -> List[str]:
51
+ names = {settings.NO_TELEMETRY_FLAG}
52
+ stack = [cli]
53
+ while stack:
54
+ cmd = stack.pop()
55
+ names.add(cmd.name or "")
56
+ for param in cmd.params:
57
+ names.update(getattr(param, "opts", []))
58
+ names.update(getattr(param, "secondary_opts", []))
59
+ if isinstance(cmd, click.Group):
60
+ stack.extend(cmd.commands.values())
61
+ values = []
62
+ for arg in args:
63
+ value = arg.split("=", 1)[1] if arg.startswith("-") and "=" in arg else arg
64
+ if value not in names:
65
+ values.append(value)
66
+ return values
67
+
68
+
69
+ def _command_path(cli: click.Group, args: List[str]) -> tuple:
70
+ path = ["testzeus"]
71
+ cmd: click.Command = cli
72
+ i = 0
73
+ while isinstance(cmd, click.Group) and i < len(args):
74
+ valued = {o for p in cmd.params if isinstance(p, click.Option) and not p.is_flag and not p.count for o in p.opts}
75
+ while i < len(args) and args[i].startswith("-"):
76
+ i += 2 if args[i] in valued else 1
77
+ if i >= len(args) or args[i] not in cmd.commands:
78
+ break
79
+ path.append(args[i])
80
+ cmd = cmd.commands[args[i]]
81
+ i += 1
82
+ return " ".join(path), args[i:]
83
+
84
+
85
+ def command_name(cli: click.Group, args: List[str]) -> str:
86
+ return _command_path(cli, args)[0]
87
+
88
+
89
+ def _root_params(cli: click.Group, args: List[str]) -> Dict[str, Any]:
90
+ try:
91
+ with cli.make_context("testzeus", list(args), resilient_parsing=True) as ctx:
92
+ return dict(ctx.params)
93
+ except Exception:
94
+ return {}
95
+
96
+
97
+ def _daemon_url(cli: click.Group, args: List[str]) -> Optional[str]:
98
+ name, rest = _command_path(cli, args)
99
+ if name != "testzeus daemon":
100
+ return None
101
+ try:
102
+ with cli.commands["daemon"].make_context("daemon", list(rest), resilient_parsing=True) as ctx:
103
+ url = ctx.params.get("pocketbase_url")
104
+ except Exception:
105
+ url = None
106
+ return url or os.environ.get("POCKETBASE_URL") or DAEMON_DEFAULT_URL
107
+
108
+
109
+ def _turns_telemetry_off(cli: click.Group, args: List[str]) -> bool:
110
+ name, rest = _command_path(cli, args)
111
+ return name == "testzeus telemetry" and "off" in rest
112
+
113
+
114
+ def start(cli: click.Group, argv: List[str]) -> Optional[List[str]]:
115
+ """Set up Sentry for this process. Returns the args click should parse (None means sys.argv)."""
116
+ args = list(argv)
117
+ stripped = [a for a in args if a != settings.NO_TELEMETRY_FLAG]
118
+ click_args = stripped if len(stripped) != len(args) else None
119
+ try:
120
+ _init(cli, args)
121
+ except Exception:
122
+ _state["enabled"] = False
123
+ return click_args
124
+
125
+
126
+ def _init(cli: click.Group, args: List[str]) -> None:
127
+ env = os.environ
128
+ _state["agent"] = settings.detect_agent(env)
129
+ if not settings.telemetry_enabled(args, env) or _turns_telemetry_off(cli, args):
130
+ return
131
+ root = _root_params(cli, [a for a in args if a != settings.NO_TELEMETRY_FLAG])
132
+ dsn = env.get("TESTZEUS_SENTRY_DSN", settings.DEFAULT_DSN).strip()
133
+ environment = settings.environment_for(_daemon_url(cli, args) or settings.api_url_for(root.get("profile"), root.get("api_url")))
134
+ if not dsn or environment is None:
135
+ return
136
+
137
+ import sentry_sdk
138
+ from sentry_sdk.integrations.argv import ArgvIntegration
139
+
140
+ if settings.should_show_notice():
141
+ click.echo(settings.TELEMETRY_NOTICE, err=True)
142
+
143
+ scrub.set_argument_values(_argument_values(cli, args))
144
+ os.environ.setdefault("SENTRY_AGENT_HINTS", "0")
145
+ sentry_sdk.init(
146
+ dsn=dsn,
147
+ environment=environment,
148
+ release=f"testzeus-cli@{__version__}",
149
+ server_name="",
150
+ traces_sample_rate=1.0,
151
+ data_collection={"stack_frame_variables": False, "http_bodies": [], "cookies": {"mode": "allowlist", "terms": []}},
152
+ disabled_integrations=[ArgvIntegration],
153
+ auto_enabling_integrations=False,
154
+ shutdown_timeout=_FLUSH_TIMEOUT_S,
155
+ before_send=scrub.before_send,
156
+ before_breadcrumb=scrub.before_breadcrumb,
157
+ before_send_span=scrub.before_send_span,
158
+ )
159
+ tags = {
160
+ "client": "cli",
161
+ "cli_version": __version__,
162
+ "sdk_version": _sdk_version(),
163
+ "os": _os_family(),
164
+ "python": ".".join(platform.python_version_tuple()[:2]),
165
+ "agent": _state["agent"],
166
+ }
167
+ sentry_sdk.set_tags(tags)
168
+ sentry_sdk.set_attributes(tags)
169
+ install_id = settings.installation_id()
170
+ if install_id:
171
+ sentry_sdk.set_user({"id": install_id})
172
+ _state["enabled"] = True
173
+
174
+
175
+ def identify(user_id: Optional[str], tenant_id: Optional[str]) -> None:
176
+ """Attach the PocketBase user id (never the email) and tenant to later events."""
177
+ if not _state["enabled"]:
178
+ return
179
+ import sentry_sdk
180
+
181
+ if user_id:
182
+ sentry_sdk.set_user({"id": str(user_id)})
183
+ if tenant_id:
184
+ sentry_sdk.set_tag("tenant_id", str(tenant_id))
185
+ sentry_sdk.set_attribute("tenant_id", str(tenant_id))
186
+
187
+
188
+ def is_expected(exc: BaseException) -> bool:
189
+ return isinstance(exc, EXPECTED_ERRORS + (KeyboardInterrupt, EOFError))
190
+
191
+
192
+ def capture(exc: BaseException) -> None:
193
+ """Report a failure the CLI handled without re-raising. Expected errors are ignored."""
194
+ if not _state["enabled"] or is_expected(exc):
195
+ return
196
+ import sentry_sdk
197
+
198
+ sentry_sdk.capture_exception(exc)
199
+
200
+
201
+ def _root_cause(exc: BaseException) -> Optional[BaseException]:
202
+ seen = set()
203
+ current: Optional[BaseException] = exc
204
+ while current is not None and id(current) not in seen:
205
+ seen.add(id(current))
206
+ if isinstance(current, (KeyboardInterrupt, EOFError, click.UsageError)) or not isinstance(current, _CONTROL_FLOW):
207
+ return current
208
+ current = current.__cause__ or current.__context__
209
+ return None
210
+
211
+
212
+ class TrackedGroup(click.Group):
213
+ """Root group that remembers the exception a command ended with, even after click turns it into an exit."""
214
+
215
+ def invoke(self, ctx: click.Context) -> Any:
216
+ _state["last_exception"] = None
217
+ try:
218
+ return super().invoke(ctx)
219
+ except BaseException as exc:
220
+ _state["last_exception"] = exc
221
+ raise
222
+
223
+
224
+ class CommandRun:
225
+ """One CLI invocation: a span, run/duration metrics, and a report for unexpected errors."""
226
+
227
+ def __init__(self, cli: click.Group, args: List[str]):
228
+ self.name = command_name(cli, args)
229
+ self.exit_code = 0
230
+ self.raw_exit_code: Any = 0
231
+ self.error: Optional[BaseException] = None
232
+ self._span: Any = None
233
+ self._started = time.monotonic()
234
+
235
+ def __enter__(self) -> "CommandRun":
236
+ if _state["enabled"]:
237
+ try:
238
+ import sentry_sdk
239
+
240
+ self._span = sentry_sdk.start_span(name=self.name, attributes={"sentry.op": "cli.command"})
241
+ self._span.__enter__()
242
+ except Exception:
243
+ self._span = None
244
+ return self
245
+
246
+ def exit(self, code: Any, error: Optional[BaseException] = None) -> None:
247
+ self.raw_exit_code = code
248
+ if code is None:
249
+ self.exit_code = 0
250
+ elif isinstance(code, int):
251
+ self.exit_code = code
252
+ else:
253
+ self.exit_code = 1
254
+ self.error = error
255
+
256
+ def _outcome(self) -> tuple:
257
+ exc = self.error or _state["last_exception"]
258
+ if self.exit_code == 0:
259
+ return "ok", None, ""
260
+ if exc is None:
261
+ return "expected_error", None, ""
262
+ root = _root_cause(exc)
263
+ if root is None:
264
+ outcome = "cancelled" if isinstance(exc, click.Abort) else "expected_error"
265
+ return outcome, None, type(exc).__name__
266
+ if isinstance(root, (KeyboardInterrupt, EOFError)):
267
+ return "cancelled", None, type(root).__name__
268
+ if is_expected(root):
269
+ return "expected_error", None, type(root).__name__
270
+ return "error", root, type(root).__name__
271
+
272
+ def __exit__(self, *exc_info: Any) -> None:
273
+ if not _state["enabled"]:
274
+ return
275
+ try:
276
+ self._finish()
277
+ except Exception:
278
+ pass
279
+
280
+ def _finish(self) -> None:
281
+ import sentry_sdk
282
+
283
+ outcome, report, error_class = self._outcome()
284
+ attributes = {
285
+ "command": self.name,
286
+ "outcome": outcome,
287
+ "exit_code": self.exit_code,
288
+ "error_class": error_class,
289
+ "agent": _state["agent"],
290
+ }
291
+ if report is not None:
292
+ sentry_sdk.capture_exception(report)
293
+ duration_ms = (time.monotonic() - self._started) * 1000
294
+ sentry_sdk.metrics.count("cli.command.run", 1, attributes=attributes)
295
+ sentry_sdk.metrics.distribution("cli.command.duration", duration_ms, unit="millisecond", attributes=attributes)
296
+ if self._span is not None:
297
+ self._span.set_attributes(attributes)
298
+ self._span.status = "ok" if outcome in ("ok", "expected_error", "cancelled") else "error"
299
+ self._span.__exit__(None, None, None)
300
+ sentry_sdk.get_client().close(timeout=_FLUSH_TIMEOUT_S)
@@ -0,0 +1,82 @@
1
+ """Remove argument values, home paths, secrets and emails from outgoing Sentry data."""
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Any, Iterable, List
6
+
7
+ _EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
8
+ _JWT = re.compile(r"\beyJ[\w-]+\.[\w-]+\.[\w-]+")
9
+ _BEARER = re.compile(r"(?i)\b(bearer|basic)\s+[\w.~+/=-]+")
10
+ _SECRET_PAIR = re.compile(r"(?i)\b([\w-]*(?:token|secret|password|passwd|api[_-]?key|authorization|cookie|session)[\w-]*)([\"']?\s*[:=]\s*|\s+)(\"[^\"]*\"|'[^']*'|[^\s,;&]+)")
11
+ _LONG_TOKEN = re.compile(r"\b[A-Za-z0-9+/_-]{32,}={0,2}")
12
+ _QUERY = re.compile(r"(https?://[^\s?#\"']+)\?[^\s#\"']*")
13
+
14
+ _HOME = str(Path.home())
15
+ _arg_values: List[str] = []
16
+
17
+
18
+ def set_argument_values(values: Iterable[str]) -> None:
19
+ _arg_values[:] = sorted({v for v in values if len(v) >= 3}, key=len, reverse=True)
20
+
21
+
22
+ def scrub_text(text: str) -> str:
23
+ for value in _arg_values:
24
+ text = text.replace(value, "[arg]")
25
+ if _HOME and len(_HOME) > 1:
26
+ text = text.replace(_HOME, "~")
27
+ text = _QUERY.sub(r"\1?[query]", text)
28
+ text = _JWT.sub("[token]", text)
29
+ text = _BEARER.sub(r"\1 [token]", text)
30
+ text = _SECRET_PAIR.sub(r"\1\2[redacted]", text)
31
+ text = _EMAIL.sub("[email]", text)
32
+ return _LONG_TOKEN.sub("[token]", text)
33
+
34
+
35
+ def scrub(value: Any) -> Any:
36
+ if isinstance(value, str):
37
+ return scrub_text(value)
38
+ if isinstance(value, dict):
39
+ return {k: scrub(v) for k, v in value.items()}
40
+ if isinstance(value, (list, tuple)):
41
+ return type(value)(scrub(v) for v in value)
42
+ return value
43
+
44
+
45
+ def _scrub_frames(event: dict) -> None:
46
+ for exc in (event.get("exception") or {}).get("values") or []:
47
+ for frame in (exc.get("stacktrace") or {}).get("frames") or []:
48
+ frame.pop("vars", None)
49
+ for key in ("abs_path", "filename"):
50
+ if isinstance(frame.get(key), str):
51
+ frame[key] = frame[key].replace(_HOME, "~")
52
+
53
+
54
+ def before_send(event: dict, hint: dict) -> dict:
55
+ event.pop("server_name", None)
56
+ event.pop("extra", None)
57
+ user = event.get("user")
58
+ if isinstance(user, dict):
59
+ event["user"] = {"id": user["id"]} if user.get("id") else {}
60
+ _scrub_frames(event)
61
+ for key in ("message", "logentry", "breadcrumbs", "request"):
62
+ if key in event:
63
+ event[key] = scrub(event[key])
64
+ for exc in (event.get("exception") or {}).get("values") or []:
65
+ if isinstance(exc.get("value"), str):
66
+ exc["value"] = scrub_text(exc["value"])
67
+ return event
68
+
69
+
70
+ def before_breadcrumb(crumb: dict, hint: dict) -> dict:
71
+ return scrub(crumb)
72
+
73
+
74
+ def before_send_span(span: dict, hint: dict) -> dict:
75
+ if isinstance(span.get("name"), str):
76
+ span["name"] = scrub_text(span["name"])
77
+ attributes = span.get("attributes")
78
+ if isinstance(attributes, dict):
79
+ for key in attributes:
80
+ if any(part in key for part in ("url", "query", "path", "description", "message")):
81
+ attributes[key] = scrub(attributes[key])
82
+ return span
@@ -0,0 +1,167 @@
1
+ """Whether telemetry is on, where it goes, and the anonymous identity it uses."""
2
+
3
+ import os
4
+ import tempfile
5
+ import uuid
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Mapping, Optional
8
+ from urllib.parse import urlparse
9
+
10
+ import yaml
11
+
12
+ from testzeus_cli.config import CONFIG_DIR, CONFIG_FILE
13
+
14
+ DEFAULT_DSN = "https://53bce359c24852def8505cb2a9e3dd43@o4508256143540224.ingest.us.sentry.io/4512535024697344"
15
+ DEFAULT_API_URL = "https://pb.prod.testzeus.app"
16
+ NO_TELEMETRY_FLAG = "--no-telemetry"
17
+
18
+ INSTALLATION_ID_FILE = CONFIG_DIR / "installation_id"
19
+ NOTICE_MARKER_FILE = CONFIG_DIR / "telemetry_notice_shown"
20
+
21
+ TELEMETRY_NOTICE = (
22
+ "TestZeus CLI sends anonymous usage and error reports to Sentry to help improve it: the command name "
23
+ "(never its arguments), outcome, exit code, duration, error class and stack trace, the CLI, SDK, Python and "
24
+ "OS versions, which coding agent ran it (such as Claude Code), a random installation id and, once you log in, "
25
+ "your TestZeus user and tenant ids. It never sends argument values, test content, file paths, emails, tokens "
26
+ "or passwords. To opt out, pass --no-telemetry, set TESTZEUS_TELEMETRY=0 or DO_NOT_TRACK=1, or run "
27
+ "`testzeus telemetry off`."
28
+ )
29
+
30
+ _FALSE = {"0", "false", "no", "off"}
31
+ _TRUE = {"1", "true", "yes", "on"}
32
+
33
+ _AGENT_ENV = (
34
+ ("CLAUDECODE", "claude-code"),
35
+ ("CLAUDE_CODE_ENTRYPOINT", "claude-code"),
36
+ ("CURSOR_AGENT", "cursor"),
37
+ ("CODEX_SANDBOX", "codex"),
38
+ ("CODEX_MANAGED_BY_NPM", "codex"),
39
+ ("GEMINI_CLI", "gemini"),
40
+ ("COPILOT_AGENT", "copilot"),
41
+ )
42
+ _AGENT_NAMES = (
43
+ ("claude", "claude-code"),
44
+ ("codex", "codex"),
45
+ ("cursor", "cursor"),
46
+ ("copilot", "copilot"),
47
+ ("visual studio code", "copilot"),
48
+ ("vscode", "copilot"),
49
+ ("gemini", "gemini"),
50
+ )
51
+
52
+
53
+ def agent_client_from_name(name: Optional[str]) -> Optional[str]:
54
+ if not name:
55
+ return None
56
+ lowered = name.lower()
57
+ for marker, client in _AGENT_NAMES:
58
+ if marker in lowered:
59
+ return client
60
+ return "other"
61
+
62
+
63
+ def detect_agent(env: Mapping[str, str]) -> str:
64
+ named = agent_client_from_name(env.get("TESTZEUS_AGENT_CLIENT"))
65
+ if named:
66
+ return named
67
+ for var, client in _AGENT_ENV:
68
+ if env.get(var):
69
+ return client
70
+ return "human"
71
+
72
+
73
+ def _read_config() -> Dict[str, Any]:
74
+ try:
75
+ with open(CONFIG_FILE, "r") as f:
76
+ data = yaml.safe_load(f)
77
+ return data if isinstance(data, dict) else {}
78
+ except (OSError, yaml.YAMLError):
79
+ return {}
80
+
81
+
82
+ def config_enabled() -> Optional[bool]:
83
+ section = _read_config().get("telemetry")
84
+ if isinstance(section, dict) and isinstance(section.get("enabled"), bool):
85
+ return section["enabled"]
86
+ return None
87
+
88
+
89
+ def set_config_enabled(enabled: bool) -> None:
90
+ from testzeus_cli.config import load_config, save_config
91
+
92
+ config = load_config()
93
+ config["telemetry"] = {"enabled": enabled}
94
+ save_config(config)
95
+
96
+
97
+ def telemetry_enabled(args: list, env: Mapping[str, str]) -> bool:
98
+ if NO_TELEMETRY_FLAG in args:
99
+ return False
100
+ explicit = env.get("TESTZEUS_TELEMETRY", "").strip().lower()
101
+ if explicit in _FALSE:
102
+ return False
103
+ if explicit in _TRUE:
104
+ return True
105
+ if env.get("DO_NOT_TRACK", "").strip().lower() not in {"", "0", "false"}:
106
+ return False
107
+ return config_enabled() is not False
108
+
109
+
110
+ def api_url_for(profile: Optional[str], api_url: Optional[str]) -> str:
111
+ if api_url:
112
+ return api_url
113
+ profile = profile or "default"
114
+ section = _read_config().get(profile)
115
+ if isinstance(section, dict) and section.get("api_url"):
116
+ return str(section["api_url"])
117
+ return DEFAULT_API_URL
118
+
119
+
120
+ def environment_for(api_url: str) -> Optional[str]:
121
+ host = (urlparse(api_url if "//" in api_url else "//" + api_url).hostname or "").lower()
122
+ if host == "pb.prod.testzeus.app":
123
+ return "production"
124
+ if not (host.endswith(".testzeus.app") or host.endswith(".testzeus.com")):
125
+ return None
126
+ labels = host.split(".")[:-2]
127
+ if any(label in {"pro", "preprod"} or label.startswith("preprod") for label in labels):
128
+ return "preprod"
129
+ if any(label.startswith("dev") for label in labels):
130
+ return "development"
131
+ return None
132
+
133
+
134
+ def _write_atomic(path: Path, text: str) -> None:
135
+ path.parent.mkdir(parents=True, exist_ok=True)
136
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
137
+ try:
138
+ with os.fdopen(fd, "w") as f:
139
+ f.write(text)
140
+ os.replace(tmp, path)
141
+ except BaseException:
142
+ Path(tmp).unlink(missing_ok=True)
143
+ raise
144
+
145
+
146
+ def installation_id() -> Optional[str]:
147
+ try:
148
+ existing = INSTALLATION_ID_FILE.read_text().strip()
149
+ return str(uuid.UUID(existing))
150
+ except (OSError, ValueError):
151
+ pass
152
+ new_id = str(uuid.uuid4())
153
+ try:
154
+ _write_atomic(INSTALLATION_ID_FILE, new_id + "\n")
155
+ except OSError:
156
+ return None
157
+ return new_id
158
+
159
+
160
+ def should_show_notice() -> bool:
161
+ if NOTICE_MARKER_FILE.exists():
162
+ return False
163
+ try:
164
+ _write_atomic(NOTICE_MARKER_FILE, "")
165
+ except OSError:
166
+ pass
167
+ return True
@@ -7,7 +7,8 @@ import json
7
7
  import os
8
8
  import logging
9
9
  import time
10
- from testzeus_sdk import TestZeusClient
10
+ from testzeus_sdk import TestZeusAuthError, TestZeusClient
11
+ from testzeus_cli import observability
11
12
  from typing import Dict, Any, Optional, cast
12
13
 
13
14
  logger = logging.getLogger("testzeus_cli.utils.auth")
@@ -83,9 +84,9 @@ def initialize_client_with_token(client: TestZeusClient, token: str, profile_ten
83
84
  # this the user gets raw gateway 401s ("requires valid record authorization
84
85
  # token") or, worse, silently empty collection lists.
85
86
  if claims is None:
86
- raise ValueError("Could not decode saved auth token - run 'testzeus login' to re-authenticate")
87
+ raise TestZeusAuthError("Could not decode saved auth token - run 'testzeus login' to re-authenticate", 401)
87
88
  if isinstance(claims.get("exp"), (int, float)) and claims["exp"] < time.time():
88
- raise ValueError("Saved auth token has expired - run 'testzeus login' to re-authenticate")
89
+ raise TestZeusAuthError("Saved auth token has expired - run 'testzeus login' to re-authenticate", 401)
89
90
 
90
91
  # Set the token
91
92
  client.token = token
@@ -148,6 +149,8 @@ def initialize_client_with_token(client: TestZeusClient, token: str, profile_ten
148
149
  # Set empty tenant ID to indicate we need to resolve it from context
149
150
  setattr(client, "_tenant_id", "")
150
151
 
152
+ observability.identify(user_id, getattr(client, "_tenant_id", "") or profile_tenant_id)
153
+
151
154
  try:
152
155
  resolved_tenant = getattr(client, "_tenant_id", "")
153
156
  _debug(
File without changes