From 437e992a896a86c56a464efb45deef3838cf2d39 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:43:45 +0000 Subject: [PATCH] facts: re-check follow-ups - a project name taken from a match ending in "." or ".." is dropped; a remote's ".git" is dropped - a record folder that is a link out of the record repo is not searched - the record search's time limit is checked for each folder, not only each file; files with a NUL byte are not text - --records names the state-table copy when that is the only hit, and prints a note (exit 0) when no record repo is configured - uninstall's running-code check ignores an OPTIONAL_LINKS path that belongs to another program Refs #1063 Co-Authored-By: Claude Opus 5.5 --- fork-kit/agent-guards/README.md | 5 +- fork-kit/agent-guards/bin/facts | 15 +++- .../agent-guards/lib/agent_guards/facts.py | 42 +++++++--- fork-kit/agent-guards/tests/facts.test.py | 78 ++++++++++++++++++- fork-kit/agent-guards/tests/install.test.py | 8 +- fork-kit/common/kit_install.py | 5 +- 6 files changed, 131 insertions(+), 22 deletions(-) diff --git a/fork-kit/agent-guards/README.md b/fork-kit/agent-guards/README.md index ddd4d82a44904..14ec9348ca0e0 100644 --- a/fork-kit/agent-guards/README.md +++ b/fork-kit/agent-guards/README.md @@ -156,7 +156,10 @@ The installer ([sbin/agent-guards-install](sbin/agent-guards-install), on the sh [kit_install.py](../common/kit_install.py)) copies the release to `/usr/local/libexec/agent-guards/versions//`, self-tests the copy, and links `/usr/local/bin/`, `/usr/local/bin/agent-guards` and `/usr/local/bin/facts` to it. It is safe to run again and to stop at any step. `facts` is a common name: when `/usr/local/bin/facts` is something other than the kit's -link, the installer leaves it alone and says so (a warning; the install goes on, and uninstall does not remove it). +link, the installer leaves it alone and says so (a warning; the install goes on, and uninstall does not remove it or +wait for it to stop running). Installing a release from before `facts` was added leaves `/usr/local/bin/facts` as a +link to a file that is not there (`facts` then says "No such file") until a newer release is installed again or the +kit is uninstalled. `--settings` also writes the hooks' entries as a Claude Code **managed settings drop-in**, `/etc/claude-code/managed-settings.d/agent-guards.json`. Every Claude Code session of every user on the machine diff --git a/fork-kit/agent-guards/bin/facts b/fork-kit/agent-guards/bin/facts index 1df345df9a0d4..f984143a76697 100755 --- a/fork-kit/agent-guards/bin/facts +++ b/fork-kit/agent-guards/bin/facts @@ -65,6 +65,9 @@ def main(argv): projects = facts.projects_for(c, cwd) if not every else c['projects'] found = facts.places(c, cwd, every=every, projects=projects) # --records: only to skip their copies recs = [] if no_records or mode == '--check' else facts.records(c, projects, every) + if mode == '--records' and not recs: + print('note: no record repo is configured (machine file "agent-guards" part "facts": records)') + return 0 if not found and not recs: print(f'{PROG}: no state table is configured for this folder (machine file "agent-guards" part "facts": ' 'dirs, projects, records; or FACTS_DIRS)') @@ -93,9 +96,15 @@ def main(argv): lines = [] rec_notes = [] if recs and mode != '--index': - skip = {p.digest for p in found if p.digest} - more, rec_notes = facts.search_records(recs, words, skip, limit=50 if mode == '--records' else 10) - lines += more or ([f'Records: no line holds all of: {" ".join(words)}'] if not rec_notes else []) + skip = {p.digest: p.file for p in found if p.digest} + more, rec_notes, copies = facts.search_records(recs, words, skip, limit=50 if mode == '--records' else 10) + if more: + lines += more + elif copies: + lines += [f'Records: only copies of state tables hold all of: {" ".join(words)}; their rows: ' + f'`{PROG} --no-records {" ".join(words)}`'] + [f' {c} (a copy of {t})' for c, t in copies] + elif not rec_notes: + lines.append(f'Records: no line holds all of: {" ".join(words)}') for line in lines: print(line) for n in (facts.notes(found) if mode != '--records' else []) + rec_notes: diff --git a/fork-kit/agent-guards/lib/agent_guards/facts.py b/fork-kit/agent-guards/lib/agent_guards/facts.py index 5204e09ed5250..f7929d096430d 100644 --- a/fork-kit/agent-guards/lib/agent_guards/facts.py +++ b/fork-kit/agent-guards/lib/agent_guards/facts.py @@ -22,6 +22,8 @@ """ import datetime, hashlib, os, re, stat, subprocess, time +from .config import _NAME_RE as NAME_RE # one rule for a project's folder name + TABLE_FILE = 'STATE.md' CALL_TO_LOOK = 'check the state table before diagnosing or redoing something: `facts ` prints the matching rows' MAX_READ = 4 * 1024 * 1024 # a table file is read up to this, the rest is cut (and named) @@ -247,10 +249,13 @@ def projects_for(cfg, cwd): def project_name(p): """The project's folder under a record repo's projects folder: its "name", else the last part of its remote - or folder.""" + (without .git) or folder; None when that is not a plain folder name ("..", ".", empty).""" if p.get('name'): return p['name'] - return os.path.basename(_expand(p['match']).rstrip('/')) or None + name = os.path.basename(_expand(p['match']).rstrip('/')) + if not p['match'].startswith(('/', '~/')) and name.lower().endswith('.git'): + name = name[:-4] + return name if NAME_RE.match(name) else None def _same(entry): @@ -436,12 +441,21 @@ def records(cfg, projects, every=False): def _record_files(rec, deadline): """(path, relative path) of every text file to search in one record repo: its folders, .git and links left - out, in a sorted order. Stops at `deadline` (time.monotonic()).""" + out, in a sorted order. A folder whose real path is outside the repo (a link on the way) is left out. Stops at + `deadline` (time.monotonic()), checked for each folder and each file.""" + try: + real_root = os.path.realpath(rec.root) + except (OSError, ValueError): + return for folder in rec.folders: top = os.path.join(rec.root, folder) if os.path.islink(top) or not os.path.isdir(top): continue + if not os.path.realpath(top).startswith(real_root.rstrip('/') + '/'): + continue for d, dirs, files in os.walk(top): + if time.monotonic() > deadline: + return dirs[:] = sorted(x for x in dirs if x != '.git' and not os.path.islink(os.path.join(d, x))) for name in sorted(files): if time.monotonic() > deadline: @@ -451,12 +465,14 @@ def _record_files(rec, deadline): yield path, os.path.relpath(path, rec.root) -def search_records(recs, words, skip=(), limit=10, seconds=RECORD_SECONDS): - """(lines, notes): the lines of the record repos' text files that hold every word (any case), as +def search_records(recs, words, skip=None, limit=10, seconds=RECORD_SECONDS): + """(lines, notes, copies): the lines of the record repos' text files that hold every word (any case), as "path:line: text" under a "Records in :" line, at most `limit` hits and then "+N more". A file over - RECORD_MAX, not a regular file, or the same bytes as a table already shown (sha256 in `skip`) is skipped.""" - ws = _words(words) - lines, out_notes, shown, total = [], [], 0, 0 + RECORD_MAX, not a regular file, holding a NUL byte (not text), or with the same bytes as a table already read + (`skip`: {sha256: table file}) is skipped; copies: [(record file, table file)] for each such copy that holds the + words.""" + ws, skip = _words(words), skip or {} + lines, out_notes, copies, shown, total = [], [], [], 0, 0 deadline = time.monotonic() + seconds for rec in recs: if rec.note: @@ -465,13 +481,15 @@ def search_records(recs, words, skip=(), limit=10, seconds=RECORD_SECONDS): head = False for path, rel in _record_files(rec, deadline): data, cut, problem = read_regular(path, RECORD_MAX) - if problem or cut or data is None: - continue - if hashlib.sha256(data).hexdigest() in skip: + if problem or cut or data is None or b'\0' in data: continue + table = skip.get(hashlib.sha256(data).hexdigest()) for n, line in enumerate(data.decode('utf-8', errors='replace').split('\n'), 1): low = line.lower() if ws and all(w in low for w in ws): + if table: + copies.append((os.path.join(rec.root, rel), table)) + break total += 1 if shown < limit: if not head: @@ -484,7 +502,7 @@ def search_records(recs, words, skip=(), limit=10, seconds=RECORD_SECONDS): break if total > shown: lines.append(f'+{total - shown} more (facts --records {" ".join(words)})') - return lines, out_notes + return lines, out_notes, copies def record_line(recs): diff --git a/fork-kit/agent-guards/tests/facts.test.py b/fork-kit/agent-guards/tests/facts.test.py index 3276591a893a6..9d005d2c5e876 100644 --- a/fork-kit/agent-guards/tests/facts.test.py +++ b/fork-kit/agent-guards/tests/facts.test.py @@ -313,6 +313,13 @@ def test_project_names_for_the_record_repo(self): self.assertEqual(facts.project_name({'match': 'github.com/example/project'}), 'project') self.assertEqual(facts.project_name({'match': '/srv/example/notes/'}), 'notes') self.assertEqual(facts.project_name({'match': 'github.com/example/project', 'name': 'own'}), 'own') + # follow-up: a remote's .git is dropped; a match that ends in "." or ".." names no folder + self.assertEqual(facts.project_name({'match': 'github.com/example/project.git'}), 'project') + self.assertEqual(facts.project_name({'match': '/srv/example/notes.git'}), 'notes.git') + for bad in ('/srv/example/..', '/srv/example/.', '/', 'github.com/example/.git'): + self.assertIsNone(facts.project_name({'match': bad}), bad) + recs = facts.records({'records': [{'path': self.tmp}]}, [{'match': '/srv/example/..'}]) + self.assertEqual(recs[0].folders, ['machines', 'orch', 'shared']) class Command(unittest.TestCase): @@ -580,12 +587,77 @@ def test_dirs_lists_the_record_folders(self): def test_a_mirrored_table_is_skipped_by_its_bytes(self): found = [facts.read_place(self.place, 'test')] recs = facts.records({'records': [{'path': self.records}]}, [], every=True) - skip = {found[0].digest} + skip = {found[0].digest: found[0].file} self.assertEqual(found[0].digest, hashlib.sha256(TABLE.encode()).hexdigest()) - lines, notes = facts.search_records(recs, ['backup'], skip) + lines, notes, copies = facts.search_records(recs, ['backup'], skip) self.assertEqual((lines, notes), ([], [])) - lines, _ = facts.search_records(recs, ['backup'], set()) + self.assertEqual(copies, [(f'{self.records}/machines/box/STATE.md', found[0].file)]) + lines, _, copies = facts.search_records(recs, ['backup'], {}) self.assertIn('machines/box/STATE.md:', lines[1]) + self.assertEqual(copies, []) + + def test_records_only_a_copy_holds_the_words_and_says_which(self): + r = self.facts('--records', 'backup') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertNotIn('no line holds all of', r.stdout) + self.assertIn('Records: only copies of state tables hold all of: backup; their rows: ' + '`facts --no-records backup`', r.stdout) + self.assertIn(f' {self.records}/machines/box/STATE.md (a copy of {self.place}/STATE.md)', r.stdout) + r = self.facts('--records', 'nothing-like-this') + self.assertIn('Records: no line holds all of: nothing-like-this', r.stdout) + + def test_records_with_no_record_repo_configured_is_a_note(self): + self.configure(records=[]) + r = self.facts('--records', 'gpu') + self.assertEqual((r.returncode, r.stdout.strip()), + (0, 'note: no record repo is configured (machine file "agent-guards" part "facts": records)')) + os.unlink(os.path.join(self.place, 'STATE.md')) + self.assertEqual(self.facts('--records', 'gpu').returncode, 0) + + def test_a_folder_that_leads_out_of_the_repo_is_not_searched(self): + outside = os.path.join(self.tmp, 'outside') + write(f'{outside}/proj/secret.md', 'gpu outside the repo\n') + write(f'{outside}/elsewhere.md', 'gpu outside too\n') + os.rename(f'{self.records}/projects', f'{self.tmp}/old-projects') + os.symlink(outside, f'{self.records}/projects') # projectsDir is a link out of the repo + os.symlink(outside, f'{self.records}/orch-link') + recs = facts.records({'records': [{'path': self.records, 'shared': ['shared', 'orch-link']}]}, + [{'match': self.proj, 'name': 'proj'}]) + lines, notes, _ = facts.search_records(recs, ['gpu']) + self.assertTrue(lines and notes == [], (lines, notes)) + self.assertNotIn('outside', '\n'.join(lines)) + self.assertIn('shared/runbook.txt:1:', '\n'.join(lines)) + linked = os.path.join(self.tmp, 'linked-records') # the repo itself reached by a link: searched + os.symlink(self.records, linked) + lines, _, _ = facts.search_records(facts.records({'records': [{'path': linked}]}, []), ['gpu']) + self.assertIn('shared/runbook.txt:1:', '\n'.join(lines)) + + def test_a_file_with_a_nul_byte_is_not_text(self): + write(f'{self.records}/shared/blob.json', b'gpu\x00binary\n', 'wb') + lines, _, _ = facts.search_records(facts.records({'records': [{'path': self.records}]}, []), ['gpu']) + self.assertNotIn('blob.json', '\n'.join(lines)) + self.assertIn('runbook.txt', '\n'.join(lines)) + + def test_the_time_limit_is_checked_for_each_folder_too(self): + for k in range(30): + os.makedirs(f'{self.records}/shared/empty/{k:02}') # folders with no files: no file-level check + seen = [] + real_walk = os.walk + + def walk(top, *a, **kw): + for d, dirs, files in real_walk(top, *a, **kw): + seen.append(d) + yield d, dirs, files + clock = iter(range(0, 10 ** 6, 1)) + old_walk, old_time = facts.os.walk, facts.time.monotonic + facts.os.walk, facts.time.monotonic = walk, lambda: next(clock) + try: + recs = facts.records({'records': [{'path': self.records, 'shared': ['shared']}]}, []) + _lines, notes, _ = facts.search_records(recs, ['gpu'], seconds=5) + finally: + facts.os.walk, facts.time.monotonic = old_walk, old_time + self.assertLess(len(seen), 10, seen) + self.assertIn('search stopped after 5 s', notes[0]) if __name__ == '__main__': diff --git a/fork-kit/agent-guards/tests/install.test.py b/fork-kit/agent-guards/tests/install.test.py index 53422c4b7c8a4..97a118235d290 100644 --- a/fork-kit/agent-guards/tests/install.test.py +++ b/fork-kit/agent-guards/tests/install.test.py @@ -125,7 +125,9 @@ def test_an_unrelated_facts_command_is_left_alone_and_our_own_link_is_kept(self) self.assertTrue(self.is_file('/usr/local/bin/facts-hook')) self.assertEqual(self.run_main('self-check')[0], 0) self.assertEqual(self.install(sha=SHA2)[0], 0) - self.assertEqual(self.run_main('uninstall')[0], 0) + self.process(4242, '/bin/sh', '/usr/local/bin/facts', 'x') # the other program running: not our code + code, _, err = self.run_main('uninstall') + self.assertEqual(code, 0, err) with open(self.path('/usr/local/bin/facts')) as f: self.assertEqual(f.read(), '#!/bin/sh\necho another program\n') os.unlink(self.path('/usr/local/bin/facts')) @@ -136,6 +138,10 @@ def test_an_unrelated_facts_command_is_left_alone_and_our_own_link_is_kept(self) self.assertEqual(self.install(sha=SHA2)[0], 0) self.assertTrue(os.path.islink(self.path('/usr/local/bin/facts'))) self.assertTrue(self.is_file('/usr/local/bin/facts')) + self.process(4243, '/usr/bin/python3', '/usr/local/bin/facts', 'x') # our link running: uninstall waits + code, _, err = self.run_main('uninstall') + self.assertEqual(code, 1) + self.assertIn('code of this kit is in use', err) def test_runs_again_and_changes_nothing(self): self.assertEqual(self.install('--settings')[0], 0) diff --git a/fork-kit/common/kit_install.py b/fork-kit/common/kit_install.py index 4e2968868b80c..be500b6369dfa 100644 --- a/fork-kit/common/kit_install.py +++ b/fork-kit/common/kit_install.py @@ -612,12 +612,13 @@ def _uninstall(self): def code_paths(self): """The paths a command line or a unit names when it runs this kit's code: / (and its real path, where /usr/local or a folder in it is a link: the kit's runs name the real path of their version), and the kit's - links.""" + links (not an OPTIONAL_LINKS path where another program is: running that is not this kit's code).""" roots = {self.LIBEXEC} real = os.path.realpath(self.p(self.LIBEXEC)) if real.startswith(self.PREFIX + '/'): roots.add(real[len(self.PREFIX):]) - return tuple(os.fsencode(r + '/') for r in sorted(roots)), {os.fsencode(p) for p in self.LINKS} + return (tuple(os.fsencode(r + '/') for r in sorted(roots)), + {os.fsencode(p) for p, t in self.links().items() if not self.foreign(p, t)}) @staticmethod def _norm(arg, cwd):