diff --git a/.github/fork-ci-tests.txt b/.github/fork-ci-tests.txt index ed6d9a07306c0..7ff70516a55cd 100644 --- a/.github/fork-ci-tests.txt +++ b/.github/fork-ci-tests.txt @@ -107,6 +107,7 @@ fork-kit/agent-guards/tests/agent-slots.test.py unittest fork-kit/agent-guards/tests/bg-guard.test.py unittest fork-kit/agent-guards/tests/capacity-pipe.test.py unittest fork-kit/agent-guards/tests/config.test.py unittest +fork-kit/agent-guards/tests/facts.test.py unittest fork-kit/agent-guards/tests/install.test.py ~20s unittest fork-kit/agent-guards/tests/memory-index.test.py unittest fork-kit/agent-guards/tests/wiring.test.py unittest diff --git a/fork-kit/agent-guards/FACTS.md b/fork-kit/agent-guards/FACTS.md new file mode 100644 index 0000000000000..ae5d7311670bf --- /dev/null +++ b/fork-kit/agent-guards/FACTS.md @@ -0,0 +1,159 @@ +# facts: one state table per place, looked up instead of re-derived + +After a compaction, a handoff or a new session, an agent does not know what was already made and why things are the +way they are. It spends usage finding out again, and sometimes gets it wrong: it calls a part broken that was set up +and switched off on purpose the day before. The answer is short and usually known. A **state table** holds it, one row +per thing, and the agent reads it before it starts. + +Part of the agent-guards kit: the `facts` command, the `facts-hook` hook, and the `"facts"` part of the machine file's +`"agent-guards"` section. Python 3 standard library only; read only, it never writes a table. After the tables, +`facts ` also searches a record repo (a private checkout of notes), when one is configured. + +## The table + +One Markdown file per place (a machine, a project, the fork's own features), named `STATE.md` by default. Its table's +header starts with `Thing`; one row per thing: + +```markdown +# What we have and how it is now (one row per thing; edit the row when it changes) + +| Thing | What we made / how to use it | State now | Why | Updated | +| ----------- | ------------------------------------------------ | ------------------------------------------ | ---------- | ------- | +| Example GPU | `gpu on\|off\|status` helper; turned off at boot | OFF on purpose; the vendor tool fails then | Quiet fans | 11-23 | +| Example job | `job-ctl start\|stop`; runs nightly at 02:00 | Paused until the disk is replaced | Disk alarm | 11-20 | +``` + +- **Thing**: the name an agent would search for. Put the words it would use (the part, the service, the feature). +- **What we made / how to use it**: the helper, unit, script or setting, and how to run it. +- **State now**: the current state, and what is normal in it (the known wrong conclusion: "fails while off: not + broken"). +- **Why**: the reason, in a few words. +- **Updated**: `MM-DD` (the latest such date not more than a day ahead: this year, last year, or for `02-29` the last + leap year) or `YYYY-MM-DD`, each with any text after it (`11-23 (checked)`). + +Current state only: no history (that is in git and the issues) and no long documents. Only the first column (`Thing`) +and the `Updated` column (found by its name) mean something to the code; the other columns are free text, and a table +may have more or fewer of them. A `|` inside a cell is written `\|`. The line under the header may be short (`|-|-|`) +or aligned (`|:-:|`). Other text and other tables in the file are skipped; a file may hold more than one state table, +and a second header row ends one table and starts the next. Only a regular file is read (a FIFO or a device is a note, +never opened to wait), up to 4 MB (the note says where it was cut); bytes that are not UTF-8 are replaced. + +**Upkeep rule:** a change that alters a thing's state edits its row in the same change (the same commit, the same +turn). A new thing gets a row when it is made; a thing that is gone loses its row. + +## Where the tables are + +The machine file's `"agent-guards"` section, part `"facts"` ([README.md](README.md), Settings). Every key is optional; +with none, the hook and the command do nothing. + +| Key | Default | What it is | +| ------------ | ------- | ------------------------------------------------------------------------------------------------ | +| `dirs` | `[]` | Tables for every session on the machine: a table file, or a folder whose `STATE.md` is the table | +| `projects` | `[]` | `{"match", "dirs", "text", "name"}`: more tables, and a line of text, for one project's sessions | +| `staleDays` | `30` | The gardener's check reports a row whose `Updated` is older | +| `maxRows` | `60` | The gardener's check reports a table with more rows | +| `indexLines` | `40` | Things the session-start hook shows at most | +| `indexChars` | `4000` | Characters of the whole session-start context at most (project text and record line included) | +| `records` | `[]` | `{"path", "projectsDir", "shared"}`: record repos that `facts ` searches after the tables | + +A project's `match` is its remote as `host/owner/repo` (compared with the checkout's `origin` remote, any spelling: +https, ssh, `.git`), or a folder (the session's folder is that one or below it). Never a glob over a shared worktrees +folder: a linked worktree of the project matches by its remote, a worktree of another project does not. A folder that +is not a checkout, a git that does not answer within 2 s, or a worktree removed while the hook runs: no project +matches, the machine's tables are still shown. The same place named twice (a link to it, a `~/` spelling, a trailing +`/`) is read once. + +```json +"agent-guards": { + "facts": { + "dirs": ["/etc/fork-kit/facts"], + "projects": [ + { "match": "github.com/example/project", "dirs": ["/srv/example/project-facts"], "text": "" }, + { "match": "/srv/example/notes-project", "dirs": ["/srv/example/notes-project/facts"], "name": "notes" } + ], + "records": [ + { "path": "/srv/example/records", "projectsDir": "projects", "shared": ["machines", "orch", "shared"] } + ] + } +} +``` + +Facts live where the thing lives: a machine's table beside the machine file, a project's table in the project (a +private project keeps it private), the fork's feature table in the fork's own project. The kit ships only the tool, +the format and the hook. + +`FACTS_DIRS` (paths joined by `:`) replaces both lists for one command or session: for a test, or a look at another +place's table. It does not change the record repos. + +## The record repo + +A record repo is a checkout of notes laid out by place: `projects//` for each project, and shared folders (by +default `machines/`, `orch/` and `shared/`). `facts ` searches it after the tables: the lines of its text files +(`.md`, `.txt`, `.json`, `.yml`, `.yaml`, `.sh`) that hold every word, as `path:line: text` (at most 160 characters), +at most 10, then `+N more (facts --records )`. It searches the shared folders and the folder of this session's +project only (`projectsDir/`, where `name` is the project's `"name"`, else the last part of its remote or +folder); with `--all`, every project's folder. + +Skipped: `.git`, links, files over 1 MiB, files that are not regular, and a file with the same bytes as a table already +read (a mirrored copy of a `STATE.md` is not shown twice). The search is a Python file walk that stops after 10 s and +says so. A record repo that is not there or cannot be read is one `note:` line in the command; the hook says nothing +of it. + +## The command + +```sh +facts gpu # the rows that hold every word (any case), with their table's header; Thing hits first +facts example job paused # no row holds all of them: the rows with some, and it says so +facts --index # every thing, one per line, under its table file +facts --dirs # where it looked: each entry, where it was configured, what it found +facts --records fan curve # the record repo only, at most 50 lines +facts --no-records gpu # the tables only +facts --check # the gardener's check of this folder's tables (report only), exit 1 when it finds something +facts --all job # also every other project's tables and record folders +facts --check --all # the check of every project's tables +``` + +**Never post `--all` output (or `--check --all`) to a public place** (an issue, a PR, a chat): it names the things of +every configured project, private ones too. Without `--all` the command reads the machine's tables and this folder's +project's only. + +A missing file or folder, a folder with no `STATE.md`, a file with no state table, or a row whose cell count differs +from the header's is a `note:` line: the rest is still shown, and a broken row is still listed and searched. + +## The hook + +`facts-hook`, wired like the kit's other hooks (`agent-guards hooks`, or the installer's managed settings drop-in): + +- **SessionStart** (startup, resume, clear, and after compaction): adds context: the `Thing` column of every table + configured for the session (at most `indexLines` things) and "Check the state table before diagnosing or redoing + something: `facts ` prints the matching rows". Then the project's `text`, and one line naming each record + repo that is there (`Records: (facts searches it)`; never its content). All of it in at most + `indexChars` characters: when the things are cut, the last one is followed by `+N more: run facts --index`. +- **PreCompact**: adds to the compaction instructions: keep only the names of the things looked up or changed, not + their rows (they are read again after compaction), and mark a thing whose row was not edited yet. + +No table with a row for the session and no record repo, or any other event: nothing. A broken `"facts"` part: the +defaults (nothing shown) and a note, as for every hook of the kit. It never fails a session: every error is caught, +git is asked at most once with a 2 s timeout, and the record repo is only checked to be there. + +## The gardener's check + +`facts --check` reads the tables of this folder (the machine's and this folder's project's; every project's with +`--all`) and reports, changing nothing. It never reads the record repo. + +- a row whose `Updated` is older than `staleDays`, is more than a day in the future, or has no date it can read; +- a table with no `Updated` column, or with more than `maxRows` rows; +- a row whose cell count differs from the header's, or a header with no `|---|` line; +- an entry that is not there, a folder with no `STATE.md`, a file with no state table. + +A daily gardener (a timer, or a project's own garden job) runs it and passes on what it prints; that wiring is a +separate change. + +## Tests + +[tests/facts.test.py](tests/facts.test.py): the table reader (escaped pipes, a broken row, a header with no `|---|` +line, short separators, a second header, two tables in one file, a FIFO, bytes that are not UTF-8, a cut file), +search, the index and the character cap, a missing and an empty folder, `Updated` dates (across the year's end, +`02-29`, a suffix, the future), project matching by remote and folder (a git that hangs or fails, asked once), the +record repo search, `--check` with and without `--all`, and the hook's answers. Dates are fixed in the tests +(`FACTS_TODAY`), so they do not depend on the day they run. diff --git a/fork-kit/agent-guards/README.md b/fork-kit/agent-guards/README.md index 376a1e615647f..ddd4d82a44904 100644 --- a/fork-kit/agent-guards/README.md +++ b/fork-kit/agent-guards/README.md @@ -1,7 +1,7 @@ # agent-guards: Claude Code hooks that guard every agent on a machine -Five Claude Code hooks. Each one stops one mistake that agents made on a shared machine, at the moment they make it. -A line in the agents' instructions did not stop any of them. The hooks are general: a project gives only its facts +Six Claude Code hooks and a lookup command. Each hook stops one mistake that agents made on a shared machine, at +the moment they make it. A line in the agents' instructions did not stop any of them. The hooks are general: a project gives only its facts (file paths, a command name, a budget) in the machine file's `"agent-guards"` section. Linux, Python 3 standard library only. One file per hook in [bin/](bin/), the shared parts in @@ -16,16 +16,18 @@ Linux, Python 3 standard library only. One file per hook in [bin/](bin/), the sh | `memory-index-guard` | PreToolUse (`Write\|Edit\|MultiEdit`) and PostToolUse (`Write\|Edit\|MultiEdit\|Bash\|Monitor`), 5 s | An auto-memory index (`/memory/MEMORY.md`) over its budget: a write that would make it too big (Pre), or one that did, through any tool (Post, once per change) | Passes (exit 1, with a line) | | `bg-guard` | Stop, 5 s | Ending a turn while a Bash command the agent started in the background still runs (the end of it may never wake the agent). At most `maxBlocks` times per session | Passes (exit 1, with a line) | | `agent-slots` | UserPromptSubmit and Stop, 5 s | Only for the orchestrator sessions listed in `sessionsFile`: adds "agents alive, slots free, ready queue" as context; blocks a stop once while slots are free and the ready queue has items | Passes (exit 1, with a line) | +| `facts-hook` | SessionStart and PreCompact, 5 s | Nothing; it adds context: at session start the things in the state tables for the session and "check the state table before diagnosing or redoing something" (`facts `); before compaction, keep the things' names, not their rows. See [FACTS.md](FACTS.md) | Passes (exit 1, "the state tables are NOT shown") | How each hook answers is what Claude Code reads: PreToolUse refuses with exit 2 and the reason on stderr. PostToolUse -and Stop block with `{"decision": "block", "reason": ...}` on stdout. UserPromptSubmit adds `additionalContext`. +and Stop block with `{"decision": "block", "reason": ...}` on stdout. UserPromptSubmit and SessionStart add `additionalContext`; PreCompact +prints text that is added to the compaction instructions. Exit 0 with nothing on stdout means pass. The messages and exit codes are the same as these hooks had before they moved into this kit, so an agent sees no change. Each hook's file says what it reads and what it does not, and where its tests are. **Why one fails closed and the others open.** `actions-disable-guard` guards against a step that cannot be undone by an agent (Actions turned off on a repo). If it is gone or broken, refusing every Bash command is the safe answer, -and the message says so. The other four guard mistakes. Refusing every call because a helper is gone would stop all +and the message says so. The other five guard mistakes or only add context. Refusing every call because a helper is gone would stop all work on the machine. The settings entry does both (`agent-guards hooks` prints it): ```sh @@ -102,7 +104,7 @@ These are the values the hooks had before. The file is `/etc/fork-kit/machine.js ([common/machine_file.py](../common/machine_file.py): owned by root, not writable by others, so an agent cannot change a guard's facts). Each hook reads only its own part (`actionsDisable`, `capacityPipe`, ...). A key in it that is broken (a wrong type, a bad path) keeps its default; an unknown key is ignored; a bad `refuseScripts` row is -dropped and the good rows kept. The hook says so to the agent (a `systemMessage`, and context for PreToolUse) and on +dropped and the good rows kept (the same for a bad `facts.projects` or `facts.records` row). The hook says so to the agent (a `systemMessage`, and context for PreToolUse) and on stderr, on every call it handles, until the file is fixed: loud on purpose. A Bash call can carry the note more than once, once from each hook that has a problem in its part (`actionsDisable` and `capacityPipe` before it, `memoryIndex` after it). A broken or unknown part of another hook changes nothing for it. `agent-guards self-check` @@ -125,6 +127,13 @@ checks the whole section strictly and names every problem. | `agentSlots.maxAlive` | `10` | Agent processes at most | | `agentSlots.processName` | `"claude"` | The process name that is counted | | `agentSlots.note` | `""` | Extra text for the context line (a build-agent limit, say) | +| `facts.dirs` | `[]` | State tables for every session: a table file, or a folder whose `STATE.md` is the table ([FACTS.md](FACTS.md)) | +| `facts.projects` | `[]` | `{"match", "dirs", "text", "name"}`: more tables for one project (`match`: its remote as `host/owner/repo`, or a folder; `name`: its record folder) | +| `facts.staleDays` | `30` | `facts --check` reports a row whose `Updated` is older | +| `facts.maxRows` | `60` | `facts --check` reports a table with more rows | +| `facts.indexLines` | `40` | Things the session-start context shows at most | +| `facts.indexChars` | `4000` | Characters of the whole session-start context at most | +| `facts.records` | `[]` | `{"path", "projectsDir", "shared"}`: record repos that `facts ` searches after the tables ([FACTS.md](FACTS.md)) | Paths are absolute or start with `~/` (the home of the user the hook runs as). An example is in [machine.example.json](../common/machine.example.json). @@ -132,7 +141,7 @@ Paths are absolute or start with `~/` (the home of the user the hook runs as). A **State and logs.** Each hook keeps going when its state folder or log cannot be written (a full disk, a folder that is not writable): the answer never depends on it. `memory-index-guard` writes its state whole (a temporary file, then a rename). `bg-guard` counts under a lock, so two Stop hooks at once count two blocks. -`actions-disable-guard` appends one line per refusal. `agent-slots` writes nothing. +`actions-disable-guard` appends one line per refusal. `agent-slots` and `facts-hook` write nothing. ## Install @@ -145,8 +154,9 @@ sh fork-kit-bootstrap.sh --kit agent-guards --repo OWNER/FORK --sha RELEASE_SHA The installer ([sbin/agent-guards-install](sbin/agent-guards-install), on the shared [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/` and `/usr/local/bin/agent-guards` to it. It is safe to run -again and to stop at any step. +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). `--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 @@ -189,8 +199,9 @@ what it names: root-owned, not writable by group or others, no link on the way. ## General vs project Everything in this kit is general. What a project or a machine adds is only its facts in the machine file: the -capacity command's name, the memory budget, the orchestrator's session file and queue, and a script of its own that -must not run with a given flag. Nothing in the hooks names a project, a person or a path of one machine. +capacity command's name, the memory budget, the orchestrator's session file and queue, a script of its own that +must not run with a given flag, and where its state tables are. The tables themselves live with the machine or the +project they describe, never in the kit. Nothing in the hooks names a project, a person or a path of one machine. ## Tests diff --git a/fork-kit/agent-guards/bin/facts b/fork-kit/agent-guards/bin/facts new file mode 100755 index 0000000000000..1df345df9a0d4 --- /dev/null +++ b/fork-kit/agent-guards/bin/facts @@ -0,0 +1,107 @@ +#!/usr/bin/python3 -IB +"""facts: look up what we made for a thing and its state now, in the state tables (fork-kit/agent-guards/FACTS.md), +then in the record repo. + + facts WORDS... the table rows that hold every word (any case), with their table's header; Thing-column + hits first. No row with all of them: the rows with some, and it says so. Then the lines + of the record repo's text files that hold every word (at most 10) + facts --records WORDS... only the record repo's lines (at most 50) + facts --index every thing, one per line, under its table file + facts --dirs where it looked: each configured entry and record repo, and what it found + facts --check the gardener's check of this folder's tables, report only: rows whose Updated is older + than staleDays (or has no date, or is in the future), tables over maxRows rows, broken + rows, entries that are missing or empty (exit 1 when any). Never reads the record repo + --all every configured project's tables (and record repo folders) too, not only the machine's + and this folder's project's. Its output may name private projects: never post it to a + public place + --no-records tables only + +The tables come from the machine file's "agent-guards" section, part "facts" (dirs, projects, records); FACTS_DIRS +(paths joined by ":") replaces dirs and projects. A missing or empty folder, or a broken row, is a note: the rest is +still shown. Read only. Tests: fork-kit/agent-guards/tests/facts.test.py +""" +import datetime, os, sys + +_kit = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +sys.path.insert(0, os.path.join(_kit, 'lib')) + +PROG = 'facts' +FLAGS = ('--all', '--no-records') +MODES = ('--index', '--dirs', '--check', '--records') + + +def today(): + """Today; FACTS_TODAY (YYYY-MM-DD) sets it, for tests.""" + try: + return datetime.date.fromisoformat(os.environ['FACTS_TODAY']) + except (KeyError, ValueError): + return datetime.date.today() + + +def main(argv): + if not argv or argv[0] in ('-h', '--help'): + print(__doc__.strip()) + return 0 if argv else 1 + from agent_guards import config, facts + every, no_records = '--all' in argv, '--no-records' in argv + argv = [a for a in argv if a not in FLAGS] + modes = [a for a in argv if a in MODES] + words = [a for a in argv if a not in modes] + bad = [a for a in words if a.startswith('--')] + needs_words = modes in ([], ['--records']) + if len(modes) > 1 or bad or (needs_words and not words) or (not needs_words and words) \ + or (no_records and modes == ['--records']): + print(f'{PROG}: use one of: WORDS..., --records WORDS..., --index, --dirs, --check (and --all, ' + f'--no-records); see {PROG} --help', file=sys.stderr) + return 1 + c, problem = config.load('facts') + if problem: + print(f'note: {config.problem_text(PROG, problem)}') + mode = modes[0] if modes else None + try: + cwd = os.getcwd() + except OSError: + cwd = '' + 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 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)') + return 0 + if mode == '--dirs': + for p in found: + what = (f'{len(p.rows())} rows in {len(p.tables)} table(s)' if p.tables else + '; '.join(p.notes) or 'no table') + print(f'{p.entry} ({p.source}): {p.file or "-"}: {what}') + for r in recs: + print(f'{r.root} (record repo): {r.note or "searched: " + ", ".join(r.folders)}') + return 0 + if mode == '--check': + out = facts.check(found, c['staleDays'], c['maxRows'], today()) + for line in out: + print(f'{PROG} check: {line}') + rows = sum(len(p.rows()) for p in found) + print(f'{PROG} check: ' + (f'{len(out)} finding(s)' if out else + f'OK ({sum(1 for p in found if p.tables)} table file(s), {rows} rows)')) + return 1 if out else 0 + if mode == '--index': + lines = facts.index(found) + elif found and mode != '--records': + lines = facts.search(found, words) + else: + 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 []) + for line in lines: + print(line) + for n in (facts.notes(found) if mode != '--records' else []) + rec_notes: + print(f'note: {n}') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/fork-kit/agent-guards/bin/facts-hook b/fork-kit/agent-guards/bin/facts-hook new file mode 100755 index 0000000000000..ead4170a2ac8b --- /dev/null +++ b/fork-kit/agent-guards/bin/facts-hook @@ -0,0 +1,102 @@ +#!/usr/bin/python3 -IB +"""Claude Code hook: show the state tables' things at session start, and keep them out of compaction summaries. +Part of fork-kit/agent-guards (README.md there: install, settings entries, the machine file's "agent-guards" +section; the table format and the `facts` command: FACTS.md there). + +SessionStart (startup, resume, clear and after compaction): adds context: the Thing column of every state table +configured for this session (the machine's, and the project's the session's folder belongs to), at most indexLines +things, "check the state table before diagnosing or redoing something", the project's text, and one line naming the +record repo when one is configured and there ("Records: (facts searches it)"; never its content). +All of it in at most indexChars characters ("+N more: run facts --index" when cut). +PreCompact: prints the compaction instructions' part: keep the things' names, not their rows. +Every other event, or no table with a row: nothing. Read only: it writes nothing, so two at once need no lock. + +General (any project, any Claude config dir). Project facts come from the machine file (facts): + dirs table files or folders holding STATE.md, for every session (default []: the hook does nothing) + projects [{"match": "host/owner/repo" or a folder, "dirs": [...], "text": "..."}]: more tables and text for + the sessions of one project, matched by the checkout's origin remote or the folder, never a glob + indexLines things shown at most (default 40) + indexChars characters of the whole answer at most (default 4000) + records [{"path": ..., "projectsDir": "projects", "shared": [...]}]: record repos (only named here) +Never fails a call because of its own error: every error is caught, git is asked once with a 2 s timeout, and +the record repo is only checked to be there (no walk). A broken machine file section: the defaults (so it does +nothing) and one line on stderr. Tests: fork-kit/agent-guards/tests/facts.test.py +""" +import json, os, sys + +NAME = 'facts-hook' + + +def _settings(): + """(facts settings, problem or None); a copy without the kit's lib keeps the defaults and says so.""" + try: + sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) + from agent_guards import config + return config.load('facts') + except BaseException as e: # noqa: BLE001 + return ({'dirs': [], 'staleDays': 30, 'maxRows': 60, 'indexLines': 40, 'indexChars': 4000, 'projects': [], + 'records': []}, + f'cannot load the kit\'s config code ({type(e).__name__}: {e})') + + +def decide(data, c): + if not isinstance(data, dict): + return None, None + event = data.get('hook_event_name', '') + if event not in ('SessionStart', 'PreCompact'): + return None, None + from agent_guards import facts + cwd = data.get('cwd') if isinstance(data.get('cwd'), str) else '' + projects = facts.projects_for(c, cwd) # git at most once + found = facts.places(c, cwd, projects=projects) + if event == 'SessionStart': + text = facts.session_text(found, projects, c['indexLines'], c['indexChars'], facts.records(c, projects)) + return ({'hookSpecificOutput': {'hookEventName': 'SessionStart', 'additionalContext': text}} if text + else None), None + return None, facts.compact_text(found, projects, c['indexChars']) or None + + +def _notice(problem, event, out): + """`out` with a config problem added where the agent and the owner see it (and one line on stderr).""" + if not problem: + return out + try: + from agent_guards import config + config.warn(NAME, problem) + return config.notice(NAME, problem, event, out) + except BaseException: # noqa: BLE001 - no lib: say it plainly + text = f'{NAME}: {problem}; built-in defaults used. Tell the owner.' + try: + sys.stderr.write(text + '\n') + except Exception: # noqa: BLE001 + pass + return dict(out or {}, systemMessage=text) + + +def main(): + if sys.argv[1:]: + sys.stderr.write('usage: facts-hook (hook: SessionStart or PreCompact JSON on stdin)\n') + return 1 + event, problem, out, text = None, None, None, None + try: + c, problem = _settings() + event = json.load(sys.stdin) + out, text = decide(event, c) + except Exception: # never break a session because of this hook + out, text = None, None + if text: # PreCompact: plain text, which Claude Code adds to the compaction instructions + if problem: + _notice(problem, event, None) + print(text) + return 0 + try: + out = _notice(problem, event, out) + except Exception: # noqa: BLE001 + pass + if out: + print(json.dumps(out)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/fork-kit/agent-guards/lib/agent_guards/__init__.py b/fork-kit/agent-guards/lib/agent_guards/__init__.py index aa312933e1799..505a9baec6bcc 100644 --- a/fork-kit/agent-guards/lib/agent_guards/__init__.py +++ b/fork-kit/agent-guards/lib/agent_guards/__init__.py @@ -3,4 +3,5 @@ config the facts of the hooks, from the machine file's "agent-guards" section, with safe defaults wiring the hooks' settings entries (Claude Code managed settings drop-in, or any settings file) check run the wired hooks with one case each hook must refuse and one it must pass + facts the state tables: read, search, index, the gardener's check (bin/facts, bin/facts-hook; FACTS.md) """ diff --git a/fork-kit/agent-guards/lib/agent_guards/check.py b/fork-kit/agent-guards/lib/agent_guards/check.py index 6a2762b03ecbe..70dfe5e008076 100644 --- a/fork-kit/agent-guards/lib/agent_guards/check.py +++ b/fork-kit/agent-guards/lib/agent_guards/check.py @@ -2,18 +2,20 @@ event it must refuse (block) and one it must let through, the way Claude Code runs it (`/bin/sh -c COMMAND`, the event on stdin), and the entry's matcher must take the case's tool (Bash, Monitor, Write). Nothing of the machine is changed: the memory index and the session ids are made up in a temporary folder, the hooks run with HOME there (so -the "~/" state folders, the refusal log and the cache are written there and removed with it; agent-slots keeps the -real HOME, it writes nothing), and the state files a hook writes in a configured absolute folder for those made-up -sessions are removed afterwards. +the "~/" state folders, the refusal log and the cache are written there and removed with it; agent-slots and +facts-hook keep the real HOME: they write nothing, and their "~/" paths must mean what the wanted answer read), and +the state files a hook writes in a configured absolute folder for those made-up sessions are removed afterwards. A hook that is not wired is reported as MISSING (a problem); agent-slots with no sessionsFile only gets its pass -case (it does nothing for any session then). +case (it does nothing for any session then); facts-hook wants context when the machine has a state table with a row +or a record repo for the check's folder, else nothing. """ import json, os, shutil, signal, subprocess, tempfile -from . import config, wiring +from . import config, facts, wiring SESSION = 'agent-guards-check-' +READ_ONLY = ('agent-slots', 'facts-hook') # hooks that write nothing: run with the caller's HOME def _run(cmd, event, cwd, env=None, argv=None, timeout=30): @@ -115,6 +117,13 @@ def write(content): ('agent-slots', 'Stop', 'a session it does not watch', {'hook_event_name': 'Stop', 'session_id': sid}, 'passed', None), ] + fc = config.load('facts')[0] # read only: the machine's own tables and record repos, if any; the hook + projects = facts.projects_for(fc, tmp) # runs with this process's HOME (READ_ONLY), so "~/" means the same + text = facts.session_text(facts.places(fc, tmp, projects=projects), projects, fc['indexLines'], + fc['indexChars'], facts.records(fc, projects)) + out.append(('facts-hook', 'SessionStart', 'a new session', + {'hook_event_name': 'SessionStart', 'source': 'startup', 'session_id': sid, 'cwd': tmp}, + 'context' if text else 'passed', None)) slots = config.load('agentSlots')[0] watched = [] try: @@ -160,7 +169,7 @@ def run(settings, source, say=print): bad += 1 say(f'MISSING {hook} ({event}{", " + tool if tool else ""}): not wired in {source}') continue - env = dict(os.environ, HOME=home) if hook != 'agent-slots' else dict(os.environ) + env = dict(os.environ, HOME=home) if hook not in READ_ONLY else dict(os.environ) if how: env.update(AG_EVENT=json.dumps(ev), AG_HOOK=cmd) r = _run(cmd, ev, tmp, env=env, argv=[fake, '-c', scripts[how]]) diff --git a/fork-kit/agent-guards/lib/agent_guards/config.py b/fork-kit/agent-guards/lib/agent_guards/config.py index 1c031bf964836..fb7e194cb6551 100644 --- a/fork-kit/agent-guards/lib/agent_guards/config.py +++ b/fork-kit/agent-guards/lib/agent_guards/config.py @@ -3,9 +3,10 @@ Every key is optional; a missing machine file or section gives the built-in defaults below (the values the hooks had before they moved into this kit). Each hook reads only its own part, key by key: a top-level key no hook knows (a later kit's section) or another hook's broken part changes nothing for it; a bad key of its own keeps that key's -default, an unknown key of its own is ignored, a bad refuseScripts row is left out (each of these is named). A broken file never weakens a guard below the defaults: the hook uses them and names the problem in its -answer (systemMessage, and additionalContext where the event takes it) and on stderr. `agent-guards self-check` -names every problem, unknown keys too. +default, an unknown key of its own is ignored, a bad refuseScripts, facts.projects or facts.records row is left out +(each of these is named). A broken file never weakens a guard below the defaults: the hook uses them and names the +problem in its answer (systemMessage, and additionalContext where the event takes it) and on stderr. +`agent-guards self-check` names every problem, unknown keys too. "agent-guards": { "actionsDisable": {"stateDir": "~/.local/state/actions-disable-guard", @@ -14,7 +15,12 @@ "memoryIndex": {"maxChars": 6000, "maxLine": 160, "stateDir": "~/.cache/memory-index-guard"}, "bgGuard": {"skipSessionsFiles": [], "maxBlocks": 3, "stateDir": "~/.local/state/bg-guard"}, "agentSlots": {"sessionsFile": "", "queue": "", "readyHeading": "## Ready", "maxAlive": 10, - "processName": "claude", "note": ""} + "processName": "claude", "note": ""}, + "facts": {"dirs": [], "staleDays": 30, "maxRows": 60, "indexLines": 40, "indexChars": 4000, + "projects": [{"match": "github.com/owner/repo", "dirs": ["/srv/repo-facts"], "text": "", + "name": "repo"}], + "records": [{"path": "/srv/records", "projectsDir": "projects", + "shared": ["machines", "orch", "shared"]}]} } Paths are absolute or start with "~/" (each user's own home). Plain Python 3 standard library. @@ -62,6 +68,22 @@ def _commands(value): return None +def _projects(value): + for k, v in enumerate(value): + p = _project_problem(k, v) + if p: + return p + return None + + +def _records(value): + for k, v in enumerate(value): + p = _record_problem(k, v) + if p: + return p + return None + + def _scripts(value): for k, v in enumerate(value): p = _row_problem(k, v) @@ -96,6 +118,15 @@ def _scripts(value): 'processName': (str, 'claude', lambda v: None if COMMAND_RE.match(v) else 'must be a process name'), 'note': (str, '', None), }, + 'facts': { + 'dirs': (list, [], _paths), + 'staleDays': (int, 30, _positive), + 'maxRows': (int, 60, _positive), + 'indexLines': (int, 40, _positive), + 'indexChars': (int, 4000, _positive), + 'projects': (list, [], _projects), + 'records': (list, [], _records), + }, } HOOKS = tuple(SPEC) @@ -117,6 +148,46 @@ def _row_problem(k, v): return None +def _project_problem(k, v): + """The problem of one facts.projects row, or None.""" + if not isinstance(v, dict) or set(v) - {'match', 'dirs', 'text', 'name'} or not isinstance(v.get('match'), str) \ + or not isinstance(v.get('dirs', []), list) or not isinstance(v.get('text', ''), str) \ + or not isinstance(v.get('name', ''), str): + return (f'entry {k} must be {{"match": "", "dirs": [], "text": "", ' + '"name": ""}') + if v.get('name') and not _NAME_RE.match(v['name']): + return f'entry {k}: "name" must be one folder name (letters, digits, . _ -), not {v["name"]!r}' + m = v['match'] + if m.startswith('/') or m.startswith('~/'): + if _path(m): + return f'entry {k}: "match" {m!r} {_path(m)}' + elif not re.match(r'^[A-Za-z0-9.-]+(:[0-9]+)?/[A-Za-z0-9._/-]+$', m): + return f'entry {k}: "match" must be a remote as host/owner/repo or a folder, not {m!r}' + p = _paths(v.get('dirs', [])) + return f'entry {k}: "dirs": {p}' if p else None + + +_NAME_RE = re.compile(r'^(?!\.\.?$)[A-Za-z0-9._-]+$') + + +def _record_problem(k, v): + """The problem of one facts.records row, or None.""" + if not isinstance(v, dict) or set(v) - {'path', 'projectsDir', 'shared'} or not isinstance(v.get('path'), str) \ + or not isinstance(v.get('projectsDir', 'projects'), str) or not isinstance(v.get('shared', []), list): + return (f'entry {k} must be {{"path": "", "projectsDir": "projects", ' + '"shared": ["machines", "orch", "shared"]}') + if not v['path'] or _path(v['path']): + return f'entry {k}: "path" {v["path"]!r} {_path(v["path"]) or "must not be empty"}' + for name in [v.get('projectsDir', 'projects')] + v.get('shared', []): + if not isinstance(name, str) or not _NAME_RE.match(name): + return (f'entry {k}: a folder of the record repo must be one folder name (letters, digits, . _ -), ' + f'not {name!r}') + return None + + +ROW_CHECKS = {'refuseScripts': _row_problem, 'projects': _project_problem, 'records': _record_problem} + + def _own(section, hook): """(settings, [problems]) of one hook from its own part of the section. Each key is checked on its own: a bad key keeps its built-in default (and is named), the others keep their values; a bad refuseScripts row is dropped @@ -131,12 +202,12 @@ def _own(section, hook): if key not in SPEC[hook]: problems.append(f'{where}: unknown key {key!r} (ignored; known: {", ".join(sorted(SPEC[hook]))})') continue - if key == 'refuseScripts' and isinstance(value, list): + if key in ROW_CHECKS and isinstance(value, list): rows = [] for k, row in enumerate(value): - p = _row_problem(k, row) + p = ROW_CHECKS[key](k, row) if p: - problems.append(f'{where}.refuseScripts: {p} (that entry is left out)') + problems.append(f'{where}.{key}: {p} (that entry is left out)') else: rows.append(row) out[key] = rows diff --git a/fork-kit/agent-guards/lib/agent_guards/facts.py b/fork-kit/agent-guards/lib/agent_guards/facts.py new file mode 100644 index 0000000000000..5204e09ed5250 --- /dev/null +++ b/fork-kit/agent-guards/lib/agent_guards/facts.py @@ -0,0 +1,539 @@ +"""agent_guards.facts: state tables, one per place (a machine, a project, the fork), looked up instead of re-derived; +and a search of the user's private record repo, after the tables. + +A state table is a Markdown table whose header's first cell is "Thing", one row per thing: + + | Thing | What we made / how to use it | State now | Why | Updated | + |---|---|---|---|---| + | Example GPU | `gpu on\\|off\\|status` helper; turned off at boot | OFF on purpose; the vendor tool fails while off | quiet fans | 11-23 | + +Only the "Thing" column (first) and an "Updated" column (by name, any place) mean something to the code; the rest is +free text. A file may hold more than one such table (a second header row starts a new one); other text and tables +in it are skipped. Current state only: history stays in git and the issues. A configured entry is a table file, or a +folder whose STATE.md is the table. Only regular files are read (a FIFO or a device is a note, never opened to wait). + +Where the tables are comes from the machine file's "agent-guards" section, part "facts" (config.py): "dirs" for +every session on the machine, and "projects" ([{"match", "dirs", "text", "name"}]) for the sessions working in one +project, matched by the checkout's origin remote (host/owner/repo) or by a folder (that folder or below it), never by +a glob. FACTS_DIRS (paths joined by ":") replaces both lists, for a test or a one-off look. "records" +([{"path", "projectsDir", "shared"}]) names record repo checkouts: `facts WORDS` searches their text files after the +tables (this project's projects// and the shared folders). Read only: nothing here writes. +Plain Python 3 standard library. +""" +import datetime, hashlib, os, re, stat, subprocess, time + +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) +RECORD_MAX = 1024 * 1024 # record repo files over this are skipped +RECORD_TYPES = ('.md', '.txt', '.json', '.yml', '.yaml', '.sh') +RECORD_SECONDS = 10 # a record repo search stops after this (and says so) +LINE_CHARS = 160 +MORE_INDEX = 'run facts --index' +_SEP = re.compile(r'^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$') + + +class Place: + """One configured entry: `entry` (as written), `source` (where it was configured), `file` (the table file or + None), `tables` [Table], `notes` [text]: a missing file or folder, an empty folder, a file with no state table; + `digest`: sha256 of the bytes read (a record repo copy of the same file is not shown again).""" + + def __init__(self, entry, source): + self.entry, self.source, self.file, self.tables, self.notes, self.digest = entry, source, None, [], [], None + + def rows(self): + return [r for t in self.tables for r in t.rows] + + +class Table: + def __init__(self, file, header, sep, columns): + self.file, self.header, self.sep, self.columns, self.rows, self.warnings = file, header, sep, columns, [], [] + + def column(self, name): + names = [c.strip().lower() for c in self.columns] + return names.index(name.lower()) if name.lower() in names else None + + +class Row: + def __init__(self, table, lineno, line, cells): + self.table, self.lineno, self.line, self.cells = table, lineno, line, cells + + @property + def thing(self): + return unescape(self.cells[0]) if self.cells else '' + + def cell(self, name): + k = self.table.column(name) + return unescape(self.cells[k]) if k is not None and k < len(self.cells) else None + + def text(self): + return ' '.join(unescape(c) for c in self.cells) + + +def cells(line): + """The cells of one table line: split on | that is not escaped (\\|), the outer pipes dropped, each stripped.""" + s = line.strip() + if s.startswith('|'): + s = s[1:] + if s.endswith('|') and not s.endswith('\\|'): + s = s[:-1] + out, cur, k = [], [], 0 + while k < len(s): + if s[k] == '\\' and k + 1 < len(s): + cur.append(s[k:k + 2]) + k += 2 + continue + if s[k] == '|': + out.append(''.join(cur).strip()) + cur = [] + else: + cur.append(s[k]) + k += 1 + out.append(''.join(cur).strip()) + return out + + +def unescape(text): + return text.replace('\\|', '|') + + +def _is_header(line): + return line.lstrip().startswith('|') and cells(line)[0].strip().lower() == 'thing' + + +def _is_sep(line): + s = line.strip() + return '|' in s and '-' in s and bool(_SEP.match(s)) + + +def parse(text, file=''): + """[Table] of every state table in `text`. A row whose cell count differs from the header's is kept (listed + and searched as it is) and named in its table's warnings. A second header row ends a table and starts the next.""" + lines = text.split('\n') + tables, k = [], 0 + while k < len(lines): + line = lines[k] + if _is_header(line): + sep = lines[k + 1] if k + 1 < len(lines) and _is_sep(lines[k + 1]) else None + t = Table(file, line.rstrip(), sep.rstrip() if sep else None, cells(line)) + if sep is None: + t.warnings.append(f'{file}:{k + 1}: the header has no |---| line under it') + k += 2 if sep is not None else 1 + while k < len(lines) and lines[k].lstrip().startswith('|') and not _is_header(lines[k]): + c = cells(lines[k]) + if any(c) and not _is_sep(lines[k]): + t.rows.append(Row(t, k + 1, lines[k].rstrip(), c)) + if len(c) != len(t.columns): + t.warnings.append(f'{file}:{k + 1}: row "{unescape(c[0])[:60]}" has {len(c)} cells, the header ' + f'has {len(t.columns)}') + k += 1 + tables.append(t) + continue + k += 1 + return tables + + +def read_regular(path, limit): + """(bytes, cut, problem): at most `limit` bytes of a regular file. A FIFO, a device or a folder is not opened + for reading (O_NONBLOCK, then fstat), so nothing here waits on a writer that never comes.""" + try: + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | getattr(os, 'O_CLOEXEC', 0)) + except OSError as e: + return None, False, f'cannot be read ({e.strerror or e})' + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None, False, 'not a regular file: skipped' + chunks, size = [], 0 + while size <= limit: + b = os.read(fd, min(1 << 20, limit + 1 - size)) + if not b: + break + chunks.append(b) + size += len(b) + data = b''.join(chunks) + return data[:limit], len(data) > limit, None + except OSError as e: + return None, False, f'cannot be read ({e.strerror or e})' + finally: + os.close(fd) + + +def _size(n): + return f'{n // (1024 * 1024)} MB' if n >= 1024 * 1024 else f'{n} bytes' + + +def _expand(entry): + return os.path.expanduser(entry) if entry.startswith('~/') else entry + + +def read_place(entry, source): + """A Place for one configured entry (a table file, or a folder holding STATE.md). Never raises.""" + p = Place(entry, source) + path = _expand(entry) + if not os.path.isabs(path): + p.notes.append(f'{entry}: not an absolute path (or ~/...): skipped') + return p + if os.path.isdir(path): + path = os.path.join(path, TABLE_FILE) + if not os.path.lexists(path): + p.notes.append(f'{entry}: no {TABLE_FILE} in this folder yet') + return p + elif not os.path.lexists(path): + p.notes.append(f'{entry}: not there') + return p + data, cut, problem = read_regular(path, MAX_READ) + if problem: + p.notes.append(f'{path}: {problem}') + return p + p.file, p.digest = path, hashlib.sha256(data).hexdigest() + if cut: + p.notes.append(f'{path}: (cut at {_size(MAX_READ)}): rows after that are not read') + p.tables = parse(data.decode('utf-8', errors='replace'), path) + if not p.tables: + p.notes.append(f'{path}: no state table in it (a header row starting "| Thing |")') + return p + + +def remote_key(url): + """'github.com/owner/repo' for any spelling of a remote URL (https, ssh, scp-like, .git, a trailing /).""" + u = (url or '').strip().lower() + u = re.sub(r'^[a-z+]+://', '', u) + u = re.sub(r'^[^@/]+@', '', u) + if ':' in u.split('/', 1)[0]: + host, rest = u.split(':', 1) + u = host + '/' + rest.lstrip('/') if not rest.split('/', 1)[0].isdigit() else host + '/' + rest.split('/', 1)[-1] + u = u.rstrip('/') + return u[:-4] if u.endswith('.git') else u + + +GIT = 'git' # tests point it at a stand-in that hangs or fails + + +def origin(cwd, timeout=2): + """The origin remote of the checkout at `cwd` (a linked worktree too), or ''. A folder that is gone, not a + checkout, or a git that hangs (killed after `timeout` s) or fails: ''.""" + try: + r = subprocess.run([GIT, '-C', cwd, 'config', '--get', 'remote.origin.url'], capture_output=True, + text=True, timeout=timeout, stdin=subprocess.DEVNULL) + return r.stdout.strip() if r.returncode == 0 else '' + except (OSError, subprocess.SubprocessError, ValueError): + return '' + + +def _below(cwd, folder): + try: + c, f = os.path.realpath(cwd), os.path.realpath(os.path.expanduser(folder)) + except (OSError, ValueError): + return False + return c == f or c.startswith(f.rstrip('/') + '/') + + +def projects_for(cfg, cwd): + """The configured projects that `cwd` belongs to: a folder match (that folder or below), or the checkout's + origin remote. git is asked only when a project matches by remote, and at most once.""" + out, remote = [], None + for p in cfg.get('projects') or []: + m = p['match'] + if m.startswith('/') or m.startswith('~/'): + if cwd and _below(cwd, m): + out.append(p) + continue + if remote is None: + remote = remote_key(origin(cwd)) if cwd and os.path.isdir(cwd) else '' + if remote and remote == remote_key(m): + out.append(p) + return out + + +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.""" + if p.get('name'): + return p['name'] + return os.path.basename(_expand(p['match']).rstrip('/')) or None + + +def _same(entry): + """What makes two entries the same place: the real path (a link, ~/ and a trailing / do not count).""" + path = _expand(entry) + try: + return os.path.realpath(path) if os.path.isabs(path) else entry + except (OSError, ValueError): + return entry + + +def entries(cfg, cwd, env=None, every=False, projects=None): + """[(entry, source)] to read: FACTS_DIRS when set; else the machine's dirs and those of `projects` (default: + the projects `cwd` belongs to; every project's with every=True), each place once (by its real path).""" + env = os.environ if env is None else env + if env.get('FACTS_DIRS'): + out = [(e, 'FACTS_DIRS') for e in env['FACTS_DIRS'].split(':') if e] + else: + out = [(e, 'machine') for e in cfg.get('dirs') or []] + if every: + projects = cfg.get('projects') or [] + elif projects is None: + projects = projects_for(cfg, cwd) + for p in projects: + out += [(e, f'project {p["match"]}') for e in p.get('dirs') or []] + seen, uniq = set(), [] + for e, s in out: + k = _same(e) + if k not in seen: + seen.add(k) + uniq.append((e, s)) + return uniq + + +def places(cfg, cwd, env=None, every=False, projects=None): + return [read_place(e, s) for e, s in entries(cfg, cwd, env, every, projects)] + + +def _words(words): + return [w.lower() for w in words if w.strip()] + + +def search(found, words): + """Output lines: for each table with a match, its file, header, |---| line and the matching rows as written. + A row matches when it holds every word (any case); rows with the words in the Thing column come first. When no + row holds them all, rows holding any of them are shown, and the first line says so.""" + ws = _words(words) + rows = [r for p in found for r in p.rows()] + + def hits(r, part): + return sum(w in part for w in ws) + every = [r for r in rows if hits(r, r.text().lower()) == len(ws)] + lines = [] + picked = every + if not every: + picked = [r for r in rows if hits(r, r.text().lower())] + if picked: + lines.append(f'No row holds all of: {" ".join(words)}. Rows with some of them:') + picked.sort(key=lambda r: (-hits(r, r.thing.lower()), -hits(r, r.text().lower()))) + for t in dict.fromkeys(r.table for r in picked): + lines.append(f'{t.file}:') + lines.append(t.header) + if t.sep: + lines.append(t.sep) + lines += [r.line for r in picked if r.table is t] + if not picked: + lines.append(f'No row matches: {" ".join(words)} (in {sum(1 for p in found if p.file)} table file(s); ' + '`facts --index` lists every thing, `facts --dirs` where it looked).') + return lines + + +def index(found, limit=None): + """Output lines: each table file, then its things, one per line (at most `limit` things in all; a file none of + whose things fit is left out, and the last line says how many more there are).""" + lines, shown, total = [], 0, sum(len(p.rows()) for p in found) + for p in found: + rows = p.rows() + if not rows or (limit is not None and shown >= limit): + continue + lines.append(f'{p.file} ({len(rows)} rows):') + for r in rows: + if limit is not None and shown >= limit: + break + lines.append(f' - {r.thing[:100]}') + shown += 1 + if total > shown: + lines.append(f' +{total - shown} more: {MORE_INDEX}') + return lines + + +def notes(found): + out = [n for p in found for n in p.notes] + out += [w for p in found for t in p.tables for w in t.warnings] + return out + + +def updated(text, today): + """The date in an Updated cell, or None: YYYY-MM-DD, or MM-DD (the latest such date that is not more than a + day ahead of `today`: this year, last year, or for 02-29 the last leap year), each with any text after it + ("11-23 (checked)").""" + text = text or '' + m = re.match(r'^\s*(\d{4})-(\d{1,2})-(\d{1,2})(?![\d])', text) + try: + if m: + return datetime.date(int(m[1]), int(m[2]), int(m[3])) + except ValueError: + return None + m = re.match(r'^\s*(\d{1,2})-(\d{1,2})(?![\d-])', text) + if not m: + return None + month, day = int(m[1]), int(m[2]) + for year in range(today.year, today.year - 8, -1): + try: + d = datetime.date(year, month, day) + except ValueError: + continue + if d <= today + datetime.timedelta(days=1): + return d + return None + + +def check(found, stale_days, max_rows, today): + """The gardener's findings (report only; nothing is changed): rows whose Updated is older than stale_days, + in the future or cannot be read, tables without an Updated column or over max_rows, broken rows, entries that + are missing, empty or hold no table.""" + out = list(notes(found)) + for p in found: + for t in p.tables: + if len(t.rows) > max_rows: + out.append(f'{t.file}: {len(t.rows)} rows, over the cap of {max_rows} (maxRows): fold or drop the ' + 'rows of things that are gone') + if t.column('updated') is None: + out.append(f'{t.file}: the table has no "Updated" column') + continue + for r in t.rows: + cell = r.cell('updated') + d = updated(cell, today) + if d is None: + out.append(f'{t.file}:{r.lineno}: "{r.thing[:60]}": no date in Updated ({(cell or "")[:20]!r})') + elif d > today + datetime.timedelta(days=1): + out.append(f'{t.file}:{r.lineno}: "{r.thing[:60]}": Updated {cell.strip()} is in the future') + elif (today - d).days > stale_days: + out.append(f'{t.file}:{r.lineno}: "{r.thing[:60]}": Updated {cell.strip()} is ' + f'{(today - d).days} days old (staleDays {stale_days}): check the state, then edit ' + 'the row') + return out + + +# The record repo ------------------------------------------------------------------------------------------------ + +class Records: + """One configured record repo: `root` (its checkout), `folders` [relative folder to search], `note` (why it + is skipped, or None).""" + + def __init__(self, root, folders, note=None): + self.root, self.folders, self.note = root, folders, note + + +def records(cfg, projects, every=False): + """[Records] for the configured record repos: the shared folders and, for each of `projects`, its folder under + the projects folder (every=True: the whole projects folder). A repo that is not there has a note.""" + out = [] + for r in cfg.get('records') or []: + root = _expand(r['path']) + pdir = r.get('projectsDir') or 'projects' + folders = list(r.get('shared', ['machines', 'orch', 'shared'])) + if every: + folders.append(pdir) + else: + folders += [f'{pdir}/{n}' for n in (project_name(p) for p in projects) if n] + folders = list(dict.fromkeys(folders)) + note = None + try: + if not os.path.isdir(root): + note = f'record repo {r["path"]}: not there (or not a folder): skipped' + elif not os.access(root, os.R_OK | os.X_OK): + note = f'record repo {r["path"]}: cannot be read: skipped' + except (OSError, ValueError) as e: + note = f'record repo {r["path"]}: {e}: skipped' + out.append(Records(root, folders, note)) + return out + + +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()).""" + for folder in rec.folders: + top = os.path.join(rec.root, folder) + if os.path.islink(top) or not os.path.isdir(top): + continue + for d, dirs, files in os.walk(top): + 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: + return + path = os.path.join(d, name) + if name.lower().endswith(RECORD_TYPES) and not os.path.islink(path): + 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 + "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 + deadline = time.monotonic() + seconds + for rec in recs: + if rec.note: + out_notes.append(rec.note) + continue + 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: + continue + 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): + total += 1 + if shown < limit: + if not head: + lines.append(f'Records in {rec.root}:') + head = True + lines.append(f'{rel}:{n}: {line.strip()}'[:LINE_CHARS]) + shown += 1 + if time.monotonic() > deadline: + out_notes.append(f'record repo {rec.root}: search stopped after {seconds} s: some files not searched') + break + if total > shown: + lines.append(f'+{total - shown} more (facts --records {" ".join(words)})') + return lines, out_notes + + +def record_line(recs): + """The session-start line naming each record repo that is there; '' when none.""" + roots = [r.root for r in recs if not r.note] + return f'Records: {", ".join(roots)} (facts searches it)' if roots else '' + + +# The hook's text ------------------------------------------------------------------------------------------------ + +def _fit(head, body, tail, chars): + """head + as many body lines as fit in `chars` + tail; a body cut short ends with "+N more: run facts + --index" (N: the things left out).""" + tail = [t[:chars // 4] for t in tail] + budget = chars - len(head) - sum(len(t) + 1 for t in tail) - 40 + kept, used = [], 0 + for k, line in enumerate(body): + if used + len(line) + 1 > budget: + rest = body[k:] + left = sum(1 for x in rest if x.startswith(' - ')) + m = re.match(r'^ \+(\d+) more', rest[-1]) if rest else None + left += int(m[1]) if m else 0 + while kept and not kept[-1].startswith(' - '): # no file line with none of its things + kept.pop() + kept.append(f' +{left} more: {MORE_INDEX}') + break + kept.append(line) + used += len(line) + 1 + return '\n'.join([head] + kept + tail) + + +def session_text(found, projects, limit, chars=4000, recs=()): + """The session-start context: the things of every table (at most `limit` things), the call to look first, the + projects' text and one line per record repo, all in at most `chars` characters; '' when there is nothing.""" + rec = record_line(recs) + extra = [p['text'] for p in projects if p.get('text')] + if not any(p.rows() for p in found): + return '\n'.join(([rec] if rec else []))[:chars] + head = (f'State tables (one row per thing: what we made, how to use it, its state now and why). ' + f'{CALL_TO_LOOK[0].upper()}{CALL_TO_LOOK[1:]}. Things:') + return _fit(head, index(found, limit), extra + ([rec] if rec else []), chars)[:chars] + + +def compact_text(found, projects, chars=4000): + """The compaction instructions' part: keep the things' names, not their rows.""" + if not any(p.rows() for p in found): + return '' + extra = [p['text'] for p in projects if p.get('text')] + return '\n'.join(['State tables: in the summary keep only the names of the things you looked up or changed in ' + 'them, not their rows; `facts ` reads the rows again after compaction. A thing whose ' + 'state changed in this conversation and whose row was not edited yet: say "row NOT YET ' + 'UPDATED" with the new state.'] + extra)[:chars] diff --git a/fork-kit/agent-guards/lib/agent_guards/wiring.py b/fork-kit/agent-guards/lib/agent_guards/wiring.py index f6fe70b5a3cb8..1ae825f05c392 100644 --- a/fork-kit/agent-guards/lib/agent_guards/wiring.py +++ b/fork-kit/agent-guards/lib/agent_guards/wiring.py @@ -10,7 +10,8 @@ "onFailure": "block" refuses the call (without it a timed-out hook lets the call run). capacity-pipe-guard, fail OPEN: exit 1, which Claude Code shows as a hook error and then runs the call. These memory-index-guard, guard mistakes, not attacks; refusing every call because a helper is gone would stop all - bg-guard, agent-slots work on the machine. + bg-guard, agent-slots, work on the machine. + facts-hook The same entries go in the managed settings drop-in the installer writes (--settings) or, by hand, in any settings file (`agent-guards hooks`). Monitor runs shell text like Bash, so every hook that reads a command reads it for @@ -23,7 +24,8 @@ MANAGED_DIR = '/etc/claude-code' # Claude Code's managed settings folder on Linux DROP_IN = f'{MANAGED_DIR}/managed-settings.d/{DROP_IN_NAME}' -HOOKS = ('actions-disable-guard', 'capacity-pipe-guard', 'memory-index-guard', 'bg-guard', 'agent-slots') +HOOKS = ('actions-disable-guard', 'capacity-pipe-guard', 'memory-index-guard', 'bg-guard', 'agent-slots', + 'facts-hook') CLOSED = {'actions-disable-guard'} # a missing or failed hook refuses WHAT_IS_LOST = { 'actions-disable-guard': 'every Bash and Monitor command is refused until it is back', @@ -31,6 +33,7 @@ 'memory-index-guard': 'hook skipped, the memory index is NOT checked', 'bg-guard': 'hook skipped, background commands are NOT checked', 'agent-slots': 'hook skipped, agent slots are NOT counted', + 'facts-hook': 'hook skipped, the state tables are NOT shown', } # (event, matcher or None, [(hook, timeout)]): one settings entry each, in this order ENTRIES = ( @@ -40,6 +43,8 @@ ('PostToolUse', 'Write|Edit|MultiEdit|Bash|Monitor', [('memory-index-guard', 5)]), ('UserPromptSubmit', None, [('agent-slots', 5)]), ('Stop', None, [('agent-slots', 5), ('bg-guard', 5)]), + ('SessionStart', None, [('facts-hook', 5)]), + ('PreCompact', None, [('facts-hook', 5)]), ) diff --git a/fork-kit/agent-guards/sbin/agent-guards-install b/fork-kit/agent-guards/sbin/agent-guards-install index 29cbbba59caa2..c39aa459f79bf 100755 --- a/fork-kit/agent-guards/sbin/agent-guards-install +++ b/fork-kit/agent-guards/sbin/agent-guards-install @@ -5,10 +5,10 @@ agent-guards-install uninstall agent-guards-install self-check -install copies bin/ (the five hooks and agent-guards), sbin/agent-guards-install, lib/agent_guards/, README.md and +install copies bin/ (the six hooks, agent-guards and facts), sbin/agent-guards-install, lib/agent_guards/, README.md, FACTS.md and fork-kit/common/{machine_file,kit_install}.py of one release into /usr/local/libexec/agent-guards/versions// (with MANIFEST.sha256), checks the copy, switches the link `current` to it and links /usr/local/bin/ and -/usr/local/bin/agent-guards to it. With --settings it also writes the hooks' Claude Code managed settings drop-in +/usr/local/bin/{agent-guards,facts} to it. With --settings it also writes the hooks' Claude Code managed settings drop-in (/etc/claude-code/managed-settings.d/agent-guards.json), which every session of every user on the machine reads and only root can change; --no-settings removes it. The choice is kept in /etc/agent-guards/config.json, so a run without either option keeps it (the first install: no drop-in). The drop-in is written only after the links, so a @@ -40,6 +40,7 @@ except ImportError as e: # a copy with a part missing: the bootstrap makes i '(fork-kit/agent-guards/README.md, Install)') HOOKS = wiring.HOOKS +COMMANDS = ('agent-guards', 'facts') # commands people and agents run, linked beside the hooks class AgentGuardsInstaller(kit_install.Installer): @@ -48,13 +49,14 @@ class AgentGuardsInstaller(kit_install.Installer): KIT = 'agent-guards' ETC = '/etc/agent-guards' LIBEXEC = '/usr/local/libexec/agent-guards' - LINKS = dict({f'{wiring.BIN}/{h}': f'bin/{h}' for h in HOOKS + ('agent-guards',)}, + LINKS = dict({f'{wiring.BIN}/{h}': f'bin/{h}' for h in HOOKS + COMMANDS}, **{'/usr/local/sbin/agent-guards-install': 'sbin/agent-guards-install'}) - SOURCE_FILES = tuple(f'bin/{h}' for h in HOOKS + ('agent-guards',)) + ( - 'sbin/agent-guards-install', 'README.md', 'common/machine_file.py', 'common/kit_install.py') - EXECUTABLE = frozenset([f'bin/{h}' for h in HOOKS + ('agent-guards',)] + ['sbin/agent-guards-install']) + OPTIONAL_LINKS = (f'{wiring.BIN}/facts',) # a common name: another program called facts is left alone + SOURCE_FILES = tuple(f'bin/{h}' for h in HOOKS + COMMANDS) + ( + 'sbin/agent-guards-install', 'README.md', 'FACTS.md', 'common/machine_file.py', 'common/kit_install.py') + EXECUTABLE = frozenset([f'bin/{h}' for h in HOOKS + COMMANDS] + ['sbin/agent-guards-install']) PACKAGE = 'agent_guards' - MODULES = ('__init__', 'approval', 'check', 'config', 'wiring') + MODULES = ('__init__', 'approval', 'check', 'config', 'facts', 'wiring') HELP = ('bin/agent-guards', 'agent-guards check') HAS_CONFIG = True CONFIG_KEYS = ('version', 'settings', 'settingsOff') # other keys of config.json (added by hand) are kept diff --git a/fork-kit/agent-guards/tests/facts.test.py b/fork-kit/agent-guards/tests/facts.test.py new file mode 100644 index 0000000000000..3276591a893a6 --- /dev/null +++ b/fork-kit/agent-guards/tests/facts.test.py @@ -0,0 +1,592 @@ +"""Tests of the state tables (fork-kit/agent-guards/FACTS.md): agent_guards.facts (read, search, index, the +gardener's check, project matching, the record repo search), the `facts` command and the `facts-hook` hook +(SessionStart: the things; PreCompact: keep names, not rows). Tables and record repos are made up in a temporary +folder; the machine file is the test's own. Dates are fixed (TODAY, FACTS_TODAY), so no test depends on the day it +runs. + + python3 -I -B fork-kit/agent-guards/tests/facts.test.py +""" +import datetime, hashlib, json, os, shutil, subprocess, sys, tempfile, time, unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import guards_fixture as fx # noqa: E402 +from agent_guards import config, facts # noqa: E402 + +HEAD = '| Thing | What we made / how to use it | State now | Why | Updated |\n|---|---|---|---|---|\n' +TABLE = ('# What we have\n\nSome text first.\n\n' + HEAD + + '| Example GPU | `gpu on\\|off\\|status` helper; off at boot | OFF on purpose; the vendor tool fails while ' + 'off | quiet fans | 11-23 |\n' + + '| Example backup job | `backup-ctl run` nightly | Paused until the new disk | disk alarm | 2026-11-20 |\n' + + '| Example web cache | none yet | not made | | 11-01 |\n' + + '\nA closing line.\n') +TODAY = datetime.date(2026, 11, 23) +HOOK = 'facts-hook' + + +def write(path, text, mode='w'): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, mode) as f: + f.write(text) + return path + + +def script(path, body): + write(path, '#!/bin/sh\n' + body + '\n') + os.chmod(path, 0o755) + return path + + +class Tables(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix='facts-test-') + self.addCleanup(shutil.rmtree, self.tmp, True) + self.place = os.path.join(self.tmp, 'machine-facts') + write(os.path.join(self.place, 'STATE.md'), TABLE) + + def found(self, *entries): + return [facts.read_place(e, 'test') for e in entries] + + def test_a_table_is_read_with_escaped_pipes_and_the_text_around_it_skipped(self): + [t] = facts.parse(TABLE, 'STATE.md') + self.assertEqual([r.thing for r in t.rows], ['Example GPU', 'Example backup job', 'Example web cache']) + self.assertEqual(t.rows[0].cell('What we made / how to use it'), '`gpu on|off|status` helper; off at boot') + self.assertEqual(t.rows[0].cell('updated'), '11-23') + self.assertEqual(t.rows[0].lineno, 7) + self.assertEqual(t.warnings, []) + + def test_a_broken_row_is_still_listed_with_a_warning(self): + text = HEAD + '| Broken thing | only two cells |\n| Good thing | a | b | c | 11-23 |\n' + [t] = facts.parse(text, 'S.md') + self.assertEqual([r.thing for r in t.rows], ['Broken thing', 'Good thing']) + self.assertEqual(t.warnings, ['S.md:3: row "Broken thing" has 2 cells, the header has 5']) + [t] = facts.parse('| Thing | State now |\n| No line under the header | on |\n', 'S.md') + self.assertEqual([r.thing for r in t.rows], ['No line under the header']) + self.assertIn('the header has no |---| line under it', t.warnings[0]) + + def test_short_separators_and_a_second_header_row(self): + [t] = facts.parse('| Thing | State now |\n|-|:-:|\n| A | on |\n', 'S.md') + self.assertEqual(([r.thing for r in t.rows], t.warnings, t.sep), (['A'], [], '|-|:-:|')) + text = HEAD + '| A | a | on | w | 11-23 |\n| Thing | State now |\n|---|---|\n| B | off |\n' + a, b = facts.parse(text, 'S.md') # the second header row ends the first table + self.assertEqual(([r.thing for r in a.rows], [r.thing for r in b.rows]), (['A'], ['B'])) + self.assertEqual((a.warnings, b.warnings, b.columns), ([], [], ['Thing', 'State now'])) + + def test_two_tables_and_other_tables(self): + text = ('| Name | x |\n|---|---|\n| not a state row | y |\n\n' + HEAD + '| A | a | on | w | 11-23 |\n\n' + + HEAD + '| B | b | off | w | 11-22 |\n') + self.assertEqual([[r.thing for r in t.rows] for t in facts.parse(text)], [['A'], ['B']]) + + def test_search_prints_the_header_and_the_matching_rows_thing_hits_first(self): + found = self.found(self.place) + lines = facts.search(found, ['GPU']) + self.assertEqual(lines[0], os.path.join(self.place, 'STATE.md') + ':') + self.assertEqual(lines[1:3], HEAD.rstrip('\n').split('\n')) + self.assertEqual(len(lines), 4) + self.assertIn('| Example GPU |', lines[3]) + lines = facts.search(found, ['disk']) # in the State and Why columns only + self.assertIn('| Example backup job |', lines[3]) + lines = facts.search(found, ['off']) # Thing column hits first, then the others + self.assertEqual([ln.split('|')[1].strip() for ln in lines[3:]], ['Example GPU']) + lines = facts.search(found, ['example', 'cache']) # every word + self.assertEqual(len(lines), 4) + self.assertIn('Example web cache', lines[3]) + + def test_search_with_no_row_holding_every_word_shows_rows_with_some_and_says_so(self): + found = self.found(self.place) + lines = facts.search(found, ['gpu', 'broken']) + self.assertEqual(lines[0], 'No row holds all of: gpu broken. Rows with some of them:') + self.assertIn('| Example GPU |', lines[-1]) + lines = facts.search(found, ['nothing-like-this']) + self.assertEqual(len(lines), 1) + self.assertTrue(lines[0].startswith('No row matches: nothing-like-this (in 1 table file(s)'), lines) + + def test_the_index_lists_every_thing_and_caps_with_no_empty_file_lines(self): + found = self.found(self.place) + self.assertEqual(facts.index(found), [f'{os.path.join(self.place, "STATE.md")} (3 rows):', + ' - Example GPU', ' - Example backup job', ' - Example web cache']) + self.assertEqual(facts.index(found, 2)[-1], ' +1 more: run facts --index') + self.assertEqual(len(facts.index(found, 2)), 4) + second = write(os.path.join(self.tmp, 'second', 'STATE.md'), HEAD + '| Z | z | on | w | 11-23 |\n') + lines = facts.index(self.found(self.place, second), 3) + self.assertNotIn(f'{second} (1 rows):', lines) # none of its things fit: no line for it + self.assertEqual(lines[-1], ' +1 more: run facts --index') + + def test_a_missing_or_empty_folder_or_a_file_with_no_table_is_a_note(self): + empty = os.path.join(self.tmp, 'empty') + os.makedirs(empty) + plain = write(os.path.join(self.tmp, 'plain.md'), '# notes\nno table here\n') + found = self.found(self.place, os.path.join(self.tmp, 'gone'), empty, plain, 'relative/path') + self.assertEqual([len(p.rows()) for p in found], [3, 0, 0, 0, 0]) + self.assertEqual(facts.notes(found), [ + f'{os.path.join(self.tmp, "gone")}: not there', + f'{empty}: no STATE.md in this folder yet', + f'{plain}: no state table in it (a header row starting "| Thing |")', + 'relative/path: not an absolute path (or ~/...): skipped']) + self.assertEqual(len(facts.search(found, ['gpu'])), 4) # the rest is still searched + self.assertEqual(facts.index(self.found(empty)), []) + + def test_a_fifo_is_never_opened_to_wait(self): + folder = os.path.join(self.tmp, 'fifo') + os.makedirs(folder) + os.mkfifo(os.path.join(folder, 'STATE.md')) + os.mkfifo(os.path.join(self.tmp, 'table.fifo')) + start = time.monotonic() + a, b = self.found(folder, os.path.join(self.tmp, 'table.fifo')) + self.assertLess(time.monotonic() - start, 5) + self.assertEqual((a.rows(), b.rows()), ([], [])) + self.assertIn('not a regular file: skipped', a.notes[0]) + self.assertIn('not a regular file: skipped', b.notes[0]) + + def test_bytes_that_are_not_utf8_and_a_cut_file(self): + path = write(os.path.join(self.tmp, 'bin', 'STATE.md'), + HEAD.encode() + b'| Caf\xe9 \xff thing | a | on | w | 11-23 |\n', 'wb') + [p] = self.found(path) + self.assertEqual(len(p.rows()), 1) + self.assertIn('thing', p.rows()[0].thing) + self.assertEqual(p.notes, []) + old = facts.MAX_READ + facts.MAX_READ = 200 + self.addCleanup(setattr, facts, 'MAX_READ', old) + long_table = HEAD + ''.join(f'| Thing {k} | a | on | w | 11-23 |\n' for k in range(20)) + [p] = self.found(write(os.path.join(self.tmp, 'long', 'STATE.md'), long_table)) + self.assertTrue(0 < len(p.rows()) < 20) + self.assertIn('(cut at 200 bytes)', p.notes[0]) + + def test_updated_dates(self): + self.assertEqual(facts.updated('11-23', TODAY), datetime.date(2026, 11, 23)) + self.assertEqual(facts.updated('2025-02-03', TODAY), datetime.date(2025, 2, 3)) + self.assertEqual(facts.updated(' 2026-11-01 (moved) ', TODAY), datetime.date(2026, 11, 1)) + self.assertEqual(facts.updated('11-20 (checked)', TODAY), datetime.date(2026, 11, 20)) + new_year = datetime.date(2027, 1, 2) + self.assertEqual(facts.updated('12-30', new_year), datetime.date(2026, 12, 30)) # across the year's end + self.assertEqual(facts.updated('01-03', new_year), datetime.date(2027, 1, 3)) # tomorrow: a time zone + self.assertEqual(facts.updated('02-29', new_year), datetime.date(2024, 2, 29)) # the last leap year + self.assertEqual(facts.updated('02-29', datetime.date(2028, 3, 1)), datetime.date(2028, 2, 29)) + for bad in ('', 'soon', '13-40', '2026-02-30', '11-23-5', None): + self.assertIsNone(facts.updated(bad, TODAY), bad) + + def test_the_gardener_check_reports_stale_future_and_missing_dates_and_big_tables(self): + found = self.found(self.place) + self.assertEqual(facts.check(found, 30, 60, TODAY), []) + out = facts.check(found, 5, 2, TODAY) + self.assertEqual(len(out), 2, out) + self.assertIn('3 rows, over the cap of 2 (maxRows)', out[0]) + self.assertIn(':9: "Example web cache": Updated 11-01 is 22 days old (staleDays 5)', out[1]) + write(os.path.join(self.place, 'STATE.md'), + HEAD + '| A | a | on | w | soon |\n| B | b | c |\n| C | c | on | w | 2027-01-05 |\n') + out = facts.check(self.found(self.place, os.path.join(self.tmp, 'gone')), 30, 60, TODAY) + self.assertEqual(len(out), 5, out) + self.assertIn('not there', out[0]) + self.assertIn('row "B" has 3 cells', out[1]) + self.assertIn('"A": no date in Updated (\'soon\')', out[2]) + self.assertIn('"B": no date in Updated (\'\')', out[3]) + self.assertIn('"C": Updated 2027-01-05 is in the future', out[4]) + write(os.path.join(self.place, 'STATE.md'), '| Thing | State now |\n|---|---|\n| A | on |\n') + self.assertEqual(facts.check(self.found(self.place), 30, 60, TODAY)[0].split(': ', 1)[1], + 'the table has no "Updated" column') + + def test_the_session_text_is_capped_as_a_whole(self): + found = [facts.read_place(write(os.path.join(self.tmp, f't{k:02}', 'STATE.md'), HEAD + ''.join( + f'| A rather long name of example thing {k}-{j} | a | on | w | 11-23 |\n' for j in range(10))), 'test') + for k in range(30)] + projects = [{'match': '/x', 'text': 'Project rule. ' * 400}] + text = facts.session_text(found, projects, 1000, 4000) + self.assertLessEqual(len(text), 4000) + lines = text.split('\n') + more = [ln for ln in lines if ln.startswith(' +')] + self.assertEqual(len(more), 1, more) + shown = sum(ln.startswith(' - ') for ln in lines) + self.assertEqual(more[0], f' +{300 - shown} more: run facts --index') + before = lines[lines.index(more[0]) - 1] + self.assertTrue(before.startswith(' - '), before) # no file line left with none of its things + self.assertIn('Project rule.', text) + self.assertLessEqual(len(facts.compact_text(found, projects, 500)), 500) + + +def git(*args, cwd=None): + subprocess.run(['git', *args], cwd=cwd, check=True, capture_output=True, stdin=subprocess.DEVNULL, + env=dict(os.environ, GIT_CONFIG_GLOBAL='/dev/null', GIT_CONFIG_NOSYSTEM='1')) + + +class Projects(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix='facts-projects-') + self.addCleanup(shutil.rmtree, self.tmp, True) + self.repo = os.path.join(self.tmp, 'repo') + os.makedirs(self.repo) + git('init', '-q', '-b', 'main', cwd=self.repo) + git('remote', 'add', 'origin', 'git@github.com:Example/Project.git', cwd=self.repo) + git('-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-q', '--allow-empty', '-m', 'x', + cwd=self.repo) + self.other = os.path.join(self.tmp, 'other') + os.makedirs(self.other) + git('init', '-q', cwd=self.other) + git('remote', 'add', 'origin', 'https://github.com/example/other.git', cwd=self.other) + self.cfg = config.defaults('facts') + self.cfg['dirs'] = ['/m'] + self.cfg['projects'] = [{'match': 'github.com/example/project', 'dirs': ['/p'], 'text': 'project text'}, + {'match': os.path.join(self.tmp, 'notes'), 'dirs': ['/n']}] + + def entries(self, cwd, **kw): + return [e for e, _s in facts.entries(self.cfg, cwd, env={}, **kw)] + + def fake_git(self, body): + path = script(os.path.join(self.tmp, 'fake-bin', 'git'), body) + old = facts.GIT + facts.GIT = path + self.addCleanup(setattr, facts, 'GIT', old) + return path + + def test_remote_spellings(self): + for url in ('git@github.com:example/project.git', 'https://github.com/Example/project', 'ssh://git@github.com/' + 'example/project.git', 'https://user@github.com/example/project/', 'ssh://git@github.com:22/' + 'example/project'): + self.assertEqual(facts.remote_key(url), 'github.com/example/project', url) + + def test_a_checkout_and_its_linked_worktree_match_by_remote_another_project_does_not(self): + self.assertEqual(self.entries(self.repo), ['/m', '/p']) + os.makedirs(os.path.join(self.repo, 'sub')) + self.assertEqual(self.entries(os.path.join(self.repo, 'sub')), ['/m', '/p']) + wt = os.path.join(self.tmp, 'worktrees', 'repo-wt') + git('worktree', 'add', '-q', wt, cwd=self.repo) + self.assertEqual(self.entries(wt), ['/m', '/p']) + self.assertEqual(self.entries(self.other), ['/m']) + self.assertEqual([p['text'] for p in facts.projects_for(self.cfg, wt)], ['project text']) + + def test_a_folder_with_no_git_a_gone_folder_or_a_changed_remote_gets_the_machine_tables_only(self): + plain = os.path.join(self.tmp, 'plain') + os.makedirs(plain) + self.assertEqual(self.entries(plain), ['/m']) + self.assertEqual(self.entries(os.path.join(self.tmp, 'gone')), ['/m']) + self.assertEqual(self.entries(''), ['/m']) + git('remote', 'set-url', 'origin', 'https://github.com/example/renamed.git', cwd=self.repo) + self.assertEqual(self.entries(self.repo), ['/m']) + + def test_a_git_that_hangs_or_fails_matches_no_remote_project(self): + self.fake_git('exec sleep 30') + start = time.monotonic() + self.assertEqual(facts.origin(self.repo, timeout=0.5), '') + self.assertLess(time.monotonic() - start, 5) + self.fake_git('echo https://github.com/example/project; exit 1') + self.assertEqual(self.entries(self.repo), ['/m']) + self.fake_git('exit 0') + self.assertEqual(self.entries(self.repo), ['/m']) + + def test_git_is_asked_once_per_hook_answer(self): + count = os.path.join(self.tmp, 'count') + self.fake_git(f'echo x >> {count}; echo https://github.com/example/project.git') + place = os.path.join(self.tmp, 'p') + write(os.path.join(place, 'STATE.md'), HEAD + '| A | a | on | w | 11-23 |\n') + self.cfg['dirs'] = [] + self.cfg['projects'][0]['dirs'] = [place] + self.cfg['projects'].append({'match': 'github.com/example/project', 'text': 'second text'}) + hook = fx.load_hook(HOOK) + for event in ('SessionStart', 'PreCompact'): + write(count, '') + out, text = hook.decide({'hook_event_name': event, 'cwd': self.repo}, self.cfg) + with open(count) as f: + self.assertEqual(f.read(), 'x\n', event) + self.assertIn('second text', json.dumps(out) if out else text) + + def test_a_folder_match_takes_that_folder_and_below_only(self): + notes = os.path.join(self.tmp, 'notes') + os.makedirs(os.path.join(notes, 'deep')) + os.makedirs(os.path.join(self.tmp, 'notes-other')) + self.assertEqual(self.entries(os.path.join(notes, 'deep')), ['/m', '/n']) + self.assertEqual(self.entries(os.path.join(self.tmp, 'notes-other')), ['/m']) + + def test_all_and_the_env_override(self): + self.assertEqual(self.entries(self.other, every=True), ['/m', '/p', '/n']) + got = facts.entries(self.cfg, self.repo, env={'FACTS_DIRS': '/a::/b:/a'}) + self.assertEqual(got, [('/a', 'FACTS_DIRS'), ('/b', 'FACTS_DIRS')]) + + def test_one_place_by_its_real_path_is_read_once(self): + real = os.path.join(self.tmp, 'facts') + os.makedirs(real) + os.symlink(real, os.path.join(self.tmp, 'link')) + self.cfg['dirs'] = [real, real + '/', os.path.join(self.tmp, 'link'), os.path.join(self.tmp, 'x', '..', + 'facts')] + self.cfg['projects'] = [{'match': self.repo, 'dirs': [real]}] + self.assertEqual(self.entries(self.repo), [real]) + + 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') + + +class Command(unittest.TestCase): + """bin/facts and bin/facts-hook, run as programs with the test's machine file.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix='facts-command-') + self.addCleanup(shutil.rmtree, self.tmp, True) + self.place = os.path.join(self.tmp, 'facts') + write(os.path.join(self.place, 'STATE.md'), TABLE) + self.configure(dirs=[self.place]) + self.env = dict(os.environ, HOME=self.tmp, FACTS_TODAY=TODAY.isoformat()) + self.env.pop('FACTS_DIRS', None) + + def configure(self, **part): + self.machine = fx.machine_file(self.tmp, {'facts': part}) + + def facts(self, *args, env=None, cwd=None): + return fx.run_hook('facts', '', self.machine, env=env or self.env, cwd=cwd or self.tmp, args=args, + hook=os.path.join(fx.BIN, 'facts')) + + def hook(self, event, **extra): + return fx.run_hook(HOOK, dict({'hook_event_name': event, 'session_id': 's', 'cwd': self.tmp}, **extra), + self.machine, env=self.env) + + def test_lookup_index_dirs(self): + r = self.facts('gpu') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.split('\n')[1], HEAD.split('\n')[0]) + self.assertIn('| Example GPU |', r.stdout) + self.assertNotIn('backup', r.stdout) + r = self.facts('--index') + self.assertEqual(r.stdout.count(' - '), 3) + r = self.facts('--dirs') + self.assertEqual(r.stdout.strip(), f'{self.place} (machine): {self.place}/STATE.md: 3 rows in 1 table(s)') + + def test_the_env_override_and_a_missing_folder(self): + env = dict(self.env, FACTS_DIRS=f'{self.tmp}/gone:{self.place}') + r = self.facts('backup', env=env) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('| Example backup job |', r.stdout) + self.assertIn(f'note: {self.tmp}/gone: not there', r.stdout) + + def test_nothing_configured_or_a_usage_error(self): + self.configure() + r = self.facts('gpu') + self.assertEqual(r.returncode, 0) + self.assertIn('no state table is configured', r.stdout) + for args in ((), ('--index', 'gpu'), ('--bogus',), ('--index', '--check'), ('--records',), + ('--records', '--no-records', 'x'), ('--check', 'x')): + self.assertEqual(self.facts(*args).returncode, 1, args) + + def test_check_reports_and_exits_1(self): + r = self.facts('--check') + self.assertEqual((r.returncode, r.stdout.strip()), (0, 'facts check: OK (1 table file(s), 3 rows)')) + r = self.facts('--check', env=dict(self.env, FACTS_TODAY='2027-01-30')) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertEqual(r.stdout.count('days old'), 3, r.stdout) + write(os.path.join(self.place, 'STATE.md'), HEAD + '| Old thing | a | on | w | 2000-01-01 |\n') + r = self.facts('--check') + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn('"Old thing": Updated 2000-01-01 is', r.stdout) + self.assertIn('facts check: 1 finding(s)', r.stdout) + + def test_check_reads_this_folders_project_only_unless_all(self): + mine, theirs = os.path.join(self.tmp, 'mine'), os.path.join(self.tmp, 'theirs') + write(os.path.join(mine, 'facts', 'STATE.md'), HEAD + '| Mine | a | on | w | 11-23 |\n') + write(os.path.join(theirs, 'facts', 'STATE.md'), HEAD + '| Private thing | a | on | w | 2000-01-01 |\n') + self.configure(projects=[{'match': mine, 'dirs': [os.path.join(mine, 'facts')]}, + {'match': theirs, 'dirs': [os.path.join(theirs, 'facts')]}]) + r = self.facts('--check', cwd=mine) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertNotIn('Private', r.stdout) + r = self.facts('--check', '--all', cwd=mine) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn('"Private thing"', r.stdout) + + def test_a_broken_part_is_named_and_the_defaults_used(self): + self.machine = fx.machine_file(self.tmp, {'facts': {'dirs': 'not a list', 'staleDays': 0}}) + r = self.facts('gpu') + self.assertIn('no state table is configured', r.stdout) + self.assertIn('built-in defaults used', r.stdout) + r = self.hook('SessionStart', source='startup') + self.assertEqual(r.returncode, 0) + self.assertNotIn('additionalContext', r.stdout) + self.assertIn('built-in defaults used', json.loads(r.stdout)['systemMessage']) + + def test_a_broken_key_beside_good_dirs_gives_the_tables_and_the_note(self): + self.machine = fx.machine_file(self.tmp, {'facts': {'dirs': [self.place], 'staleDays': 0}}) + r = self.hook('SessionStart', source='startup') + self.assertEqual(r.returncode, 0, r.stderr) + out = json.loads(r.stdout) + self.assertIn(' - Example GPU', out['hookSpecificOutput']['additionalContext']) + self.assertIn('staleDays', out['systemMessage']) + self.assertIn('staleDays', r.stderr) + + def test_a_bad_project_or_record_row_is_left_out_the_others_kept(self): + fx.use_machine(fx.machine_file(self.tmp, {'facts': { + 'projects': [{'match': 'github.com/a/b', 'dirs': ['/x']}, {'match': 'not a remote'}, + {'match': '/d', 'extra': 1}, {'match': '/e', 'name': '../up'}], + 'records': [{'path': '/r'}, {'path': 'relative'}, {'path': '/r2', 'shared': ['../etc']}, + {'path': '/r3', 'projectsDir': 'a/b'}, {'path': '/r4', 'extra': 1}]}})) + self.addCleanup(fx.use_machine, fx.NO_MACHINE) + got, problem = config.load('facts') + self.assertEqual(got['projects'], [{'match': 'github.com/a/b', 'dirs': ['/x']}]) + self.assertEqual(got['records'], [{'path': '/r'}]) + for k in (1, 2, 3): + self.assertIn(f'facts.projects: entry {k}', problem) + for k in (1, 2, 3, 4): + self.assertIn(f'facts.records: entry {k}', problem) + + def test_the_hook_at_session_start_shows_the_things_capped(self): + for source in ('startup', 'resume', 'clear', 'compact'): + r = self.hook('SessionStart', source=source) + self.assertEqual(fx.answer(r), 'context', r.stderr) + text = json.loads(r.stdout)['hookSpecificOutput']['additionalContext'] + self.assertIn('Check the state table before diagnosing or redoing something: `facts `', text) + self.assertIn(' - Example GPU', text) + self.configure(dirs=[self.place], indexLines=1) + text = json.loads(self.hook('SessionStart').stdout)['hookSpecificOutput']['additionalContext'] + self.assertIn(' - Example GPU', text) + self.assertNotIn('Example web cache', text) + self.assertIn(' +2 more: run facts --index', text) + self.configure(dirs=[self.place], indexChars=300) + text = json.loads(self.hook('SessionStart').stdout)['hookSpecificOutput']['additionalContext'] + self.assertLessEqual(len(text), 300) + self.assertIn('more: run facts --index', text) + + def test_the_hook_before_compaction_says_keep_names_not_rows(self): + r = self.hook('PreCompact', trigger='auto') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('keep only the names of the things', r.stdout) + self.assertIn('`facts `', r.stdout) + + def test_the_hook_adds_the_project_text_in_that_project_only(self): + proj = os.path.join(self.tmp, 'proj') + write(os.path.join(proj, 'facts', 'STATE.md'), HEAD + '| Project thing | a | on | w | 11-23 |\n') + self.configure(projects=[{'match': proj, 'dirs': [os.path.join(proj, 'facts')], 'text': 'Project rule.'}]) + r = self.hook('SessionStart', cwd=proj) + text = json.loads(r.stdout)['hookSpecificOutput']['additionalContext'] + self.assertIn(' - Project thing', text) + self.assertTrue(text.endswith('Project rule.'), text) + self.assertIn('Project rule.', self.hook('PreCompact', cwd=proj).stdout) + self.assertEqual(self.hook('SessionStart').stdout, '') # another folder: no table, nothing + + def test_the_hook_with_a_git_that_hangs_still_answers_with_the_machine_tables(self): + fake = os.path.join(self.tmp, 'fake-bin') + script(os.path.join(fake, 'git'), 'exec sleep 30') + self.configure(dirs=[self.place], projects=[{'match': 'github.com/example/project', 'text': 'Remote rule.'}]) + env = dict(self.env, PATH=f'{fake}:{os.environ.get("PATH", "/usr/bin:/bin")}') + start = time.monotonic() + r = fx.run_hook(HOOK, {'hook_event_name': 'SessionStart', 'cwd': self.tmp}, self.machine, env=env) + self.assertLess(time.monotonic() - start, 10) + text = json.loads(r.stdout)['hookSpecificOutput']['additionalContext'] + self.assertIn(' - Example GPU', text) + self.assertNotIn('Remote rule.', text) + + def test_the_hook_is_quiet_with_nothing_to_show(self): + for event in ('Stop', 'UserPromptSubmit'): + self.assertEqual(self.hook(event).stdout, '') + os.unlink(os.path.join(self.place, 'STATE.md')) + for event in ('SessionStart', 'PreCompact'): + r = self.hook(event) + self.assertEqual((r.returncode, r.stdout), (0, ''), r.stderr) + for text in ('', 'not json', '[]', '{"hook_event_name": "SessionStart", "cwd": 5}'): + r = fx.run_hook(HOOK, text, self.machine, env=self.env) + self.assertEqual((r.returncode, r.stdout), (0, ''), text) + + +class RecordRepo(unittest.TestCase): + """`facts WORDS` after the tables: the record repo's text files (this project's folder and the shared ones).""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix='facts-records-') + self.addCleanup(shutil.rmtree, self.tmp, True) + self.place = os.path.join(self.tmp, 'facts') + write(os.path.join(self.place, 'STATE.md'), TABLE) + self.proj = os.path.join(self.tmp, 'work', 'proj') + os.makedirs(self.proj) + r = self.records = os.path.join(self.tmp, 'records') + write(f'{r}/projects/proj/notes.md', '# Notes\nThe example GPU fan curve: gpu-fan.sh\n') + write(f'{r}/projects/other/notes.md', 'Other project: gpu private detail\n') + write(f'{r}/machines/box/STATE.md', TABLE) # a mirrored copy of the table + write(f'{r}/shared/runbook.txt', 'Example GPU: switch it on with gpu on\n') + write(f'{r}/shared/image.png', 'gpu in a file of another type\n') + write(f'{r}/shared/.git/notes.md', 'gpu inside .git\n') + write(f'{r}/orch/big.md', 'gpu\n' + 'x' * (facts.RECORD_MAX + 10)) + os.mkfifo(f'{r}/orch/pipe.md') + os.symlink(f'{r}/projects/other/notes.md', f'{r}/shared/link.md') + self.configure() + self.env = dict(os.environ, HOME=self.tmp, FACTS_TODAY=TODAY.isoformat()) + self.env.pop('FACTS_DIRS', None) + + def configure(self, records=None): + self.machine = fx.machine_file(self.tmp, {'facts': { + 'dirs': [self.place], 'projects': [{'match': self.proj, 'name': 'proj'}], + 'records': [{'path': self.records}] if records is None else records}}) + + def facts(self, *args, cwd=None): + return fx.run_hook('facts', '', self.machine, env=self.env, cwd=cwd or self.proj, args=args, + hook=os.path.join(fx.BIN, 'facts')) + + def test_tables_first_then_this_projects_and_the_shared_record_files(self): + r = self.facts('gpu') + self.assertEqual(r.returncode, 0, r.stderr) + out = r.stdout + self.assertLess(out.index('| Example GPU |'), out.index(f'Records in {self.records}:')) + self.assertIn('projects/proj/notes.md:2: The example GPU fan curve: gpu-fan.sh', out) + self.assertIn('shared/runbook.txt:1: Example GPU: switch it on with gpu on', out) + for absent in ('projects/other', 'machines/box/STATE.md', 'image.png', '.git', 'big.md', 'pipe.md', + 'link.md'): + self.assertNotIn(absent, out) + self.assertEqual(out.count('| Example GPU |'), 1) # the mirrored table is not shown again + r = self.facts('gpu', '--all') + self.assertIn('projects/other/notes.md:1: Other project: gpu private detail', r.stdout) + r = self.facts('gpu', '--no-records') + self.assertNotIn('Records in', r.stdout) + + def test_hits_are_capped_and_lines_trimmed(self): + write(f'{self.records}/shared/many.md', ''.join(f'gpu line {k} ' + 'y' * 300 + '\n' for k in range(70))) + r = self.facts('gpu') + hits = [ln for ln in r.stdout.split('\n') if ':' in ln and ('many.md' in ln or 'notes.md' in ln + or 'runbook' in ln)] + self.assertEqual(len(hits), 10, r.stdout) + self.assertTrue(all(len(ln) <= 160 for ln in hits)) + self.assertIn('+62 more (facts --records gpu)', r.stdout) + r = self.facts('--records', 'gpu') + self.assertNotIn('| Example GPU |', r.stdout) + self.assertEqual(r.stdout.count('many.md:'), 50) + self.assertIn('+22 more (facts --records gpu)', r.stdout) + + def test_a_missing_record_repo_is_one_note_in_the_command_and_silent_in_the_hook(self): + self.configure(records=[{'path': os.path.join(self.tmp, 'gone')}]) + r = self.facts('gpu') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('| Example GPU |', r.stdout) + self.assertEqual([ln for ln in r.stdout.split('\n') if 'gone' in ln], + [f'note: record repo {self.tmp}/gone: not there (or not a folder): skipped']) + r = fx.run_hook(HOOK, {'hook_event_name': 'SessionStart', 'cwd': self.proj}, self.machine, env=self.env) + text = json.loads(r.stdout)['hookSpecificOutput']['additionalContext'] + self.assertNotIn('Records', text) + self.assertNotIn('gone', r.stdout + r.stderr) + + def test_the_hook_names_the_record_repo_in_one_line_and_never_its_content(self): + r = fx.run_hook(HOOK, {'hook_event_name': 'SessionStart', 'cwd': self.proj}, self.machine, env=self.env) + text = json.loads(r.stdout)['hookSpecificOutput']['additionalContext'] + self.assertEqual([ln for ln in text.split('\n') if 'Records' in ln], + [f'Records: {self.records} (facts searches it)']) + self.assertNotIn('fan curve', text) + os.unlink(os.path.join(self.place, 'STATE.md')) # no table: the line alone + r = fx.run_hook(HOOK, {'hook_event_name': 'SessionStart', 'cwd': self.proj}, self.machine, env=self.env) + self.assertEqual(json.loads(r.stdout)['hookSpecificOutput']['additionalContext'], + f'Records: {self.records} (facts searches it)') + + def test_check_never_reads_the_record_repo(self): + write(f'{self.records}/shared/STATE.md', HEAD + '| Stale record | a | on | w | 2000-01-01 |\n') + r = self.facts('--check', '--all') + self.assertEqual(r.returncode, 0, r.stdout) + self.assertNotIn('record', r.stdout.lower()) + + def test_dirs_lists_the_record_folders(self): + r = self.facts('--dirs') + self.assertIn(f'{self.records} (record repo): searched: machines, orch, shared, projects/proj', r.stdout) + + 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} + self.assertEqual(found[0].digest, hashlib.sha256(TABLE.encode()).hexdigest()) + lines, notes = facts.search_records(recs, ['backup'], skip) + self.assertEqual((lines, notes), ([], [])) + lines, _ = facts.search_records(recs, ['backup'], set()) + self.assertIn('machines/box/STATE.md:', lines[1]) + + +if __name__ == '__main__': + unittest.main() diff --git a/fork-kit/agent-guards/tests/install.test.py b/fork-kit/agent-guards/tests/install.test.py index 5b863a695dbdd..53422c4b7c8a4 100644 --- a/fork-kit/agent-guards/tests/install.test.py +++ b/fork-kit/agent-guards/tests/install.test.py @@ -114,6 +114,29 @@ def test_the_choice_is_kept_and_no_settings_removes_it(self): self.assertEqual(self.config()['settings'], False) self.assertEqual(self.run_main('self-check')[0], 0) + def test_an_unrelated_facts_command_is_left_alone_and_our_own_link_is_kept(self): + # review round 1: `facts` is a common name; another program there is never replaced or removed + os.makedirs(self.path('/usr/local/bin'), exist_ok=True) + with open(self.path('/usr/local/bin/facts'), 'w') as f: + f.write('#!/bin/sh\necho another program\n') + code, out, err = self.install() + self.assertEqual(code, 0, err) + self.assertIn('warning: /usr/local/bin/facts is there and is not this kit\'s link: left alone', out) + 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) + 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')) + self.fresh() + code, out, _ = self.install() # nothing there: our link, kept by the next run + self.assertNotIn('warning', out) + self.assertTrue(os.path.islink(self.path('/usr/local/bin/facts'))) + 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')) + def test_runs_again_and_changes_nothing(self): self.assertEqual(self.install('--settings')[0], 0) before = self.snapshot() diff --git a/fork-kit/agent-guards/tests/wiring.test.py b/fork-kit/agent-guards/tests/wiring.test.py index ce946ba0f2415..0b6eb1e1d100a 100644 --- a/fork-kit/agent-guards/tests/wiring.test.py +++ b/fork-kit/agent-guards/tests/wiring.test.py @@ -52,7 +52,8 @@ def test_the_entries_are_the_ones_settings_had(self): sorted([('PreToolUse', 'Write|Edit|MultiEdit', [5]), ('PreToolUse', 'Bash|Monitor', [10]), ('PreToolUse', 'Bash|Monitor', [10]), ('PostToolUse', 'Write|Edit|MultiEdit|Bash|Monitor', [5]), - ('UserPromptSubmit', None, [5]), ('Stop', None, [5, 5])])) + ('UserPromptSubmit', None, [5]), ('Stop', None, [5, 5]), + ('SessionStart', None, [5]), ('PreCompact', None, [5])])) for _e, _m, cmd in wiring.commands_in({'hooks': wiring.hooks()}): self.assertIn('/usr/local/bin/', cmd) self.assertIn('/usr/bin/python3 -IB "$g"', cmd) @@ -182,12 +183,28 @@ def run_check(self, settings): def test_the_kit_entries_pass(self): code, lines = self.run_check(self.settings) self.assertEqual(code, 0, '\n'.join(lines)) - self.assertEqual(sum(ln.startswith('PASS') for ln in lines), 13, '\n'.join(lines)) + self.assertEqual(sum(ln.startswith('PASS') for ln in lines), 14, '\n'.join(lines)) self.assertEqual(lines[-1], 'check: test settings: OK') # lens A nit: the hooks ran with HOME in check's own temporary folder; nothing (log, cache, state) is # written in the caller's HOME self.assertEqual(os.listdir(self.home), []) + def test_facts_hook_with_a_home_folder_table_wants_and_gets_context(self): + # review round 1: the wanted answer and the hook read "~/" under the same HOME (a false FAIL before) + os.makedirs(os.path.join(self.home, 'facts')) + with open(os.path.join(self.home, 'facts', 'STATE.md'), 'w') as f: + f.write('| Thing | State now | Updated |\n|---|---|---|\n| Example thing | on | 11-23 |\n') + machine = fx.machine_file(self.tmp, {'facts': {'dirs': ['~/facts']}}) + fx.use_machine(machine) + with open(os.path.join(self.bin, 'facts-hook'), 'w') as f: + f.write(STAND_IN.format(lib=fx.LIB, machine=machine, uid=os.geteuid(), + hook=os.path.join(fx.BIN, 'facts-hook'))) + code, lines = self.run_check(self.settings) + self.assertEqual(code, 0, '\n'.join(lines)) + self.assertEqual([ln.split(':')[0] for ln in lines if 'facts-hook' in ln], + ['PASS facts-hook (SessionStart) a new session']) + self.assertIn('context', [ln for ln in lines if 'facts-hook' in ln][0]) + def test_a_hook_not_wired_is_missing(self): s = json.loads(json.dumps(self.settings)) s['hooks']['Stop'] = [{'hooks': [h for h in s['hooks']['Stop'][0]['hooks'] if 'bg-guard' not in h['command']]}] diff --git a/fork-kit/common/kit_install.py b/fork-kit/common/kit_install.py index c4da8b26c7568..4e2968868b80c 100644 --- a/fork-kit/common/kit_install.py +++ b/fork-kit/common/kit_install.py @@ -82,6 +82,7 @@ class Installer: LIBEXEC = None # '/usr/local/libexec/fork-cleaner': versions/, current, replaced/ LINKS = {} # {'/usr/local/bin/fork-cleaner': 'bin/fork-cleaner'}: path -> file under current KEEP_OLD = () # link paths where a plain old file (a hand copy) is kept, not refused + OPTIONAL_LINKS = () # link paths with a common name: when something else is there it is left alone (a warning) SOURCE_FILES = () # the files of a release, relative to the kit folder (common/... from fork-kit/common) EXECUTABLE = frozenset() PACKAGE = None # 'cleaner': lib//.py for each of MODULES; each is imported by the self-test @@ -420,7 +421,7 @@ def check_old_state(self): """Refuse, before writing anything, what the installer must not overwrite.""" for path, target in self.links().items(): real = self.p(path) - if not os.path.lexists(real) or self.ours(path, target): + if not os.path.lexists(real) or self.ours(path, target) or path in self.OPTIONAL_LINKS: continue if path in self.KEEP_OLD and self.plain_file(real): continue # a plain old copy: kept in REPLACED, put back by uninstall @@ -525,8 +526,13 @@ def replaced(self): order = [n for n in self.kept_order() if n in found] return [found[n] for n in order] + [found[n] for n in sorted(set(found) - set(order))] + def foreign(self, path, target): + """An OPTIONAL_LINKS path where something that is not the kit's link is: left alone.""" + return path in self.OPTIONAL_LINKS and os.path.lexists(self.p(path)) and not self.ours(path, target) + def record_rows(self, sha, plan): - rows = [(path, 'link', target) for path, target in sorted(self.links().items())] + rows = [(path, 'link', target) for path, target in sorted(self.links().items()) + if not self.foreign(path, target)] rows.append((self.CURRENT, 'link', f'{self.VERSIONS}/{sha}')) for rel, digest in sorted(read_manifest(self.p(f'{self.VERSIONS}/{sha}')).items()): rows.append((f'{self.VERSIONS}/{sha}/{rel}', 'file', digest)) @@ -567,6 +573,10 @@ def _install(self, a, done): self.switch_link(self.CURRENT, f'{self.VERSIONS}/{a.sha}') done('switch') for path, target in self.links().items(): + if self.foreign(path, target): + self.say(f'warning: {path} is there and is not this kit\'s link: left alone (run ' + f'{target} by its full path, or remove {path} and install again)') + continue if path in self.KEEP_OLD: self.drop_restore_leftover(path) self.keep_old(path) diff --git a/fork-kit/common/machine.example.json b/fork-kit/common/machine.example.json index 400676081d616..722549c771b20 100644 --- a/fork-kit/common/machine.example.json +++ b/fork-kit/common/machine.example.json @@ -74,6 +74,28 @@ "maxAlive": 10, "processName": "claude", "note": "at most 4 build agents" + }, + "facts": { + "dirs": ["/etc/fork-kit/facts"], + "staleDays": 30, + "maxRows": 60, + "indexLines": 40, + "indexChars": 4000, + "projects": [ + { + "match": "github.com/example/project", + "dirs": ["/srv/example/project-facts"], + "text": "Project notes: see the project's AGENTS.md.", + "name": "project" + } + ], + "records": [ + { + "path": "/srv/example/records", + "projectsDir": "projects", + "shared": ["machines", "orch", "shared"] + } + ] } }, "cleaner": { diff --git a/fork-kit/common/tests/kit_install.test.py b/fork-kit/common/tests/kit_install.test.py index b8a85658ad4ff..8922fbfa4059d 100644 --- a/fork-kit/common/tests/kit_install.test.py +++ b/fork-kit/common/tests/kit_install.test.py @@ -576,7 +576,13 @@ def test_foreign_link_is_refused_before_anything_is_written(self): shutil.rmtree(self.root) os.makedirs(self.path(os.path.dirname(path))) os.symlink('/somewhere/else', self.path(path)) - code, _, err = self.install() + code, out, err = self.install() + if path in self.m.OPTIONAL_LINKS: # a common name: left alone with a warning, install goes on + self.assertEqual(code, 0, err) + self.assertIn(f"warning: {path} is there and is not this kit's link: left alone", out) + self.assertEqual(os.readlink(self.path(path)), '/somewhere/else') + self.assertEqual(self.run_main('self-check')[0], 0) + continue self.assertEqual(code, 1) self.assertIn("is not the kit's link", err) self.assertFalse(os.path.exists(self.path(self.m.LIBEXEC)))