codedd-cli 0.1.9__py3-none-any.whl → 0.1.10__py3-none-any.whl

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.
codedd_cli/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """CodeDD CLI — run code audits from your terminal."""
2
2
 
3
- __version__ = "0.1.9"
3
+ __version__ = "0.1.10"
@@ -78,11 +78,14 @@ def require_auth(func: Callable) -> Callable:
78
78
  Decorator that aborts a CLI command when the user is not authenticated.
79
79
 
80
80
  Checks:
81
- 1. Config file has a ``token_hint`` (session metadata present).
82
- 2. OS keychain (or ``CODEDD_API_TOKEN`` env-var) has the actual token.
83
- 3. Server confirms the token is still valid — result cached for
81
+ 1. OS keychain or ``CODEDD_API_TOKEN`` has the actual token. A prior
82
+ ``token_hint`` in the config file is not required — headless and CI
83
+ environments can authenticate with the env-var alone.
84
+ 2. Server confirms the token is still valid — result cached for
84
85
  ``TOKEN_VERIFY_CACHE_TTL_SECONDS`` to avoid a network call on every
85
86
  rapid-fire command.
87
+ 3. After a successful verify, a missing ``token_hint`` is hydrated from
88
+ the retrieved token so ``auth status`` / ``config show`` stay consistent.
86
89
  """
87
90
 
88
91
  @functools.wraps(func)
@@ -90,11 +93,20 @@ def require_auth(func: Callable) -> Callable:
90
93
  cfg = ConfigManager()
91
94
  token = TokenManager.retrieve()
92
95
 
93
- if not cfg.is_authenticated or not token:
94
- console.print(
95
- "[bold red]Not authenticated.[/bold red] "
96
- "Run [bold cyan]codedd auth login[/bold cyan] first."
97
- )
96
+ if not token:
97
+ if cfg.is_authenticated:
98
+ console.print(
99
+ "[bold red]Not authenticated.[/bold red] "
100
+ "A session is stored but no token could be retrieved. "
101
+ "Set [bold cyan]CODEDD_API_TOKEN[/bold cyan] or install a keyring backend, "
102
+ "then retry or run [bold cyan]codedd auth login[/bold cyan]."
103
+ )
104
+ else:
105
+ console.print(
106
+ "[bold red]Not authenticated.[/bold red] "
107
+ "Run [bold cyan]codedd auth login[/bold cyan] first, "
108
+ "or set [bold cyan]CODEDD_API_TOKEN[/bold cyan]."
109
+ )
98
110
  raise typer.Exit(code=1)
99
111
 
100
112
  if not _verify_token_server_side(cfg):
@@ -104,6 +116,10 @@ def require_auth(func: Callable) -> Callable:
104
116
  )
105
117
  raise typer.Exit(code=1)
106
118
 
119
+ if not cfg.token_hint:
120
+ cfg.token_hint = TokenManager.token_hint(token)
121
+ cfg.save()
122
+
107
123
  return func(*args, **kwargs)
108
124
 
109
125
  return wrapper
@@ -224,9 +224,12 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
224
224
  Workflow Pattern:
225
225
  1. Fetch overview (codedd fix fetch {flags|vulns})
226
226
  2. Get next issue (codedd fix {flags|vulns} next [OPTIONS])
227
- 3. Record progress (codedd fix comment \"...\")
228
- 4. Mark resolved (codedd fix resolve)
229
- 5. Iterate or check status (codedd fix status)
227
+ 3. Apply the fix, then record and advance in one call
228
+ (codedd fix resolve --comment \"what changed and why\")
229
+ 4. Repeat step 3 until the output shows QUEUE EMPTY (exit code 3)
230
+
231
+ Every issue-bearing command reprints the loop protocol, so the contract
232
+ does not need to be remembered from earlier in the conversation.
230
233
  """).strip(),
231
234
  )
232
235
 
@@ -566,20 +569,51 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
566
569
  # RESOLVE ISSUE
567
570
  # =========================================================================
568
571
  _subsection(
569
- "Step 4: Mark Issue Resolved",
570
- "Complete remediation and advance to next issue.",
572
+ "Step 4: Mark Issue Resolved (the one command per issue)",
573
+ "Records the comment, resolves, and prints the next issue in one call.",
571
574
  )
572
575
 
573
576
  _code_block(
574
- "Mark current issue resolved (auto-detect type):",
575
- "codedd fix resolve",
577
+ "Preferred form -- comment and resolve together:",
578
+ 'codedd fix resolve --comment "parameterised the user lookup query"',
579
+ )
580
+ _code_block(
581
+ "Comment from a file (no shell quoting):",
582
+ "codedd fix resolve --comment-file note.txt",
576
583
  )
577
584
  _code_block("Resolve with explicit type:", "codedd fix resolve --issue-type vulns")
585
+ _code_block("Resolve without advancing the queue:", "codedd fix resolve --no-next")
578
586
 
579
587
  console.print("[bold]Command Format:[/bold]")
580
588
  console.print(" codedd fix resolve [OPTIONS]")
581
589
 
582
590
  console.print("\n[bold]Options:[/bold]")
591
+ _table_item(
592
+ "--comment, -m TEXT",
593
+ "Record what changed before resolving. Removes the need for a separate "
594
+ "'codedd fix comment' call.",
595
+ 2,
596
+ )
597
+ _table_item(
598
+ "--comment-file PATH",
599
+ "Read the comment from a file. Use for multi-line or quote-heavy text.",
600
+ 2,
601
+ )
602
+ _table_item(
603
+ "--issue-uuid UUID",
604
+ "Safety check: abort unless this matches the last issue delivered by 'next'.",
605
+ 2,
606
+ )
607
+ _table_item(
608
+ "--next / --no-next",
609
+ "Fetch and print the next issue after resolving (default: --next).",
610
+ 2,
611
+ )
612
+ _table_item(
613
+ "--json",
614
+ "Machine-readable output including the next issue and the loop protocol.",
615
+ 2,
616
+ )
583
617
  _table_item(
584
618
  "--issue-type {flags|vulns}",
585
619
  "Explicitly specify session type (auto-detected if omitted). Shorthand: -t flags",
@@ -591,9 +625,9 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
591
625
  textwrap.dedent("""
592
626
  - Sets is_resolved=true on current_issue
593
627
  - Increments resolved_issues counter
594
- - Automatically fetches next unresolved issue
595
- - Advances queue_position in workflow
596
- - Returns next issue details (if available)
628
+ - Advances queue_position and prints the next unresolved issue
629
+ - The advance uses a dedicated next-call, because the resolve response
630
+ can echo back the issue that was just closed
597
631
  - For flags: forwards Issue Compass selection id and applies the same
598
632
  saved-list filter when computing progress and the next issue (progress
599
633
  stays scoped to the selection, e.g. 1/42 not 1/171)
@@ -602,7 +636,10 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
602
636
  - Confirmation of resolved issue UUID
603
637
  - Next issue block (same rendering as 'fix {flags|vulns} next')
604
638
  - Updated progress (resolved M/total, pending P)
605
- - Message if no unresolved issues remain
639
+ - The loop protocol block, reprinted on every call
640
+
641
+ Exit codes: 0 = resolved and next issue delivered, 1 = error,
642
+ 3 = resolved and the queue is now empty.
606
643
  """).strip()
607
644
  )
608
645
 
@@ -713,18 +750,21 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
713
750
  )
714
751
 
715
752
  _subsection(
716
- "Workflow 2: Remediate Security Flags (Interactive)",
717
- "Step through flags one by one with manual priority.",
753
+ "Workflow 2: Remediate Security Flags (the remediation loop)",
754
+ "One command per issue. Repeat until the queue reports QUEUE EMPTY.",
718
755
  )
719
756
  console.print(
720
757
  textwrap.dedent("""
721
758
  codedd fix fetch flags
722
- codedd fix flags next # Load first flag
723
- # ... developer reviews and makes fix ...
724
- codedd fix comment "Fixed null check in line 42"
725
- codedd fix resolve # Mark resolved, load next
726
- codedd fix comment "Refactored error handling"
727
- codedd fix resolve # Continue...
759
+ codedd fix flags next --auto # Load the highest-priority flag
760
+ # ... apply the fix ...
761
+ codedd fix resolve --comment "parameterised the user lookup query"
762
+ # -> records the comment, resolves, and prints the NEXT issue
763
+ # ... apply the next fix, then run resolve again ...
764
+
765
+ # Repeat until the output shows QUEUE EMPTY (exit code 3).
766
+ # Every resolve reprints the loop protocol, so the contract stays in
767
+ # context even after many issues. Do not wait to be told to continue.
728
768
  """).strip()
729
769
  )
730
770
 
@@ -738,8 +778,7 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
738
778
  codedd fix vulns next --auto # Critical first
739
779
  codedd fix vulns affected-files lodash # See which files import it
740
780
  # ... developer updates package version ...
741
- codedd fix comment "Updated lodash to 4.17.21"
742
- codedd fix resolve # Move to next critical
781
+ codedd fix resolve --comment "Updated lodash to 4.17.21"
743
782
  """).strip()
744
783
  )
745
784
 
@@ -804,9 +843,8 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
804
843
  codedd fix fetch flags
805
844
  codedd fix flags next --auto
806
845
  # Review flag, determine it's a false positive
807
- codedd fix flags invalidate # Mark invalid, load next
808
- codedd fix flags invalidate # Skip another invalid flag
809
- codedd fix flags next # Load next valid one
846
+ codedd fix flags invalidate --reason "value is a compile-time constant"
847
+ # -> marks invalid and prints the next issue (same shape as resolve)
810
848
  """).strip()
811
849
  )
812
850
 
@@ -843,6 +881,57 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
843
881
  """).strip()
844
882
  )
845
883
 
884
+ _subsection(
885
+ "Workflow 10: Unattended loop (shell / CI)",
886
+ "Exit code 3 is the stop condition, so the loop needs no issue counting.",
887
+ )
888
+ console.print(
889
+ textwrap.dedent("""
890
+ # Bash
891
+ codedd fix flags next --auto --json > issue.json
892
+ while [ $? -eq 0 ]; do
893
+ # ... apply the fix described in issue.json ...
894
+ codedd fix resolve --comment-file note.txt --json > issue.json
895
+ done
896
+ # Loop ends when a command exits 3 (queue empty); exit 1 means a real error.
897
+
898
+ # PowerShell
899
+ codedd fix flags next --auto --json | Set-Content issue.json
900
+ while ($LASTEXITCODE -eq 0) {
901
+ # ... apply the fix ...
902
+ codedd fix resolve --comment-file note.txt --json | Set-Content issue.json
903
+ }
904
+ """).strip()
905
+ )
906
+
907
+ _subsection(
908
+ "The loop protocol block",
909
+ "Re-emitted by every issue-bearing command; also in --json as 'protocol'.",
910
+ )
911
+ console.print(
912
+ textwrap.dedent("""
913
+ A remediation queue can hold thousands of issues, far more than fits in
914
+ one context window. Rather than relying on the operator's opening
915
+ instruction surviving hundreds of file reads, every command that
916
+ delivers or advances an issue reprints the loop contract:
917
+
918
+ - loop ordered steps, each with the literal command to run
919
+ - pending_issues how many issues remain in the current scope
920
+ - queue_empty true once the scope is exhausted
921
+ - stop_condition the QUEUE EMPTY marker and exit code 3
922
+ - autonomy do not pause to ask whether to continue
923
+ - recovery 'codedd fix context' rehydrates a lost session
924
+
925
+ Agents should read the protocol block from the most recent command
926
+ output rather than from earlier conversation history.
927
+
928
+ Exit codes:
929
+ 0 issue delivered / action succeeded
930
+ 1 error (auth, network, validation, server rejection)
931
+ 3 no unresolved issues left in this scope
932
+ """).strip()
933
+ )
934
+
846
935
  # =========================================================================
847
936
  # PART 6: DATA STRUCTURES AND RESPONSE FORMATS
848
937
  # =========================================================================
@@ -1037,22 +1126,31 @@ def show_ai_docs(ctx: typer.Context = None) -> None:
1037
1126
  console.print(" codedd fix fetch vulns [--sub-audit-uuid UUID | --sub-audit-index INT]")
1038
1127
 
1039
1128
  console.print("\n[bold]Fix Workflow - Progress (Flags)[/bold]")
1040
- console.print(" codedd fix flags next [--auto] [--sub-audit-uuid UUID]")
1041
- console.print(" codedd fix flags invalidate")
1129
+ console.print(" codedd fix flags next [--auto] [--sub-audit-uuid UUID] [--json]")
1130
+ console.print(' codedd fix flags invalidate [--reason "TEXT" | --reason-file PATH] [--json]')
1042
1131
 
1043
1132
  console.print("\n[bold]Fix Workflow - Progress (Vulnerabilities)[/bold]")
1044
1133
  console.print(
1045
- " codedd fix vulns next [--auto] [--severity SEVERITY] [--used-only] [--sub-audit-uuid UUID]"
1134
+ " codedd fix vulns next [--auto] [--severity SEVERITY] [--used-only] "
1135
+ "[--sub-audit-uuid UUID] [--json]"
1046
1136
  )
1047
- console.print(" codedd fix vulns affected-files PACKAGE_NAME")
1137
+ console.print(" codedd fix vulns affected-files PACKAGE_NAME [--json]")
1048
1138
 
1049
1139
  console.print("\n[bold]Fix Workflow - Common Operations[/bold]")
1050
- console.print(' codedd fix comment "COMMENT_TEXT" [--issue-type {flags|vulns}]')
1051
- console.print(" codedd fix resolve [--issue-type {flags|vulns}]")
1052
- console.print(" codedd fix status")
1140
+ console.print(
1141
+ ' codedd fix resolve [--comment "TEXT" | --comment-file PATH] '
1142
+ "[--no-next] [--issue-type {flags|vulns}] [--json]"
1143
+ )
1144
+ console.print(' codedd fix comment "TEXT" | --comment-file PATH | - [--issue-type {flags|vulns}] [--json]')
1145
+ console.print(" codedd fix status [--json]")
1053
1146
  console.print(" codedd fix context [--json]")
1054
1147
  console.print(" codedd fix summarize")
1055
1148
 
1149
+ console.print("\n[bold]Exit Codes[/bold]")
1150
+ console.print(" 0 issue delivered / action succeeded")
1151
+ console.print(" 1 error")
1152
+ console.print(" 3 no unresolved issues left in this scope (QUEUE EMPTY)")
1153
+
1056
1154
  console.print("\n[bold]Issue Compass Selections[/bold]")
1057
1155
  console.print(" codedd fix selections list")
1058
1156
  console.print(" codedd fix selections show <n>")
@@ -1195,7 +1195,11 @@ def _check_llm_keys(cfg: ConfigManager) -> bool:
1195
1195
  print_error(
1196
1196
  "No LLM API keys configured.\n"
1197
1197
  " CodeDD uses LLMs (Anthropic, OpenAI, Gemini, or Grok) to run the source code audit.\n"
1198
- " Add an API key with [bold cyan]codedd config set-key[/bold cyan].",
1198
+ " Add an API key with [bold cyan]codedd config set-key[/bold cyan], "
1199
+ "or set an environment variable "
1200
+ "([bold]ANTHROPIC_API_KEY[/bold], [bold]OPENAI_API_KEY[/bold], "
1201
+ "[bold]GEMINI_API_KEY[/bold], [bold]XAI_API_KEY[/bold], "
1202
+ "or the [bold]CODEDD_*[/bold] equivalents).",
1199
1203
  escape_content=False,
1200
1204
  )
1201
1205
  return False
@@ -2,6 +2,9 @@
2
2
  ``codedd auth`` sub-commands: login, logout, status.
3
3
  """
4
4
 
5
+ import os
6
+
7
+ import keyring
5
8
  import typer
6
9
  from rich.console import Console
7
10
  from rich.panel import Panel
@@ -11,10 +14,17 @@ from codedd_cli.api.endpoints import Endpoints
11
14
  from codedd_cli.auth.token_manager import TokenManager
12
15
  from codedd_cli.config.settings import ConfigManager
13
16
  from codedd_cli.models.account import AccountInfo
14
- from codedd_cli.utils.display import print_error, print_info, print_success
17
+ from codedd_cli.utils.display import print_error, print_info, print_success, print_warning
15
18
  from codedd_cli.utils.payload_inspector import review_request
16
19
  from codedd_cli.utils.validators import is_valid_cli_token
17
20
 
21
+ # Shown when the OS credential store cannot persist the CLI token.
22
+ _KEYRING_UNAVAILABLE_MSG = (
23
+ "No OS credential store is available. "
24
+ "Install a keyring backend (for example gnome-keyring or KWallet), "
25
+ "or set [bold]CODEDD_API_TOKEN[/bold]."
26
+ )
27
+
18
28
  console = Console()
19
29
  auth_app = typer.Typer(no_args_is_help=True)
20
30
 
@@ -96,43 +106,63 @@ def login(
96
106
 
97
107
  with CodeDDClient(config=cfg, token=token) as client:
98
108
  resp = client.post(Endpoints.VERIFY_TOKEN)
109
+ except typer.Exit:
110
+ raise
111
+ except Exception as exc:
112
+ print_error(f"Connection error: {exc}")
113
+ raise typer.Exit(code=1) from exc
99
114
 
100
- if resp.status_code == 200:
101
- data = resp.json()
102
- if data.get("status") == "success":
103
- account = AccountInfo(
104
- account_uuid=data["account_uuid"],
105
- account_name=data.get("account_name", ""),
106
- email=data.get("email", ""),
107
- token_name=data.get("token_name", ""),
108
- )
115
+ if resp.status_code == 200:
116
+ data = resp.json()
117
+ if data.get("status") == "success":
118
+ account = AccountInfo(
119
+ account_uuid=data["account_uuid"],
120
+ account_name=data.get("account_name", ""),
121
+ email=data.get("email", ""),
122
+ token_name=data.get("token_name", ""),
123
+ )
109
124
 
110
- # Verification passed — now safe to persist the token
125
+ # Persist session metadata even if the keyring cannot store the token.
126
+ # Headless environments rely on CODEDD_API_TOKEN for the secret itself.
127
+ cfg.account_uuid = account.account_uuid
128
+ cfg.account_name = account.account_name
129
+ cfg.account_email = account.email
130
+ cfg.token_hint = TokenManager.token_hint(token)
131
+ cfg.save()
132
+
133
+ try:
111
134
  TokenManager.store(token)
112
- cfg.account_uuid = account.account_uuid
113
- cfg.account_name = account.account_name
114
- cfg.account_email = account.email
115
- cfg.token_hint = TokenManager.token_hint(token)
116
- cfg.save()
117
-
118
- print_success(f"Authenticated as [bold]{account.account_name}[/bold] ({account.email})", escape_content=False)
119
- if account.token_name:
120
- print_info(f"Token: {account.token_name}")
121
- return
122
-
123
- error_msg = "Authentication failed"
124
- try:
125
- error_msg = resp.json().get("message", error_msg)
126
- except Exception:
127
- pass
128
- print_error(error_msg)
129
- raise typer.Exit(code=1)
135
+ except keyring.errors.KeyringError:
136
+ print_error(_KEYRING_UNAVAILABLE_MSG, escape_content=False)
137
+ env_token = os.environ.get("CODEDD_API_TOKEN", "")
138
+ if env_token and is_valid_cli_token(env_token):
139
+ print_warning(
140
+ "CODEDD_API_TOKEN is set — login can proceed without the keyring."
141
+ )
142
+ print_success(
143
+ f"Authenticated as [bold]{account.account_name}[/bold] ({account.email})",
144
+ escape_content=False,
145
+ )
146
+ if account.token_name:
147
+ print_info(f"Token: {account.token_name}")
148
+ return
149
+ raise typer.Exit(code=1)
130
150
 
131
- except Exception as exc:
132
- if isinstance(exc, typer.Exit):
133
- raise
134
- print_error(f"Connection error: {exc}")
135
- raise typer.Exit(code=1)
151
+ print_success(
152
+ f"Authenticated as [bold]{account.account_name}[/bold] ({account.email})",
153
+ escape_content=False,
154
+ )
155
+ if account.token_name:
156
+ print_info(f"Token: {account.token_name}")
157
+ return
158
+
159
+ error_msg = "Authentication failed"
160
+ try:
161
+ error_msg = resp.json().get("message", error_msg)
162
+ except Exception:
163
+ pass
164
+ print_error(error_msg)
165
+ raise typer.Exit(code=1)
136
166
 
137
167
 
138
168
  @auth_app.command("logout")
@@ -168,16 +198,26 @@ def status(
168
198
  cfg = ConfigManager()
169
199
  token = TokenManager.retrieve()
170
200
 
171
- if not cfg.is_authenticated or not token:
172
- console.print(
173
- Panel(
174
- "[bold red]Not authenticated[/bold red]\n\nRun [bold cyan]codedd auth login[/bold cyan] to connect.",
175
- title="Auth Status",
176
- expand=False,
201
+ if not token:
202
+ if cfg.is_authenticated:
203
+ help_text = (
204
+ "[bold red]Not authenticated[/bold red]\n\n"
205
+ "A session is stored but no token could be retrieved.\n"
206
+ "Set [bold cyan]CODEDD_API_TOKEN[/bold cyan] or install a keyring backend."
177
207
  )
178
- )
208
+ else:
209
+ help_text = (
210
+ "[bold red]Not authenticated[/bold red]\n\n"
211
+ "Run [bold cyan]codedd auth login[/bold cyan] to connect, "
212
+ "or set [bold cyan]CODEDD_API_TOKEN[/bold cyan]."
213
+ )
214
+ console.print(Panel(help_text, title="Auth Status", expand=False))
179
215
  return
180
216
 
217
+ if not cfg.token_hint:
218
+ cfg.token_hint = TokenManager.token_hint(token)
219
+ cfg.save()
220
+
181
221
  # Optionally verify token is still valid server-side
182
222
  if show:
183
223
  confirmed = review_request(
@@ -247,7 +247,14 @@ def set_key(
247
247
  try:
248
248
  LLMKeyManager.store_key(provider, api_key)
249
249
  except Exception as exc:
250
+ env_names = LLMKeyManager.env_var_names(provider)
251
+ extras = f" (also accepted: {', '.join(env_names[1:])})" if len(env_names) > 1 else ""
252
+ primary = env_names[0] if env_names else "the provider environment variable"
250
253
  console.print(f"[red]{SYMBOL_FAIL}[/red] Failed to store key in OS keychain: {exc}")
254
+ console.print(
255
+ f"[dim]On headless systems, set [bold]{primary}[/bold]"
256
+ f"{extras} instead of using the keychain.[/dim]"
257
+ )
251
258
  raise typer.Exit(code=1)
252
259
 
253
260
  masked = LLMKeyManager.mask_key(api_key)