| Age | Commit message (Collapse) | Author |
|
Co-authored-by: mhegazy <mhegazy@anthropic.com>
|
|
security-guidance: count commits that no commit hook saw
|
|
A record lost before one Stop was treated as whole by the next, and a prompt
that was never stored as having no edits, so the note could name the
session's own file. File names in the note are quoted as JSON.
Co-authored-by: mhegazy <mhegazy@anthropic.com>
|
|
A commit review starts from a hook on the Bash tool, so a commit made any
other way starts none. The Stop row now carries turn_commits: how many
commits the turn made, how many have no review, and how many of those no
commit hook saw. Count only; what is reviewed does not change, and no hook
entry is added.
Co-authored-by: mhegazy <mhegazy@anthropic.com>
|
|
Measure only: path globs a wider reading would change, refused and counted
repeats in regexes, and the slowest custom regex, on the Stop row. Which
rules apply does not change.
Co-authored-by: mhegazy <mhegazy@anthropic.com>
|
|
mhegazy/sg-stop-finding-names-unwritten
# Conflicts:
# plugins/security-guidance/hooks/security_reminder_hook.py
|
|
security-guidance: keep a renamed file paired with its old name in the Stop review
|
|
stash create checks the work tree on one thread. add -u into the throwaway
index copy, write-tree and commit-tree produce the same commit and use git's
index preload instead, which matters where each file status is slow. See #6854.
|
|
# Conflicts:
# plugins/security-guidance/hooks/diffstate.py
|
|
|
|
security-guidance: count reviews of a diff that was already reviewed
|
|
A commit or push review marks the commits it is reviewing by holding a
lock on .git/sg-inflight-<sha>, so a push made meanwhile waits for that
review instead of reviewing the same commit again. The lock was flock
only. Native Windows Python has no fcntl, so there were no markers there
and a push right after a commit still ran a second full review.
On Windows the same shared/exclusive, never-waiting lock is now taken
with LockFileEx, on a byte far past the end of the empty marker so that
reading or copying the file is never refused. Windows will not delete an
open file, so a marker is closed before it is deleted there, with a short
retry while another review has it open; what cannot be deleted is left
unlocked and swept once old, as before.
Also: one marker that cannot be opened, or whose last holder deletes it
between this review's open and lock, no longer costs the review its
claim on the remaining commits.
The in-flight tests no longer require fcntl, so they run on Windows.
|
|
Prompts that wait a second or more in the UserPromptSubmit hook send one
metrics row: total, baseline and untracked listing time, index size, and
whether the repository is on a Windows drive under WSL. Measures only;
capture is unchanged. See #6854.
|
|
Keeps both sides in emit_metrics: diff_seen stays after the other review
tail keys, and the launcher probe keys stay after everything else.
|
|
|
|
security-guidance: keep nested repositories out of the index copy
|
|
symlinked folder
When the tool's path and the session directory name the same repo through
different symlinks (/tmp and /var on macOS), the relative path between the two
spellings left the repo and the lookup found nothing, so a rewrite re-reported
code that was already in the file. The lookup now tries again with both paths
resolved. The first attempt is unchanged.
|
|
another case
On file systems that ignore case, realpath keeps the case a path was given
in, so an edit recorded as /TMP/x/REPO/app.py for a repo at /tmp/x/repo was
counted as outside the repo. Fold case (and, on macOS, normalize) the whole
path and the root before taking the relative path, not only the result.
|
|
|
|
record of editing
The Stop review takes its files from git, so it can report a finding in a
file another session or process changed in the same checkout, or in earlier
uncommitted work when no turn-start snapshot could be taken. The finding then
read as an instruction to fix code the session did not write.
A finding in a reviewed file with no record of the session's edit tools
writing it since the prompt now carries a note naming the file: the change may
have been made another way, leave it and tell the user if it is not yours,
handle it as usual if it is. What gets reviewed is unchanged.
The note is left out when the record is known to be incomplete (state file
lost or overwritten, or more edited paths than the list keeps). Stop rows with
findings carry finding_no_edit_record: the number of such findings, or -1 when
the record was incomplete.
Refs #4524
|
|
The hooks run `git stash create` (the turn baseline) and
`git add --intent-to-add` (untracked files) on a throwaway copy of the
index. A nested repository that the index records is a gitlink entry
there. `git stash create` takes no --ignore-submodules option and
`git add` reads the gitlinks its paths cover, so both started a second
git inside that directory.
Before anything runs on the copy, remove the gitlink entry of every
nested repository from the copy, never from the real index. If that
removal fails, do not use the copy at all: the baseline falls back to
HEAD and runs no stash create, and the diff reads the real index with
--ignore-submodules=all. A gitlink whose directory has no `.git` (a
submodule that is not checked out) stays; git starts nothing there.
Run the intent-to-add `git add` with literal pathspecs, in that one
call's environment only.
The index file is scanned for a gitlink's mode bytes first, so a
repository without one starts no extra git process.
|
|
A change that comes back under a new commit (undo and re-commit, rebase
before the first push) is unknown to the reviewed-shas record, so the
commit or push review runs on it again. Nothing says how often.
Each commit and push review now notes a hash of every hunk it is sent in
.git/sg-reviewed-diffs, once when it starts and once when it has a
verdict, and reports one new metric, diff_seen:
0 some hunk was never reviewed in this clone
1 all were seen, but a review of one has no verdict (yet)
2 all had a finished review, on different repo contents
3 all had a finished review, on the same tree
-1 the record could not be read or written
Count only: no review is skipped, delayed or changed. The record is
bounded (1 MB, 7 days), is not written in portable output mode, and its
lock is never waited on for more than half a second.
|
|
secret_renamed is sent only when it is not zero.
|
|
review
The Stop review limits its diff to the changed paths. For a rename that git
already knows about (git mv, or a rename committed during the turn) that list
held only the new name, so the diff showed a new file and the parsers could
not apply the rule that leaves out a file renamed away from a secret-shaped
name. The old name now goes into the list beside the new one, as it already
did for a plain mv.
The file listings themselves are unchanged.
|
|
Resolves the overlap with the baseline-origin change in security_reminder_hook.py: both sets of state keys are stored beside the baseline.
|
|
The turn baseline (stash SHA, HEAD, untracked snapshot) is kept per
session, and the Stop review used it in whatever checkout the turn ended
in. After the session entered another worktree, that worktree's older
commits looked like commits made this turn and its files were diffed
against the first checkout's, so code committed long before was reviewed
and reported again (anthropics/claude-code#102567).
The prompt hook now stores the repo root and the prompt time beside the
baseline. When the Stop review runs in a different checkout it leaves the
baseline out and uses what that checkout can say for itself: its own HEAD
when the turn began (from its reflog) for the commit range, HEAD for file
contents, and file times to leave out uncommitted files last written
before the turn. A baseline taken after a finding records the checkout it
was taken in.
A prompt in a folder that is not a repo no longer replaces the untracked
snapshot of the kept baseline with an empty one, which made every
untracked file in the repo look new at the next Stop.
Stop rows carry `bl_origin`: 0 same checkout, 1 another worktree, 2
another repository, 3 a folder that is gone, 4 no baseline; plus 10 or 20
when the baseline is an earlier turn's.
|
|
The Stop review takes its file list from git state, so it can cover files
the session's edit tools never wrote. Add one count-only metric,
review_scope, to Stop rows: whether the edit-tool paths lie inside the
reviewed repo, how many reviewed files no edit tool wrote, and whether the
turn-start snapshot was a real one. No change to what is reviewed.
Refs #4524
|
|
subdirectory
A full-file Write is checked against the file as it was at the start of the turn, so risky calls that were already there are not reported as new. The lookup passed git a path relative to the session directory, which git reads from the repo root, so it failed for any session started below the root, and on Windows for any path with a separator. Ask for ./<path> with forward slashes.
Fixes #5684
|
|
security-guidance: do not review a commit twice while its first review is running
|
|
running
A commit review records its commits only once it has a verdict. A push
(or the next commit's reflog scan) that started before then reviewed the
same diff again. A running review now holds a lock file per commit in the
git dir; a push review waits for it and skips what it recorded, and the
reflog scan leaves those commits to it.
|
|
security-guidance: keep the session state when a save is cut short
|
|
mhegazy/sg-skip-untracked-listing
|
|
|
|
(#6541)
* security-guidance: stop re-reviewing untracked files past the snapshot cap
The untracked-file snapshot stops at 2,000 entries. Every pre-existing untracked file past the cap looked new on each turn, so the same files were reviewed again and again.
Record when a capped snapshot was taken and treat unlisted files older than that as pre-existing.
* security-guidance: test the metric that shows the capped-snapshot path
preexisting_untracked_excluded stays at the 2,000 cap before this fix and rises above it after, which is how the fix can be confirmed from metrics. No new key.
|
|
UserPromptSubmit listed every untracked file in the worktree and stored the
result in the session state on each prompt, for a snapshot that only the Stop
review reads. With ENABLE_STOP_REVIEW=0 or ENABLE_CODE_SECURITY_REVIEW=0 the
Stop hook skips before reading it, so the listing is now skipped too. The
stash baseline is still captured for the Write pattern filter.
When the review is switched back on, the next prompt takes a fresh snapshot,
including after an interrupted turn whose baseline is kept.
Refs #6612
|
|
The state file was rewritten in place, so a hook killed during a save left a truncated file that the next hook read as an empty state: the turn baseline, the touched paths and the shown warnings were gone. Write a temporary file and rename it over the state file. Windows keeps writing in place for now: hooks have no state lock there, and a rename can be refused or make a concurrent read fail.
A state file that cannot be decoded no longer stops the hook. The Stop metrics gain two keys, sent only when nonzero: state_resets (the state file was unreadable and the state started over) and state_overwrites (without a lock, a save replaced one made by another hook since the read).
Refs #1944
|
|
With a very large git index the hook's git calls hit their time limits and
are killed, so git cannot clean up. Each kill could leave an index-sized
file in the temp directory, index.stash.<pid> files in .git, and a dead
.git/index.lock that fails the user's next git add or commit.
- `git stash create` and the work-tree diff run on a throwaway index copy.
- Every git the hook spawns gets GIT_OPTIONAL_LOCKS=0.
- Copies live in a private per-user folder and are removed together with
the files git writes next to them.
- Leftovers older than 30 minutes are swept, including existing ones.
Co-Authored-By: Claude <noreply@anthropic.com>
|
|
- SubagentStop reviews without consuming or advancing the session's
Stop state; an identical diff is not reviewed twice.
- SubagentStop from a different working tree than the project is skipped.
- An explicit `git -C <dir>` / `cd <dir>` naming another repository takes
precedence over the hook cwd.
- Narrows the `git -C … commit` matcher; keeps Windows path separators
when tokenizing; adds `--no-textconv` to diff/show invocations.
- Adds tests.
:house: Remote-Dev: homespace
|
|
followup)
Followup to PR #2086 (which added the flag to 4 specific git call
sites) and PR #2100 (text=True purge for #2099).
The Windows reporter for #2099 noticed more git invocations still
lacked the flag — rev-parse path queries (--show-toplevel, --git-dir,
--git-common-dir), reflog %gs subjects, and `git show <sha>:<path>`
all output paths but the per-site PR #2086 approach missed them. The
result: an Arabic-named directory shows up via _git_diff_range but
rev-parse-emitted paths get C-quoted, breaking downstream
os.path.isabs() checks.
Fix: add `-c core.quotePath=false` to GIT_CMD itself as the 4th
config-set. Every subprocess.run using the *GIT_CMD splat picks it
up automatically — diff feeders, rev-parse path queries, reflog log,
ls-files, status, git show. No more per-site flag duplication.
This commit:
1. gitutil.py: add -c core.quotePath=false to GIT_CMD.
2. Remove the now-redundant per-site flags at the 7 call sites that
previously had inline -c core.quotePath=false (cleanup, since the
global setting subsumes them):
gitutil.py: _git_diff_range, _git_name_only, _git_status_porcelain,
get_git_diff (4 sites)
diffstate.py: _list_untracked git ls-files (1 site)
security_reminder_hook.py: commit-review git diff + git show (2 sites)
Verified locally on latest main (post PR #2100 merge) with macOS
Python 3.13:
- py_compile clean on all 3 modified files.
- Bare main BEFORE my fix: 400/401 pass — 1 failure proves the gap
(test_git_cmd_contains_quotepath_false catches the missing flag).
- Main + my fix: 401/401 pass.
- 23 new tests in test_quotepath_global.py (added to internal test
suite at sg-staging/tests/, not in this PR):
* 1 GIT_CMD-level: GIT_CMD list contains core.quotePath=false as
a (-c, value) pair. Single source of truth — single place a
future PR will be caught if the flag gets dropped.
* 10 static-shape (one per hooks/*.py): every subprocess.run
uses the *GIT_CMD splat (no bare git invocation that would
bypass the global flag).
* 12 end-to-end (parametrized over Arabic, Hebrew, CJK directory
names): real git repo, _git_diff_range emits unquoted diff,
extract_file_paths_from_diff and parse_diff_into_files keep
the non-ASCII path in their output, _git_toplevel returns the
non-ASCII path intact.
- 1 staleness fix in test_diff_parser_non_ascii.py
(test_no_bare_git_diff_or_show_without_flag): updated to accept
EITHER inline core.quotePath=false OR *GIT_CMD splat (which
globally provides it).
NOT verified end-to-end on Windows with a non-ASCII repo root path.
The new global-flag test pins the contract permanently, and the
parametrized macOS tests confirm parser behavior on ASCII-control
paths in non-ASCII directories. The Windows-specific rev-parse
quoting behavior follows from the same git contract our macOS test
environment exercises (POSIX git always emits raw UTF-8 regardless
of quotePath; on Windows the flag is what makes output raw).
Closes the #2099 followup specifically about _git_diff_range /
rev-parse --show-toplevel / git log %gs paths slipping past.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
|
Fixes anthropics/claude-plugins-official#2056 — on Windows, when the
worktree contains an untracked file whose name has a character undefined
in cp1252 (accented capitals like Á Í Ï Ð Ý, most CJK, emoji), the
UserPromptSubmit hook crashes:
Exception in thread Thread-5 (_readerthread):
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81
Traceback (most recent call last):
File diffstate.py, line 338, in _list_untracked
for p in r.stdout.split('\\0'):
AttributeError: 'NoneType' object has no attribute 'split'
Non-blocking (UPS failures still let the prompt through) but the
baseline-untracked snapshot is silently lost, so the Stop-hook review
mis-handles pre-existing untracked files.
Root cause (reporter's diagnosis, verified):
1. core.quotePath=false makes git emit raw UTF-8 for non-ASCII filenames.
2. subprocess.run(..., text=True) decodes via
locale.getpreferredencoding(False) in strict mode — on Windows that
is cp1252, in which 0x81 / 0x8D / 0x8F / 0x90 / 0x9D are undefined.
Those bytes appear in the UTF-8 encodings of Á (C3 81), Í (C3 8D),
Ï (C3 8F), Ð (C3 90), Ý (C3 9D), and a large fraction of CJK / emoji
codepoints.
3. The decode runs in the subprocess reader thread. The thread raises
UnicodeDecodeError, threading prints 'Exception in thread Thread-N',
subprocess.run returns with stdout=None. The handler then does
None.split('\\0') -> AttributeError, which is NOT in the narrow
except (TimeoutExpired, FileNotFoundError, OSError) tuple, so it
escapes the helper, propagates out of UserPromptSubmit's
ThreadPoolExecutor.result(), and exits the hook non-zero.
This is internally inconsistent: gitutil._git_diff_range,
security_reminder_hook._reflog_amend_lookup (line ~540), and the commit
diff loop (line ~1115) already do bytes + decode utf-8/replace, with
comments explicitly noting that text=True would crash. The fix below
extends that established pattern to the helpers that were holdouts.
Affected helpers (6 total):
- diffstate._list_untracked <- reporter, hot path, CRITICAL
- diffstate.capture_git_baseline <- reporter, latent
- diffstate.get_baseline_file_content <- audit, file content read, HIGH
- gitutil._git_name_only <- reporter, latent
- gitutil._git_status_porcelain <- reporter, latent
- gitutil._git_reflog_recent_commits <- audit, embeds %gs commit msg, HIGH
For each one:
- Drop text=True from subprocess.run.
- Decode r.stdout / r.stderr as .decode('utf-8', errors='replace').
- Add ValueError to the except tuple as defense against any future
strict-decode regression (UnicodeDecodeError is a ValueError
subclass; including it explicitly degrades the helper to its
empty/None return instead of escaping out of the hook).
Verified locally on macOS Python 3.13:
- py_compile clean on both files.
- 45 existing smoke + extensibility tests still pass.
- 21 new internal tests (not in this PR — added to the team's local
test suite at staging/tests/test_unicode_decode.py):
* 18 static-shape parametrized: each of the 6 fixed helpers has
no text=True in its subprocess calls, contains errors='replace',
and lists ValueError in its except.
* Deterministic end-to-end: create real git repo + Ávila_report.txt
untracked, call _list_untracked, verify it returns
{'Ávila_report.txt': <mtime>} without crashing.
* Deterministic end-to-end: same for capture_git_baseline (verifies
the latent stderr-warning case stays valid).
* Deterministic end-to-end: get_baseline_file_content on a file
whose content has 山田太郎 + 🎉; verify the bytes round-trip
through the decode.
- 66/66 tests pass total (45 existing + 21 new).
NOT verified end-to-end on Windows — would need actual cp1252 strict
decode to fire. Reporter has the deterministic repro and will
re-verify on their Win11 / Python 3.14.x setup before merge.
Not in this PR (defense-in-depth, lower risk):
- 3 git rev-parse calls returning path output (gitutil._find_git_index,
_git_toplevel, _git_dir) could fail on Windows if cwd is in a
non-ASCII install directory. Same fix shape but unreported and
much lower probability — worth a separate follow-up if anyone
actually hits it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
|
|