Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "java-functional-lsp",
"description": "Java LSP with functional programming rules enforcement — null safety, immutability, no exceptions, Spring best practices. Wraps jdtls for full Java language support.",
"version": "0.4.3",
"version": "0.4.4",
"lspServers": {
"java-functional": {
"command": "java-functional-lsp",
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ moving on. Fix any type errors or missing imports immediately.
| "java-functional-lsp not found" | Run `brew install aviadshiber/tap/java-functional-lsp` |
| Plugin not active | Run `claude plugin list` to verify, then `/reload-plugins` |
| Diagnostics slow on first open | Normal — tree-sitter parses on first load, then incremental |
| Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)); jdtls results arrive with the next tool result. See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) |
| Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)). The plugin's hook waits up to 3s for them; if jdtls is slower (large projects), raise `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` (max 4). See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) |

### Other Editors

Expand Down Expand Up @@ -317,13 +317,19 @@ jdtls re-validates a file 0.4–2.4s after the last edit to *any* file, and its
| `hold-all` | Other editors | Nothing is published for the file until jdtls has re-validated (no flickering squiggles) |
| `off` | — | Previous behavior: custom diagnostics plus the last known jdtls diagnostics after 150ms |

With Claude Code two more things happen:

- **The plugin's PostToolUse hook waits for fresh results.** Claude Code attaches diagnostics as soon as its PostToolUse hooks finish, without waiting for the server ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)). The server records when it last published final diagnostics for each file, and `hooks/post_tool_lint.py` waits until that is newer than the edit (at most `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` seconds, default 3, max 4), so jdtls's result for the edit arrives in the same tool result. The markers live in a private per-user temp directory and contain only a timestamp.
- **jdtls gets a didSave after each edit.** Claude Code writes the file itself; when the edited buffer matches the file on disk, the server forwards a didSave. Without it, jdtls can re-check dependent files against the old version of the edited one (e.g. a caller keeps reporting a constructor's old arity) and never correct them.

If jdtls doesn't publish in time (3s after the last edit, stretched when jdtls is slow, 10s at most), the last known jdtls diagnostics are used. Files whose module is still being imported, and files matched by `java.diagnostic.filter`, are never held. While you edit the same file in quick succession, its diagnostics update only once the burst settles.

Environment variables:

| Variable | Values | Effect |
|----------|--------|--------|
| `JAVA_FUNCTIONAL_LSP_DIAG_HOLD` | `custom-first`, `hold-all`, `off` | Overrides the mode above; `off` restores the previous behavior |
| `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` | seconds, `0`–`4` (default `3`) | How long the Claude Code PostToolUse hook waits for fresh jdtls diagnostics; `0` disables the wait |
| `JAVA_FUNCTIONAL_LSP_LOG_LEVEL` | `DEBUG`, `INFO` (default), `WARNING` | Verbosity of java-functional-lsp's own logs; `DEBUG` adds one line per publish decision (file name, trigger, counts). Library logging (pygls) is unaffected — note that pygls already logs the JSON it sends, including diagnostic messages, at `INFO` |

The log reports `jdtls freshness: released=… too_early=… timeout=… late_correction=…` every 100 decisions and when jdtls stops. Repeated `timeout` lines mean jdtls is slow or stuck on that module. A growing `late_correction` count means jdtls results were released too early.
Expand Down
97 changes: 96 additions & 1 deletion hooks/post_tool_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

Reads the Claude Code PostToolUse JSON payload on stdin, runs java-functional-lsp
on the edited file, and emits diagnostics as ``hookSpecificOutput.additionalContext``
so the agent sees them in context and can fix them immediately (issue #70).
so the agent sees them in context and can fix them immediately (issue #70). Before
returning it waits (bounded) for the running language server to publish fresh jdtls
diagnostics for the file, so Claude Code attaches current ones to this edit (#109).

Failure-safe by design: every path exits 0 — a linter problem must never break the
editing session. Prefers the fast in-process import; falls back to the CLI when the
Expand All @@ -12,14 +14,101 @@

from __future__ import annotations

import getpass
import hashlib
import json
import os
import signal
import stat
import subprocess
import sys
import tempfile
import time
from pathlib import Path

TIMEOUT_SECONDS = 5 # hard cap; single-file analysis is typically <200ms
MAX_DIAGNOSTICS = 25 # keep additionalContext bounded
POLL_SECONDS = 0.05
DEFAULT_WAIT_SECONDS = 3.0
MAX_WAIT_SECONDS = 4.0
EXIT_MARGIN_SECONDS = 0.5 # finish well before SIGALRM so the lint output is printed
MARKER_MAX_BYTES = 128


def _fresh_wait_seconds() -> float:
try:
wait = float(os.environ.get("JAVA_FUNCTIONAL_LSP_HOOK_WAIT", DEFAULT_WAIT_SECONDS))
except ValueError:
return DEFAULT_WAIT_SECONDS
return max(0.0, min(wait, MAX_WAIT_SECONDS))


def _user() -> str:
try:
return getpass.getuser()
except Exception:
return str(os.getuid()) if hasattr(os, "getuid") else "user"


def _marker_path(file_path: str) -> Path:
"""Must match java_functional_lsp.freshness_marker.marker_path (a test checks)."""
digest = hashlib.sha256(os.path.realpath(file_path).encode()).hexdigest()[:32]
return Path(tempfile.gettempdir()) / f"java-functional-lsp-{_user()}" / "fresh" / digest


def _owned(st: os.stat_result) -> bool:
return not hasattr(os, "getuid") or st.st_uid == os.getuid()


def _read_marker(marker: Path) -> tuple[int, str] | None:
"""(server pid, content digest), or None unless the marker and its dirs are private and ours."""
try:
for level in (marker.parent.parent, marker.parent):
st = os.lstat(level)
if not stat.S_ISDIR(st.st_mode) or not _owned(st) or st.st_mode & 0o077:
return None
fd = os.open(marker, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
try:
st = os.fstat(fd)
if not stat.S_ISREG(st.st_mode) or not _owned(st):
return None
pid, digest = os.read(fd, MARKER_MAX_BYTES).decode().split()
finally:
os.close(fd)
server_pid = int(pid)
return (server_pid, digest) if server_pid > 0 else None # kill(0|-n, 0) targets groups
except (OSError, ValueError):
return None


def _server_alive(pid: int) -> bool:
try:
os.kill(pid, 0)
except PermissionError:
return True
except OSError:
return False
return True


def _wait_for_fresh_diagnostics(path: Path, budget: float) -> None:
"""Wait until the language server has published final diagnostics for this edit.

Claude Code attaches LSP diagnostics right after PostToolUse hooks finish, but jdtls
needs 0.4-2.4s to re-validate (#109). On each final publish the server records its pid
and a hash of the content it analyzed; waiting until that hash matches the file puts
fresh results in this tool result. No marker, or a dead server, means nobody will
publish — don't wait.
"""
marker = _marker_path(str(path))
current = _read_marker(marker)
if current is None or not _server_alive(current[0]):
return
want = hashlib.sha256(path.read_bytes()).hexdigest()
deadline = time.monotonic() + min(_fresh_wait_seconds(), budget)
while current is not None and current[1] != want and time.monotonic() < deadline:
time.sleep(POLL_SECONDS)
current = _read_marker(marker)


def _lint_in_process(path: Path) -> list[str] | None:
Expand Down Expand Up @@ -48,6 +137,7 @@ def _lint_via_cli(path: Path) -> list[str]:


def main() -> None:
started = time.monotonic()
hook_input = json.load(sys.stdin)
file_path = (hook_input.get("tool_input") or {}).get("file_path", "")
if not file_path.endswith(".java"):
Expand All @@ -59,6 +149,11 @@ def main() -> None:
lines = _lint_in_process(path)
if lines is None:
lines = _lint_via_cli(path)
try:
budget = TIMEOUT_SECONDS - EXIT_MARGIN_SECONDS - (time.monotonic() - started)
_wait_for_fresh_diagnostics(path, budget=budget)
except Exception:
pass # a marker problem must never suppress the lint output below
if not lines:
return # clean file: stay silent, no per-edit context noise

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "java-functional-lsp"
version = "0.12.1"
version = "0.13.0"
description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions"
readme = "README.md"
license = { text = "MIT" }
Expand Down
2 changes: 1 addition & 1 deletion src/java_functional_lsp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""java-functional-lsp: A Java LSP server enforcing functional programming best practices."""

__version__ = "0.12.1"
__version__ = "0.13.0"
78 changes: 78 additions & 0 deletions src/java_functional_lsp/freshness_marker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""Per-file "diagnostics are final" markers for the Claude Code PostToolUse hook (#109).

Claude Code collects LSP diagnostics right after its PostToolUse hooks finish, without
waiting for the server. When the server publishes final diagnostics for a file (fresh
jdtls results merged in) it records the server pid and a hash of the content it analyzed;
``hooks/post_tool_lint.py`` waits until the hash matches the file on disk, so the fresh
set lands in the same tool result. A hash (not a time) means a publish for an older
version of the file can never satisfy the hook, and the pid lets the hook skip waiting
when the server that wrote the marker is gone.

The hook keeps its own copy of :func:`marker_path` and of the directory checks (it may run
without this package importable); tests keep the two in sync.
"""

from __future__ import annotations

import getpass
import hashlib
import os
import stat
import tempfile
from pathlib import Path

#: Written at didOpen: never equals a content hash, so the hook waits for jdtls's first result.
OPENING = "opening"

_validated: set[Path] = set()


def _user() -> str:
try:
return getpass.getuser()
except Exception: # containers without a passwd entry: KeyError (<3.13) / OSError (3.13+)
return str(os.getuid()) if hasattr(os, "getuid") else "user"


def marker_dir() -> Path:
return Path(tempfile.gettempdir()) / f"java-functional-lsp-{_user()}" / "fresh"


def marker_path(file_path: str) -> Path:
digest = hashlib.sha256(os.path.realpath(file_path).encode()).hexdigest()[:32]
return marker_dir() / digest


def content_digest(content: bytes) -> str:
return hashlib.sha256(content).hexdigest()


def _ensure_private_dir(path: Path) -> bool:
"""Create *path* if needed; True only for a real directory we own with no group/other access."""
path.mkdir(mode=0o700, exist_ok=True)
st = os.lstat(path) # lstat: a symlink is never S_ISDIR
if not stat.S_ISDIR(st.st_mode) or (hasattr(os, "getuid") and st.st_uid != os.getuid()):
return False
if st.st_mode & 0o077:
os.chmod(path, 0o700)
return True


def write_marker(file_path: str, digest: str) -> None:
"""Record that final diagnostics for *file_path* were published for content *digest*. Never raises."""
try:
directory = marker_dir()
if directory not in _validated:
# Check each level before creating below it, so nothing lands behind a
# symlink planted in a shared temp dir.
if not (_ensure_private_dir(directory.parent) and _ensure_private_dir(directory)):
return
_validated.add(directory)
target = marker_path(file_path)
tmp = target.with_name(f"{target.name}.{os.getpid()}.tmp")
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(tmp, flags, 0o600), "w") as f:
f.write(f"{os.getpid()} {digest}")
os.replace(tmp, target)
except Exception:
_validated.clear()
Loading
Loading