pythia-plsql 0.15.3__tar.gz → 0.15.5__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 (66) hide show
  1. {pythia_plsql-0.15.3/scripts/pythia_plsql.egg-info → pythia_plsql-0.15.5}/PKG-INFO +11 -3
  2. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/README.md +10 -2
  3. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/pyproject.toml +1 -1
  4. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/scripts/pythia.py +189 -21
  5. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5/scripts/pythia_plsql.egg-info}/PKG-INFO +11 -3
  6. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-setup/SKILL.md +4 -3
  7. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-setup/reference/environment.md +10 -2
  8. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_install.py +161 -0
  9. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_phase3.py +14 -5
  10. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_phase6.py +216 -0
  11. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/LICENSE +0 -0
  12. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/comment-current.sql +0 -0
  13. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/compile-errors.sql +0 -0
  14. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/current-schema.sql +0 -0
  15. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/db-nls.sql +0 -0
  16. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/db-version.sql +0 -0
  17. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/dependencies.sql +0 -0
  18. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/explain-display.sql +0 -0
  19. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/impact.sql +0 -0
  20. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/invalid-objects.sql +0 -0
  21. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/name-occupants.sql +0 -0
  22. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/object-names.sql +0 -0
  23. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/object-source.sql +0 -0
  24. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/plscope-enabled.sql +0 -0
  25. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/plscope-statements.sql +0 -0
  26. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/plscope-usages.sql +0 -0
  27. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/schema-settings.sql +0 -0
  28. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/session-privileges.sql +0 -0
  29. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/similar-candidates.sql +0 -0
  30. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/source.sql +0 -0
  31. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/table-comments.sql +0 -0
  32. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/table-indexes.sql +0 -0
  33. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/table-stats.sql +0 -0
  34. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/queries/unindexed-fks.sql +0 -0
  35. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/scripts/pythia_plsql.egg-info/SOURCES.txt +0 -0
  36. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/scripts/pythia_plsql.egg-info/dependency_links.txt +0 -0
  37. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/scripts/pythia_plsql.egg-info/entry_points.txt +0 -0
  38. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/scripts/pythia_plsql.egg-info/requires.txt +0 -0
  39. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/scripts/pythia_plsql.egg-info/top_level.txt +0 -0
  40. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/setup.cfg +0 -0
  41. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-apply/SKILL.md +0 -0
  42. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-autopilot/SKILL.md +0 -0
  43. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-comment/SKILL.md +0 -0
  44. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-conventions/SKILL.md +0 -0
  45. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-deploy/SKILL.md +0 -0
  46. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-explore/SKILL.md +0 -0
  47. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-explore/reference/data-dictionary.md +0 -0
  48. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-impact/SKILL.md +0 -0
  49. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-package/SKILL.md +0 -0
  50. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-package/reference/plsql-standards.md +0 -0
  51. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-review/SKILL.md +0 -0
  52. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-review/reference/antipatterns.md +0 -0
  53. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-skill-author/SKILL.md +0 -0
  54. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-spec/SKILL.md +0 -0
  55. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-table/SKILL.md +0 -0
  56. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-table/reference/ddl-standards.md +0 -0
  57. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-tune/SKILL.md +0 -0
  58. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-tune/reference/tuning-checklist.md +0 -0
  59. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-verify/SKILL.md +0 -0
  60. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-write/SKILL.md +0 -0
  61. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/pythia-write/reference/patterns.md +0 -0
  62. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/skills/using-pythia/SKILL.md +0 -0
  63. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_mcp.py +0 -0
  64. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_phase1.py +0 -0
  65. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_phase2.py +0 -0
  66. {pythia_plsql-0.15.3 → pythia_plsql-0.15.5}/tests/test_phase5.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pythia-plsql
3
- Version: 0.15.3
3
+ Version: 0.15.5
4
4
  Summary: PL/SQL development for AI agents on Oracle Database - expert data-dictionary queries, impact analysis, and a snapshot-verified write path with honest rollback.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/thaildhe172591/pythia
@@ -20,7 +20,7 @@ Dynamic: license-file
20
20
 
21
21
  > Oracle's MCP gives your agent a connection. **pythia gives it the judgment to use it.**
22
22
 
23
- **English** · [Tiếng Việt](README.vi.md) · **[The Complete Guide →](GUIDE.md)**
23
+ **English** · [Tiếng Việt](README.vi.md) · **[The Complete Guide →](GUIDE.md)** · **[Website →](https://thaildhe172591.github.io/pythia/)**
24
24
 
25
25
  [![ci](https://github.com/thaildhe172591/pythia/actions/workflows/ci.yml/badge.svg)](https://github.com/thaildhe172591/pythia/actions/workflows/ci.yml)
26
26
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
@@ -191,6 +191,11 @@ each agent needs you to finish by hand.
191
191
  - a `deny` rule so the agent cannot forge a grant, and the MCP server
192
192
  enabled.
193
193
 
194
+ It scaffolds `.pythia/connections.json` (mode 600) and adds it to the
195
+ project's `.gitignore` — commit that line — and warns if git already
196
+ tracks the file: its passwords are then in the history, so untrack it and
197
+ change them.
198
+
194
199
  It also writes the harness into **`CLAUDE.md`** — the file Claude Code
195
200
  itself loads every session — in a marker-delimited block, leaving your own
196
201
  text untouched. The rules hold even with `--no-hooks`, before a restart,
@@ -205,7 +210,10 @@ each agent needs you to finish by hand.
205
210
  `.claude/settings.local.json` (this machine's file, kept out of git) with
206
211
  the absolute interpreter, and the MCP approver to Claude Code's local scope
207
212
  (`claude mcp add --scope local`); your teammates never get a path from your
208
- machine. `pythia doctor` starts every launcher it finds and fails the ones
213
+ machine. Every command pythia prints uses the spelling that starts it here,
214
+ the session preamble's `RUN` line names it for the agent (CLAUDE.md, being
215
+ shared, can only say `pythia`), and the guard lets reads through in that
216
+ spelling — this interpreter's own path, never another. `pythia doctor` starts every launcher it finds and fails the ones
209
217
  that cannot import pythia — except where this machine's own launcher
210
218
  already serves the same hooks: then the team's shared copy erroring here
211
219
  is a warning (keep it for teammates or remove it). Codex's session hook is
@@ -6,7 +6,7 @@
6
6
 
7
7
  > Oracle's MCP gives your agent a connection. **pythia gives it the judgment to use it.**
8
8
 
9
- **English** · [Tiếng Việt](README.vi.md) · **[The Complete Guide →](GUIDE.md)**
9
+ **English** · [Tiếng Việt](README.vi.md) · **[The Complete Guide →](GUIDE.md)** · **[Website →](https://thaildhe172591.github.io/pythia/)**
10
10
 
11
11
  [![ci](https://github.com/thaildhe172591/pythia/actions/workflows/ci.yml/badge.svg)](https://github.com/thaildhe172591/pythia/actions/workflows/ci.yml)
12
12
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
@@ -177,6 +177,11 @@ each agent needs you to finish by hand.
177
177
  - a `deny` rule so the agent cannot forge a grant, and the MCP server
178
178
  enabled.
179
179
 
180
+ It scaffolds `.pythia/connections.json` (mode 600) and adds it to the
181
+ project's `.gitignore` — commit that line — and warns if git already
182
+ tracks the file: its passwords are then in the history, so untrack it and
183
+ change them.
184
+
180
185
  It also writes the harness into **`CLAUDE.md`** — the file Claude Code
181
186
  itself loads every session — in a marker-delimited block, leaving your own
182
187
  text untouched. The rules hold even with `--no-hooks`, before a restart,
@@ -191,7 +196,10 @@ each agent needs you to finish by hand.
191
196
  `.claude/settings.local.json` (this machine's file, kept out of git) with
192
197
  the absolute interpreter, and the MCP approver to Claude Code's local scope
193
198
  (`claude mcp add --scope local`); your teammates never get a path from your
194
- machine. `pythia doctor` starts every launcher it finds and fails the ones
199
+ machine. Every command pythia prints uses the spelling that starts it here,
200
+ the session preamble's `RUN` line names it for the agent (CLAUDE.md, being
201
+ shared, can only say `pythia`), and the guard lets reads through in that
202
+ spelling — this interpreter's own path, never another. `pythia doctor` starts every launcher it finds and fails the ones
195
203
  that cannot import pythia — except where this machine's own launcher
196
204
  already serves the same hooks: then the team's shared copy erroring here
197
205
  is a warning (keep it for teammates or remove it). Codex's session hook is
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pythia-plsql"
7
- version = "0.15.3"
7
+ version = "0.15.5"
8
8
  description = "PL/SQL development for AI agents on Oracle Database - expert data-dictionary queries, impact analysis, and a snapshot-verified write path with honest rollback."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -61,7 +61,7 @@ import pathlib
61
61
  import re
62
62
  import sys
63
63
 
64
- __version__ = "0.15.3" # kept equal to pyproject.toml (tests/test_install.py)
64
+ __version__ = "0.15.5" # kept equal to pyproject.toml (tests/test_install.py)
65
65
 
66
66
  READONLY = re.compile(r"^\s*(select|with)\b", re.I)
67
67
  CONFIG_DIR = ".pythia"
@@ -239,7 +239,7 @@ def offer_path_fix(scripts_dir, interactive, forced=False):
239
239
  print(" " + warn)
240
240
  print(" Open a NEW terminal for it to take effect — an already-running")
241
241
  print(" one keeps the environment it started with, and so do its tabs.")
242
- print(f" Until then: {pathlib.Path(sys.executable).stem} -m pythia <command>")
242
+ print(f" Until then: {interpreter_word()} -m pythia <command>")
243
243
  return True
244
244
 
245
245
 
@@ -357,7 +357,7 @@ def entry_point_hint(found, scripts_dir, in_stored_path=False):
357
357
  "Windows Terminal,",
358
358
  " VS Code or Cursor, restart the application itself.",
359
359
  " In this one, keep using: "
360
- + pathlib.Path(sys.executable).stem + " -m pythia <command>",
360
+ + interpreter_word() + " -m pythia <command>",
361
361
  ]))
362
362
  out = ["`pythia` is installed but not on your PATH."]
363
363
  if scripts_dir:
@@ -367,8 +367,7 @@ def entry_point_hint(found, scripts_dir, in_stored_path=False):
367
367
  # that variable is system and user merged, so writing it
368
368
  # back into user scope copies every system entry into the
369
369
  # user's. Let the tool do it correctly instead.
370
- out.append(" Put it there with: "
371
- + pathlib.Path(sys.executable).stem
370
+ out.append(" Put it there with: " + interpreter_word()
372
371
  + " -m pythia install --add-to-path")
373
372
  else:
374
373
  out.append(" Add it to your shell profile:")
@@ -376,25 +375,54 @@ def entry_point_hint(found, scripts_dir, in_stored_path=False):
376
375
  else:
377
376
  out.append(" Add pip's scripts directory to PATH.")
378
377
  out.append("Either way, this works right now, PATH or no PATH:")
379
- out.append(" " + pathlib.Path(sys.executable).stem + " -m pythia <command>")
378
+ out.append(" " + interpreter_word() + " -m pythia <command>")
380
379
  return "\n".join(out)
381
380
 
382
381
 
382
+ def _same_path(a, b):
383
+ """The same file by spelling, symlinks NOT followed: a venv's python is a
384
+ symlink to the base interpreter, and only the venv's own path loads the
385
+ venv's packages."""
386
+ norm = lambda p: os.path.normcase(os.path.abspath(p)) # noqa: E731
387
+ return norm(a) == norm(b)
388
+
389
+
390
+ def interpreter_word():
391
+ """This interpreter as a shell here can type it: its bare name when PATH
392
+ finds this very file, else its absolute path, quoted. "python3" on most
393
+ Linux/macOS, "python" on Windows — and in a venv nobody activated (Claude
394
+ Code started from an app or an IDE), the venv's own path: the bare name
395
+ would start the system interpreter, which has no pythia."""
396
+ exe = sys.executable
397
+ if not exe:
398
+ return "python"
399
+ # the name as typed: Path.stem would turn "python3.9" into "python3"
400
+ name = re.sub(r"\.exe$", "", pathlib.Path(exe).name, flags=re.I)
401
+ found = path_lookup(name)
402
+ if found and _same_path(found, exe):
403
+ return name
404
+ return launcher_text([pathlib.Path(exe).as_posix()])
405
+
406
+
383
407
  def invocation():
384
- """How to invoke this tool, exactly as the user actually ran it. Every
385
- printed command must be paste-able: a bare `pythia ...` is
386
- CommandNotFound for anyone running from source."""
408
+ """How to invoke this tool from a shell on this machine. Every printed
409
+ command must be paste-able: a bare `pythia ...` is CommandNotFound for
410
+ anyone running from source, or from a venv that is not on PATH."""
387
411
  main_spec = getattr(sys.modules.get("__main__"), "__spec__", None)
388
412
  if getattr(main_spec, "name", "") == "pythia":
389
413
  # `python -m pythia` — argv[0] is the module's site-packages path,
390
414
  # which nobody typed; the -m form is the paste-able one
391
- return f"{pathlib.Path(sys.executable).stem} -m pythia"
415
+ return f"{interpreter_word()} -m pythia"
392
416
  prog = sys.argv[0] or "pythia"
393
417
  if prog.lower().endswith(".py"):
394
- # the interpreter actually running us: "python3" on most Linux/macOS,
395
- # "python" on Windows — a hardcoded "python" would not paste on Ubuntu
396
- return f"{pathlib.Path(sys.executable).stem} {prog}"
397
- return pathlib.Path(prog).name
418
+ return f"{interpreter_word()} {launcher_text([prog]) if ' ' in prog else prog}"
419
+ name = pathlib.Path(prog).name
420
+ if not re.search(r"[/\\]", prog):
421
+ return name # found by name: PATH has it
422
+ found = path_lookup(name)
423
+ if found and (_same_path(found, prog) or _same_path(found, prog + ".exe")):
424
+ return name
425
+ return f"{interpreter_word()} -m pythia"
398
426
 
399
427
 
400
428
  HEADLESS_YES_MSG = (
@@ -4095,6 +4123,117 @@ def exclude_local_settings(project_root):
4095
4123
  return exclude
4096
4124
 
4097
4125
 
4126
+ SECRET_REL = f"{CONFIG_DIR}/{CONFIG_NAME}"
4127
+
4128
+
4129
+ def git_ignore_source(root, rel):
4130
+ """How git treats `rel` under root: ("shared", source) when a .gitignore
4131
+ in the repository ignores it — every clone; ("local", source) when only
4132
+ this machine does (.git/info/exclude, a personal excludes file);
4133
+ ("none", "") when `git add -A` would take it. None outside a repository
4134
+ or without git. The index is not consulted: tracked is git_tracks()."""
4135
+ import subprocess
4136
+ git = path_lookup("git")
4137
+ if not git:
4138
+ return None
4139
+ try:
4140
+ r = subprocess.run([git, "-C", str(root), "check-ignore", "-v",
4141
+ "--no-index", "--", rel], stdin=subprocess.DEVNULL,
4142
+ capture_output=True, text=True, encoding="utf-8",
4143
+ errors="replace", timeout=15)
4144
+ except (OSError, subprocess.SubprocessError):
4145
+ return None
4146
+ if r.returncode not in (0, 1):
4147
+ return None
4148
+ # <source>:<line>:<pattern>TAB<path>; a match on "!pattern" un-ignores it
4149
+ m = re.match(r"(.+?):(\d+):(.*?)\t", r.stdout)
4150
+ if r.returncode == 1 or not m or m.group(3).startswith("!"):
4151
+ return "none", ""
4152
+ src = m.group(1)
4153
+ shared = (not _is_abs_path(src)
4154
+ and os.path.basename(src.replace("\\", "/")) == ".gitignore")
4155
+ return ("shared" if shared else "local"), src
4156
+
4157
+
4158
+ def _gitignore_covers(path, rel):
4159
+ """Read as text where git cannot answer: does the last rule in `path`
4160
+ naming rel (or its folder) ignore it?"""
4161
+ if not path.is_file():
4162
+ return False
4163
+ folder = rel.split("/")[0]
4164
+ names = {rel, folder, folder + "/", folder + "/*", folder + "/**"}
4165
+ covered = False
4166
+ for ln in path.read_text(encoding="utf-8", errors="replace").splitlines():
4167
+ s = ln.strip()
4168
+ neg = s.startswith("!")
4169
+ body = (s[1:] if neg else s).lstrip("/")
4170
+ if body in names:
4171
+ covered = not neg
4172
+ return covered
4173
+
4174
+
4175
+ def ignore_connections(project_root):
4176
+ """Keep .pythia/connections.json — the passwords — out of every clone:
4177
+ append it to the project's .gitignore unless a rule there already ignores
4178
+ it. A rule only this machine has is not enough, and outside git the line
4179
+ is written anyway, so a later `git init` starts safe. Returns the
4180
+ .gitignore written, or None."""
4181
+ root = pathlib.Path(project_root)
4182
+ gi = root / ".gitignore"
4183
+ state = git_ignore_source(root, SECRET_REL)
4184
+ if state is not None and state[0] == "shared":
4185
+ return None
4186
+ if _gitignore_covers(gi, SECRET_REL):
4187
+ return None # written already; a rule deeper down overrides it
4188
+ data = gi.read_bytes() if gi.is_file() else b""
4189
+ with open(gi, "ab") as f: # their bytes stay theirs
4190
+ f.write((b"\n" if data and not data.endswith(b"\n") else b"")
4191
+ + b"# pythia: database passwords, never committed\n"
4192
+ + SECRET_REL.encode("utf-8") + b"\n")
4193
+ return gi
4194
+
4195
+
4196
+ def report_connections_ignore(project_root):
4197
+ root = pathlib.Path(project_root)
4198
+ try:
4199
+ gi = ignore_connections(root)
4200
+ except OSError as e: # a safeguard, never a reason to abort
4201
+ gi = None
4202
+ print(f"WARNING: could not write {root / '.gitignore'} ({e}) — "
4203
+ f"add {SECRET_REL} to it by hand; the file holds passwords.")
4204
+ if gi is not None:
4205
+ print(f"Added {SECRET_REL} to {gi} — it holds passwords; commit the "
4206
+ ".gitignore so every clone keeps it out")
4207
+ if git_tracks(root, SECRET_REL):
4208
+ print(f"WARNING: git already tracks {SECRET_REL}, so its passwords are "
4209
+ f"in the repository. Run `git rm --cached {SECRET_REL}`, commit, "
4210
+ "and change those passwords — the history keeps the old ones.")
4211
+
4212
+
4213
+ def credentials_check(root):
4214
+ """doctor's row for the password file: fail when git tracks it, warn
4215
+ when git would commit it, ok when a shared rule keeps it out."""
4216
+ state = git_ignore_source(root, SECRET_REL)
4217
+ if state is None:
4218
+ return ("info", "credentials", f"{SECRET_REL} not checked — no git "
4219
+ "repository here (or git is not on PATH)")
4220
+ if git_tracks(root, SECRET_REL):
4221
+ return ("fail", "credentials", f"git tracks {SECRET_REL} — its "
4222
+ f"passwords are in the repository; `git rm --cached "
4223
+ f"{SECRET_REL}`, commit, then change those passwords (the "
4224
+ "history keeps the old ones)")
4225
+ kind, src = state
4226
+ fix = f"{invocation()} install adds it to .gitignore"
4227
+ if kind == "shared":
4228
+ return ("ok", "credentials", f"{SECRET_REL} is git-ignored ({src})")
4229
+ if kind == "local":
4230
+ return ("warn", "credentials", f"{SECRET_REL} is ignored only on this "
4231
+ f"machine ({src}) — a teammate's clone would commit theirs; "
4232
+ + fix)
4233
+ return ("warn", "credentials", f"{SECRET_REL} is not git-ignored — one "
4234
+ f"`git add -A` commits the passwords; " + fix)
4235
+
4236
+
4098
4237
  def git_common_dir(root):
4099
4238
  """The directory holding info/exclude: .git itself, or — in a worktree or
4100
4239
  a submodule, where .git is a file — the gitdir it names (a worktree's
@@ -4653,6 +4792,7 @@ def cmd_install(conn, schema, ns):
4653
4792
  return
4654
4793
  path, created = scaffold_config(ns.project_root)
4655
4794
  print(f"{'Created' if created else 'Kept existing'} {path}")
4795
+ report_connections_ignore(ns.project_root)
4656
4796
  if global_pack_present():
4657
4797
  print("Skill pack found in the global install — it already serves "
4658
4798
  "this project,\nso no project copy is made (a second copy "
@@ -6666,6 +6806,23 @@ def parse_pythia_command(command, cwd=None):
6666
6806
  exe = re.sub(r"\.exe$", "", first.lower())
6667
6807
  if exe == "pythia": # by name only: PATH decides, not the agent
6668
6808
  return toks[1:]
6809
+ if _is_abs_path(first) and sys.executable:
6810
+ # this hook's own interpreter by absolute path — the spelling that
6811
+ # runs where pythia's venv is not on PATH (field test 0.15.4) — or
6812
+ # the pythia script beside it; any other path is a stranger's file
6813
+ own = pathlib.Path(sys.executable)
6814
+ if _same_path(first, own) and toks[1:3] == ["-m", "pythia"]:
6815
+ base = pathlib.Path(cwd or os.getcwd())
6816
+ if (base / "pythia.py").exists() or (base / "pythia").is_dir():
6817
+ return None # python -m would import that one
6818
+ return toks[3:]
6819
+ if _same_path(first, own) and len(toks) > 1 and _is_real_pythia(
6820
+ pathlib.Path(cwd or os.getcwd()) / toks[1]):
6821
+ return toks[2:] # a clone's launcher: this very file
6822
+ if any(_same_path(first, own.with_name(n))
6823
+ for n in ("pythia", "pythia.exe")):
6824
+ return toks[1:]
6825
+ return None
6669
6826
  if re.fullmatch(r"python(\d+(\.\d+)?)?|py", exe):
6670
6827
  if toks[1:3] == ["-m", "pythia"]:
6671
6828
  base = pathlib.Path(cwd or os.getcwd())
@@ -6860,9 +7017,10 @@ def post_tool_note(payload):
6860
7017
  return _hook_out("PostToolUse", context="pythia: " + " ".join(notes))
6861
7018
 
6862
7019
 
6863
- def session_state_lines(root):
7020
+ def session_state_lines(root, home=None):
6864
7021
  """The project's live state, for the session preamble — no database."""
6865
7022
  lines = []
7023
+ run = invocation()
6866
7024
  cfg_path = pathlib.Path(root) / CONFIG_DIR / CONFIG_NAME
6867
7025
  if cfg_path.is_file():
6868
7026
  try:
@@ -6871,16 +7029,19 @@ def session_state_lines(root):
6871
7029
  rows = []
6872
7030
  names = ", ".join(r["name"] + ("*" if r["default"] else "") for r in rows)
6873
7031
  lines.append(f"connections: {names or 'none filled in'} (* = default; "
6874
- "`pythia connections` for details)")
7032
+ f"`{run} connections` for details)")
6875
7033
  else:
6876
- lines.append("connections: none — `pythia install` scaffolds "
7034
+ lines.append(f"connections: none — `{run} install` scaffolds "
6877
7035
  ".pythia/connections.json")
6878
7036
  lines.append(lease_line(read_lease(root)))
6879
7037
  if (pathlib.Path(root) / CONFIG_DIR / "conventions.md").is_file():
6880
7038
  lines.append("conventions: .pythia/conventions.md exists — read it "
6881
7039
  "before writing any object")
6882
7040
  mcp = _read_json(pathlib.Path(root) / ".mcp.json") or {}
6883
- if "pythia" in (mcp.get("mcpServers") or {}):
7041
+ # a venv install registers the approver in Claude Code's local scope
7042
+ # (~/.claude.json), never in the shared .mcp.json
7043
+ if ("pythia" in (mcp.get("mcpServers") or {})
7044
+ or local_mcp_entry(root, home) is not None):
6884
7045
  lines.append("approval door: the pythia_approve tool (MCP) — prompts in "
6885
7046
  "every permission mode; AskUserQuestion is the fallback")
6886
7047
  return lines
@@ -6903,13 +7064,19 @@ def cmd_hook(conn, schema, ns):
6903
7064
  md = pathlib.Path(root) / "CLAUDE.md"
6904
7065
  loaded = md.is_file() and AGENTS_BEGIN in md.read_text(
6905
7066
  encoding="utf-8", errors="replace")
7067
+ run = invocation()
6906
7068
  if loaded:
6907
7069
  # Claude Code already loaded the guide from CLAUDE.md: the
6908
7070
  # hook adds what a static file cannot — the live state
6909
7071
  print("PYTHIA HARNESS ACTIVE - the rules are in CLAUDE.md "
6910
- "(pythia block); `pythia guide` prints the full contract.")
7072
+ f"(pythia block); `{run} guide` prints the full contract.")
6911
7073
  else:
6912
7074
  print(BRIEF_GUIDE.rstrip())
7075
+ if run not in ("pythia", "pythia.exe"):
7076
+ # the shared files say `pythia`; this machine runs it otherwise
7077
+ # (a venv nobody activated, a clone) — field test 0.15.4
7078
+ print(f"RUN `pythia` here is `{run}` — spell every pythia "
7079
+ "command the rules name that way.")
6913
7080
  print("STATE " + "\n ".join(session_state_lines(root)))
6914
7081
  return
6915
7082
  out = (pre_tool_decision(payload) if event == "pre-tool"
@@ -7126,6 +7293,7 @@ def harness_checks(project_root, home=None):
7126
7293
  + ("" if filled else f" — fill in {cfg}")))
7127
7294
  except ValueError:
7128
7295
  out.append(("fail", "connections", f"{cfg} is not valid JSON"))
7296
+ out.append(credentials_check(root))
7129
7297
  else:
7130
7298
  out.append(("warn", "connections", f"no {CONFIG_DIR}/{CONFIG_NAME} — "
7131
7299
  f"{invocation()} install"))
@@ -7273,8 +7441,8 @@ def cmd_doctor(conn, schema, ns):
7273
7441
  print(f" {paint(f'{s:<4}', color[s], en)} {a:<15} {m}")
7274
7442
  bad = sum(1 for s, _, _ in rows if s == "fail")
7275
7443
  if bad:
7276
- print(paint(f"\n {bad} problem(s) will stop approvals or the guard "
7277
- "from working.", "red", en))
7444
+ print(paint(f"\n {bad} problem(s) to fix first — each fail line "
7445
+ "names its fix.", "red", en))
7278
7446
  if conn is None:
7279
7447
  print(f"\n Database environment: {invocation()} doctor --db")
7280
7448
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pythia-plsql
3
- Version: 0.15.3
3
+ Version: 0.15.5
4
4
  Summary: PL/SQL development for AI agents on Oracle Database - expert data-dictionary queries, impact analysis, and a snapshot-verified write path with honest rollback.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/thaildhe172591/pythia
@@ -20,7 +20,7 @@ Dynamic: license-file
20
20
 
21
21
  > Oracle's MCP gives your agent a connection. **pythia gives it the judgment to use it.**
22
22
 
23
- **English** · [Tiếng Việt](README.vi.md) · **[The Complete Guide →](GUIDE.md)**
23
+ **English** · [Tiếng Việt](README.vi.md) · **[The Complete Guide →](GUIDE.md)** · **[Website →](https://thaildhe172591.github.io/pythia/)**
24
24
 
25
25
  [![ci](https://github.com/thaildhe172591/pythia/actions/workflows/ci.yml/badge.svg)](https://github.com/thaildhe172591/pythia/actions/workflows/ci.yml)
26
26
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
@@ -191,6 +191,11 @@ each agent needs you to finish by hand.
191
191
  - a `deny` rule so the agent cannot forge a grant, and the MCP server
192
192
  enabled.
193
193
 
194
+ It scaffolds `.pythia/connections.json` (mode 600) and adds it to the
195
+ project's `.gitignore` — commit that line — and warns if git already
196
+ tracks the file: its passwords are then in the history, so untrack it and
197
+ change them.
198
+
194
199
  It also writes the harness into **`CLAUDE.md`** — the file Claude Code
195
200
  itself loads every session — in a marker-delimited block, leaving your own
196
201
  text untouched. The rules hold even with `--no-hooks`, before a restart,
@@ -205,7 +210,10 @@ each agent needs you to finish by hand.
205
210
  `.claude/settings.local.json` (this machine's file, kept out of git) with
206
211
  the absolute interpreter, and the MCP approver to Claude Code's local scope
207
212
  (`claude mcp add --scope local`); your teammates never get a path from your
208
- machine. `pythia doctor` starts every launcher it finds and fails the ones
213
+ machine. Every command pythia prints uses the spelling that starts it here,
214
+ the session preamble's `RUN` line names it for the agent (CLAUDE.md, being
215
+ shared, can only say `pythia`), and the guard lets reads through in that
216
+ spelling — this interpreter's own path, never another. `pythia doctor` starts every launcher it finds and fails the ones
209
217
  that cannot import pythia — except where this machine's own launcher
210
218
  already serves the same hooks: then the team's shared copy erroring here
211
219
  is a warning (keep it for teammates or remove it). Codex's session hook is
@@ -25,8 +25,9 @@ applies:
25
25
  top-level `"default": "<name>"`. Ambiguity is an error, never a guess.
26
26
  - `--conn NAME` and `PYTHIA_CONNECTION` override everything; the
27
27
  `PYTHIA_USER/PYTHIA_PASSWORD/PYTHIA_DSN` variables bypass the file.
28
- - The file holds credentials: it is gitignored — keep it that way, and keep
29
- it out of chat and screenshots.
28
+ - The file holds credentials: install writes it into `.gitignore` (commit
29
+ that line) — keep it that way, and keep it out of chat and screenshots.
30
+ `pythia doctor` fails if git tracks it.
30
31
 
31
32
  Verify with `pythia check`: it prints who you are connected as and object
32
33
  counts. A failure names the connection and what to check.
@@ -89,7 +90,7 @@ until you want it.
89
90
 
90
91
  | File | Created by | What it does |
91
92
  |---|---|---|
92
- | `connections.json` | `pythia install` | Where to connect. **Holds passwords — never open it**; `pythia connections` lists names, users, schemas and targets with no secrets. Gitignored. |
93
+ | `connections.json` | `pythia install` | Where to connect. **Holds passwords — never open it**; `pythia connections` lists names, users, schemas and targets with no secrets. Install adds it to `.gitignore`. |
93
94
  | `journal/` | first write or snapshot | Every captured version, with a runnable rollback per entry. |
94
95
  | `conventions.json` | `pythia conventions --init` | Naming patterns per object type. Every apply preview warns when a new name drifts. |
95
96
  | `conventions.md` | `pythia conventions --init` | The house rules in prose. **`pythia-write` reads this before writing anything**, and it outranks the generic patterns this pack ships with. |
@@ -88,8 +88,10 @@ then only happen at the developer's console (`pythia approve <token>`), or
88
88
  through an autopilot lease started there (`pythia autopilot on`).
89
89
 
90
90
  After `pythia install`: restart the session, run `pythia doctor`, and fix
91
- every `fail` line — each one is a setting that will stop approvals from
92
- arriving. A `fail` on **hook launch** means a hook's interpreter cannot import
91
+ every `fail` line — each one names its fix. Most are a setting that will stop
92
+ approvals from arriving; a `fail` on **credentials** means git tracks
93
+ `.pythia/connections.json`: `git rm --cached` it, commit, and change those
94
+ passwords. A `fail` on **hook launch** means a hook's interpreter cannot import
93
95
  pythia, so the guard is off: common when pythia lives in a venv or pipx and
94
96
  Claude Code starts from a desktop app or IDE. Re-run `pythia install` — it pins
95
97
  that machine's interpreter in `.claude/settings.local.json` and Claude Code's
@@ -97,3 +99,9 @@ local MCP scope, never in the shared files. A `warn` naming
97
99
  `.claude/settings.json` is the team's shared copy failing on this machine
98
100
  while your own launcher already serves the same hooks: keep it for teammates
99
101
  or remove it.
102
+
103
+ `pythia: command not found` in the agent's shell does not mean the hooks are
104
+ off: pythia's venv is just not on PATH. The session preamble's `RUN` line names
105
+ the spelling that works on this machine (the venv's interpreter by absolute
106
+ path, `-m pythia`); use it for every pythia command the rules name. Commands
107
+ pythia prints already use it.
@@ -4,6 +4,7 @@ no network, no npx needed.
4
4
 
5
5
  Run: python tests/test_install.py
6
6
  """
7
+ import contextlib
7
8
  import io
8
9
  import json
9
10
  import os
@@ -48,6 +49,142 @@ def test_scaffold_creates_the_config_readable_by_its_owner_only():
48
49
  assert created and path.stat().st_mode & 0o777 == 0o600
49
50
 
50
51
 
52
+ SECRET = ".pythia/connections.json"
53
+
54
+
55
+ @contextlib.contextmanager
56
+ def hermetic_git():
57
+ """git with no system or personal config: a developer's own excludes file
58
+ must not decide what these tests see."""
59
+ keys = ("GIT_CONFIG_NOSYSTEM", "GIT_CONFIG_GLOBAL", "XDG_CONFIG_HOME", "HOME")
60
+ old = {k: os.environ.get(k) for k in keys}
61
+ with tempfile.TemporaryDirectory() as home:
62
+ empty = os.path.join(home, "gitconfig")
63
+ open(empty, "w").close()
64
+ os.environ.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=empty,
65
+ XDG_CONFIG_HOME=home, HOME=home)
66
+ try:
67
+ yield
68
+ finally:
69
+ for k, v in old.items():
70
+ if v is None:
71
+ os.environ.pop(k, None)
72
+ else:
73
+ os.environ[k] = v
74
+
75
+
76
+ def git_init(td):
77
+ """A fresh repository at td; None where git is absent (the test skips)."""
78
+ import subprocess
79
+ git = pythia.path_lookup("git")
80
+ if git:
81
+ subprocess.run([git, "init", "-q", str(td)], check=True,
82
+ stdin=subprocess.DEVNULL)
83
+ return git
84
+
85
+
86
+ def test_install_keeps_the_password_file_out_of_every_clone():
87
+ """GUIDE and SECURITY said connections.json is "gitignored by the
88
+ scaffold", but nothing wrote the rule: in the 0.15.3 field test `git
89
+ status` listed `.pythia/`, one `git add -A` away from committing the
90
+ passwords. The rule goes in the project's .gitignore, so it reaches every
91
+ clone — .git/info/exclude would protect this machine only."""
92
+ with hermetic_git(), tempfile.TemporaryDirectory() as td:
93
+ if git_init(td) is None:
94
+ return
95
+ root = pathlib.Path(td)
96
+ gi = root / ".gitignore"
97
+ gi.write_bytes(b"node_modules") # no final newline: theirs stays
98
+ pythia.scaffold_config(root)
99
+ assert pythia.git_ignore_source(root, SECRET)[0] == "none"
100
+ assert pythia.ignore_connections(root) == gi
101
+ text = gi.read_text(encoding="utf-8")
102
+ assert text.startswith("node_modules\n") and SECRET in text.splitlines()
103
+ assert pythia.git_ignore_source(root, SECRET)[0] == "shared"
104
+ assert pythia.ignore_connections(root) is None # once
105
+ assert gi.read_text(encoding="utf-8") == text
106
+
107
+
108
+ def test_install_trusts_a_shared_rule_but_not_a_negated_or_private_one():
109
+ with hermetic_git(), tempfile.TemporaryDirectory() as td:
110
+ if git_init(td) is None:
111
+ return
112
+ root = pathlib.Path(td)
113
+ gi = root / ".gitignore"
114
+ gi.write_text(".pythia/\n", encoding="utf-8")
115
+ assert pythia.ignore_connections(root) is None # covered already
116
+ assert gi.read_text(encoding="utf-8") == ".pythia/\n"
117
+ # a later negation un-ignores it: the appended rule comes last and wins
118
+ gi.write_text(".pythia/*\n!.pythia/connections.json\n", encoding="utf-8")
119
+ assert pythia.git_ignore_source(root, SECRET)[0] == "none"
120
+ assert pythia.ignore_connections(root) == gi
121
+ assert pythia.git_ignore_source(root, SECRET)[0] == "shared"
122
+ # ignored on this machine only: a teammate's clone would still commit it
123
+ gi.unlink()
124
+ exclude = root / ".git" / "info" / "exclude"
125
+ exclude.parent.mkdir(exist_ok=True)
126
+ exclude.write_text(SECRET + "\n", encoding="utf-8")
127
+ state, source = pythia.git_ignore_source(root, SECRET)
128
+ assert state == "local" and "exclude" in source
129
+ assert pythia.ignore_connections(root) == gi
130
+ assert pythia.git_ignore_source(root, SECRET)[0] == "shared"
131
+
132
+
133
+ def test_install_writes_the_rule_outside_git_too():
134
+ """No repository yet, or no git at all: the rule is written anyway, so a
135
+ later `git init` starts safe — and read back as text, written once."""
136
+ with hermetic_git(), tempfile.TemporaryDirectory() as td:
137
+ root = pathlib.Path(td)
138
+ assert pythia.git_ignore_source(root, SECRET) is None
139
+ assert pythia.ignore_connections(root) == root / ".gitignore"
140
+ assert pythia.ignore_connections(root) is None
141
+ real = pythia.path_lookup
142
+ pythia.path_lookup = lambda *a, **k: None
143
+ try:
144
+ with tempfile.TemporaryDirectory() as td:
145
+ root = pathlib.Path(td)
146
+ (root / ".gitignore").write_text("/.pythia/connections.json\n",
147
+ encoding="utf-8")
148
+ assert pythia.ignore_connections(root) is None
149
+ (root / ".gitignore").write_text(
150
+ ".pythia\n!.pythia/connections.json\n", encoding="utf-8")
151
+ assert pythia.ignore_connections(root) == root / ".gitignore"
152
+ finally:
153
+ pythia.path_lookup = real
154
+
155
+
156
+ def test_install_warns_when_git_already_tracks_the_password_file():
157
+ """A rule cannot untrack a committed file; the passwords are already in
158
+ the history. Say so, with the commands, at install time."""
159
+ import subprocess
160
+ with hermetic_git(), tempfile.TemporaryDirectory() as td:
161
+ git = git_init(td)
162
+ if git is None:
163
+ return
164
+ root = pathlib.Path(td)
165
+ pythia.scaffold_config(root)
166
+ subprocess.run([git, "-C", td, "add", "-f", SECRET], check=True,
167
+ stdin=subprocess.DEVNULL)
168
+ buf = io.StringIO()
169
+ with contextlib.redirect_stdout(buf):
170
+ pythia.report_connections_ignore(root)
171
+ out = buf.getvalue()
172
+ assert f"git rm --cached {SECRET}" in out and "password" in out, out
173
+
174
+
175
+ def test_install_survives_a_gitignore_it_cannot_write():
176
+ """The rule is a safeguard, not a reason to abort the install: say what
177
+ to add by hand and carry on."""
178
+ with tempfile.TemporaryDirectory() as td:
179
+ root = pathlib.Path(td)
180
+ (root / ".gitignore").mkdir()
181
+ buf = io.StringIO()
182
+ with contextlib.redirect_stdout(buf):
183
+ pythia.report_connections_ignore(root)
184
+ out = buf.getvalue()
185
+ assert "WARNING" in out and f"add {SECRET}" in out, out
186
+
187
+
51
188
  def test_a_readable_config_is_warned_about_once_per_process():
52
189
  if os.name != "posix":
53
190
  return
@@ -208,6 +345,27 @@ def test_devnull_stdin_is_not_a_human():
208
345
  assert not (pathlib.Path(td) / ".pythia" / "policy.json").is_file()
209
346
 
210
347
 
348
+ def test_the_website_states_what_the_code_is():
349
+ """site/ is published to GitHub Pages. What it states — the release, the
350
+ counts, every skill by name — must be what this commit is, so a version
351
+ bump or a new skill that forgets the site fails here, not in public."""
352
+ site = ROOT / "site"
353
+ html = (site / "index.html").read_text(encoding="utf-8")
354
+ v = pythia.__version__
355
+ assert f'data-version="{v}"' in html
356
+ assert set(re.findall(r'class="ver">([^<]+)<', html)) == {v}
357
+ skills = sorted(p.parent.name for p in (ROOT / "skills").glob("*/SKILL.md"))
358
+ want = {"commands": len(pythia.COMMANDS), "skills": len(skills),
359
+ "queries": len(list((ROOT / "queries").glob("*.sql"))),
360
+ "lint": len(pythia.LINT_RULES)}
361
+ for key, n in want.items():
362
+ assert set(re.findall(rf'data-count="{key}">(\d+)<', html)) == {str(n)}, key
363
+ for name in skills:
364
+ assert f"<b>{name}</b>" in html, name
365
+ for f in ("logo.webp", "logo.png", "favicon.png"): # what the page loads
366
+ assert (site / f).is_file(), f
367
+
368
+
211
369
  def test_one_version_across_every_manifest():
212
370
  """pyproject, plugin.json, marketplace.json and npm/package.json must all
213
371
  carry the same version — the release workflow publishes from one tag."""
@@ -273,6 +431,9 @@ def test_cmd_install_runs_end_to_end():
273
431
  out = buf.getvalue()
274
432
  assert (pathlib.Path(td) / ".pythia" / "connections.json").is_file()
275
433
  assert "Next: fill in" in out
434
+ gi = pathlib.Path(td) / ".gitignore"
435
+ assert SECRET in gi.read_text(encoding="utf-8").splitlines()
436
+ assert f"Added {SECRET} to" in out
276
437
  assert env is not None
277
438
 
278
439
 
@@ -796,10 +796,18 @@ def test_apply_preview_warns_on_naming_drift():
796
796
 
797
797
 
798
798
  def test_invocation_reflects_how_the_tool_was_run():
799
+ """...as it runs from a shell here: a bare name only when PATH finds this
800
+ very file (tests/test_phase6.py covers the venv that is not on PATH)."""
799
801
  import os
800
- interp = pathlib.Path(sys.executable).stem # python / python3 / python3.13
801
- old = sys.argv[0]
802
+ import re
803
+ # python / python3 / python3.13 — the name, not Path.stem ("python3.9"
804
+ # would lose its ".9")
805
+ interp = re.sub(r"\.exe$", "", pathlib.Path(sys.executable).name, flags=re.I)
806
+ old, old_lookup = sys.argv[0], pythia.path_lookup
802
807
  try:
808
+ # PATH finds this interpreter by its name, and the entry point by its
809
+ pythia.path_lookup = lambda name, *a, **k: (
810
+ sys.executable if name == interp else sys.argv[0])
803
811
  sys.argv[0] = "scripts/pythia.py" # run from source
804
812
  assert pythia.invocation() == f"{interp} scripts/pythia.py"
805
813
  # packaged entry point — a native path for whichever OS runs the test
@@ -812,7 +820,7 @@ def test_invocation_reflects_how_the_tool_was_run():
812
820
  sys.argv[0] = "/usr/local/bin/pythia"
813
821
  assert pythia.invocation() == "pythia"
814
822
  finally:
815
- sys.argv[0] = old
823
+ sys.argv[0], pythia.path_lookup = old, old_lookup
816
824
 
817
825
 
818
826
  def test_preview_hint_is_pasteable():
@@ -830,8 +838,9 @@ def test_preview_hint_is_pasteable():
830
838
  pythia.run_apply(conn, "APP", apply_ns(td, file="f.sql"), NEW_FILE)
831
839
  finally:
832
840
  sys.argv[0] = old
833
- interp = pathlib.Path(sys.executable).stem
834
- assert f"{interp} scripts/pythia.py apply f.sql --confirm " in buf.getvalue()
841
+ # this interpreter as a shell here types it (tests/test_phase6.py)
842
+ assert (f"{pythia.interpreter_word()} scripts/pythia.py apply f.sql "
843
+ "--confirm ") in buf.getvalue()
835
844
 
836
845
 
837
846
  def test_preview_diff_ignores_the_create_header():
@@ -20,6 +20,7 @@ sys.path.insert(0, str(HERE.parent / "scripts"))
20
20
  sys.path.insert(0, str(HERE))
21
21
  import pythia # noqa: E402
22
22
  import test_phase3 as p3 # noqa: E402 (fakes only; its tests are not re-run)
23
+ import test_install as ti # noqa: E402 (git helpers only; its tests are not re-run)
23
24
 
24
25
  FakeConn, base_script, apply_ns, expect_exit = (
25
26
  p3.FakeConn, p3.base_script, p3.apply_ns, p3.expect_exit)
@@ -1027,6 +1028,166 @@ def test_pre_tool_cannot_be_talked_into_a_second_command():
1027
1028
  expect_exit(lambda: pythia.build_parser().parse_args(["approve", "--ho"]))
1028
1029
 
1029
1030
 
1031
+ @contextlib.contextmanager
1032
+ def _interpreter(path):
1033
+ """Run as if sys.executable were `path` — the hook's own interpreter."""
1034
+ old = sys.executable
1035
+ sys.executable = str(path)
1036
+ try:
1037
+ yield
1038
+ finally:
1039
+ sys.executable = old
1040
+
1041
+
1042
+ def test_pre_tool_lets_reads_through_this_interpreter_by_absolute_path():
1043
+ """Field test 0.15.4: pythia in a venv that is not on PATH. The commands
1044
+ that run there are spelled with the venv's interpreter by absolute path —
1045
+ the same launcher the hooks use — and every read was a prompt, because
1046
+ the guard knew only `pythia` and `python -m pythia`."""
1047
+ with tempfile.TemporaryDirectory() as td, tempfile.TemporaryDirectory() as v:
1048
+ exe = pathlib.Path(v) / "bin" / ("python.exe" if os.name == "nt" else "python3")
1049
+ script = exe.with_name("pythia.exe" if os.name == "nt" else "pythia")
1050
+ with _interpreter(exe):
1051
+ q = exe.as_posix()
1052
+ assert decision(pre(td, f'"{q}" -m pythia src PKG_ORDER')) == "allow"
1053
+ assert decision(pre(td, f"{q} -m pythia connections")) == "allow"
1054
+ assert decision(pre(td, f'"{q}" -m pythia apply f.sql')) == "allow" # preview
1055
+ # the install's own entry point, beside its interpreter
1056
+ assert decision(pre(td, f'"{script.as_posix()}" src PKG_ORDER')) == "allow"
1057
+ # a clone's launcher: this interpreter and this very pythia.py
1058
+ real = pathlib.Path(pythia.__file__).resolve().as_posix()
1059
+ assert decision(pre(td, f'"{q}" "{real}" src PKG_ORDER')) == "allow"
1060
+
1061
+
1062
+ def test_pre_tool_trusts_no_other_absolute_launcher():
1063
+ """Allowing a command runs it without asking. An absolute path is
1064
+ trusted only when it is, by spelling, the interpreter running this hook
1065
+ (or its own pythia script): not a look-alike, not a symlink to it — a
1066
+ venv's python IS a symlink, and only its own path loads its packages."""
1067
+ with tempfile.TemporaryDirectory() as td, tempfile.TemporaryDirectory() as v:
1068
+ exe = pathlib.Path(v) / "bin" / "python3"
1069
+ with _interpreter(exe):
1070
+ q = exe.as_posix()
1071
+ for cmd in (f'"{pathlib.Path(v).as_posix()}/evil/python3" -m pythia src X',
1072
+ f'"{q}x" -m pythia src X',
1073
+ f'"{exe.with_name("python4").as_posix()}" -m pythia src X',
1074
+ f'"{exe.with_name("evil").as_posix()}" src X',
1075
+ "./bin/python3 -m pythia src X", # relative: cwd decides
1076
+ f'"{q}" -c "import os" -m pythia src X',
1077
+ f'"{q}" -m pythia src X; rm -rf ~',
1078
+ f'"{q}" -m pythia src X && touch y',
1079
+ f'"{q}" -m pythia apply f.sql --yes',
1080
+ f'"{q}" -m pythia policy set structural allow',
1081
+ f'"{q}" -m pythiax src X',
1082
+ f'"{q}" /tmp/elsewhere/pythia.py src X'):
1083
+ assert decision(pre(td, cmd)) is None, cmd
1084
+ # a pythia.py in the working directory shadows `-m pythia`
1085
+ (pathlib.Path(td) / "pythia.py").write_text("print('x')\n", encoding="utf-8")
1086
+ assert decision(pre(td, f'"{q}" -m pythia src X')) is None
1087
+ # the same path while ANOTHER interpreter runs the hook: not trusted
1088
+ with _interpreter(pathlib.Path(v) / "other" / "python3"), \
1089
+ tempfile.TemporaryDirectory() as clean:
1090
+ assert decision(pre(clean, f'"{exe.as_posix()}" -m pythia src X')) is None
1091
+ # a symlink to the real interpreter is another spelling: not trusted
1092
+ link = pathlib.Path(v) / "link-python3"
1093
+ try:
1094
+ os.symlink(sys.executable, link)
1095
+ except (OSError, NotImplementedError):
1096
+ return # no symlinks here (Windows without rights)
1097
+ with tempfile.TemporaryDirectory() as clean:
1098
+ assert decision(pre(clean, f'"{link.as_posix()}" -m pythia src X')) is None
1099
+
1100
+
1101
+ @contextlib.contextmanager
1102
+ def _path_finds(found):
1103
+ """path_lookup answering `found(name)` instead of reading PATH."""
1104
+ old = pythia.path_lookup
1105
+ pythia.path_lookup = lambda name, *a, **k: found(name)
1106
+ try:
1107
+ yield
1108
+ finally:
1109
+ pythia.path_lookup = old
1110
+
1111
+
1112
+ def test_printed_commands_run_where_pythia_is_not_on_path():
1113
+ """Field test 0.15.4: a real Claude Code session in a project whose
1114
+ pythia lives in a venv that is not on PATH ran `pythia ...` and got
1115
+ `command not found`; the install's fallback said `python3 -m pythia`,
1116
+ which on that machine is the system interpreter, without pythia. A
1117
+ printed command names what runs here: the bare name only when PATH finds
1118
+ this very file, else this interpreter by absolute path."""
1119
+ with tempfile.TemporaryDirectory() as v:
1120
+ exe = pathlib.Path(v) / "bin" / "python3"
1121
+ script = exe.with_name("pythia")
1122
+ launcher = f'"{exe.as_posix()}" -m pythia'
1123
+ old = sys.argv[0]
1124
+ try:
1125
+ with _interpreter(exe):
1126
+ sys.argv[0] = str(script) # console script
1127
+ with _path_finds(lambda n: "/usr/bin/" + n): # PATH: other ones
1128
+ assert pythia.invocation() == launcher
1129
+ hint = pythia.entry_point_hint(None, str(exe.parent))
1130
+ assert launcher in hint and "\n python3 -m pythia" not in hint
1131
+ with _path_finds(lambda n: str(script) if n == "pythia" else None):
1132
+ assert pythia.invocation() == "pythia"
1133
+ sys.argv[0] = "scripts/pythia.py" # from a clone
1134
+ with _path_finds(lambda n: str(exe) if n == "python3" else None):
1135
+ assert pythia.invocation() == "python3 scripts/pythia.py"
1136
+ with _path_finds(lambda n: None):
1137
+ assert pythia.invocation() == f'"{exe.as_posix()}" scripts/pythia.py'
1138
+ finally:
1139
+ sys.argv[0] = old
1140
+
1141
+
1142
+ def _session_start(td, home=None):
1143
+ import argparse
1144
+ old_stdin = sys.stdin
1145
+ sys.stdin = io.StringIO("")
1146
+ try:
1147
+ _, out = quiet(pythia.cmd_hook, None, None,
1148
+ argparse.Namespace(event="session-start", project_root=td))
1149
+ finally:
1150
+ sys.stdin = old_stdin
1151
+ return out
1152
+
1153
+
1154
+ def test_session_start_names_the_launcher_that_runs_here():
1155
+ """CLAUDE.md is shared, so it says `pythia`. The hook runs on this
1156
+ machine: it says how `pythia` is spelled here, once, and spells its own
1157
+ pointers that way."""
1158
+ launcher = '"/v/bin/python3" -m pythia'
1159
+ with tempfile.TemporaryDirectory() as td:
1160
+ pythia.scaffold_config(td)
1161
+ pythia.merge_marked_block(pathlib.Path(td) / "CLAUDE.md",
1162
+ pythia.claude_md_block())
1163
+ old = pythia.invocation
1164
+ try:
1165
+ pythia.invocation = lambda: launcher
1166
+ out = _session_start(td)
1167
+ assert f"`pythia` here is `{launcher}`" in out, out
1168
+ assert f"`{launcher} guide`" in out and f"`{launcher} connections`" in out
1169
+ pythia.invocation = lambda: "pythia"
1170
+ out = _session_start(td)
1171
+ assert "`pythia` here is" not in out and "`pythia guide`" in out
1172
+ finally:
1173
+ pythia.invocation = old
1174
+
1175
+
1176
+ def test_session_state_names_a_local_scope_approval_door():
1177
+ """Field test 0.15.4: in a venv project the MCP approver lives in Claude
1178
+ Code's local scope (~/.claude.json), not .mcp.json — and the session
1179
+ state said nothing about the door that prompts in every mode."""
1180
+ with tempfile.TemporaryDirectory() as td, tempfile.TemporaryDirectory() as home:
1181
+ assert not any("approval door" in ln
1182
+ for ln in pythia.session_state_lines(td, home=home))
1183
+ (pathlib.Path(home) / ".claude.json").write_text(json.dumps({"projects": {
1184
+ str(pathlib.Path(td)): {"mcpServers": {"pythia": {
1185
+ "command": "/v/bin/python3", "args": ["-m", "pythia", "mcp"]}}}}}),
1186
+ encoding="utf-8")
1187
+ assert any("approval door" in ln and "pythia_approve" in ln
1188
+ for ln in pythia.session_state_lines(td, home=home))
1189
+
1190
+
1030
1191
  def test_tokens_that_are_not_tokens_name_nothing():
1031
1192
  with tempfile.TemporaryDirectory() as td:
1032
1193
  lease(td)
@@ -1173,6 +1334,61 @@ def test_doctor_reports_the_wiring_after_install():
1173
1334
  and "shares" in m for s, a, m in rows), rows
1174
1335
 
1175
1336
 
1337
+ def _cred(rows):
1338
+ found = [(s, m) for s, a, m in rows if a == "credentials"]
1339
+ assert len(found) == 1, rows
1340
+ return found[0]
1341
+
1342
+
1343
+ def test_doctor_fails_a_password_file_git_tracks():
1344
+ """Not ignored is a risk (warn); tracked is a leak (fail) — the passwords
1345
+ are in the repository already, and a .gitignore line cannot take them
1346
+ back out. The fix names the commands and the rotation."""
1347
+ import subprocess
1348
+ with ti.hermetic_git(), tempfile.TemporaryDirectory() as td, \
1349
+ tempfile.TemporaryDirectory() as home:
1350
+ git = ti.git_init(td)
1351
+ if git is None:
1352
+ return
1353
+ root = pathlib.Path(td)
1354
+ pythia.scaffold_config(root)
1355
+ st, msg = _cred(pythia.harness_checks(td, home))
1356
+ assert st == "warn" and "git add -A" in msg and "install" in msg, msg
1357
+ pythia.ignore_connections(root)
1358
+ assert _cred(pythia.harness_checks(td, home))[0] == "ok"
1359
+ subprocess.run([git, "-C", td, "add", "-f", ti.SECRET], check=True,
1360
+ stdin=subprocess.DEVNULL)
1361
+ st, msg = _cred(pythia.harness_checks(td, home))
1362
+ assert st == "fail", msg
1363
+ assert f"git rm --cached {ti.SECRET}" in msg and "password" in msg, msg
1364
+
1365
+
1366
+ def test_doctor_warns_a_rule_only_this_machine_has():
1367
+ with ti.hermetic_git(), tempfile.TemporaryDirectory() as td, \
1368
+ tempfile.TemporaryDirectory() as home:
1369
+ if ti.git_init(td) is None:
1370
+ return
1371
+ root = pathlib.Path(td)
1372
+ pythia.scaffold_config(root)
1373
+ exclude = root / ".git" / "info" / "exclude"
1374
+ exclude.parent.mkdir(exist_ok=True)
1375
+ exclude.write_text(ti.SECRET + "\n", encoding="utf-8")
1376
+ st, msg = _cred(pythia.harness_checks(td, home))
1377
+ assert st == "warn" and "only on this machine" in msg, msg
1378
+
1379
+
1380
+ def test_doctor_says_plainly_when_there_is_no_git_to_ask():
1381
+ with ti.hermetic_git(), tempfile.TemporaryDirectory() as td, \
1382
+ tempfile.TemporaryDirectory() as home:
1383
+ pythia.scaffold_config(pathlib.Path(td))
1384
+ st, msg = _cred(pythia.harness_checks(td, home))
1385
+ assert st == "info" and "git" in msg, msg
1386
+ # no password file, nothing to protect: no row at all
1387
+ with tempfile.TemporaryDirectory() as td, tempfile.TemporaryDirectory() as home:
1388
+ assert not [a for _, a, _ in pythia.harness_checks(td, home)
1389
+ if a == "credentials"]
1390
+
1391
+
1176
1392
  def test_install_registers_the_mcp_approver_once_and_keeps_other_servers():
1177
1393
  with tempfile.TemporaryDirectory() as td:
1178
1394
  path = pathlib.Path(td) / ".mcp.json"
File without changes
File without changes