diff --git a/.claude/skills/readme-media/SKILL.md b/.claude/skills/readme-media/SKILL.md index b6633bb..28f4084 100644 --- a/.claude/skills/readme-media/SKILL.md +++ b/.claude/skills/readme-media/SKILL.md @@ -55,16 +55,16 @@ AW_DISCARD=$D $S/vm.sh down # копия удаляется | `rows` | части строки по одной, потом виджет растягивают за край и возвращают | | `look` | Light и своя тема, размер, две лампы в редакторе темы | | `folders` | Tooling: две папки Claude Code выбираются в диалоге, в каждую ставятся хуки | -| `fullscreen` | терминал на весь экран и точка в углу; завершает остальные сессии | +| `fullscreen` | ручной сценарий для проверки маячка; в автоматическую запись не входит | | `icon` | значок и одна сессия в терминале под ним | | `counts` | то же в виде Counts; последним — оставляет значок в этом виде | -Перед `order`, `rows`, `look`, `folders` и `fullscreen` шаг перезапускает копию с настройками по +Перед `order`, `rows`, `look` и `folders` шаг перезапускает копию с настройками по умолчанию (`stage.sh reset-settings`): ни один дубль не снимает следы предыдущего, и любой можно переснять отдельно. Весь сценарий записан в файлах, по которым новый интерфейс переснимается теми же командами: -`takes/*.sh` — что происходит на экране, `clips.txt` и `clips/*.keys` — что вырезать и куда +`native/devtool/src/media/takes/` — действия и расположение окон, `clips.txt` и `clips/*.keys` — что вырезать и куда смотрит камера, `vm.sh shoot` — порядок. Править их нужно, только когда изменились подписи или раскладка окон (ниже, «Когда изменился интерфейс»); новый ролик — строка в `clips.txt`. @@ -84,7 +84,7 @@ list» ждёт дублей `start` и `menu`; если сцена поднят Каждый дубль пишет `<дубль>.mov` и `<дубль>.marks` в `~/Library/Caches/agent-watch-media` машины, `fetch` переносит их в тот же каталог на Mac; там же кадры, ролики и раскладки. Дубль можно повторить отдельно: `vm.sh run takes/<дубль>.sh`; перед повторным `order`, `rows`, -`look`, `folders` или `fullscreen` — `vm.sh run stage.sh reset-settings`, как это делает `shoot`. +`look` или `folders` — `vm.sh run stage.sh reset-settings`, как это делает `shoot`. Ролики режутся и по одному: `scripts/devtool media cut --sheet clip-menu`. Если сцена встала на полпути, `vm.sh shoot stage` поднимает её заново и снимает всё, что после. @@ -160,10 +160,10 @@ list» ждёт дублей `start` и `menu`; если сцена поднят - **Чужого в кадре нет:** уведомлений, файлов рабочего стола (они видны на любом столе — сцену целиком закрывают окна), почты и названия организации (их прячет `IS_DEMO=1`), путей, кроме `~/CommonProjects/agent-watch`, строк чужих сессий (виджет и сводка меню). -- **Размер и лишние файлы.** `scripts/devtool media cut --publish` печатает размер всех роликов — сейчас около - 6,4 МБ на тринадцать — и называет ролик, который есть в `docs/images`, но не в `clips.txt` или - README: переименованный ролик оставлял там старый файл. Вырос ролик — проверить, не стоит ли в - кадре что-то мигающее, или поднять `CRF`. +- **Размер и лишние файлы.** До записи запустите `scripts/devtool check-docs`: он сверяет + ссылки в README, `clips.txt` и файлы в `docs/images`. После монтажа + `scripts/devtool media cut --publish` печатает общий размер. Вырос ролик — проверить, + не стоит ли в кадре что-то мигающее, или поднять `CRF`. - **После пуша ветки** открыть README на её странице на GitHub и только потом переносить в main: показ AVIF на GitHub проверяется только так. @@ -179,7 +179,7 @@ list» ждёт дублей `start` и `menu`; если сцена поднят - **Подписи.** Сценарий находит элемент по тексту Accessibility: `click find <конец текста>` или `click findc <часть текста>`. Дерево Accessibility держит пункты меню и закрытым, и поиск по концу текста берёт первое совпадение — «Hide Widget» тоже кончается на «Widget». -- **Раскладка окон.** Координаты окон в `takes/*.sh` — точки экрана; сцена дубля (`STAGE`) — его +- **Раскладка окон.** Координаты окон в `native/devtool/src/media/takes/` — точки экрана; сцена дубля (`STAGE`) — его кадр. Рамки камеры в `clips/*.keys` — пиксели сцены: `(точка − начало сцены) × 2`. Строка `.keys`: момент (`@отметка±секунды`), x, y, ширина рамки; высота следует из размера ролика. Одна строка — камера стоит; между двумя разными строками она плавно едет. Клики сценария diff --git a/.claude/skills/readme-media/scripts/clips.txt b/.claude/skills/readme-media/scripts/clips.txt index e6229e3..74d02ba 100644 --- a/.claude/skills/readme-media/scripts/clips.txt +++ b/.claude/skills/readme-media/scripts/clips.txt @@ -1,13 +1,11 @@ # One clip a line: name, take, in, out, width, height, camera keys, and `fade=` where the # loop would jump from a busy last frame to a calm first one. In and out are marks of the take # (`@mark±seconds`); the size is twice the width the README shows it at. The keys hold the whole -# scene and a focus on what changes; a focus goes no closer than pixel for pixel, but for the -# full-screen dot, which is 8 points. +# scene and a focus on what changes; a focus goes no closer than pixel for pixel. clip-start start @scroll-2.2 @done+4.0 1600 1000 clips/start.keys fade=1 clip-menu menu @open-menu-1.2 @escape+1.4 1600 1000 clips/menu.keys clip-icon icon @ask-1.0 @done+2.2 1280 800 clips/icon.keys clip-counts counts @ask-1.0 @done+2.2 1280 800 clips/icon.keys -clip-fullscreen fullscreen @ask-1.2 @done+2.0 1600 1000 clips/fullscreen.keys clip-order order @order-1.0 @drag+3.6 1600 1000 clips/order.keys clip-rows rows @rows-0.8 @on-model+2.2 1600 1000 clips/rows.keys clip-resize rows @wider-2.4 @back+1.6 1600 1000 clips/resize.keys diff --git a/.claude/skills/readme-media/scripts/clips/fullscreen.keys b/.claude/skills/readme-media/scripts/clips/fullscreen.keys deleted file mode 100644 index d5006b5..0000000 --- a/.claude/skills/readme-media/scripts/clips/fullscreen.keys +++ /dev/null @@ -1,13 +0,0 @@ -# The whole screen: a full-screen terminal's lines start at its left edge. Then onto the corner as the -# dot comes on, blue and orange, with the menu bar sliding over it and away; out for the answer, and -# in again as the dot goes out. The dot is 8 points: the focus is twice as close and the one that -# goes past pixel for pixel. -@ask-1.2 0 0 2304 -@ask-0.2 0 0 2304 -@ask+0.6 1152 0 1152 -@back+1.2 1152 0 1152 -@approve-0.6 0 0 2304 -@approve+0.2 0 0 2304 -@approve+1.0 1152 0 1152 -@done+0.8 1152 0 1152 -@done+1.6 0 0 2304 diff --git a/.github/workflows/verify-plugin.yml b/.github/workflows/verify-plugin.yml index db0bffd..c7cdeef 100644 --- a/.github/workflows/verify-plugin.yml +++ b/.github/workflows/verify-plugin.yml @@ -2,7 +2,7 @@ name: verify-plugin on: push: - branches: ["**"] + branches: ["main"] paths: - "ide-plugin/**" - ".github/workflows/verify-plugin.yml" diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 736655b..09d059e 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -2,7 +2,7 @@ name: verify on: push: - branches: ["**"] + branches: ["main"] pull_request: workflow_dispatch: @@ -12,12 +12,7 @@ concurrency: jobs: verify: - # Both systems the app is used on: they lay out the same windows differently. - strategy: - fail-fast: false - matrix: - os: [macos-15, macos-26] - runs-on: ${{ matrix.os }} + runs-on: macos-26 steps: - uses: actions/checkout@v5 diff --git a/AGENTS.md b/AGENTS.md index 82cc9c2..7ff31d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,14 +42,14 @@ can be tested in `AgentWatchCoreTests` without launching an application. holds it. To create it: Keychain Access → Certificate Assistant → Create a Certificate…, Self Signed Root, Code Signing. It need not be trusted, so `security find-identity -v` will not list it. -- **`task verify` rebuilds `dist/` from scratch**, so hooks installed from `dist/AgentWatch.app` - point at a bundle that will be replaced. Copy it to `/Applications` and install from the copy. +- **`task verify` replaces `dist/AgentWatch.app`.** Install hooks from a copy in + `/Applications` so they keep pointing at the installed bundle. - **A debug copy that installs hooks needs `AGENT_WATCH_HOME_DIR` beside `AGENT_WATCH_SUPPORT_DIR`.** It names the home that holds `.claude` and `.codex`. `HOME` cannot do it: Foundation returns the account's home whatever `HOME` says, while both agents follow `HOME`. Give the same value to a sender you run by hand, or it reports its default folder as another one. -- **One Agent Watch runs at a time.** Quit an installed copy before running a build: - `osascript -e 'quit app "AgentWatch"'`. +- **`task dev` runs beside the installed app.** Dev has its own bundle identity, settings and + socket. Quit the installed app before replacing the copy it is running from. - **Every worktree runs the gates of its own branch, so `core.hooksPath` stays unset.** `task setup` puts a small dispatcher for each hook into the shared `.git/hooks/`; it runs `.githooks/` of the worktree Git is working in. Claude rewrites `core.hooksPath` when it creates a worktree: diff --git a/README.md b/README.md index c734d50..e422586 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,8 @@ **See which Claude Code or Codex session needs you, without switching between terminals.** -A menu bar app for Apple Silicon Macs with macOS 14 or newer. Alpha: used every day, still changing. +A menu bar app for Apple Silicon Macs. Alpha: used every day, still changing. +Runtime checks use the macOS version installed on the development Mac. [Download](https://github.com/glockbender/agentwatcher/releases) · [Install](#install) · [What it works with](#what-it-works-with) · [Troubleshooting](TROUBLESHOOTING.md) @@ -254,6 +255,10 @@ Trash. Each proposed action names the folder and explains why it qualifies. a `PreToolUse` entry in that profile. App state lives in `~/Library/Application Support/AgentWatch/`. - The updater contacts GitHub to check for and download releases. When handling a push, the Git tool contacts the project’s configured remote to check its refs and perform an approved change. +- While a Claude session is working, Agent Watch can ask Claude Code for updated plan limits + using the sign-in for its default profile. It does this at most once every 30 minutes when + the last reading is stale. The request sends no prompt and counts as a Claude Code session + in the organisation’s usage metrics. Details: [installing into the agents](docs/agent-install.md), [architecture](docs/architecture.md). diff --git a/Resources/GitProtection/hooks/git_guard.py b/Resources/GitProtection/hooks/git_guard.py deleted file mode 100644 index e887bf9..0000000 --- a/Resources/GitProtection/hooks/git_guard.py +++ /dev/null @@ -1,1053 +0,0 @@ -"""Check shell tool calls before execution. Only the native CLI performs a push.""" - -from __future__ import annotations - -import json -import os -import re -import shlex -import signal -import sys -import time -from collections.abc import Mapping, Sequence -from dataclasses import dataclass, field -from pathlib import Path -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - import subprocess - -MAX_COMMAND = 1_000_000 -MAX_DEPTH = 6 -# Leave time to deny before the client hook times out. -TIME_BUDGET = 6.0 -DEADLINE = [0.0] - - -class TimeBudgetError(Exception): - """The time budget of this hook run is spent.""" - - -class GitInspectionError(Exception): - """A required Git fact could not be read.""" - - -# --- Splitting a command the way a shell does --------------------------------- - - -@dataclass(eq=False) -class Word: - text: str # after quote removal; substitutions kept as written, e.g. $(git branch) - has_substitution: bool = False - quoted: bool = False - - -@dataclass(eq=False) -class Simple: - words: list[Word] = field(default_factory=list) - has_redirect: bool = False - - def texts(self) -> list[str]: - return [word.text for word in self.words] - - -@dataclass(eq=False) -class Pipeline: - commands: list[Simple] = field(default_factory=list) - scope: int = 0 # the shell that runs it: a subshell, a substitution or a script has its own - - -@dataclass -class Scopes: - """Which shell runs inside which: a child starts with its parent's state.""" - - parents: dict[int, int] = field(default_factory=dict) - next_id: int = 1 - - def child_of(self, parent: int) -> int: - scope = self.next_id - self.next_id += 1 - self.parents[scope] = parent - return scope - - -SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "fish"} -# Words that run the command after them; with the options that take a value. -WRAPPERS: dict[str, set[str]] = { - "sudo": {"-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U"}, - "doas": {"-u", "-C"}, - "env": {"-u", "-C", "-S"}, - "command": set(), - "builtin": set(), - "exec": {"-a"}, - "nice": {"-n"}, - "nohup": set(), - "time": set(), - "timeout": {"-k", "-s", "--kill-after", "--signal"}, - "gtimeout": {"-k", "-s", "--kill-after", "--signal"}, - "xargs": {"-I", "-L", "-n", "-P", "-s", "-E", "-d", "-a"}, - "stdbuf": {"-i", "-o", "-e"}, - "caffeinate": {"-t", "-w"}, - "chronic": set(), - "ionice": {"-c", "-n", "-p"}, -} -# Shell words that may stand before the command on the same line. -RESERVED = {"!", "{", "}", "if", "then", "elif", "else", "fi", "do", "done", "while", "until"} -# Programs that run a shell inside a container or a pod; its script is code too. -CONTAINER_TOOLS = {"docker", "podman", "nerdctl", "kubectl"} -SSH_VALUE_OPTIONS = set("bcDEeFIiJLlmOopQRSWw") -ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") -OPERATOR_CHARS = set(";&|()<>") - - -def basename(word: str) -> str: - return word.rsplit("/", 1)[-1] - - -def command_index(words: Sequence[Word]) -> int: - """Index of the word that names the program: after reserved words, assignments, wrappers.""" - index = 0 - while index < len(words) and words[index].text in RESERVED: - index += 1 - while index < len(words): - text = words[index].text - if ASSIGNMENT.match(text): - index += 1 - continue - name = basename(text) - if name not in WRAPPERS: - return index - index += 1 - while index < len(words) and words[index].text.startswith("-"): - option = words[index].text - index += 1 - if option == "--": - break - if option in WRAPPERS[name]: - index += 1 - if name in ("timeout", "gtimeout") and index < len(words): - index += 1 # the duration - return index - - -def program(command: Simple) -> str: - index = command_index(command.words) - if index < len(command.words): - return basename(command.words[index].text) - return "" - - -def wrapper_names(command: Simple) -> set[str]: - index = command_index(command.words) - return {basename(word.text) for word in command.words[:index]} & set(WRAPPERS) - - -def find_closing(text: str, start: int, opening: str = "(", closing: str = ")") -> int: - """Index of the bracket that closes one opened just before start; len(text) if none. - - Only for ${…} and $((…)), which hold no heredocs; $(…) is parsed properly. - """ - depth = 1 - index = start - while index < len(text): - char = text[index] - if char == "\\": - index += 2 - continue - if char == "'": - end = text.find("'", index + 1) - index = len(text) if end < 0 else end + 1 - continue - if char == '"': - index += 1 - while index < len(text) and text[index] != '"': - index += 2 if text[index] == "\\" else 1 - index += 1 - continue - if char == opening: - depth += 1 - elif char == closing: - depth -= 1 - if depth == 0: - return index - index += 1 - return len(text) - - -def option_values(arguments: Sequence[str], start: int = 0) -> tuple[int, set[str], set[str]]: - """Walks the options of a shell: (index of the first operand, its letters, its -o names).""" - index = start - letters: set[str] = set() - names: set[str] = set() - while index < len(arguments): - word = arguments[index] - if word in ("-o", "+o", "-O", "+O"): - if index + 1 < len(arguments) and word == "-o": - names.add(arguments[index + 1]) - index += 2 - elif word in ("--rcfile", "--init-file"): - index += 2 - elif word == "--": - return index + 1, letters, names - elif word.startswith("--"): - index += 1 - elif word.startswith("-") and len(word) > 1: - letters.update(word[1:]) - index += 1 - if word[-1] in "oO" and index < len(arguments): - # -euo pipefail: the cluster's last letter takes the next word - if word[-1] == "o": - names.add(arguments[index]) - index += 1 - else: - break - return index, letters, names - - -def shell_script(arguments: Sequence[str]) -> str | None: - """The script of `sh -c SCRIPT`, from the words after the shell's name.""" - index, letters, _ = option_values(arguments) - if "c" in letters and index < len(arguments): - return arguments[index] - return None - - -def ssh_remote_command(arguments: Sequence[str]) -> str: - index = 0 - while index < len(arguments) and arguments[index].startswith("-"): - option = arguments[index] - index += 1 - if len(option) == 2 and option[1] in SSH_VALUE_OPTIONS: - index += 1 - return " ".join(arguments[index + 1 :]) - - -def shell_position(command: Simple) -> int | None: - """Index of the shell word this command runs: itself, or one inside a container.""" - words = command.texts() - index = command_index(command.words) - if index >= len(words): - return None - if basename(words[index]) in SHELLS: - return index - if basename(words[index]) in CONTAINER_TOOLS: - for position in range(index + 1, len(words)): - if basename(words[position]) in SHELLS: - return position - return None - - -def reads_stdin_as_code(command: Simple) -> bool: - """A shell that would run what it reads on stdin: no -c script of its own.""" - words = command.texts() - position = shell_position(command) - if position is not None: - return shell_script(words[position + 1 :]) is None - index = command_index(command.words) - name = program(command) - if name == "ssh": - remote = ssh_remote_command(words[index + 1 :]).split() - if not remote: - return True - return basename(remote[0]) in SHELLS and shell_script(remote[1:]) is None - if index >= len(words) and "sudo" in wrapper_names(command): - return any(word in ("-s", "-i") for word in words) - return False - - -class Parser: - """Turns command text into pipelines, nested ones included. - - The text of a heredoc counts as code only when a shell reads it (`bash < s.sh < None: - if not normalized: - text = text.replace("\r", "").replace("\\\n", "") - self.text = text - self.position = start - self.depth = depth - self.until_paren = until_paren - self.scopes = scopes if scopes is not None else Scopes() - self.scope = scope - self.pipelines: list[Pipeline] = [] - self.pipeline = Pipeline() - self.command = Simple() - # Heredocs started on the current line: (pipeline, command, delimiter). - self.pending: list[tuple[Pipeline, Simple, str]] = [] - # Parentheses create a shell scope; braces keep the existing working folder. - self.groups: list[tuple[str, int]] = [] - - def parse(self) -> list[Pipeline]: - if self.depth > MAX_DEPTH: - self.position = len(self.text) - return [] - text = self.text - while self.position < len(text): - char = text[self.position] - if char in " \t": - self.position += 1 - elif char == "\n": - self.position += 1 - self.end_pipeline() - self.read_heredocs() - elif char == "#": - end = text.find("\n", self.position) - end = len(text) if end < 0 else end - self.position = end - elif text.startswith("&&", self.position) or text.startswith("||", self.position): - self.position += 2 - self.end_pipeline() - elif text.startswith(";;", self.position): - self.position += 2 - self.end_pipeline() - elif char == ";": - self.position += 1 - self.end_pipeline() - elif text.startswith("|&", self.position): - self.position += 2 - self.end_command() - elif char == "|": - self.position += 1 - self.end_command() - elif char == "&" and not text.startswith("&>", self.position): - self.position += 1 - self.end_pipeline() - elif char == "(": - words = self.command.texts() - if text.startswith("((", self.position) and words in ([], ["for"]): - # Arithmetic: (( i++ )), and the head of for ((;;)). - end = text.find("))", self.position + 2) - end = len(text) if end < 0 else end - self.command.words.append(Word(text[self.position : end + 2])) - self.position = end + 2 - else: - self.position += 1 - self.open_group("(") - elif char == ")": - self.position += 1 - if self.close_group("("): - continue - if self.until_paren: - self.end_pipeline() - return self.pipelines - self.end_pipeline() - elif self.at_redirect(): - self.read_redirect() - else: - word = self.read_word() - if word is None: - continue - if word.text == "{" and not word.quoted and not self.command.words: - self.open_group("{") - elif word.text == "}" and not word.quoted and not self.command.words: - if not self.close_group("{"): - self.command.words.append(word) - else: - self.command.words.append(word) - self.end_pipeline() - self.read_heredocs() - return self.pipelines - - # Groups: ( … ) runs in a subshell of its own; { …; } in the same shell. - - def open_group(self, kind: str) -> None: - self.end_pipeline() - self.groups.append((kind, self.scope)) - if kind == "(": - self.scope = self.scopes.child_of(self.scope) - - def close_group(self, kind: str) -> bool: - if not self.groups or self.groups[-1][0] != kind: - return False - self.end_pipeline() - _, self.scope = self.groups.pop() - return True - - def end_command(self) -> None: - if self.command.words or self.command.has_redirect: - self.pipeline.commands.append(self.command) - self.parse_scripts(self.command) - self.command = Simple() - - def end_pipeline(self) -> None: - self.end_command() - if self.pipeline.commands: - self.pipeline.scope = self.scope - self.pipelines.append(self.pipeline) - self.pipeline = Pipeline() - - def nested(self, text: str) -> None: - scope = self.scopes.child_of(self.scope) - self.pipelines.extend(Parser(text, self.depth + 1, scopes=self.scopes, scope=scope).parse()) - - def nested_command(self, words: Sequence[Word]) -> None: - """Words that another program runs as a command of their own: git bisect run …""" - if not words: - return - command = Simple(list(words)) - self.pipelines.append(Pipeline([command], scope=self.scope)) - self.parse_scripts(command) - - def substitution(self, start: int) -> int: - """Parses $(…) or <(…) from start; returns the index just after its `)`.""" - if self.depth >= MAX_DEPTH: - return find_closing(self.text, start) + 1 - scope = self.scopes.child_of(self.scope) - inner = Parser( - self.text, - self.depth + 1, - start=start, - until_paren=True, - scopes=self.scopes, - scope=scope, - normalized=True, - ) - self.pipelines.extend(inner.parse()) - return inner.position - - def parse_scripts(self, command: Simple) -> None: - """Code that this command runs from its arguments: sh -c, eval, ssh, and the like.""" - words = command.texts() - index = command_index(command.words) - for position, word in enumerate(words[:index]): - # env -S 'cmd args' splits the string and runs it. - if basename(word) == "env": - for offset in range(position + 1, index): - if words[offset] in ("-S", "--split-string") and offset + 1 < len(words): - self.nested(words[offset + 1]) - if index >= len(words): - return - name = basename(words[index]) - rest = words[index + 1 :] - shell = shell_position(command) - if shell is not None: - script = shell_script(words[shell + 1 :]) - if script is not None: - self.nested(script) - elif name == "eval": - self.nested(" ".join(rest)) - elif name == "ssh": - remote = ssh_remote_command(rest) - if remote: - self.nested(remote) - elif name == "watch": - position = 0 - while position < len(rest) and rest[position].startswith("-"): - takes_value = rest[position] in ("-n", "--interval", "-q", "--equexit") - position += 2 if takes_value else 1 - if position < len(rest): - self.nested(" ".join(rest[position:])) - elif name == "parallel": - template = [word for word in rest if not word.startswith("-")][:1] - if template and template[0] != ":::": - self.nested(template[0]) - elif name == "git": - self.git_runs(command.words[index + 1 :]) - elif name == "find": - for position, word in enumerate(words): - if word in ("-exec", "-execdir") and position + 1 < len(words): - if basename(words[position + 1]) in SHELLS: - script = shell_script(words[position + 2 :]) - if script is not None: - self.nested(script) - - def git_runs(self, arguments: Sequence[Word]) -> None: - """git submodule foreach CMD runs CMD with sh; git bisect run CMD execs it.""" - texts = [word.text for word in arguments] - position = git_subcommand(texts) - if position + 1 >= len(texts): - return - sub, after = texts[position], texts[position + 1] - if sub == "submodule" and after == "foreach": - rest = [ - word - for word in texts[position + 2 :] - if word not in ("--recursive", "-q", "--quiet") - ] - if rest: - self.nested(" ".join(rest)) - elif sub == "bisect" and after == "run": - self.nested_command(arguments[position + 2 :]) - - # Heredocs. - - def read_heredocs(self) -> None: - pending, self.pending = self.pending, [] - # Whether a shell reads stdin at or after each command, once per pipeline. - code_after: dict[int, list[bool]] = {} - for pipeline, command, delimiter in pending: - lines = [] - while self.position < len(self.text): - end = self.text.find("\n", self.position) - end = len(self.text) if end < 0 else end - line = self.text[self.position : end] - self.position = end + 1 - if line.strip(" \t") == delimiter: - break - lines.append(line) - body = "\n".join(lines) - commands = pipeline.commands or [command] - key = id(pipeline) - if key not in code_after: - flags = [reads_stdin_as_code(each) for each in commands] - for position in range(len(flags) - 2, -1, -1): - flags[position] = flags[position] or flags[position + 1] - code_after[key] = flags - place = next((n for n, each in enumerate(commands) if each is command), 0) - if code_after[key] and code_after[key][place]: - self.nested(body) - - # Redirections. - - def at_redirect(self) -> bool: - text = self.text[self.position :] - return bool(re.match(r"(\d*|&)(>>?|<\||<>|>&|<&)", text)) and not re.match( - r"[<>]\(", text - ) - - def read_redirect(self) -> None: - match = re.match(r"(\d*|&)(<<<|<<-|<<|>>|>\||<>|>&|<&|>|<)", self.text[self.position :]) - assert match is not None - op = match.group(1) + match.group(2) if match.group(1) == "&" else match.group(2) - self.command.has_redirect = True - self.position += match.end() - while self.position < len(self.text) and self.text[self.position] in " \t": - self.position += 1 - if op in (">&", "<&"): - duplicate = re.match(r"\d+-?|-", self.text[self.position :]) - if duplicate: - self.position += duplicate.end() - return - target = self.read_word() - target_text = target.text if target is not None else "" - if op in ("<<", "<<-"): - self.pending.append((self.pipeline, self.command, target_text)) - - # Words. - - def read_word(self) -> Word | None: - text = self.text - parts: list[str] = [] - substitution = quoted = False - start = self.position - while self.position < len(text): - char = text[self.position] - if char in " \t\n" or char in OPERATOR_CHARS: - if char in "<>" and text.startswith("(", self.position + 1): - # Process substitution <(…) / >(…): it runs a command. - end = self.substitution(self.position + 2) - parts.append(text[self.position : end]) - substitution = True - self.position = end - continue - break - if char == "\\": - parts.append(text[self.position + 1 : self.position + 2]) - self.position += 2 - elif char == "'": - end = text.find("'", self.position + 1) - end = len(text) if end < 0 else end - parts.append(text[self.position + 1 : end]) - self.position = end + 1 - quoted = True - elif text.startswith("$'", self.position): - end = self.position + 2 - while end < len(text) and text[end] != "'": - end += 2 if text[end] == "\\" else 1 - parts.append(text[self.position + 2 : end]) - self.position = end + 1 - quoted = True - elif char == '"': - substitution = self.read_double_quoted(parts) or substitution - quoted = True - elif char == "`": - end = text.find("`", self.position + 1) - end = len(text) if end < 0 else end - self.nested(text[self.position + 1 : end]) - parts.append(text[self.position : end + 1]) - substitution = True - self.position = end + 1 - elif text.startswith("$((", self.position): - end = find_closing(text, self.position + 3) - self.arithmetic(text[self.position + 3 : end]) - parts.append(text[self.position : end + 2]) - self.position = end + 2 - elif text.startswith("$(", self.position): - end = self.substitution(self.position + 2) - parts.append(text[self.position : end]) - substitution = True - self.position = end - elif text.startswith("${", self.position): - end = find_closing(text, self.position + 2, "{", "}") - parts.append(text[self.position : end + 1]) - self.position = end + 1 - else: - parts.append(char) - self.position += 1 - if self.position == start: - self.position += 1 - return None - return Word("".join(parts), substitution, quoted) - - def read_double_quoted(self, parts: list[str]) -> bool: - text = self.text - self.position += 1 - substitution = False - while self.position < len(text) and text[self.position] != '"': - char = text[self.position] - if char == "\\" and self.position + 1 < len(text): - following = text[self.position + 1] - parts.append(following if following in '$`"\\' else char + following) - self.position += 2 - elif text.startswith("$((", self.position): - end = find_closing(text, self.position + 3) - self.arithmetic(text[self.position + 3 : end]) - parts.append(text[self.position : end + 2]) - self.position = end + 2 - elif text.startswith("$(", self.position): - end = self.substitution(self.position + 2) - parts.append(text[self.position : end]) - substitution = True - self.position = end - elif char == "`": - end = text.find("`", self.position + 1) - end = len(text) if end < 0 else end - self.nested(text[self.position + 1 : end]) - parts.append(text[self.position : end + 1]) - substitution = True - self.position = end + 1 - else: - parts.append(char) - self.position += 1 - self.position += 1 - return substitution - - def arithmetic(self, inner: str) -> None: - """$((…)) is arithmetic, not a command; a $(…) inside it does run.""" - index = inner.find("$(") - while index >= 0: - if inner.startswith("$((", index): - index = inner.find("$(", index + 3) - continue - end = find_closing(inner, index + 2) - self.nested(inner[index + 2 : end]) - index = inner.find("$(", end) - - -@dataclass -class Folders: - """The folder each shell is in: a subshell starts in its parent's, and its cd ends with it.""" - - parents: Mapping[int, int] - start: str - by_scope: dict[int, str] = field(default_factory=dict) - - def of(self, scope: int) -> str: - if scope not in self.by_scope: - parent = self.parents.get(scope) - inherited = self.of(parent) if parent is not None and parent != scope else self.start - self.by_scope[scope] = inherited - return self.by_scope[scope] - - def move(self, scope: int, folder: str) -> None: - self.by_scope[scope] = folder - - -def git_subcommand(arguments: Sequence[str]) -> int: - """Index of git's subcommand in the words after `git`, past its own options.""" - position = 0 - while position < len(arguments) and arguments[position].startswith("-"): - option = arguments[position] - if option in ("-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"): - position += 2 - else: - position += 1 - return position - - -PROTECTED = ("main", "master") -CURRENT_BRANCH_WORDS = ("HEAD", "@") - - -def run_git(repo: str, *arguments: str) -> subprocess.CompletedProcess[str] | None: - """git in the time left; when that runs out, the whole guard stops (TimeBudgetError).""" - import subprocess - - left = DEADLINE[0] - time.monotonic() - if left <= 0: - raise TimeBudgetError("git did not answer in time") - try: - return subprocess.run( - ["git", "-C", repo, *arguments], capture_output=True, text=True, timeout=left - ) - except subprocess.TimeoutExpired as error: - raise TimeBudgetError("git did not answer in time") from error - except OSError: - return None - - -def current_branch(repo: str) -> str: - result = run_git(repo, "rev-parse", "--abbrev-ref", "HEAD") - if result is None or result.returncode != 0 or not result.stdout.strip(): - raise GitInspectionError("The current branch could not be determined.") - return result.stdout.strip() - - -def push_config_risks(repo: str, remote: str | None, refspecs: Sequence[str], implicit: bool) -> list[str]: - result = run_git(repo, "config", "--null", "--get-regexp", r"^(push\.default|remote\..*\.(mirror|push))$") - if result is None or result.returncode not in (0, 1): - raise GitInspectionError("Git push defaults could not be read.") - push_default = "simple" - refspec = mirror = False - for entry in result.stdout.split("\0"): - key, _, value = entry.partition("\n") - if key == "push.default": - push_default = value.lower() - elif key and (remote is None or key.rsplit(".", 1)[0] == f"remote.{remote}"): - if key.endswith(".push"): - refspec = True - elif key.endswith(".mirror"): - mirror |= value.lower() not in {"false", "no", "off", "0"} - risks = ["the remote defaults to a mirror push"] if mirror else [] - unmapped = any(":" not in word for word in refspecs) - if (refspec and (implicit or unmapped) - or implicit and push_default not in {"simple", "current", "nothing"} - or unmapped and push_default in {"upstream", "tracking"}): - risks.append("the push destination depends on Git configuration; name the exact destination") - return risks - - -def is_known_branch(repo: str, name: str) -> bool: - result = run_git(repo, "for-each-ref", "--format=%(refname)", f"refs/heads/{name}") - if result is not None and result.stdout.strip(): - return True - result = run_git(repo, "for-each-ref", "--format=%(refname)", f"refs/remotes/*/{name}") - return result is not None and bool(result.stdout.strip()) - - -def is_local_tag(repo: str, name: str) -> bool: - result = run_git(repo, "show-ref", "--verify", "--quiet", f"refs/tags/{name}") - return result is not None and result.returncode == 0 - - -def is_protected(ref: str) -> bool: - for name in PROTECTED: - if ref in (name, "heads/" + name) or ref.endswith("/heads/" + name): - return True - return False - - -@dataclass -class GitContext: - home: str - switched: str = "" # the branch a checkout/switch earlier in the command moved to - deleted_tags: set[str] = field(default_factory=set) # tags a `git tag -d` removed - # Branches a `git branch -d` removed: deleting them on the remote is no tag delete. - deleted_branches: set[str] = field(default_factory=set) - - def resolve(self, path: str, cwd: str) -> str: - if path == "~": - return self.home - if path.startswith("~/"): - return os.path.join(self.home, path[2:]) - return os.path.join(cwd, path) - - -def push_option(argument: str, *names: str) -> bool: - option = argument.partition("=")[0] - return ( - option.startswith("--") - and len(option) > 2 - and any(name.startswith(option) for name in names) - ) - - -def check_push(repo: str, context: GitContext, arguments: Sequence[str], overrides: bool) -> list[str]: - dry = force = push_all = delete = tags_only = prune = False - refs: list[str] = [] - skip = False - options = True - remote_option = None - read_remote = False - for argument in arguments: - if read_remote: - remote_option = argument - read_remote = False - continue - if skip: - skip = False - continue - if options and argument == "--": - options = False - continue - if not options: - if argument.startswith("+"): - force = True - argument = argument[1:] - refs.append(argument) - continue - if argument == "-n" or (argument.startswith("--dr") and "--dry-run".startswith(argument)): - dry = True - elif argument.startswith("--no-dr") and "--no-dry-run".startswith(argument): - dry = False - elif push_option( - argument, "--force", "--force-if-includes", "--force-with-lease", "--mirror" - ): - force = True - elif push_option(argument, "--all", "--branches"): - push_all = True - elif argument in ("--prune", "--prun", "--pru"): - prune = True - elif argument in ("--no-prune", "--no-prun", "--no-pru"): - prune = False - elif push_option(argument, "--delete"): - delete = True - elif push_option(argument, "--tags"): - tags_only = True - elif push_option(argument, "--no-tags"): - tags_only = False - elif push_option(argument, "--repo"): - _, separator, value = argument.partition("=") - if separator: - remote_option = value - else: - read_remote = True - elif argument == "-o" or push_option( - argument, "--receive-pack", "--exec", "--push-option" - ): - skip = "=" not in argument - elif argument.startswith("--"): - pass - elif argument.startswith("-") and len(argument) > 1: - letters = argument[1:] - for index, letter in enumerate(letters): - if letter == "o": - skip = index == len(letters) - 1 - break - if letter == "n": - dry = True - elif letter == "f": - force = True - elif letter == "d": - delete = True - elif argument.startswith("+"): - force = True - refs.append(argument[1:]) - else: - refs.append(argument) - if dry: - return [] - risks = [] - if prune: - risks.append("push --prune may delete remote branches or tags") - if force: - risks.append("force push") - if push_all: - risks.append("push --all includes main/master") - - def current() -> str: - return context.switched or current_branch(repo) - - remote = refs[0] if refs else remote_option - refspecs = refs[1:] - implicit = not refspecs and not tags_only and not push_all - if overrides: - risks.append("command-local Git configuration may override push routing") - risks.extend(push_config_risks(repo, remote, refspecs, implicit)) - after_tag_word = False - for refspec in refspecs: - if refspec == "tag": - after_tag_word = True - continue - name = "" - if delete: - name = refspec - elif refspec.startswith(":") and refspec != ":": - name = refspec[1:] - if name: - if is_protected(name): - risks.append("push targets main/master") - elif name.startswith("refs/tags/") or after_tag_word or name in context.deleted_tags: - risks.append(f"deletes tag '{name.rsplit('/', 1)[-1]}' on the remote") - elif name.startswith("refs/heads/") or name in context.deleted_branches: - risks.append(f"deletes branch '{name.rsplit('/', 1)[-1]}' on the remote") - elif not is_known_branch(repo, name): - if is_local_tag(repo, name) or re.match(r"^v?\d", name): - risks.append(f"deletes tag '{name}' on the remote") - else: - risks.append( - f"deletes '{name}' on the remote; it is not a known branch, " - "so it may be a tag" - ) - else: - risks.append(f"deletes branch '{name}' on the remote") - after_tag_word = False - continue - after_tag_word = False - if refspec == ":" or "*" in refspec: - risks.append("pushes matching branches, main/master included") - continue - source, _, destination = refspec.partition(":") - destination = destination or source - if is_protected(destination): - risks.append("push targets main/master") - elif destination in CURRENT_BRANCH_WORDS or "$(" in destination or "`" in destination: - branch = current() - if branch in PROTECTED: - risks.append(f"pushes the current branch '{branch}' (protected)") - if implicit: - branch = current() - if branch in PROTECTED: - risks.append(f"current branch is '{branch}' (protected)") - return risks - - -def git_guard( - pipelines: Sequence[Pipeline], cwd: str, home: str, scopes: Scopes -) -> tuple[str, str] | None: - context = GitContext(home) - folders = Folders(scopes.parents, cwd) - risks: list[str] = [] - for pipeline, command in [(each, command) for each in pipelines for command in each.commands]: - words = command.texts() - index = command_index(command.words) - if index >= len(words): - continue - here = folders.of(pipeline.scope) - name = basename(words[index]) - if name in ("cd", "pushd") and index + 1 < len(words) and "$" not in words[index + 1]: - folders.move(pipeline.scope, context.resolve(words[index + 1], here)) - continue - if name != "git": - continue - # -C moves git's folder, one after another; a relative --git-dir or GIT_DIR - # (also behind env) is taken from the folder that results. - folder = here - git_dir = "" - for word in words[:index]: - if word.startswith("GIT_DIR=") and "$" not in word: - git_dir = word[len("GIT_DIR=") :] - arguments = words[index + 1 :] - position = git_subcommand(arguments) - for offset in range(position): - option = arguments[offset] - value = arguments[offset + 1] if offset + 1 < position else "" - if option == "-C" and value: - folder = context.resolve(value, folder) - elif option == "--git-dir" and value: - git_dir = value - elif option.startswith("--git-dir="): - git_dir = option[len("--git-dir=") :] - repo = context.resolve(git_dir, folder) if git_dir else folder - if position >= len(arguments): - continue - sub = arguments[position] - rest = arguments[position + 1 :] - if sub in ("checkout", "switch") and "--" not in rest: - tracking = any(word in ("--track", "-t") for word in rest) - for offset, word in enumerate(rest): - if word in ("-b", "-B", "-c", "-C"): - context.switched = rest[offset + 1] if offset + 1 < len(rest) else "" - break - if not word.startswith("-"): - # --track origin/main creates and checks out main - context.switched = word.split("/", 1)[1] if tracking and "/" in word else word - elif sub == "branch" and any(word in ("-d", "-D", "--delete") for word in rest): - context.deleted_branches.update(word for word in rest if not word.startswith("-")) - elif sub == "tag" and ("-d" in rest or "--delete" in rest): - context.deleted_tags.update(word for word in rest if not word.startswith("-")) - elif sub == "push": - overrides = any( - option in ("-c", "--config-env") or option.startswith(("-c", "--config-env=")) - for option in arguments[:position] - ) or any(word.startswith(("GIT_CONFIG", "GIT_NAMESPACE=")) for word in words[:index]) - for risk in check_push(repo, context, rest, overrides): - if risk not in risks: - risks.append(risk) - if risks: - return "ask", "; ".join(risks) - return None - - -def deny(reason: str) -> str: - return json.dumps({"hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "deny", - "permissionDecisionReason": "Agent Watch Git: " + reason, - }}, separators=(",", ":")) - - -def inspect(payload: dict) -> str: - tool = payload.get("tool_input") - if not isinstance(tool, dict): - return "" - command = tool.get("command", tool.get("cmd")) - if not isinstance(command, str) or not command.strip(): - return "" - if len(command) > MAX_COMMAND: - return deny("The command is too long to check. Split it into smaller commands.") - cwd = payload.get("cwd") or os.getcwd() - if tool.get("workdir"): - cwd = os.path.join(cwd, tool["workdir"]) - DEADLINE[0] = time.monotonic() + TIME_BUDGET - parser = Parser(command) - result = git_guard(parser.parse(), cwd, os.path.expanduser("~"), parser.scopes) - if result is None: - return "" - _, reason = result - binary = Path(__file__).resolve().parents[3] / "MacOS" / "AgentWatchGit" - return deny( - f"{reason}. For one intended reference call {shlex.quote(str(binary))} push '' " - "with repository (absolute working tree path), destination (refs/heads/name or refs/tags/name), " - "remote (configured name, default origin), and reason. For deletion set delete to true and omit " - "source and force. For an update use source (default HEAD) and set force to true only when " - "explicitly requested. The CLI shows the user an approval window and executes the approved " - "operation itself. Never answer the window, retry a refusal or execute a fallback push." - ) - - -def main() -> None: - def timed_out(_signal, _frame): - raise TimeBudgetError("the hook did not finish") - - signal.signal(signal.SIGALRM, timed_out) - signal.setitimer(signal.ITIMER_REAL, TIME_BUDGET) - try: - payload = json.loads(sys.stdin.buffer.read()) - if not isinstance(payload, dict): - raise ValueError("expected a hook event object") - result = inspect(payload) - except TimeBudgetError: - result = deny("The repository could not be inspected before the hook deadline.") - except GitInspectionError as error: - result = deny(str(error)) - except Exception as error: - result = deny(f"The hook could not check this command ({type(error).__name__}).") - finally: - signal.setitimer(signal.ITIMER_REAL, 0) - if result: - print(result) - - -if __name__ == "__main__": - if sys.version_info < (3, 9): - sys.exit(3) - if sys.argv[1:] == ["--check"]: - print("agent-watch-git-hook-ok") - else: - main() diff --git a/Sources/AgentWatchApp/AgentHeardStore.swift b/Sources/AgentWatchApp/AgentHeardStore.swift index 00d4489..bde3207 100644 --- a/Sources/AgentWatchApp/AgentHeardStore.swift +++ b/Sources/AgentWatchApp/AgentHeardStore.swift @@ -22,14 +22,15 @@ enum HeardFolder: Hashable { /// The agent and folder a key in the file names, or `nil` for a key this app never wrote. static func parse(_ key: String) -> (AgentSource, HeardFolder)? { - let parts = key.split(separator: "@", maxSplits: 1).map(String.init) - guard let source = AgentSource(rawValue: parts[0]) else { + let parts = key.split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false).map(String.init) + guard let name = parts.first, let source = AgentSource(rawValue: name) else { return nil } guard parts.count == 2 else { return (source, .default) } - return (source, .listed(label: parts[1])) + guard let label = HookIngressRequest.sanitizedFolderLabel(parts[1]) else { return nil } + return (source, .listed(label: label)) } } diff --git a/Sources/AgentWatchApp/AppDelegate.swift b/Sources/AgentWatchApp/AppDelegate.swift index d61a952..10b954f 100644 --- a/Sources/AgentWatchApp/AppDelegate.swift +++ b/Sources/AgentWatchApp/AppDelegate.swift @@ -474,6 +474,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate { updateMenuBarIcon(sessions: shown) } + private var transcriptAccessGeneration = 0 + private var worktreeLookupGeneration = 0 + private var worktreeFolderRead: Task?, Never>? + + private func transcriptAccessChanged() { + transcriptAccessGeneration += 1 + worktreeFolderRead?.cancel() + } + /// Who has to be told when a setting changes, written once rather than by every writer: /// a writer that forgot one would leave a setting that appears not to work and then fixes /// itself minutes later. @@ -489,6 +498,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { statusMenu?.refresh() supervisor.runMaintenance() case .transcriptPollInterval: + transcriptAccessChanged() supervisor.transcriptSettingsChanged() updateProjects(supervisor.sessions) statusMenu?.refresh() @@ -516,9 +526,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { renderWidget() statusMenu?.refreshSessions() case .agentFolders: + transcriptAccessChanged() + supervisor.transcriptFoldersChanged() updateProjects(supervisor.sessions) - // The rows of the Tooling page and the widget's complaint both count folders. The - // sessions read the list where they use it, so nothing else needs a poke. refreshToolingComplaint() if settingsWindow.model.isShowingTooling { settingsWindow.model.tooling.reread() @@ -656,16 +666,27 @@ extension AppDelegate: StatusMenuHost, SettingsHost { guard !AgentWatchPaths.isDevelopmentBuild, ingress.isListening else { return nil } let observed = supervisor.sessions let folders = AgentFolders(home: AgentWatchPaths.homeDirectory(), extra: settings.extraAgentFolders) - let readMetadata = supervisor.isReadingTranscripts - let paths = await Task.detached(priority: .utility) { + let readMetadata = settings.transcriptPollInterval != nil + let generation = transcriptAccessGeneration + worktreeLookupGeneration += 1 + let lookup = worktreeLookupGeneration + worktreeFolderRead?.cancel() + let worker = Task.detached(priority: .utility) { ProjectSessionLookup(folders: folders, transcriptFiles: readMetadata ? .live : nil) .openWorkingFolders(of: observed) - }.value - guard let paths else { return nil } + } + worktreeFolderRead = worker + let paths = await withTaskCancellationHandler { + await worker.value + } onCancel: { + worker.cancel() + } + if worktreeLookupGeneration == lookup { worktreeFolderRead = nil } + guard !worker.isCancelled, let paths else { return nil } let reading = WorktreeSessionReading(folders: paths) { [weak self] in guard let self else { return false } return self.ingress.isListening && self.supervisor.sessions == observed - && self.supervisor.isReadingTranscripts == readMetadata + && self.transcriptAccessGeneration == generation } return reading.isCurrent() ? reading : nil } diff --git a/Sources/AgentWatchApp/HookIngressController.swift b/Sources/AgentWatchApp/HookIngressController.swift index 96451f0..5033daf 100644 --- a/Sources/AgentWatchApp/HookIngressController.swift +++ b/Sources/AgentWatchApp/HookIngressController.swift @@ -14,7 +14,9 @@ final class HookIngressController { private let ingest: (HookIngressRequest) -> EventEnvelope? private let reveal: () -> Void private let log: (String) -> Void + private let makeListener: (String, @escaping UnixSocketIngress.Handler) -> UnixSocketIngress private var ingress: UnixSocketIngress? + private var generation = 0 /// - Parameters: /// - socketURL: where to listen, or `nil` when this copy of the app has no address of @@ -26,12 +28,16 @@ final class HookIngressController { socketURL: @escaping () -> URL?, ingest: @escaping (HookIngressRequest) -> EventEnvelope?, reveal: @escaping () -> Void, - log: @escaping (String) -> Void + log: @escaping (String) -> Void, + makeListener: @escaping (String, @escaping UnixSocketIngress.Handler) -> UnixSocketIngress = { + UnixSocketIngress(socketPath: $0, handler: $1) + } ) { self.socketURL = socketURL self.ingest = ingest self.reveal = reveal self.log = log + self.makeListener = makeListener } var isListening: Bool { ingress != nil } @@ -41,19 +47,23 @@ final class HookIngressController { /// Never throws: monitoring is fail-open, so an app that cannot hear its hooks still runs /// and still shows whatever it can find by other means. func start() { + guard ingress == nil else { return } guard let socketURL = socketURL() else { log("Local hook listener is unavailable") return } + generation += 1 + let started = generation do { - let ingress = UnixSocketIngress(socketPath: socketURL.path) { [weak self] result in + let ingress = makeListener(socketURL.path) { [weak self] result in // `DispatchQueue.main.async` and not `Task { @MainActor }`: the listener hands // events over in the order they arrived, and separately created tasks have no // order between them, so the hop was giving back the guarantee the listener // had just established. The main queue is first-in first-out. DispatchQueue.main.async { MainActor.assumeIsolated { - self?.handle(result) + guard let self, self.generation == started, self.ingress != nil else { return } + self.handle(result) } } } @@ -66,6 +76,7 @@ final class HookIngressController { } func stop() { + generation += 1 ingress?.stop() ingress = nil } diff --git a/Sources/AgentWatchApp/LampScheme.swift b/Sources/AgentWatchApp/LampScheme.swift index 7a67762..9fa2d3e 100644 --- a/Sources/AgentWatchApp/LampScheme.swift +++ b/Sources/AgentWatchApp/LampScheme.swift @@ -119,10 +119,6 @@ struct LampScheme: Equatable { styles[phase]?.color = color } - mutating func setMotion(_ motion: SessionLampAppearance.Motion, for phase: SessionPhase) { - styles[phase]?.motion = motion - } - var isDefault: Bool { SessionPhase.allCases.allSatisfy { phase in let style = style(for: phase) diff --git a/Sources/AgentWatchApp/MenuBarIconView.swift b/Sources/AgentWatchApp/MenuBarIconView.swift index 2e8f599..93d393e 100644 --- a/Sources/AgentWatchApp/MenuBarIconView.swift +++ b/Sources/AgentWatchApp/MenuBarIconView.swift @@ -396,10 +396,4 @@ final class MenuBarIconView: NSView { var breathBeginTimes: [CFTimeInterval] { cellLayers.compactMap { $0.animation(forKey: Self.breathKey)?.beginTime } } - - /// What the render tree is showing right now — the proof that an animation is running and - /// not merely attached. - var presentedOpacities: [Float] { - cellLayers.map { $0.presentation()?.opacity ?? 1 } - } } diff --git a/Sources/AgentWatchApp/PreferenceFile.swift b/Sources/AgentWatchApp/PreferenceFile.swift index 59ca276..6b796cd 100644 --- a/Sources/AgentWatchApp/PreferenceFile.swift +++ b/Sources/AgentWatchApp/PreferenceFile.swift @@ -38,7 +38,7 @@ final class PreferenceFile { directoryURL ?? AgentWatchPaths.supportDirectory(fileManager: fileManager) fileURL = directory?.appendingPathComponent("settings.json") - switch Self.read(fileURL, fileManager: fileManager) { + switch Self.read(fileURL) { case .none: values = [:] case let .values(stored): @@ -151,7 +151,7 @@ final class PreferenceFile { at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true ) - keepAsideAFileThatCouldNotBeRead() + guard keepAsideAFileThatCouldNotBeRead() else { return } try? data.write(to: fileURL, options: .atomic) } @@ -164,17 +164,26 @@ final class PreferenceFile { /// /// Fail-open like every other write here: if the file cannot be moved it is left alone /// and nothing is written over it, which loses a setting rather than a file. - private func keepAsideAFileThatCouldNotBeRead() { - guard let unreadableFile else { - return - } - self.unreadableFile = nil + private func keepAsideAFileThatCouldNotBeRead() -> Bool { + guard let unreadableFile else { return true } let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-") - let kept = unreadableFile.appendingPathExtension("unreadable-\(stamp)") - guard (try? fileManager.moveItem(at: unreadableFile, to: kept)) != nil else { - return + let kept = unreadableFile.appendingPathExtension("unreadable-\(stamp)-\(UUID().uuidString)") + do { + try fileManager.moveItem(at: unreadableFile, to: kept) + unreadableFileKeptAt = kept + } catch { + // The owner may have removed the bad file after the first failed write. + do { + _ = try fileManager.attributesOfItem(atPath: unreadableFile.path) + return false + } catch let error as CocoaError where error.code == .fileNoSuchFile || error.code == .fileReadNoSuchFile { + // There is no file left to preserve. + } catch { + return false + } } - unreadableFileKeptAt = kept + self.unreadableFile = nil + return true } /// What was found where the settings live. @@ -186,13 +195,15 @@ final class PreferenceFile { case unreadable } - private static func read(_ fileURL: URL?, fileManager: FileManager) -> StoredValues { - guard let fileURL, let data = fileManager.contents(atPath: fileURL.path) else { + private static func read(_ fileURL: URL?) -> StoredValues { + guard let fileURL else { return .none } + do { + let data = try Data(contentsOf: fileURL) + return .values(try JSONDecoder().decode([String: JSONValue].self, from: data)) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { return .none - } - guard let values = try? JSONDecoder().decode([String: JSONValue].self, from: data) else { + } catch { return .unreadable } - return .values(values) } } diff --git a/Sources/AgentWatchApp/SessionSupervisor.swift b/Sources/AgentWatchApp/SessionSupervisor.swift index d08f269..3fa971c 100644 --- a/Sources/AgentWatchApp/SessionSupervisor.swift +++ b/Sources/AgentWatchApp/SessionSupervisor.swift @@ -311,6 +311,10 @@ final class SessionSupervisor { transcripts.settingsChanged() } + func transcriptFoldersChanged() { + transcripts.foldersChanged() + } + func reach(for snapshot: SessionSnapshot) -> SessionReach { // Before the host: the process tree still leads to the IDE the terminal was in, and // raising it would show a window with no tab left for this session. @@ -323,45 +327,34 @@ final class SessionSupervisor { return hostRegistry.reach(for: snapshot) } + private func verifiedAgent(of snapshot: SessionSnapshot) -> (pid: Int32, startedAt: Date)? { + guard let pid = snapshot.agentProcessID, let startedAt = agentProcessStartedAt(pid), + startedAt <= snapshot.lastObservedAt + else { return nil } + return (pid, startedAt) + } + /// How a click would end a headless run: by its process, while that is still the run's. private func headlessRunEnding(of snapshot: SessionSnapshot) -> AgentEnding? { - guard - snapshot.phase != .sessionClosed, - let agentProcessID = snapshot.agentProcessID, - SessionHostRegistry.isStillTheAgent( - agentProcessID: agentProcessID, lastObservedAt: snapshot.lastObservedAt, - processStartedAt: agentProcessStartedAt) - else { - return nil - } - return .terminate(processID: agentProcessID) + guard snapshot.phase != .sessionClosed, let agent = verifiedAgent(of: snapshot) else { return nil } + return .terminate(processID: agent.pid) } - /// How a click would end the agent of a row marked closed, read from the kernel alone: - /// this is asked on every hover, and a hover sends Ghostty nothing. + /// The card and the confirmation both need a fresh process and terminal identity. private func closedTerminalEnding(of snapshot: SessionSnapshot) -> AgentEnding? { - guard let agentProcessID = snapshot.agentProcessID else { - return nil - } - switch terminalState(agentProcessID) { + guard let agent = verifiedAgent(of: snapshot) else { return nil } + let ending: AgentEnding? + switch terminalState(agent.pid) { case .lost: - return terminalDevicePath(agentProcessID).map { .discardOutput(devicePath: $0) } + ending = terminalDevicePath(agent.pid).map { .discardOutput(devicePath: $0) } case .attached: - // Only a click that found the tab gone marks a row whose agent still has its - // terminal, so this is the Ghostty case. The numbers are shown for a person to - // run by hand, so they are shown only while they are still this agent's. - guard - SessionHostRegistry.isStillTheAgent( - agentProcessID: agentProcessID, lastObservedAt: snapshot.lastObservedAt, - processStartedAt: agentProcessStartedAt) - else { - return nil - } - let chain = terminalProcessChain(agentProcessID) - return chain.isEmpty ? nil : .hangUp(processIDs: chain) + let chain = terminalProcessChain(agent.pid) + ending = chain.first == agent.pid ? .hangUp(processIDs: chain) : nil case .neverHad, nil: return nil } + guard agentProcessStartedAt(agent.pid) == agent.startedAt else { return nil } + return ending } /// Menu lines keep their wording while the session can change, so the click is answered @@ -662,12 +655,12 @@ final class SessionSupervisor { /// agent's exit, a moment later, is reported by the watch on its process like any other, /// and `endAgent` takes the row away then. Answers whether the ending went out. private func releaseAgent(of snapshot: SessionSnapshot) -> Bool { - switch snapshot.agentProcessID.flatMap(terminalState) { - case .lost: - return discardOutput(of: snapshot) - case .attached: - return hangUpAgent(of: snapshot) - case .neverHad, nil: + switch closedTerminalEnding(of: snapshot) { + case let .discardOutput(devicePath): + return discardOutput(at: devicePath, for: snapshot) + case let .hangUp(processIDs): + return hangUpAgent(of: snapshot, processIDs: processIDs) + default: onNotableEvent("\(Self.label(snapshot)) · its agent no longer hangs without a terminal; nothing was done") return false } @@ -689,11 +682,7 @@ final class SessionSupervisor { } /// Ends an agent that hangs without its terminal by discarding the output it waits on. - private func discardOutput(of snapshot: SessionSnapshot) -> Bool { - guard let agentProcessID = snapshot.agentProcessID, let devicePath = terminalDevicePath(agentProcessID) else { - onNotableEvent("\(Self.label(snapshot)) · no descriptor of its agent names a terminal; nothing to discard") - return false - } + private func discardOutput(at devicePath: String, for snapshot: SessionSnapshot) -> Bool { let discarded = releaseTerminal(devicePath) onNotableEvent( discarded @@ -705,18 +694,8 @@ final class SessionSupervisor { /// Ends an agent whose tab Ghostty closed and kept, and the shell it was started from, /// with the hang-up the closed tab never sent — once it is still the same process and its /// tab is still gone. - private func hangUpAgent(of snapshot: SessionSnapshot) -> Bool { - guard - let agentProcessID = snapshot.agentProcessID, - SessionHostRegistry.isStillTheAgent( - agentProcessID: agentProcessID, - lastObservedAt: snapshot.lastObservedAt, - processStartedAt: agentProcessStartedAt - ) - else { - onNotableEvent("\(Self.label(snapshot)) · its agent is gone; nothing was sent") - return false - } + private func hangUpAgent(of snapshot: SessionSnapshot, processIDs: [Int32]) -> Bool { + guard let agent = verifiedAgent(of: snapshot), processIDs.first == agent.pid else { return false } let otherNames = otherSessionNames(than: snapshot) guard tabIsGoneWithTerminalKept?(snapshot, otherNames) @@ -725,13 +704,12 @@ final class SessionSupervisor { onNotableEvent("\(Self.label(snapshot)) · its tab is no longer missing from Ghostty; nothing was sent") return false } - let chain = terminalProcessChain(agentProcessID) - guard chain.first == agentProcessID else { - onNotableEvent("\(Self.label(snapshot)) · its agent has no terminal to hang up; nothing was sent") - return false - } - let processes = chain.map(String.init).joined(separator: " ") - let sent = hangUp(chain) + guard agentProcessStartedAt(agent.pid) == agent.startedAt, + terminalProcessChain(agent.pid) == processIDs, + agentProcessStartedAt(agent.pid) == agent.startedAt + else { return false } + let processes = processIDs.map(String.init).joined(separator: " ") + let sent = hangUp(processIDs) onNotableEvent( sent ? "\(Self.label(snapshot)) · hung up its agent and shell (\(processes)), as closing the tab should have" diff --git a/Sources/AgentWatchApp/SettingsWindowController.swift b/Sources/AgentWatchApp/SettingsWindowController.swift index 5778de7..ed45a97 100644 --- a/Sources/AgentWatchApp/SettingsWindowController.swift +++ b/Sources/AgentWatchApp/SettingsWindowController.swift @@ -55,10 +55,6 @@ final class SettingsWindowController: NSWindowController, NSWindowDelegate { nil } - var isShowing: Bool { - window?.isVisible == true - } - /// Opens the window, or brings it forward. Not a toggle: a settings window is closed with its /// own close button. func present() { diff --git a/Sources/AgentWatchApp/ToolingInstaller.swift b/Sources/AgentWatchApp/ToolingInstaller.swift index 6137f77..37b660e 100644 --- a/Sources/AgentWatchApp/ToolingInstaller.swift +++ b/Sources/AgentWatchApp/ToolingInstaller.swift @@ -164,7 +164,7 @@ final class ToolingInstaller { private func codexHookState(in folder: URL, delivery: HookDelivery) -> ToolingInstallationState { let document: JSONValue? do { - document = try read(codexHooksURL(in: folder)) + document = try readCodexHooks(codexHooksURL(in: folder)) } catch { return .unreadable } @@ -202,7 +202,7 @@ final class ToolingInstaller { let lock = try AgentProfileLock(folder) defer { withExtendedLifetime(lock) {} } let url = codexHooksURL(in: folder) - let existing = try read(url) ?? .object([:]) + let existing = try readCodexHooks(url) ?? .object([:]) let changed = change(existing) guard changed != existing else { return @@ -222,12 +222,26 @@ final class ToolingInstaller { /// emptiness over the rest of it. One trailing comma in `settings.json` cost the model, /// the permissions and every MCP server it named. private func read(_ url: URL) throws -> JSONValue? { - guard let data = try? Data(contentsOf: url) else { + do { + let data = try Data(contentsOf: url) + return try JSONDecoder().decode(JSONValue.self, from: data) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { return nil - } - guard let document = try? JSONDecoder().decode(JSONValue.self, from: data) else { + } catch { throw ToolingInstallerError.unreadable(url) } + } + + private func readCodexHooks(_ url: URL) throws -> JSONValue? { + guard let document = try read(url) else { return nil } + guard case let .object(root) = document else { throw ToolingInstallerError.unreadable(url) } + if let hooks = root["hooks"] { + guard case let .object(events) = hooks else { throw ToolingInstallerError.unreadable(url) } + for event in ToolingHooks.hooks(for: .codex) { + guard let groups = events[event] else { continue } + guard case .array = groups else { throw ToolingInstallerError.unreadable(url) } + } + } return document } diff --git a/Sources/AgentWatchApp/TranscriptWatcher.swift b/Sources/AgentWatchApp/TranscriptWatcher.swift index 9a22181..4c46fc4 100644 --- a/Sources/AgentWatchApp/TranscriptWatcher.swift +++ b/Sources/AgentWatchApp/TranscriptWatcher.swift @@ -84,6 +84,7 @@ final class TranscriptWatcher { static let coalesceWindow: TimeInterval = 0.5 private struct Watch { + let identity = UUID() var url: URL? var offset: UInt64 = 0 let firstSeenAt: Date @@ -100,6 +101,7 @@ final class TranscriptWatcher { let sessionID: String let source: AgentSource let sessionLabel: String + let watchIdentity: UUID /// Every folder's transcript root for this agent, the default first. let roots: [URL] let url: URL? @@ -110,17 +112,12 @@ final class TranscriptWatcher { var liveSince: Date? /// The wait this session was remembered in, when the file is being asked about one. var rememberedWait: SessionHistory.RememberedWait? + var isFinalRead = false + var isCatchUp = false func isDefaultCodexTranscript(_ url: URL) -> Bool { guard source == .codex, let root = roots.first else { return false } - let file = AgentFolders.canonicalPath(of: url) - let defaultRoot = AgentFolders.canonicalPath(of: root) - guard file.hasPrefix(defaultRoot + "/") else { return false } - // A nested profile owns the file even if its path also sits under the default root. - return !roots.dropFirst().contains { root in - let otherRoot = AgentFolders.canonicalPath(of: root) - return otherRoot.count > defaultRoot.count && file.hasPrefix(otherRoot + "/") - } + return TranscriptLocator.root(containing: url, source: source, among: roots) == root } func codexUsage(from data: Data, at url: URL) -> AgentUsageLimits? { @@ -156,11 +153,13 @@ final class TranscriptWatcher { private var watches: [String: Watch] = [:] private var sessions: [SessionSnapshot] = [] private var timer: Timer? + private var timerGeneration = 0 private var lastReadAt: Date? private var hasRead = false private var lastHookAt: Date? - /// Guards against a slow disk stacking one tick on top of the last. - private var isReading = false + /// A cancelled pass still owns its reads until it has left the worker. + private(set) var readTask: Task? + private var readGeneration = 0 /// Rows a catch-up was declined for because another read was running, asked again when /// that read ends. See `catchUp`. private var declinedCatchUpIDs: Set = [] @@ -201,7 +200,7 @@ final class TranscriptWatcher { /// the moment it fires, and the read it started outlives it. The menu asks this question /// to say whether reading is happening, so a read in flight has to count. var isPolling: Bool { - timer != nil || isReading + settings.transcriptPollInterval != nil && (timer != nil || readTask != nil) } /// When the next read is due, or `nil` while nothing is being read. @@ -257,6 +256,7 @@ final class TranscriptWatcher { func update(sessions: [SessionSnapshot]) { self.sessions = sessions + guard settings.transcriptPollInterval != nil else { return } let live = Set(sessions.map(\.id)) watches = watches.filter { live.contains($0.key) } let moment = now() @@ -282,8 +282,34 @@ final class TranscriptWatcher { } func stop() { - timer?.invalidate() - timer = nil + sessions = [] + watches = [:] + declinedCatchUpIDs = [] + invalidateRead() + rescheduleReads() + } + + /// A revoked folder cannot be read using a URL an earlier pass found. + func foldersChanged() { + invalidateRead() + let folders = agentFolders + let moment = now() + for snapshot in sessions { + guard var watch = watches[snapshot.id] else { continue } + if let url = watch.url { + let roots = TranscriptLocator.roots(for: snapshot.source, in: folders) + guard TranscriptLocator.root(containing: url, source: snapshot.source, among: roots) == nil else { + continue + } + watch = Watch( + firstSeenAt: moment, nextLocateAttemptAt: moment, readAfterCodexStop: watch.readAfterCodexStop, + sessionLabel: snapshot.transcriptLabel) + } else { + watch.nextLocateAttemptAt = moment + } + watches[snapshot.id] = watch + } + rescheduleReads() } /// Applies a change of interval, including turning reading off. @@ -291,20 +317,28 @@ final class TranscriptWatcher { /// Turning it off clears every fault it had reported. A warning triangle left behind by a /// reader that is no longer running would be a claim about a session nobody is watching. func settingsChanged() { - rescheduleReads() - guard settings.transcriptPollInterval == nil else { - if defaultCodexUsage == nil { - let moment = now() - catchUp( - sessions: sessions.filter { - $0.source == .codex && $0.phase != .sessionClosed && !Self.isWatchable($0, now: moment) - }) - } + guard settings.transcriptPollInterval != nil else { + invalidateRead() + watches.removeAll() + declinedCatchUpIDs = [] + defaultCodexUsage = nil + rescheduleReads() + onUpdates(sessions.map { TranscriptUpdate(sessionID: $0.id, facts: [], fault: nil) }) return } - watches.removeAll() - defaultCodexUsage = nil - onUpdates(sessions.map { TranscriptUpdate(sessionID: $0.id, facts: [], fault: nil) }) + update(sessions: sessions) + if defaultCodexUsage == nil { + let moment = now() + catchUp( + sessions: sessions.filter { + $0.source == .codex && $0.phase != .sessionClosed && !Self.isWatchable($0, now: moment) + }) + } + } + + private func invalidateRead() { + readGeneration += 1 + readTask?.cancel() } // MARK: - The tick @@ -312,14 +346,12 @@ final class TranscriptWatcher { /// What a fired timer does. The timer is spent the moment it fires — it does not /// repeat — so it is dropped here, before anything else can decide there is still one. func timerFired() { - timer?.invalidate() - timer = nil - nextReadAt = nil + cancelTimer() poll() } func poll() { - guard !isReading else { + guard settings.transcriptPollInterval != nil, readTask == nil else { // Deliberately schedules nothing. The moment this tick would compute has already // passed — it is the one that just fired — so scheduling from it would fire again // at once, and again, for as long as the read takes. `finish` schedules instead, @@ -336,13 +368,7 @@ final class TranscriptWatcher { return } - isReading = true - Task.detached(priority: .utility) { [weak self] in - let results = Self.perform(jobs, observedAt: moment) - await MainActor.run { [weak self] in - self?.finish(results, at: moment) - } - } + startRead(jobs, at: moment) { Self.perform(jobs, observedAt: moment) } } /// Catches up sessions restored from a previous launch, once and not on the timer. @@ -377,7 +403,7 @@ final class TranscriptWatcher { guard settings.transcriptPollInterval != nil else { return [] } - guard !isReading else { + guard readTask == nil else { // Asked again when the running read ends, because nothing else may ask soon. At // launch this is always the case for a row found by its process: the restored // sessions' own catch-up is the read in the way, and the next scan comes with the @@ -392,12 +418,14 @@ final class TranscriptWatcher { guard watches[snapshot.id] == nil else { return nil } - watches[snapshot.id] = Watch( + let watch = Watch( firstSeenAt: moment, nextLocateAttemptAt: moment, sessionLabel: snapshot.transcriptLabel) + watches[snapshot.id] = watch return ReadJob( sessionID: snapshot.id, source: snapshot.source, sessionLabel: snapshot.transcriptLabel, + watchIdentity: watch.identity, roots: TranscriptLocator.roots(for: snapshot.source, in: agentFolders), url: nil, offset: 0, @@ -406,21 +434,26 @@ final class TranscriptWatcher { // no claim about it — while a fault would put a warning triangle on the widget // at every launch. reportsNotFound: false, - rememberedWait: waits[snapshot.id] + rememberedWait: waits[snapshot.id], + isCatchUp: true ) } guard !jobs.isEmpty else { return [] } - isReading = true - Task.detached(priority: .utility) { [weak self] in - let results = Self.locateAndDate(jobs) + startRead(jobs, at: moment) { Self.locateAndDate(jobs) } + return Set(jobs.map(\.sessionID)) + } + + private func startRead(_ jobs: [ReadJob], at moment: Date, work: @escaping @Sendable () -> [ReadResult]) { + let generation = readGeneration + readTask = Task.detached(priority: .utility) { [weak self] in + let results = work() await MainActor.run { [weak self] in - self?.finish(results, at: moment) + self?.finish(results, jobs: jobs, at: moment, generation: generation) } } - return Set(jobs.map(\.sessionID)) } private func makeJobs(at moment: Date) -> [ReadJob] { @@ -447,23 +480,36 @@ final class TranscriptWatcher { sessionID: snapshot.id, source: snapshot.source, sessionLabel: snapshot.transcriptLabel, + watchIdentity: watch.identity, roots: TranscriptLocator.roots(for: snapshot.source, in: agentFolders), url: watch.url, offset: watch.offset, reportsNotFound: moment.timeIntervalSince(watch.firstSeenAt) >= Self.locateGrace, - liveSince: watch.firstSeenAt + liveSince: watch.firstSeenAt, + isFinalRead: finalRead ) } } - private func finish(_ results: [ReadResult], at moment: Date) { - isReading = false + private func finish(_ results: [ReadResult], jobs: [ReadJob], at moment: Date, generation: Int) { + readTask = nil // The read is over, so the next one can be scheduled — and for a tick that arrived // while this one ran, this is the only place that will. defer { rescheduleReads() } + guard settings.transcriptPollInterval != nil else { return } + guard generation == readGeneration else { + // A cancelled final pass has not delivered the facts that may precede Codex Stop. + for job in jobs where job.isFinalRead && watches[job.sessionID]?.sessionLabel == job.sessionLabel { + watches[job.sessionID]?.readAfterCodexStop = true + } + retryInvalidatedCatchUps(jobs) + askDeclinedCatchUpsAgain() + return + } + let requested = Dictionary(uniqueKeysWithValues: jobs.map { ($0.sessionID, $0.watchIdentity) }) var updates: [TranscriptUpdate] = [] for result in results { - guard var watch = watches[result.sessionID], watch.sessionLabel == result.sessionLabel else { + guard var watch = watches[result.sessionID], requested[result.sessionID] == watch.identity else { // Nobody's result: the row is gone, or its watch was replaced while the read // ran and now looks for another file. Writing this file's address into the // new watch would stop it from ever looking. @@ -505,6 +551,27 @@ final class TranscriptWatcher { askDeclinedCatchUpsAgain() } + /// Catch-up can be the only read an idle restored row ever gets. Rebuild it with the + /// current roots only while the same watch still owns it. + private func retryInvalidatedCatchUps(_ jobs: [ReadJob]) { + let current = Dictionary(uniqueKeysWithValues: sessions.map { ($0.id, $0) }) + var retry: [SessionSnapshot] = [] + var waits: [String: SessionHistory.RememberedWait] = [:] + var unresolved: [TranscriptUpdate] = [] + for job in jobs where job.isCatchUp { + guard let snapshot = current[job.sessionID] else { continue } + if snapshot.transcriptLabel == job.sessionLabel, watches[job.sessionID]?.identity == job.watchIdentity { + watches.removeValue(forKey: job.sessionID) + retry.append(snapshot) + waits[job.sessionID] = job.rememberedWait + } else if job.rememberedWait != nil { + unresolved.append(TranscriptUpdate(sessionID: job.sessionID, facts: [], fault: nil)) + } + } + if !retry.isEmpty { catchUp(sessions: retry, waits: waits) } + if !unresolved.isEmpty { onUpdates(unresolved) } + } + /// Only the rows still in the list, as they are now: a row can leave, or change the file it /// is read from, while the read that was in the way runs. private func askDeclinedCatchUpsAgain() { @@ -566,7 +633,8 @@ final class TranscriptWatcher { /// while it is being drawn. A scan of a transcript root was measured at 44 ms, which is /// three dropped frames if it happens on the main thread every few seconds. private nonisolated static func perform(_ jobs: [ReadJob], observedAt: Date) -> [ReadResult] { - jobs.map { job in + jobs.compactMap { job in + guard !Task.isCancelled else { return nil } guard let url = job.url else { return locateLive(job) } @@ -615,8 +683,10 @@ final class TranscriptWatcher { /// Where each session's file stands, and the two questions a restart has to ask of it. /// See `catchUp`. private nonisolated static func locateAndDate(_ jobs: [ReadJob]) -> [ReadResult] { - jobs.map { job in + jobs.compactMap { job in + guard !Task.isCancelled else { return nil } var result = locate(job) + guard !Task.isCancelled else { return nil } guard let url = result.url else { return result } @@ -707,7 +777,7 @@ final class TranscriptWatcher { // The index of the folder the transcript lies in: a thread in a listed folder is named // in that folder's index and in no other. guard - let root = TranscriptLocator.root(containing: transcript, among: job.roots), + let root = TranscriptLocator.root(containing: transcript, source: job.source, among: job.roots), let index = try? Data( contentsOf: TranscriptLocator.codexThreadIndex(inRoot: root)), let threadName = CodexThreadIndex.threadName( @@ -729,7 +799,7 @@ final class TranscriptWatcher { /// deliberately uses `locate` instead, because its state still awaits a real hook. private nonisolated static func locateLive(_ job: ReadJob) -> ReadResult { var result = locate(job) - guard let url = result.url, let boundary = job.liveSince else { + guard !Task.isCancelled, let url = result.url, let boundary = job.liveSince else { return result } do { @@ -902,15 +972,20 @@ final class TranscriptWatcher { // MARK: - Timer + private func cancelTimer() { + timerGeneration += 1 + timer?.invalidate() + timer = nil + nextReadAt = nil + } + private func rescheduleReads() { let moment = now() guard let floor = settings.transcriptPollInterval, sessions.contains(where: { needsRead($0, at: moment) }) else { - timer?.invalidate() - timer = nil - nextReadAt = nil + cancelTimer() lastReadAt = nil hasRead = false return @@ -929,14 +1004,16 @@ final class TranscriptWatcher { return } + cancelTimer() nextReadAt = due - timer?.invalidate() + let generation = timerGeneration timer = Timer.scheduledTimer( withTimeInterval: max(0, due.timeIntervalSince(moment)), repeats: false ) { [weak self] _ in Task { @MainActor [weak self] in - self?.timerFired() + guard let self, self.timerGeneration == generation else { return } + self.timerFired() } } } diff --git a/Sources/AgentWatchCore/ProcessResources.swift b/Sources/AgentWatchCore/ProcessResources.swift index 0024c6e..817ca86 100644 --- a/Sources/AgentWatchCore/ProcessResources.swift +++ b/Sources/AgentWatchCore/ProcessResources.swift @@ -21,6 +21,7 @@ public struct SessionMarker: Hashable, Sendable { public struct SampledProcess: Equatable, Sendable { public let processID: Int32 public let parentProcessID: Int32 + public let startedAt: UInt64? /// The executable's file name, never its path: what a helper is called (`plata-mcp`). public let name: String /// Bytes, as Activity Monitor's «Memory» column counts them: the process's own memory, @@ -44,6 +45,7 @@ public struct SampledProcess: Equatable, Sendable { processID: Int32, parentProcessID: Int32, name: String, + startedAt: UInt64? = nil, footprint: UInt64 = 0, resident: UInt64 = 0, cpuTime: TimeInterval = 0, @@ -54,6 +56,7 @@ public struct SampledProcess: Equatable, Sendable { self.processID = processID self.parentProcessID = parentProcessID self.name = name + self.startedAt = startedAt self.footprint = footprint self.resident = resident self.cpuTime = cpuTime @@ -326,8 +329,8 @@ public struct ResourceReport: Equatable, Sendable { struct Member: Equatable, Sendable { let bucket: String - /// The process's name: a number reused by another program is not the same process. let name: String + let startedAt: UInt64? let cpuTime: TimeInterval /// The part of `cpuTime` that came from children it reaped. What it reaps in the interval /// it changes bucket was done in the old one. @@ -336,6 +339,7 @@ public struct ResourceReport: Equatable, Sendable { struct Boundary: Equatable, Sendable { let enclosingBucket: String + let startedAt: UInt64? let cpuTime: TimeInterval } } diff --git a/Sources/AgentWatchCore/ResourceAttribution.swift b/Sources/AgentWatchCore/ResourceAttribution.swift index 92f6486..356d7f0 100644 --- a/Sources/AgentWatchCore/ResourceAttribution.swift +++ b/Sources/AgentWatchCore/ResourceAttribution.swift @@ -54,6 +54,7 @@ public enum ResourceAttribution { let owner = tree.owner(of: process.processID) basis.members[process.processID] = ResourceReport.Member( bucket: tree.bucket(of: owner) ?? ProcessTree.unattributedBucket, name: process.name, + startedAt: process.startedAt, cpuTime: whole.cpuTime, finishedChildrenCPUTime: process.finishedChildrenCPUTime) switch owner { case let .session(id, part): @@ -186,13 +187,14 @@ public enum ResourceAttribution { return [:] } var reaped: [String: TimeInterval] = [:] - for (processID, boundary) in previous.rateBasis.boundaries where liveProcesses[processID] == nil { + for (processID, boundary) in previous.rateBasis.boundaries { + if let live = liveProcesses[processID], live.startedAt == boundary.startedAt { continue } reaped[boundary.enclosingBucket, default: 0] += boundary.cpuTime } var moved: [String: TimeInterval] = [:] for (processID, member) in now.members { guard let before = previous.rateBasis.members[processID], before.name == member.name, - before.bucket != member.bucket + before.startedAt == member.startedAt, before.bucket != member.bucket else { continue } @@ -318,6 +320,7 @@ final class ProcessTree { } found[processID] = ResourceReport.Boundary( enclosingBucket: enclosing, + startedAt: process.startedAt, cpuTime: subtreeTime(below: processID, bucket: own) ) } diff --git a/Sources/AgentWatchCore/SessionStateEngine.swift b/Sources/AgentWatchCore/SessionStateEngine.swift index 895f78f..01f5e2b 100644 --- a/Sources/AgentWatchCore/SessionStateEngine.swift +++ b/Sources/AgentWatchCore/SessionStateEngine.swift @@ -140,6 +140,10 @@ public struct SessionStateEngine: Sendable { /// that left, and what is worth saying out loud. Both are reported here rather than /// worked out again from the snapshots before and after. public mutating func receive(_ event: EventEnvelope) throws -> RowChange { + guard event.schemaVersion == EventEnvelope.currentSchemaVersion else { + throw EventIngestionError.unsupportedSchemaVersion(event.schemaVersion) + } + if let withheld = withholding(for: event) { return RowChange(row: nil, withheld: withheld, rowsThatLeft: [], note: nil) } @@ -162,16 +166,12 @@ public struct SessionStateEngine: Sendable { left.append(RowChange.Departure(row: folded, reason: .foldedIntoTheRowItContinues)) } - let row = try apply(event) + let row = apply(event) return RowChange(row: row, withheld: nil, rowsThatLeft: left, note: lastIngestNote) } @discardableResult - private mutating func apply(_ event: EventEnvelope) throws -> SessionSnapshot { - guard event.schemaVersion == EventEnvelope.currentSchemaVersion else { - throw EventIngestionError.unsupportedSchemaVersion(event.schemaVersion) - } - + private mutating func apply(_ event: EventEnvelope) -> SessionSnapshot { lastIngestNote = noteForNextIngest noteForNextIngest = nil let snapshotID = rowID(for: event) diff --git a/Sources/AgentWatchCore/TranscriptLocator.swift b/Sources/AgentWatchCore/TranscriptLocator.swift index 46d5041..dd3ea12 100644 --- a/Sources/AgentWatchCore/TranscriptLocator.swift +++ b/Sources/AgentWatchCore/TranscriptLocator.swift @@ -37,9 +37,27 @@ public enum TranscriptLocator { /// The root among these that holds a transcript, so that what lies beside the root — the /// thread index Codex keeps there — is read from the folder the transcript came from. - public static func root(containing transcript: URL, among roots: [URL]) -> URL? { - let path = transcript.standardizedFileURL.path - return roots.first { path.hasPrefix($0.standardizedFileURL.path + "/") } + public static func root(containing transcript: URL, source: AgentSource, among roots: [URL]) -> URL? { + let file = transcript.resolvingSymlinksInPath().standardizedFileURL + let directory = file.deletingLastPathComponent() + if source == .codex, directory.lastPathComponent == "archived_sessions" { + return roots.first { AgentFolders.canonicalPath(of: $0) == directory.path } + } + if let folder = AgentFolders.folder(ofTranscriptAt: file.path, source: source) { + let owner = AgentFolders.canonicalPath(of: root(for: source, inFolder: folder)) + return roots.first { AgentFolders.canonicalPath(of: $0) == owner } + } + + // Older or flat layouts can still identify their closest projects/sessions directory. + // A parent directory cannot claim a nested profile, even after the profile was removed. + let marker = root(for: source, inFolder: directory).lastPathComponent + let components = Array(file.pathComponents.dropLast()) + if let index = components.lastIndex(of: marker) { + let owner = NSString.path(withComponents: Array(components[...index])) + return roots.first { AgentFolders.canonicalPath(of: $0) == owner } + } + return roots.filter { file.path.hasPrefix(AgentFolders.canonicalPath(of: $0) + "/") } + .max { $0.path.count < $1.path.count } } /// Where Codex keeps the name of every thread: one short record each, beside the sessions @@ -71,7 +89,9 @@ public enum TranscriptLocator { ) -> URL? { var match: URL? visit(in: root, source: source, fileManager: fileManager) { label, file in - if label == sessionLabel { match = file } + if label == sessionLabel, Self.root(containing: file, source: source, among: [root]) != nil { + match = file + } return match == nil } return match @@ -86,7 +106,7 @@ public enum TranscriptLocator { for root in roots { visit(in: root, source: source, fileManager: .default) { label, file in guard !Task.isCancelled else { return false } - if sessionLabels.contains(label) { + if sessionLabels.contains(label), Self.root(containing: file, source: source, among: [root]) != nil { if files.updateValue(file, forKey: label) != nil { duplicates.insert(label) } } return true @@ -104,7 +124,9 @@ public enum TranscriptLocator { let enumerator = fileManager.enumerator( at: root, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return } - for case let url as URL in enumerator where url.pathExtension == "jsonl" { + for case let url as URL in enumerator { + guard !Task.isCancelled else { return } + guard url.pathExtension == "jsonl" else { continue } guard let identifier = sessionIdentifier( inFileNamed: url.deletingPathExtension().lastPathComponent, source: source) @@ -125,6 +147,7 @@ public enum TranscriptLocator { fileManager: FileManager = .default ) -> URL? { for root in roots { + guard !Task.isCancelled else { return nil } if let found = locate(sessionLabel: sessionLabel, source: source, root: root, fileManager: fileManager) { return found } diff --git a/Sources/AgentWatchGit/GitBranchTypes.swift b/Sources/AgentWatchGit/GitBranchTypes.swift index 51ddfec..14919b2 100644 --- a/Sources/AgentWatchGit/GitBranchTypes.swift +++ b/Sources/AgentWatchGit/GitBranchTypes.swift @@ -48,53 +48,17 @@ extension GitBranchType: Equatable { } } -/// The table of branch types the app writes and `AgentWatchGit` reads, one for all repositories. -/// -/// The Rust side reads `~/Library/Application Support/AgentWatch/git-branch-types.json` through -/// `HOME` and treats an unreadable file as no types; it lowers nothing below the floor of -/// ADR-0025, whatever the file says. -public struct GitBranchTypes: Codable, Equatable, Sendable { - public static let fileName = "git-branch-types.json" - public static let currentVersion = 1 - - public var version = currentVersion - public var types: [GitBranchType] - - public init(types: [GitBranchType] = []) { - self.types = types - } - - /// A missing file is an empty table. Anything else that cannot be read is an error, so - /// the settings page can say so instead of silently showing no types. - public static func load(from url: URL) throws -> Self { - let data: Data - do { - data = try Data(contentsOf: url) - } catch CocoaError.fileReadNoSuchFile { - return Self() - } - let table = try JSONDecoder().decode(Self.self, from: data) - guard table.version == currentVersion else { throw TableError.unknownVersion(table.version) } - return table - } - - /// Written whole, through a temporary file, so a reader never sees half a table. - public func save(to url: URL) throws { - try FileManager.default.createDirectory( - at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] - try encoder.encode(self).write(to: url, options: .atomic) - } - - /// The first type with a pattern that matches the short branch name. - public func matching(_ branch: String) -> GitBranchType? { - types.first { type in type.patterns.contains { Self.matches(pattern: $0, name: branch) } } +/// Version 1 is read to migrate existing settings into GitProtectionRules. +enum LegacyGitBranchRules { + struct Table: Decodable { + let types: [GitBranchType] } +} +enum GitBranchTypes { /// `*` matches any run of characters, `/` included; `?` matches one character; everything /// else matches itself. Compared by Unicode scalar, as the Rust side compares `char`s. - public static func matches(pattern: String, name: String) -> Bool { + static func matches(pattern: String, name: String) -> Bool { let pattern = Array(pattern.unicodeScalars) let name = Array(name.unicodeScalars) var p = 0 @@ -118,14 +82,4 @@ public struct GitBranchTypes: Codable, Equatable, Sendable { return pattern[p...].allSatisfy { $0 == "*" } } - public enum TableError: LocalizedError, Equatable { - case unknownVersion(Int) - - public var errorDescription: String? { - switch self { - case .unknownVersion(let version): - "The branch types file has version \(version), which this Agent Watch cannot read." - } - } - } } diff --git a/Sources/AgentWatchGit/GitDeletionPreview.swift b/Sources/AgentWatchGit/GitDeletionPreview.swift index 2f6a78f..d493868 100644 --- a/Sources/AgentWatchGit/GitDeletionPreview.swift +++ b/Sources/AgentWatchGit/GitDeletionPreview.swift @@ -66,15 +66,3 @@ public enum GitDeletionPreview: Equatable, Sendable { try GitCommand.run(arguments, in: folder) } } - -extension GitDeletionPreview { - /// The level a remote deletion of `branch` gets, as far as the preview can tell without the - /// network: the first matching type, or one click without one, raised to the repository name - /// by the floor this preview found. `.dependsOnRemote` below `.name` can still be raised by - /// the remote's default branch. - public func deletionLevel(in table: GitBranchTypes, branch: String) -> (level: GitCheckLevel, type: String?) { - let type = table.matching(branch) - let chosen = type?.level ?? .click - return (self == .dependsOnRemote ? chosen : max(chosen, .name), type?.name) - } -} diff --git a/Sources/AgentWatchGit/GitProtectionRules.swift b/Sources/AgentWatchGit/GitProtectionRules.swift index 2d2e5dc..b2a5ce5 100644 --- a/Sources/AgentWatchGit/GitProtectionRules.swift +++ b/Sources/AgentWatchGit/GitProtectionRules.swift @@ -43,7 +43,7 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { } } - public static let fileName = GitBranchTypes.fileName + public static let fileName = "git-branch-types.json" private static let maxBytes = 1024 * 1024 private let version: Int public var enabled: Bool @@ -101,7 +101,7 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { let decoder = JSONDecoder() switch try decoder.decode(Version.self, from: data).version { case 1: - let old = try decoder.decode(GitBranchTypes.self, from: data) + let old = try decoder.decode(LegacyGitBranchRules.Table.self, from: data) var rules = Self() rules.global.forcePush = old.types // The editor uses the rule ID to locate changes. Each operation owns its copy. @@ -110,7 +110,7 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { case 2: return try decoder.decode(Self.self, from: data) case let version: - throw GitBranchTypes.TableError.unknownVersion(version) + throw Failure.unknownVersion(version) } } @@ -170,8 +170,15 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { private enum Failure: LocalizedError { case tooLarge + case unknownVersion(Int) - var errorDescription: String? { "The Git protection rules file is too large (maximum 1 MB)." } + var errorDescription: String? { + switch self { + case .tooLarge: "The Git protection rules file is too large (maximum 1 MB)." + case let .unknownVersion(version): + "The branch rules file has version \(version), which this Agent Watch cannot read." + } + } } } diff --git a/Sources/AgentWatchIngress/UnixSocketIngress.swift b/Sources/AgentWatchIngress/UnixSocketIngress.swift index 0e6195b..4693c86 100644 --- a/Sources/AgentWatchIngress/UnixSocketIngress.swift +++ b/Sources/AgentWatchIngress/UnixSocketIngress.swift @@ -23,11 +23,13 @@ public final class UnixSocketIngress: @unchecked Sendable { /// The ordering is part of this interface, not an accident of the implementation: what /// arrives here are lifecycle transitions, and a caller that reorders them undoes the /// guarantee. A handler that hands the work to another queue has to keep it — an - /// unstructured `Task` does not, `DispatchQueue.main.async` does. + /// unstructured `Task` does not, `DispatchQueue.main.async` does. A caller that queues + /// delivery must also discard callbacks from an earlier start after it stops the listener. public typealias Handler = @Sendable (Result) -> Void private let socketPath: String private let handler: Handler + private let connectionStarted: (@Sendable () -> Void)? /// How long one connection may take to deliver its message before it is abandoned. private let readTimeoutMilliseconds: Int32 private let stateLock = NSLock() @@ -45,6 +47,7 @@ public final class UnixSocketIngress: @unchecked Sendable { /// is no throughput here for concurrency to win back. private let connectionQueue = DispatchQueue(label: "AgentWatch.UnixSocketIngress.connection") private var listenerDescriptor: Int32 = -1 + private var listenerGeneration = 0 private var listenerSource: DispatchSourceRead? private var ownedSocket: SocketIdentity? @@ -72,9 +75,19 @@ public final class UnixSocketIngress: @unchecked Sendable { /// open on purpose gives itself room here, so that a slow machine does not turn its /// pause into an abandoned connection — the CI machine did, and the ordering test failed /// with the first event missing. - public init(socketPath: String, readTimeoutMilliseconds: Int32 = 200, handler: @escaping Handler) { + public convenience init(socketPath: String, readTimeoutMilliseconds: Int32 = 200, handler: @escaping Handler) { + self.init( + socketPath: socketPath, readTimeoutMilliseconds: readTimeoutMilliseconds, connectionStarted: nil, + handler: handler) + } + + package init( + socketPath: String, readTimeoutMilliseconds: Int32, connectionStarted: (@Sendable () -> Void)?, + handler: @escaping Handler + ) { self.socketPath = socketPath self.readTimeoutMilliseconds = readTimeoutMilliseconds + self.connectionStarted = connectionStarted self.handler = handler } @@ -97,6 +110,10 @@ public final class UnixSocketIngress: @unchecked Sendable { } do { + let flags = fcntl(descriptor, F_GETFL) + guard flags >= 0, fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == 0 else { + throw UnixSocketIngressError.listenFailed + } try bind(descriptor) ownedSocket = SocketIdentity(at: socketPath) guard ownedSocket != nil else { @@ -114,11 +131,14 @@ public final class UnixSocketIngress: @unchecked Sendable { throw error } + listenerGeneration += 1 + let generation = listenerGeneration let source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: acceptQueue) source.setEventHandler { [weak self] in - self?.acceptConnection() + self?.acceptConnection(from: descriptor, generation: generation) } - source.setCancelHandler {} + // Dispatch may still be running the event handler after cancel() returns. + source.setCancelHandler { close(descriptor) } listenerDescriptor = descriptor listenerSource = source source.resume() @@ -127,15 +147,12 @@ public final class UnixSocketIngress: @unchecked Sendable { public func stop() { stateLock.lock() defer { stateLock.unlock() } - let descriptor = listenerDescriptor let source = listenerSource listenerDescriptor = -1 + listenerGeneration += 1 listenerSource = nil source?.cancel() - if descriptor >= 0 { - close(descriptor) - } removeOwnedSocket() } @@ -148,34 +165,35 @@ public final class UnixSocketIngress: @unchecked Sendable { _ = unlink(socketPath) } - private func acceptConnection() { - stateLock.lock() - let descriptor = listenerDescriptor - stateLock.unlock() - guard descriptor >= 0 else { - return - } + private func isListening(generation: Int) -> Bool { + stateLock.withLock { listenerDescriptor >= 0 && listenerGeneration == generation } + } + private func acceptConnection(from descriptor: Int32, generation: Int) { + guard isListening(generation: generation) else { return } let connectionDescriptor = accept(descriptor, nil, nil) - guard connectionDescriptor >= 0 else { - return - } + guard connectionDescriptor >= 0 else { return } connectionQueue.async { [weak self] in defer { close(connectionDescriptor) } - self?.readAndHandleConnection(connectionDescriptor) + self?.readAndHandleConnection(connectionDescriptor, generation: generation) } } - private func readAndHandleConnection(_ descriptor: Int32) { + private func readAndHandleConnection(_ descriptor: Int32, generation: Int) { + guard isListening(generation: generation) else { return } + connectionStarted?() + let result: Result do { - let request = try Self.readRequest(from: descriptor, timeoutMilliseconds: readTimeoutMilliseconds) - handler(.success(request)) + result = .success(try Self.readRequest(from: descriptor, timeoutMilliseconds: readTimeoutMilliseconds)) } catch let error as UnixSocketIngressError { - handler(.failure(error)) + result = .failure(error) } catch { - handler(.failure(.malformedMessage)) + result = .failure(.malformedMessage) } + // A handler can call stop itself. Check delivery eligibility without holding the + // state lock while calling it; delivery already accepted here may outlive stop(). + if isListening(generation: generation) { handler(result) } } private func bind(_ descriptor: Int32) throws { @@ -245,9 +263,8 @@ public final class UnixSocketIngress: @unchecked Sendable { throw UnixSocketIngressError.malformedMessage } - guard !data.isEmpty, data.count <= maximumMessageByteCount else { - throw UnixSocketIngressError.malformedMessage - } + guard data.count <= maximumMessageByteCount else { throw UnixSocketIngressError.messageTooLarge } + guard !data.isEmpty else { throw UnixSocketIngressError.malformedMessage } do { return try JSONDecoder().decode(HookIngressRequest.self, from: data) } catch { diff --git a/Sources/AgentWatchLookup/ProcessResourceSampler.swift b/Sources/AgentWatchLookup/ProcessResourceSampler.swift index 9f2ab8e..b843455 100644 --- a/Sources/AgentWatchLookup/ProcessResourceSampler.swift +++ b/Sources/AgentWatchLookup/ProcessResourceSampler.swift @@ -143,6 +143,7 @@ private struct Pass { processID: processID, parentProcessID: found.parentProcessID, name: name(processID), + startedAt: found.startedAt, footprint: usage.footprint, resident: usage.resident, cpuTime: usage.cpuTime, diff --git a/Sources/AgentWatchLookup/ProjectSessionLookup.swift b/Sources/AgentWatchLookup/ProjectSessionLookup.swift index 35c9737..d6a9255 100644 --- a/Sources/AgentWatchLookup/ProjectSessionLookup.swift +++ b/Sources/AgentWatchLookup/ProjectSessionLookup.swift @@ -72,6 +72,7 @@ public struct ProjectSessionLookup: Sendable { let directories = desktop.isEmpty ? [:] : desktopLocations(of: desktop) var folders: Set = [] for session in open { + guard !Task.isCancelled else { return nil } if session.hostKind == .desktop { guard let directory = directories[session.id]?.directory else { return nil } folders.insert(directory.resolvingSymlinksInPath().standardizedFileURL) diff --git a/Sources/AgentWatchLookup/WorktreeCacheCleanup.swift b/Sources/AgentWatchLookup/WorktreeCacheCleanup.swift index 1dc531a..225f8e0 100644 --- a/Sources/AgentWatchLookup/WorktreeCacheCleanup.swift +++ b/Sources/AgentWatchLookup/WorktreeCacheCleanup.swift @@ -40,13 +40,31 @@ public enum WorktreeCacheCleanup { var errorDescription: String? { text } } + struct ScanEvidence { + fileprivate let tree: URL + fileprivate let common: URL + fileprivate let treeID: CacheFileID + fileprivate let commonID: CacheFileID + fileprivate let records: [WorktreeDiskScanner.Record] + } + public static func assess( repository: URL, worktree: URL, folder: URL, activeFolders: Set, deadline: Date + ) -> WorktreeCacheAssessment { + assess(folder: folder, in: worktree, deadline: deadline) { + try scanEvidence( + repository: repository, worktree: worktree, activeFolders: activeFolders, deadline: deadline + ) { + try openFileIDs(deadline: deadline) + } + } + } + + static func assess( + folder: URL, in tree: URL, deadline: Date, evidence: () throws -> ScanEvidence ) -> WorktreeCacheAssessment { do { - let candidate = try inspect( - repository: repository, worktree: worktree, folder: folder, activeFolders: activeFolders, - deadline: deadline) + let candidate = try inspect(folder: folder, in: tree, deadline: deadline, evidence: evidence) return WorktreeCacheAssessment( reason: "The cache tag identifies rebuildable data. Git has no files here, the working copy is clean, and no use by your processes or monitored sessions was found.", @@ -59,9 +77,15 @@ public enum WorktreeCacheCleanup { /// A volume-relative object path keeps Foundation from trashing a replacement with the same name. /// The caller passes this URL directly to trashItem, immediately after the person's confirmation. public static func verifiedTrashURL(_ candidate: WorktreeCacheCandidate, activeFolders: Set) throws -> URL { - let current = try inspect( - repository: candidate.repository, worktree: candidate.worktree, folder: candidate.folder, - activeFolders: activeFolders, deadline: Date().addingTimeInterval(30)) + let deadline = Date().addingTimeInterval(30) + let current = try inspect(folder: candidate.folder, in: candidate.worktree, deadline: deadline) { + try scanEvidence( + repository: candidate.repository, worktree: candidate.worktree, activeFolders: activeFolders, + deadline: deadline + ) { + try openFileIDs(deadline: deadline) + } + } guard current == candidate else { throw Refusal("The folder or its contents changed since the scan. Scan again before moving it.") } @@ -73,22 +97,13 @@ public enum WorktreeCacheCleanup { return object } - private static func inspect( - repository: URL, worktree: URL, folder: URL, activeFolders: Set, deadline: Date - ) throws -> WorktreeCacheCandidate { + static func scanEvidence( + repository: URL, worktree: URL, activeFolders: Set, deadline: Date, + openFiles: () throws -> Set + ) throws -> ScanEvidence { let tree = worktree.resolvingSymlinksInPath().standardizedFileURL let common = repository.resolvingSymlinksInPath().standardizedFileURL - let name = folder.lastPathComponent - guard WorktreeDiskScanner.buildFolderNames.contains(name), - samePath(folder.deletingLastPathComponent(), tree) - else { throw Refusal("Only a build folder directly inside this working copy can be moved.") } - let cache = tree.appendingPathComponent(name, isDirectory: true) - let cacheInfo = try info(cache) - let treeInfo = try info(tree) - guard cacheInfo.st_mode & S_IFMT == S_IFDIR, cacheInfo.st_dev == treeInfo.st_dev else { - throw Refusal("This path is a link, mount point, or inaccessible folder.") - } - try readCacheTag(in: cache) + let treeID = CacheFileID(try info(tree)) if activeFolders.contains(where: { contains(tree, $0.resolvingSymlinksInPath().standardizedFileURL) }) { throw Refusal("A monitored session is using this working copy.") } @@ -106,7 +121,6 @@ public enum WorktreeCacheCleanup { guard try samePath(gitPath(["rev-parse", "--show-toplevel"]), tree), try samePath(gitPath(["rev-parse", "--path-format=absolute", "--git-common-dir"]), common) else { throw Refusal("This working copy no longer belongs to the selected repository.") } - let treeID = CacheFileID(treeInfo) let commonID = CacheFileID(try info(common)) let list = try git(["worktree", "list", "--porcelain", "-z"]) guard list.status == 0 else { throw Refusal("Could not verify registered working copies.") } @@ -114,10 +128,7 @@ public enum WorktreeCacheCleanup { guard let registration = records.first(where: { samePath(URL(fileURLWithPath: $0.path), tree) }), !registration.locked, !registration.prunable, !registration.bare else { throw Refusal("Git marks this working copy as locked, missing, or unavailable.") } - if records.contains(where: { contains(cache, URL(fileURLWithPath: $0.path).standardizedFileURL) }) { - throw Refusal("A linked working copy is registered inside this folder.") - } - let openFiles = try openFileIDs(deadline: deadline) + let openFiles = try openFiles() let boundaries = WorktreeDiskScanner.measurementBoundaries(records: records, common: common) _ = try WorktreeDiskScanner.measuredBytes(tree, boundaries: boundaries, deadline: deadline) { item in if openFiles.contains(OpenFileID(device: item.st_dev, inode: item.st_ino)) { @@ -132,6 +143,34 @@ public enum WorktreeCacheCleanup { for marker in WorktreeDiskScanner.operationMarkers where try exists(admin.appendingPathComponent(marker)) { throw Refusal("Git has an unfinished operation or lock here (\(marker)).") } + guard try WorktreeDiskScanner.workingChanges(in: tree, deadline: deadline).isClean else { + throw Refusal( + "The working copy has uncommitted changes. Keep the cache until those changes are accounted for.") + } + return ScanEvidence(tree: tree, common: common, treeID: treeID, commonID: commonID, records: records) + } + + private static func inspect( + folder: URL, in worktree: URL, deadline: Date, evidence: () throws -> ScanEvidence + ) throws -> WorktreeCacheCandidate { + let tree = worktree.resolvingSymlinksInPath().standardizedFileURL + let name = folder.lastPathComponent + guard WorktreeDiskScanner.buildFolderNames.contains(name), samePath(folder.deletingLastPathComponent(), tree) + else { throw Refusal("Only a build folder directly inside this working copy can be moved.") } + let cache = tree.appendingPathComponent(name, isDirectory: true) + let cacheInfo = try info(cache) + guard cacheInfo.st_mode & S_IFMT == S_IFDIR, cacheInfo.st_dev == (try info(tree)).st_dev else { + throw Refusal("This path is a link, mount point, or inaccessible folder.") + } + try readCacheTag(in: cache) + let snapshot = try evidence() + guard snapshot.tree == tree, + !snapshot.records.contains(where: { contains(cache, URL(fileURLWithPath: $0.path).standardizedFileURL) }) + else { throw Refusal("A linked working copy is registered inside this folder.") } + + func git(_ args: [String]) throws -> GitCommand.Result { + try GitCommand.run(args, in: tree, timeout: min(10, try remaining(deadline))) + } let index = try git(["ls-files", "--cached", "-z", "--", name]) let head = try git(["ls-tree", "-z", "HEAD", "--", name]) let ignored = try git(["check-ignore", "--quiet", "--", name]) @@ -141,16 +180,13 @@ public enum WorktreeCacheCleanup { guard index.output.isEmpty, head.output.isEmpty else { throw Refusal("The index or current commit contains files in this folder.") } - guard try WorktreeDiskScanner.workingChanges(in: tree, deadline: deadline).isClean else { - throw Refusal( - "The working copy has uncommitted changes. Keep the cache until those changes are accounted for.") - } let fingerprint = try contentsFingerprint(cache, device: cacheInfo.st_dev, deadline: deadline) - guard CacheFileID(try info(cache)) == CacheFileID(cacheInfo), CacheFileID(try info(tree)) == treeID, - CacheFileID(try info(common)) == commonID + guard CacheFileID(try info(cache)) == CacheFileID(cacheInfo), CacheFileID(try info(tree)) == snapshot.treeID, + CacheFileID(try info(snapshot.common)) == snapshot.commonID else { throw Refusal("The working copy changed during inspection.") } return WorktreeCacheCandidate( - repository: common, worktree: tree, folder: cache, treeID: treeID, repositoryID: commonID, + repository: snapshot.common, worktree: tree, folder: cache, treeID: snapshot.treeID, + repositoryID: snapshot.commonID, folderID: CacheFileID(cacheInfo), fingerprint: fingerprint) } @@ -217,7 +253,7 @@ public enum WorktreeCacheCleanup { // lsof prints only numeric identities and object types. Comparing identities also // catches a file held open through a hard link or an alternate mount path. - private static func openFileIDs(deadline: Date) throws -> Set { + static func openFileIDs(deadline: Date) throws -> Set { try openFileIDs(attempts: 3) { let result = try BoundedCommand.run( executable: URL(fileURLWithPath: "/usr/sbin/lsof"), diff --git a/Sources/AgentWatchLookup/WorktreeDiskReport.swift b/Sources/AgentWatchLookup/WorktreeDiskReport.swift index 32d1878..27bb4ae 100644 --- a/Sources/AgentWatchLookup/WorktreeDiskReport.swift +++ b/Sources/AgentWatchLookup/WorktreeDiskReport.swift @@ -69,8 +69,16 @@ public enum WorktreeDiskScanner { guard list.status == 0 else { throw ScanError.repository } let records = try parse(list.output) let boundaries = measurementBoundaries(records: records, common: common) + var openFiles: Result, Error>? + func openFileSnapshot() throws -> Set { + let snapshot = openFiles ?? Result { try WorktreeCacheCleanup.openFileIDs(deadline: deadline) } + openFiles = snapshot + return try snapshot.get() + } let entries = records.map { - inspect($0, common: common, boundaries: boundaries, activeFolders: activeFolders, deadline: deadline) + inspect( + $0, common: common, boundaries: boundaries, activeFolders: activeFolders, deadline: deadline, + openFiles: openFileSnapshot) }.sorted { if $0.allocatedBytes == $1.allocatedBytes { return $0.id < $1.id } return ($0.allocatedBytes ?? -1) > ($1.allocatedBytes ?? -1) @@ -120,7 +128,8 @@ public enum WorktreeDiskScanner { } private static func inspect( - _ record: Record, common: URL, boundaries: Set, activeFolders: Set?, deadline: Date + _ record: Record, common: URL, boundaries: Set, activeFolders: Set?, deadline: Date, + openFiles: () throws -> Set ) -> WorktreeDiskEntry { let folder = URL(fileURLWithPath: record.path) var concerns: [String] = [] @@ -170,12 +179,25 @@ public enum WorktreeDiskScanner { } else { concerns.append("Session activity is unavailable. Review this working copy manually.") } + var cleanupEvidence: Result? + func cacheEvidence() throws -> WorktreeCacheCleanup.ScanEvidence { + let snapshot = + cleanupEvidence + ?? Result { + guard let activeFolders else { throw ScanError.metadata } + return try WorktreeCacheCleanup.scanEvidence( + repository: common, worktree: root, activeFolders: activeFolders, deadline: deadline, + openFiles: openFiles) + } + cleanupEvidence = snapshot + return try snapshot.get() + } let canInspectCache = concerns.isEmpty let folders = buildFolderNames.compactMap { name -> WorktreeBuildFolder? in let candidate = root.appendingPathComponent(name, isDirectory: true) return inspectBuildFolder( - candidate, in: root, common: common, boundaries: boundaries, - activeFolders: canInspectCache ? activeFolders : nil, deadline: deadline) + candidate, in: root, boundaries: boundaries, + checkCleanup: canInspectCache, deadline: deadline, cacheEvidence: cacheEvidence) }.sorted { if $0.allocatedBytes == $1.allocatedBytes { return $0.id < $1.id } return ($0.allocatedBytes ?? -1) > ($1.allocatedBytes ?? -1) @@ -206,7 +228,8 @@ public enum WorktreeDiskScanner { } private static func inspectBuildFolder( - _ folder: URL, in tree: URL, common: URL, boundaries: Set, activeFolders: Set?, deadline: Date + _ folder: URL, in tree: URL, boundaries: Set, checkCleanup: Bool, deadline: Date, + cacheEvidence: () throws -> WorktreeCacheCleanup.ScanEvidence ) -> WorktreeBuildFolder? { do { let attributes: [FileAttributeKey: Any] @@ -254,17 +277,16 @@ public enum WorktreeDiskScanner { } let bytes = try measuredBytes(folder, boundaries: boundaries, deadline: deadline) let knownCacheOnHold = - activeFolders == nil && tracked.output.isEmpty && ignored.status == 0 + !checkCleanup && tracked.output.isEmpty && ignored.status == 0 && (try? WorktreeCacheCleanup.readCacheTag(in: folder)) != nil var result = WorktreeBuildFolder( folder: folder, allocatedBytes: bytes, evidence: evidence, concern: knownCacheOnHold ? "The cache tag marks these files as rebuildable. Resolve the working-copy warnings above and scan again." : concern) - if let activeFolders, tracked.output.isEmpty, ignored.status == 0 { + if checkCleanup, tracked.output.isEmpty, ignored.status == 0 { result.cleanup = WorktreeCacheCleanup.assess( - repository: common, worktree: tree, folder: folder, - activeFolders: activeFolders, deadline: deadline) + folder: folder, in: tree, deadline: deadline, evidence: cacheEvidence) } return result } catch { diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md index 723796e..fb8bed0 100644 --- a/TROUBLESHOOTING.md +++ b/TROUBLESHOOTING.md @@ -239,16 +239,16 @@ and links to the [request for a supported event](https://github.com/openai/codex captured through a conditional DevTools breakpoint: 2026-11-25, on the newer version. Database and OpenTelemetry export were not retested on the newer version. -## The agent says a Git push is "forbidden by branch type" +## The agent says a Git push is "forbidden by branch rule" -**Why:** A branch type in `Settings… → Git Protection → Branch types` has the level `Forbid`, and -the branch matched its pattern first. Agent Watch refuses a force push or a remote deletion of such -a branch without a window, both in the Git hook and in `AgentWatchGit push`. Types are checked from -the top, so a broad pattern such as `*` above a narrower one takes the branch first. +**Why:** The effective rule in **Settings… → Git Protection → Branch rules** is **Block**. +Each operation has its own rules for push, force push and remote deletion. The first matching +pattern applies, with protected-branch defaults and any stricter repository rule also considered. +A blocked operation is refused before a confirmation window opens. -**What to do:** Run the command yourself in a terminal; the refusal names the branch and the type, -and `AgentWatchGit push` also returns the command. To let the agent do it, choose another level for -the type or move a narrower type above it. +**What to do:** Select the operation and open **Preview a Branch**. Enter the branch and choose +its repository to see which rule applies. You can run the operation yourself in a terminal or +change the applicable rule and retry. **Checked on:** not recorded. Tests with local repositories cover the hook and `AgentWatchGit push`; a live Claude Code or Codex session has not been tried yet. diff --git a/Taskfile.yml b/Taskfile.yml index 1aafaa5..80307c0 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -21,7 +21,6 @@ tasks: test-native-git: desc: Test the Git hook and the one-shot confirmation executable cmds: - - python3 -B scripts/test-git-guard.py - CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$PWD/.build/devtool}" rustup run 1.98.1 cargo test --locked --manifest-path native/git-protection/Cargo.toml - CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$PWD/.build/devtool}" rustup run 1.98.1 cargo test --locked --manifest-path native/git-protection/Cargo.toml --profile fixture --features mcp-fixture --test push --test protocol -- --test-threads=2 @@ -73,7 +72,6 @@ tasks: - task: lint - task: test - task: build - - task: build-release - task: build-app build-release: diff --git a/Tests/AgentWatchAppTests/AgentHeardStoreTests.swift b/Tests/AgentWatchAppTests/AgentHeardStoreTests.swift index 4255d7a..1bce4ac 100644 --- a/Tests/AgentWatchAppTests/AgentHeardStoreTests.swift +++ b/Tests/AgentWatchAppTests/AgentHeardStoreTests.swift @@ -95,6 +95,22 @@ final class AgentHeardStoreTests: XCTestCase { /// Fail open, like every other read of a file this app did not just write. A file somebody /// edited, or one a full disk truncated, must not stop the app — it costs one sentence in /// a menu, and the price of throwing here would be the whole launch. + func testMalformedKeysAreSkippedWithoutDiscardingValidRecords() throws { + let directory = try makeDirectory() + let file = directory.appendingPathComponent("agents-heard.json") + let invalid = #""" + {"heard":{"":123,"@":124,"@codex":125,"codex@":126,"claude":127,"codex@@garbage":128}, + "installed":["","@","codex"]} + """# + try Data(invalid.utf8).write(to: file) + + let store = AgentHeardStore(directoryURL: directory) + + XCTAssertEqual(store.delivery(for: .claude), .arrived) + XCTAssertEqual(store.delivery(for: .codex), .nothingSinceInstall) + XCTAssertFalse(store.hasHeard(from: .codex)) + } + func testAFileThatCannotBeUnderstoodReadsAsHavingHeardNothing() throws { let directory = try makeDirectory() defer { try? FileManager.default.removeItem(at: directory) } diff --git a/Tests/AgentWatchAppTests/ClosedTerminalRowTests.swift b/Tests/AgentWatchAppTests/ClosedTerminalRowTests.swift index 33d1ec2..7960f66 100644 --- a/Tests/AgentWatchAppTests/ClosedTerminalRowTests.swift +++ b/Tests/AgentWatchAppTests/ClosedTerminalRowTests.swift @@ -478,6 +478,28 @@ final class ClosedTerminalRowTests: XCTestCase { XCTAssertEqual(hungUp, []) } + func testAYesDiscardsNoOutputAfterTheProcessNumberWasReused() throws { + var startedAt = Date.distantPast + var released: [String] = [] + let supervisor = makeSupervisor( + terminalState: { _ in .lost }, + agentProcessStartedAt: { _ in startedAt }, + released: { released.append($0) }) + supervisor.start() + defer { supervisor.stop() } + supervisor.ingest( + testRequest(event: "SessionStart", sessionID: "devx", agentProcessID: agent, clientKind: .cli)) + supervisor.discoverAgentProcesses() + let row = try XCTUnwrap(supervisor.sessions.first) + XCTAssertEqual(supervisor.focus(row), .asksToEndAgent(.discardOutput(devicePath: device))) + + startedAt = now.addingTimeInterval(60) + supervisor.endAgent(ofSessionWithID: row.id) + + XCTAssertEqual(released, []) + XCTAssertEqual(supervisor.reach(for: row), .closedTerminal(nil)) + } + // MARK: - Scaffolding /// Nothing here reaches a real host: the process running the tests may be in a Ghostty diff --git a/Tests/AgentWatchAppTests/HookIngressControllerTests.swift b/Tests/AgentWatchAppTests/HookIngressControllerTests.swift index 84ea073..eabfd93 100644 --- a/Tests/AgentWatchAppTests/HookIngressControllerTests.swift +++ b/Tests/AgentWatchAppTests/HookIngressControllerTests.swift @@ -144,6 +144,37 @@ final class HookIngressControllerTests: XCTestCase { XCTAssertEqual(revealed, 1) } + func testAQueuedCallbackFromTheOldListenerIsDiscardedOnRestart() async throws { + let address = URL(fileURLWithPath: "/private/tmp/aw-\(UUID().uuidString).sock") + var callbacks: [UnixSocketIngress.Handler] = [] + var requests: [HookIngressRequest] = [] + let controller = HookIngressController( + socketURL: { address }, + ingest: { request in + requests.append(request) + return nil + }, + reveal: { XCTFail("An old listener must not reveal the app") }, + log: { _ in }, + makeListener: { path, callback in + callbacks.append(callback) + return UnixSocketIngress(socketPath: path, handler: callback) + }) + controller.start() + defer { controller.stop() } + try XCTUnwrap(callbacks.first)(.success(LocalAgentWatchControl.revealExistingInstanceRequest())) + controller.stop() + controller.start() + XCTAssertEqual(callbacks.count, 2) + let request = hookRequest() + try XCTUnwrap(callbacks.last)(.success(request)) + await withCheckedContinuation { continuation in + DispatchQueue.main.async { continuation.resume() } + } + + XCTAssertEqual(requests, [request]) + } + private func makeController( ingest: @escaping (HookIngressRequest) -> EventEnvelope?, reveal: @escaping () -> Void = {}, diff --git a/Tests/AgentWatchAppTests/PreferenceFileTests.swift b/Tests/AgentWatchAppTests/PreferenceFileTests.swift index 8c46255..40d4909 100644 --- a/Tests/AgentWatchAppTests/PreferenceFileTests.swift +++ b/Tests/AgentWatchAppTests/PreferenceFileTests.swift @@ -94,15 +94,57 @@ final class PreferenceFileTests: XCTestCase { XCTAssertNil(reopened.number(forKey: "aFlag"), "a stored flag is not a number") } - func testAnUnreadableFileReadsAsEmptyAndIsWrittenOverRatherThanKept() throws { + func testFailedBackupPreservesSettingsAndIsRetried() throws { let directory = try makeDirectory() let fileURL = directory.appendingPathComponent("settings.json") - try Data("this is not the file we left".utf8).write(to: fileURL) + let original = Data("invalid JSON".utf8) + try original.write(to: fileURL) + let files = BackupFileManager() + let preferences = PreferenceFile(fileManager: files, directoryURL: directory) - let preferences = PreferenceFile(directoryURL: directory) - XCTAssertNil(preferences.string(forKey: "widgetBackground")) + preferences.set("mint", forKey: "widgetBackground") + + XCTAssertNil(preferences.unreadableFileKeptAt) + XCTAssertEqual(try Data(contentsOf: fileURL), original) + + files.blocksMove = false + preferences.set("graphite", forKey: "widgetBackground") + + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(preferences.unreadableFileKeptAt)), original) + XCTAssertEqual(PreferenceFile(directoryURL: directory).string(forKey: "widgetBackground"), "graphite") + } + + func testSavingResumesWhenTheUnpreservedFileIsRemoved() throws { + let directory = try makeDirectory() + let fileURL = directory.appendingPathComponent("settings.json") + let original = Data("invalid JSON".utf8) + try original.write(to: fileURL) + let files = BackupFileManager() + let preferences = PreferenceFile(fileManager: files, directoryURL: directory) preferences.set("mint", forKey: "widgetBackground") + XCTAssertEqual(try Data(contentsOf: fileURL), original) + try FileManager.default.moveItem(at: fileURL, to: directory.appendingPathComponent("original.json")) + preferences.set("graphite", forKey: "widgetBackground") + + XCTAssertNil(preferences.unreadableFileKeptAt) + XCTAssertEqual(PreferenceFile(directoryURL: directory).string(forKey: "widgetBackground"), "graphite") + } + + func testAFileWithoutReadPermissionIsKeptBeforeWriting() throws { + let directory = try makeDirectory() + let fileURL = directory.appendingPathComponent("settings.json") + let original = Data(#"{"widgetBackground":"slate"}"#.utf8) + try original.write(to: fileURL) + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: fileURL.path) + guard (try? Data(contentsOf: fileURL)) == nil else { throw XCTSkip("The runner can read mode 000 files") } + + let preferences = PreferenceFile(directoryURL: directory) + preferences.set("mint", forKey: "widgetBackground") + + let kept = try XCTUnwrap(preferences.unreadableFileKeptAt) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: kept.path) + XCTAssertEqual(try Data(contentsOf: kept), original) XCTAssertEqual(PreferenceFile(directoryURL: directory).string(forKey: "widgetBackground"), "mint") } @@ -194,3 +236,12 @@ final class PreferenceFileTests: XCTestCase { return directory } } + +private final class BackupFileManager: FileManager, @unchecked Sendable { + var blocksMove = true + + override func moveItem(at source: URL, to destination: URL) throws { + if blocksMove { throw CocoaError(.fileWriteNoPermission) } + try super.moveItem(at: source, to: destination) + } +} diff --git a/Tests/AgentWatchAppTests/ToolingInstallerTests.swift b/Tests/AgentWatchAppTests/ToolingInstallerTests.swift index 4e0e6ec..6120a48 100644 --- a/Tests/AgentWatchAppTests/ToolingInstallerTests.swift +++ b/Tests/AgentWatchAppTests/ToolingInstallerTests.swift @@ -132,6 +132,24 @@ final class ToolingInstallerTests: XCTestCase { XCTAssertEqual(try String(contentsOf: hooksURL, encoding: .utf8), theirs) } + func testInstallingCodexHooksRefusesUnexpectedJSONShapes() throws { + let home = try makeHome() + let sender = try makeSender(in: home) + let hooksURL = home.appendingPathComponent(".codex/hooks.json") + try FileManager.default.createDirectory( + at: hooksURL.deletingLastPathComponent(), withIntermediateDirectories: true) + let installer = ToolingInstaller(home: home) + for json in ["[]", #"{"hooks":[]}"#, #"{"hooks":{"Stop":{}}}"#] { + let original = Data(json.utf8) + try original.write(to: hooksURL) + XCTAssertEqual(installer.hookState(for: .codex, delivery: .unknown), .unreadable) + XCTAssertThrowsError( + try installer.installHooks(for: .codex, senderPath: sender.path, hooks: ToolingHooks.hooks(for: .codex)) + ) + XCTAssertEqual(try Data(contentsOf: hooksURL), original) + } + } + /// A configuration the app cannot read is not an absent one, and the menu must not offer /// to install over it: the offer would be a promise to repair something whose contents /// are unknown. diff --git a/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift b/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift index 3cf8522..31b8035 100644 --- a/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift +++ b/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift @@ -697,6 +697,107 @@ final class TranscriptWatcherTests: XCTestCase { XCTAssertNil(inbox.first?.fault, "a warning left by a reader that has stopped is a claim about nobody") } + func testAQueuedTimerCannotReadAfterSwitchingOff() throws { + try write(toolResult(id: "old")) + let settings = try makeSettings() + let watcher = makeWatcher(settings: settings) + watcher.update(sessions: [working()]) + + settings.setTranscriptPollInterval(nil) + watcher.settingsChanged() + watcher.update(sessions: [working()]) + watcher.timerFired() + + XCTAssertNil(watcher.readTask) + XCTAssertNil(watcher.transcriptURL(forSessionWithID: working().id)) + } + + func testAReadFromBeforeSwitchingOffCannotUpdateTheSameRowWhenReenabled() async throws { + try write(toolResult(id: "old")) + let settings = try makeSettings() + let watcher = makeWatcher(settings: settings) + watcher.update(sessions: [working()]) + _ = try await poll(watcher) + try append(toolResult(id: "late")) + + watcher.poll() + let oldRead = try XCTUnwrap(watcher.readTask) + settings.setTranscriptPollInterval(nil) + watcher.settingsChanged() + settings.setTranscriptPollInterval(3) + watcher.settingsChanged() + inbox = [] + await oldRead.value + + XCTAssertNil(watcher.transcriptURL(forSessionWithID: working().id)) + XCTAssertTrue(inbox.isEmpty) + _ = try await poll(watcher) + XCTAssertEqual( + watcher.transcriptURL(forSessionWithID: working().id)?.resolvingSymlinksInPath(), + transcriptURL.resolvingSymlinksInPath()) + } + + func testChangingProfilesRetriesACancelledCatchUpForAnIdleRow() async throws { + try write(toolResult(id: "old")) + let watcher = try makeWatcher() + let row = restored() + watcher.update(sessions: [row]) + XCTAssertEqual(watcher.catchUp(sessions: [row]), [row.id]) + let oldRead = try XCTUnwrap(watcher.readTask) + + watcher.foldersChanged() + await oldRead.value + let retry = try XCTUnwrap(watcher.readTask) + await retry.value + + XCTAssertNotNil(watcher.transcriptURL(forSessionWithID: row.id)) + XCTAssertEqual(inbox.first?.sessionID, row.id) + XCTAssertNotNil(inbox.first?.newestRecordAt) + XCTAssertFalse(watcher.isPolling) + } + + func testChangingProfilesRearmsACancelledFinalCodexRead() async throws { + try writeCodex([Self.codexOpening]) + let watcher = try makeWatcher() + watcher.update(sessions: [workingCodex()]) + _ = try await poll(watcher) + + var stopped = workingCodex() + stopped.phase = .completed + watcher.update(sessions: [stopped]) + watcher.poll() + let oldRead = try XCTUnwrap(watcher.readTask) + watcher.foldersChanged() + await oldRead.value + + XCTAssertNotNil(watcher.nextReadAt) + _ = try await poll(watcher) + XCTAssertNil(watcher.nextReadAt) + } + + func testRemovingFolderInvalidatesItsLocatedFile() async throws { + let extra = TranscriptLocator.defaultRoot(for: .claude, home: home) + .appendingPathComponent("nested-profile", isDirectory: true) + let project = extra.appendingPathComponent("projects/project", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + let file = project.appendingPathComponent(transcriptURL.lastPathComponent) + try Data((toolResult(id: "old") + "\n").utf8).write(to: file) + var folders = [AgentSource.claude: [extra.path]] + let watcher = makeWatcher(settings: try makeSettings(), currentFolders: { folders }) + watcher.update(sessions: [working()]) + _ = try await poll(watcher) + XCTAssertEqual( + watcher.transcriptURL(forSessionWithID: working().id)?.resolvingSymlinksInPath(), + file.resolvingSymlinksInPath()) + + folders = [:] + watcher.foldersChanged() + + XCTAssertNil(watcher.transcriptURL(forSessionWithID: working().id)) + _ = try await poll(watcher) + XCTAssertNil(watcher.transcriptURL(forSessionWithID: working().id)) + } + // MARK: - Helpers private func makeSettings() throws -> WidgetSettingsStore { @@ -977,12 +1078,10 @@ final class TranscriptWatcherTests: XCTestCase { sessions: [SessionSnapshot], waits: [String: SessionHistory.RememberedWait] = [:] ) async throws -> [TranscriptUpdate] { - let reported = expectation(description: "the catch-up reported back") - arrival = reported inbox = [] watcher.catchUp(sessions: sessions, waits: waits) - await fulfillment(of: [reported], timeout: 2) - arrival = nil + let reading = try XCTUnwrap(watcher.readTask) + await reading.value return inbox } @@ -992,12 +1091,13 @@ final class TranscriptWatcherTests: XCTestCase { private func makeWatcher( settings: WidgetSettingsStore, - extraAgentFolders: [AgentSource: [String]] = [:] + extraAgentFolders: [AgentSource: [String]] = [:], + currentFolders: (() -> [AgentSource: [String]])? = nil ) -> TranscriptWatcher { let watcher = TranscriptWatcher( settings: settings, home: home, - extraAgentFolders: { extraAgentFolders }, + extraAgentFolders: currentFolders ?? { extraAgentFolders }, now: { [weak self] in self?.clock ?? Date() }, onUpdates: { [weak self] updates in self?.inbox = updates diff --git a/Tests/AgentWatchCoreTests/DiscoveredProcessTests.swift b/Tests/AgentWatchCoreTests/DiscoveredProcessTests.swift index afdd222..6d73797 100644 --- a/Tests/AgentWatchCoreTests/DiscoveredProcessTests.swift +++ b/Tests/AgentWatchCoreTests/DiscoveredProcessTests.swift @@ -102,6 +102,22 @@ final class DiscoveredProcessTests: XCTestCase { XCTAssertEqual(engine.snapshots.count, 2) } + func testAnUnsupportedEventLeavesTheDiscoveredRowIntact() { + var engine = SessionStateEngine() + engine.reconcileDiscoveredProcesses([process(id: 501, startedAt: now - 900)]) + let before = engine.snapshots + let event = EventEnvelope( + schemaVersion: EventEnvelope.currentSchemaVersion + 1, + source: .claude, + sessionID: "abc", + observedAt: now, + kind: .sessionStarted, + agentProcessID: 501) + + XCTAssertThrowsError(try engine.receive(event)) + XCTAssertEqual(engine.snapshots, before) + } + /// A process a hook once named is not an anonymous process any more. The row it makes is /// the session itself — which is what lets the row be asked the questions a session can /// answer, starting with which file it writes and therefore what it is called. diff --git a/Tests/AgentWatchCoreTests/ResourceAttributionTests.swift b/Tests/AgentWatchCoreTests/ResourceAttributionTests.swift index 518586f..92aa751 100644 --- a/Tests/AgentWatchCoreTests/ResourceAttributionTests.swift +++ b/Tests/AgentWatchCoreTests/ResourceAttributionTests.swift @@ -337,6 +337,33 @@ final class ResourceAttributionTests: XCTestCase { XCTAssertEqual(second.hosts.first?.cpuLoad ?? -1, 1, accuracy: 0.001, "five seconds of work over five") } + func testAReusedProcessNumberDoesNotTransferItsPredecessorsCPUTime() { + let hosts = [SharedAgentHost(processID: 500, source: .codex)] + let thread = row("t1", source: .codex) + let first = ResourceAttribution.report( + table: ProcessTable( + sampledAt: start, + processes: [ + process(500, parent: 1, "codex", cpu: 100), + process(501, parent: 500, "zsh", cpu: 20, markers: [marker("t1", source: .codex)], startedAt: 1), + ], + hosts: hosts), + sessions: [thread], + previous: nil) + let second = ResourceAttribution.report( + table: ProcessTable( + sampledAt: start.addingTimeInterval(5), + processes: [ + process(500, parent: 1, "codex", cpu: 100, finished: 20), + process(501, parent: 500, "zsh", cpu: 5, startedAt: 2), + ], + hosts: hosts), + sessions: [thread], + previous: first) + + XCTAssertEqual(second.hosts.first?.cpuLoad ?? -1, 1, accuracy: 0.001) + } + /// The thread's command ends in the same interval its shell moves to the host: with no /// marker left below it, the shell is the host's now, holding the command's whole life in /// its counter of finished children. That life was the thread's; the host gets only what @@ -440,12 +467,14 @@ final class ResourceAttributionTests: XCTestCase { cpu: TimeInterval = 0, finished: TimeInterval = 0, markers: [SessionMarker] = [], - workingDirectory: String? = nil + workingDirectory: String? = nil, + startedAt: UInt64? = nil ) -> SampledProcess { SampledProcess( processID: processID, parentProcessID: parent, name: name, + startedAt: startedAt, footprint: megabytes * megabyte, resident: megabytes * megabyte / 2, cpuTime: cpu, diff --git a/Tests/AgentWatchCoreTests/TranscriptLocatorTests.swift b/Tests/AgentWatchCoreTests/TranscriptLocatorTests.swift index 3df1616..a72a3a8 100644 --- a/Tests/AgentWatchCoreTests/TranscriptLocatorTests.swift +++ b/Tests/AgentWatchCoreTests/TranscriptLocatorTests.swift @@ -100,10 +100,33 @@ final class TranscriptLocatorTests: XCTestCase { XCTAssertEqual(found?.lastPathComponent, "rollout-2026-10-09T01-10-29-\(codexSession).jsonl") XCTAssertEqual( - found.flatMap { TranscriptLocator.root(containing: $0, among: [defaultRoot, listedRoot]) }, listedRoot, + found.flatMap { TranscriptLocator.root(containing: $0, source: .codex, among: [defaultRoot, listedRoot]) }, + listedRoot, "the thread index is read beside the root the transcript came from") } + func testANestedProfileIsVisibleOnlyWhenItsOwnRootIsAllowed() throws { + let home = try makeRoot(named: [ + ".codex/sessions/child/sessions/2026/10/09/rollout-\(codexSession).jsonl", + ".codex/sessions/child/archived_sessions/rollout-\(codexSession).jsonl", + ]) + let outer = TranscriptLocator.defaultRoot(for: .codex, home: home) + let inner = outer.appendingPathComponent("child/sessions", isDirectory: true) + let label = HookCaptureRedactor.label(forRawIdentifier: codexSession) + + XCTAssertNil(TranscriptLocator.locate(sessionLabel: label, source: .codex, root: outer)) + XCTAssertTrue(TranscriptLocator.uniqueMatches(sessionLabels: [label], source: .codex, roots: [outer]).isEmpty) + let found = try XCTUnwrap(TranscriptLocator.locate(sessionLabel: label, source: .codex, roots: [outer, inner])) + XCTAssertEqual(TranscriptLocator.root(containing: found, source: .codex, among: [outer, inner]), inner) + XCTAssertNotNil( + TranscriptLocator.uniqueMatches(sessionLabels: [label], source: .codex, roots: [outer, inner])[label]) + + let archive = TranscriptLocator.codexArchivedSessions(inRoot: inner) + let archived = try XCTUnwrap(TranscriptLocator.locate(sessionLabel: label, source: .codex, root: archive)) + XCTAssertEqual(TranscriptLocator.root(containing: archived, source: .codex, among: [outer, archive]), archive) + XCTAssertNil(TranscriptLocator.root(containing: archived, source: .codex, among: [outer])) + } + func testEachFolderKeepsItsTranscriptsWhereItsAgentWritesThem() { let folders = AgentFolders( home: URL(fileURLWithPath: "/Users/someone"), extra: [.codex: ["/Users/someone/.codex-work"]]) diff --git a/Tests/AgentWatchGitTests/GitBranchTypesTests.swift b/Tests/AgentWatchGitTests/GitBranchTypesTests.swift index 764dde6..3933309 100644 --- a/Tests/AgentWatchGitTests/GitBranchTypesTests.swift +++ b/Tests/AgentWatchGitTests/GitBranchTypesTests.swift @@ -38,30 +38,14 @@ final class GitBranchTypesTests: XCTestCase { } } - func testTheAppWritesTheTableTheRustSideReads() throws { - let table = GitBranchTypes(types: [ - GitBranchType(name: "Features", patterns: ["feature/*", "fix/*"], level: .click), - GitBranchType(name: "Releases", patterns: ["release/*", "hotfix/*"], level: .name), - GitBranchType(name: "Agent drafts", patterns: ["agent/*", "tmp/*"], level: .none), - GitBranchType(name: "Archive", patterns: ["archive/*"], level: .forbid), - ]) - let url = try scratch().appendingPathComponent("AgentWatch/\(GitBranchTypes.fileName)") - try table.save(to: url) - let written = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? NSDictionary - let expected = try JSONSerialization.jsonObject(with: fixture("branch-types.json")) as? NSDictionary - XCTAssertEqual(written, expected) - XCTAssertEqual(try GitBranchTypes.load(from: url), table) - } - - func testTheFirstMatchingTypeWins() { - let table = GitBranchTypes(types: [ + func testTheFirstMatchingRuleWins() { + var rules = GitProtectionRules() + rules.global[.delete] = [ GitBranchType(name: "Drafts", patterns: ["agent/*"], level: .none), - GitBranchType(name: "Everything", patterns: ["*"], level: .forbid), - GitBranchType(name: "Late", patterns: ["agent/x"], level: .name), - ]) - XCTAssertEqual(table.matching("agent/x")?.name, "Drafts") - XCTAssertEqual(table.matching("feature/y")?.name, "Everything") - XCTAssertNil(GitBranchTypes().matching("feature/y")) + GitBranchType(name: "Locked", patterns: ["*"], level: .forbid), + ] + XCTAssertEqual(rules.level(for: .delete, branch: "agent/x", repository: nil).source, "Drafts") + XCTAssertEqual(rules.level(for: .delete, branch: "feature/y", repository: nil).source, "Locked") } func testLevelsAreOrderedWeakestFirst() { @@ -69,16 +53,12 @@ final class GitBranchTypesTests: XCTestCase { XCTAssertEqual(max(GitCheckLevel.none, .name), .name) } - func testAMissingFileIsAnEmptyTableAndABrokenOneIsAnError() throws { - let folder = try scratch() - let missing = folder.appendingPathComponent(GitBranchTypes.fileName) - XCTAssertEqual(try GitBranchTypes.load(from: missing), GitBranchTypes()) - try Data("{".utf8).write(to: missing) - XCTAssertThrowsError(try GitBranchTypes.load(from: missing)) - try Data(#"{"version":2,"types":[]}"#.utf8).write(to: missing) - XCTAssertThrowsError(try GitBranchTypes.load(from: missing)) { error in - XCTAssertEqual(error as? GitBranchTypes.TableError, .unknownVersion(2)) - } + func testBrokenAndUnknownVersionFilesAreRejected() throws { + let file = try scratch().appendingPathComponent(GitProtectionRules.fileName) + try Data("{".utf8).write(to: file) + XCTAssertThrowsError(try GitProtectionRules.load(from: file)) + try Data(#"{"version":3,"types":[]}"#.utf8).write(to: file) + XCTAssertThrowsError(try GitProtectionRules.load(from: file)) } func testV1RulesCarryOverToBothOperationsAndCanBeEditedIndependently() throws { @@ -116,23 +96,6 @@ final class GitBranchTypesTests: XCTestCase { XCTAssertEqual(written, expected) } - func testThePreviewAppliesTheFloorToTheType() { - let table = GitBranchTypes(types: [ - GitBranchType(name: "Drafts", patterns: ["agent/*", "main"], level: .none), - GitBranchType(name: "Locked", patterns: ["locked/*"], level: .forbid), - ]) - XCTAssertEqual(GitDeletionPreview.builtIn.deletionLevel(in: table, branch: "main").level, .name) - XCTAssertEqual(GitDeletionPreview.projectRule.deletionLevel(in: table, branch: "agent/x").level, .name) - XCTAssertEqual(GitDeletionPreview.includedRule.deletionLevel(in: table, branch: "agent/x").level, .name) - let draft = GitDeletionPreview.dependsOnRemote.deletionLevel(in: table, branch: "agent/x") - XCTAssertEqual(draft.level, .none) - XCTAssertEqual(draft.type, "Drafts") - XCTAssertEqual(GitDeletionPreview.builtIn.deletionLevel(in: table, branch: "locked/x").level, .forbid) - let plain = GitDeletionPreview.dependsOnRemote.deletionLevel(in: table, branch: "feature/x") - XCTAssertEqual(plain.level, .click) - XCTAssertNil(plain.type) - } - func testEditedDefaultsRoundTripAndOnlyChangeTheirOwnOperations() throws { let url = try scratch().appendingPathComponent(GitProtectionRules.fileName) var config = GitProtectionRules() diff --git a/Tests/AgentWatchIngressTests/UnixSocketIngressTests.swift b/Tests/AgentWatchIngressTests/UnixSocketIngressTests.swift index bf460d9..88ac4fc 100644 --- a/Tests/AgentWatchIngressTests/UnixSocketIngressTests.swift +++ b/Tests/AgentWatchIngressTests/UnixSocketIngressTests.swift @@ -646,13 +646,46 @@ final class UnixSocketIngressTests: XCTestCase { XCTAssertEqual(try failure(sending: Data("not json at all\n".utf8), to: socketPath), .messageDecodingFailed) // A peer that connects and says nothing at all before hanging up. XCTAssertEqual(try failure(sending: Data(), to: socketPath), .malformedMessage) - // Bulk with no line ending in it. Measured rather than assumed: what answers is the - // read deadline, not the size cap — a megabyte of nonsense takes longer than 200 ms - // to accumulate, so the reader gives up before the guard on `count` is ever reached. - // The cap is the backstop behind the deadline, not the thing doing the work, and a - // test asserting otherwise would describe a path this listener does not take. + } + + func testRejectsAnOversizeMessageBeforeItsReadDeadline() throws { + let directoryURL = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let socketPath = directoryURL.appendingPathComponent("agent-watch.sock").path let oversize = Data(repeating: 0x41, count: UnixSocketIngress.maximumMessageByteCount + 1) - XCTAssertEqual(try failure(sending: oversize, to: socketPath), .readTimedOut) + XCTAssertEqual(try failure(sending: oversize, to: socketPath, timeout: 5_000), .messageTooLarge) + XCTAssertEqual(try failure(sending: oversize + Data([10]), to: socketPath, timeout: 5_000), .messageTooLarge) + } + + func testRestartWhileAnOldConnectionIsOpenReceivesOnlyTheNewRequest() throws { + let directoryURL = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let socketPath = directoryURL.appendingPathComponent("agent-watch.sock").path + let results = IngressResults() + let received = expectation(description: "the new listener received a message") + let reading = expectation(description: "the old listener began reading") + reading.assertForOverFulfill = false + let ingress = UnixSocketIngress( + socketPath: socketPath, readTimeoutMilliseconds: 5_000, + connectionStarted: { reading.fulfill() } + ) { result in + results.append(result) + received.fulfill() + } + try ingress.start() + defer { ingress.stop() } + let old = try openConnection(to: socketPath) + defer { close(old) } + wait(for: [reading], timeout: 5) + + ingress.stop() + try ingress.start() + _ = shutdown(old, SHUT_WR) + let newRequest = request(named: "SessionStart") + try send(newRequest, to: socketPath) + + wait(for: [received], timeout: 5) + XCTAssertEqual(results.snapshot(), [.success(newRequest)]) } /// The socket path is a name in a folder the app does not own outright. Finding a regular @@ -746,10 +779,12 @@ final class UnixSocketIngressTests: XCTestCase { } /// Sends bytes on a fresh listener and answers with the one failure they produced. - private func failure(sending bytes: Data, to socketPath: String) throws -> UnixSocketIngressError? { + private func failure( + sending bytes: Data, to socketPath: String, timeout: Int32 = 200 + ) throws -> UnixSocketIngressError? { let results = IngressResults() let received = expectation(description: "a refusal") - let ingress = UnixSocketIngress(socketPath: socketPath) { result in + let ingress = UnixSocketIngress(socketPath: socketPath, readTimeoutMilliseconds: timeout) { result in results.append(result) received.fulfill() } @@ -777,7 +812,7 @@ final class UnixSocketIngressTests: XCTestCase { } _ = shutdown(descriptor, SHUT_WR) - wait(for: [received], timeout: 2) + wait(for: [received], timeout: 6) guard case let .failure(error)? = results.snapshot().first else { return nil } diff --git a/Tests/AgentWatchLookupTests/WorktreeCacheCleanupTests.swift b/Tests/AgentWatchLookupTests/WorktreeCacheCleanupTests.swift index 710b9ff..d2fbb1c 100644 --- a/Tests/AgentWatchLookupTests/WorktreeCacheCleanupTests.swift +++ b/Tests/AgentWatchLookupTests/WorktreeCacheCleanupTests.swift @@ -82,6 +82,25 @@ final class WorktreeCacheCleanupTests: XCTestCase { XCTAssertThrowsError(try WorktreeCacheCleanup.verifiedTrashURL(candidate, activeFolders: [])) } + func testReportCanOfferTwoCachesAndRechecksTheSelectedOne() throws { + let fixture = try Fixture(tag: signature) + let second = fixture.tree.appendingPathComponent("build", isDirectory: true) + try FileManager.default.createDirectory(at: second, withIntermediateDirectories: false) + try signature.write(to: second.appendingPathComponent("CACHEDIR.TAG")) + try "target/\nbuild/\n".write( + to: fixture.tree.appendingPathComponent(".gitignore"), atomically: true, encoding: .utf8) + try fixture.git(["add", ".gitignore"]) + try fixture.git(["commit", "-qm", "ignore both caches"]) + + let report = try WorktreeDiskScanner.scan(in: fixture.tree, activeFolders: []) + let candidates = report.worktrees.flatMap(\.folders).compactMap { $0.cleanup?.candidate } + XCTAssertEqual(Set(candidates.map { $0.folder.lastPathComponent }), ["target", "build"]) + + let target = try XCTUnwrap(candidates.first { $0.folder.lastPathComponent == "target" }) + try Data([1]).write(to: fixture.cache.appendingPathComponent("new-build-output")) + XCTAssertThrowsError(try WorktreeCacheCleanup.verifiedTrashURL(target, activeFolders: [])) + } + func testADescriptorClosingDuringTheScanIsScannedAgain() throws { func scan(_ lines: [String]) -> Data { Data((lines.joined(separator: "\n") + "\n").utf8) } let complete = scan(["p7\0", "f3\0tREG\0D0x1000011\0i42\0"]) diff --git a/docs/agent-install.md b/docs/agent-install.md index beb1ea4..1d92f82 100644 --- a/docs/agent-install.md +++ b/docs/agent-install.md @@ -38,7 +38,8 @@ Claude Code загружает любой каталог под `~/.claude/skill Плагинов с работающими хуками у Codex нет (см. [«Отклонено: плагин с хуками у Codex»](#отклонено-плагин-с-хуками-у-codex)), поэтому его хуки сливаются в `~/.codex/hooks.json` рядом с чужими. Повторная установка ничего не добавляет: наши записи сначала снимаются, а потом ставятся — это же делает переустановку после переезда бинарника -перезаписью пути, а не второй записью. +перезаписью пути, а не второй записью. При ошибке чтения или неверной структуре `hooks.json` +страница `Tooling` сообщает о проблеме и сохраняет текущий файл. **Наши записи дописываются в конец списка**, и это не стилистика: доверие у Codex позиционное ([«Доверие к хукам у Codex»](#доверие-к-хукам-у-codex)), поэтому сдвиг чужой записи стоил бы человеку её подтверждения. Свойство закреплено diff --git a/docs/architecture.md b/docs/architecture.md index fc7e431..855ab1e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -95,7 +95,7 @@ Agent Watch — локальное приложение, а не облачны ## Части приложения -Приложение — один Swift Package из нескольких целей (targets) и отдельный плагин JetBrains IDE: +Основное приложение, отправитель и библиотеки собраны одним Swift Package. - `AgentWatchCore` — состояние сессий и правила над ним: события, фазы, порядок строк, что переживает перезапуск. Не импортирует AppKit и не открывает сокетов, поэтому проверяется тестами @@ -113,6 +113,11 @@ Agent Watch — локальное приложение, а не облачны этот хук, как сессия называет себя в своих файлах. Её спрашивают и приложение, и хук; сама она ничего не отправляет. - `AgentWatchGit` запускает запросы Git с ограничением времени и меняет правила репозитория по явному действию человека. Компонент поиска использует только его запросы на чтение. +- `WidgetExtension` — расширение WidgetKit, которое открывает разделы приложения по ссылкам. + Сборщик помещает его внутрь комплекта приложения. +- `native/git-protection/` — исполняемый файл на Rust. Он проверяет команды Git и выполняет + операции, которые человек подтвердил. Его вызывает агент, в том числе при закрытом приложении. +- `native/devtool/` — инструмент разработки на Rust для проверок, сборки и подготовки релизов. - `ide-plugin/` — плагин на Kotlin, который находит вкладку терминала сессии внутри IDE ([ide-plugin.md](ide-plugin.md)). В сборку Swift не входит. @@ -253,7 +258,7 @@ Claude Code и Codex поддерживают lifecycle hooks, получающ Устройство файла настроек — в [settings.md](settings.md#файл-настроек). -Только последний файл содержит что-то о самих сессиях, поэтому его состав назван целиком: +В `sessions-remembered.json` записаны поля истории сессий: хешированная метка сессии, агент, порядковый номер строки, имя сессии, имя проекта, ветка, режим, модель, размер контекста, PID агента и время последнего наблюдения. Рядом с сессиями в том же файле лежит второй список — пары «этот процесс есть эта сессия»: имя процесса (его номер и время запуска) diff --git a/docs/distribution.md b/docs/distribution.md index e2307b1..7db1abf 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -7,8 +7,8 @@ ## Поддерживаемая платформа -Первый релиз предназначен только для Apple Silicon (ARM64), macOS 14 и новее. -Intel и universal-бандл в объём релиза не входят. Сборка релиза выполняется на ARM runner. +Приложение собирается для Apple Silicon (ARM64). Запуск и поведение проверяются на версии +macOS, установленной на машине разработчика. Для сборки релиза используется ARM в CI. В комплекте поставляются обработчик команд Claude и Codex и исполнитель Git на Rust. Порядок подключения при переходе с Mothership описан в [защите Git](git-protection.md). diff --git a/docs/images/clip-fullscreen.avif b/docs/images/clip-fullscreen.avif deleted file mode 100644 index 4e0af84..0000000 Binary files a/docs/images/clip-fullscreen.avif and /dev/null differ diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index c03fae4..103347e 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -5,9 +5,7 @@ как устроено то, что уже сделано, — остальные документы в `docs/`; что и когда сделано — история git. -**Статус исходного плана наблюдения на 10.10.2026:** этап 1 — функциональная alpha и dogfooding; последний релиз — 0.5.0 (2026-11-22), с -changelog и окном обновления, где видно, что изменилось. -**Дата актуализации плана:** 2026-11-23 +Состояние опубликованных версий описывает [CHANGELOG.md](../CHANGELOG.md). ## Управляемая память @@ -89,7 +87,7 @@ Code и Codex-сессий, а затем постепенно получает ## Зафиксированные решения -- Первый релиз — только Apple Silicon (ARM64), macOS 14+. Intel и universal-сборка не планируются. +- Сборка для Apple Silicon (ARM64). Работу приложения проверяем на macOS машины разработчика. - Runtime и единственный источник состояния находятся в `AgentWatch.app`. - Отдельный daemon не создаётся. - Приложение строится AppKit-first и продолжает работать после закрытия окна настроек. @@ -133,7 +131,7 @@ flowchart LR | 1. AppKit MVP | **active dogfooding** | замеры простоя и обратная связь для этапов 4 и 5 | | 1.5. Session host | **сделан, с известными границами** | ничего; границы — в критериях этапа | | 2. Встраивание в агентов | **сделан** | проверка в релизной матрице — [план до 1.0](release-plan.md#4-проверить-релизную-матрицу) | -| 3. Установка и обновление | **частично** | changelog и окно обновления — с 0.4.0, что осталось — [после 0.5.0](release-plan.md#после-050); подпись Developer ID, чистая установка, новый агент после первой настройки — [план до 1.0](release-plan.md#что-осталось-до-10) | +| 3. Установка и обновление | **частично** | подпись Developer ID, чистая установка, новый агент после первой настройки — [план до 1.0](release-plan.md#что-осталось-до-10) | | 4. Hang watchdog | planned | всё | | 5. Full config UI | **частично** | окно настроек есть ([ADR-0016](adr/0016-every-setting-lives-in-one-window.md)); запуск при входе и настройки будущих этапов | | 6. Ollama и LLM | planned, product gate required | всё | @@ -408,36 +406,16 @@ flowchart LR - **Качество.** State machine проверяется табличными unit-тестами, адаптеры — на обезличенных payload fixtures; каждая найденная ошибка перехода получает regression fixture. -## Десктопные клиенты — аудит 2026-10-07 - -Человек перешёл с терминалов на Claude.app и ChatGPT.app. Замеры — -[«Десктопные приложения»](agent-processes.md#десктопные-приложения) и -[«Десктопные клиенты»](session-focus.md#десктопные-клиенты). - -1. **Сделано:** десктопная сессия Claude узнаётся по записи реестра — - [«Claude.app»](agent-processes.md#claudeapp). -2. **Сделано:** клик ведёт к самой сессии ссылкой клиента — - [«Десктопные клиенты»](session-focus.md#десктопные-клиенты). -3. **Сделано:** Codex не теряет начало первого хода — - [«Приём сеансов Codex, и открытый вопрос про `/clear`»](agent-events.md#приём-сеансов-codex-и-открытый-вопрос-про-clear). - Решено человеком 2026-10-08: запуски без окна — своя категория у обоих агентов - ([«Запуски без окна»](agent-processes.md#запуски-без-окна)), по умолчанию скрыта, клик - предлагает её завершить ([ADR-0021](adr/0021-a-headless-run-is-hidden-until-asked-for.md)). - Открыто: как `codex exec` отвечает на `SIGTERM` и `SIGINT` — на этой машине его запрос - отклоняет один из хуков `UserPromptSubmit` (замер: Codex 0.153.4). -4. **Решено человеком 2026-10-07: оставить как есть.** Строка сессии, процесс которой Claude.app - остановил за бездействием, закрывается, хотя сессия видна в приложении и продолжится по первому - сообщению. Сама остановка на этой машине ни разу не наблюдалась. -5. **Сделано:** контекст Claude читается из транскрипта в терминале и настольном приложении ([ADR-0027](adr/0027-claude-context-comes-from-the-transcript.md)). -6. **Сделано:** значок вопроса MCP-сервера, проверен с человеком на настоящей установке - 2026-10-07 — [«Вопрос MCP-сервера: `Elicitation`»](agent-events.md#вопрос-mcp-сервера-elicitation). - Каталог событий Claude закреплён тестом — [«Какие события мы просим»](agent-events.md#какие-события-мы-просим). - Открыто: у `Notification` есть виды `agent_needs_input` и `worker_permission_prompt` (замер: - Claude Code 2.1.293), а когда они приходят, не замерено. Если это ожидание человека, о котором - другие хуки молчат, событие стоит просить. -7. **Сделано:** сессия, открытая в Claude.app без работающего приложения, находится по процессу с - именем и кликом в саму сессию — [«Агент работает, а приложение о нём не - слышало»](session-recovery.md#агент-работает-а-приложение-о-нём-не-слышало). +## Открытые проверки настольных клиентов + +Известное поведение описано в [agent-processes.md](agent-processes.md#десктопные-приложения) +и [session-focus.md](session-focus.md#десктопные-клиенты). + +- Проверить, как `codex exec` отвечает на `SIGTERM` и `SIGINT`. Прежнюю пробу остановил + `UserPromptSubmit` (замер: Codex 0.153.4). +- Измерить, когда Claude посылает `agent_needs_input` и `worker_permission_prompt` в + `Notification` (замер: Claude Code 2.1.293). Добавлять подписку есть смысл, если эти события + сообщают об ожидании, которое пропускают текущие хуки. ## Технический долг @@ -452,19 +430,8 @@ flowchart LR ответили»; - установка хуков и значок. -## Сбои, которые не повторились - -Оба — на одной демо-копии в виртуальной машине, в первую минуту после её запуска, 2026-10-09. -Причина не найдена; что её покажет — в конце каждого пункта. - -- **Клик по строке виджета пропал.** Нажатие и отпускание пришли на строку ждущей сессии, а - вкладка не открылась, и обращения к Ghostty в системном журнале нет (замер: macOS 15.7.7). Не - повторилось ни в 36 кликах по строкам на работающей копии, ни в повторе дубля. Покажет строка в - `event-debug.log` на нажатие и отпускание в строке. -- **Карточка строки при спрятанном виджете.** После выбора сессии в меню над терминалом появилась - карточка строки (`SessionHoverCard`) другой сессии, хотя виджет был спрятан, а показывает её - только `HUDPanelController` (замер: macOS 15.7.7). При повторе дубля не появилась. Покажет строка - в том же журнале на показ и скрытие карточки, с сессией. +Если снова пропадёт клик по строке или появится карточка скрытого виджета, собрать +в `event-debug.log` нажатие и отпускание либо показ и скрытие карточки с меткой сессии. ## Открытые решения diff --git a/docs/measurements.md b/docs/measurements.md index 01621fe..726a1df 100644 --- a/docs/measurements.md +++ b/docs/measurements.md @@ -63,7 +63,7 @@ | Claude Code 2.1.293 | Прогон неинтерактивный (`claude -p`), и там вопрос отменяется сразу, без человека: | [agent-events.md, «Вопрос MCP-сервера: `Elicitation`»](agent-events.md#вопрос-mcp-сервера-elicitation) | | Claude Code 2.1.293 | `claude -p`, запущенный с чистым окружением, записал `sdk-cli` и `kind: "interactive"`, так что `kind` запуск не отличает. | [agent-processes.md, «Запуски без окна»](agent-processes.md#запуски-без-окна) | | Claude Code 2.1.293 | Аргументы спрашиваются первыми, потому что `entrypoint` — это переменная окружения `CLAUDE_CODE_ENTRYPOINT`, а дочерний процесс наследует её от родителя: `claude -p`, запущенный инструментом оболочки сессии Claude.app, записал… | [agent-processes.md, «Запуски без окна»](agent-processes.md#запуски-без-окна) | -| Claude Code 2.1.293 | Открыто: у `Notification` есть виды `agent_needs_input` и `worker_permission_prompt`, а когда они приходят, не замерено. | [implementation-plan.md, «Десктопные клиенты — аудит 2026-10-07»](implementation-plan.md#десктопные-клиенты--аудит-2026-10-07) | +| Claude Code 2.1.293 | - Измерить, когда Claude посылает `agent_needs_input` и `worker_permission_prompt` в `Notification`. | [implementation-plan.md, «Открытые проверки настольных клиентов»](implementation-plan.md#открытые-проверки-настольных-клиентов) | | Claude Code 2.1.293 | Claude Code отвечает на неё обычным выходом: код 143 и `SessionEnd` меньше чем через секунду; на `SIGINT` — то же с кодом 0. | [session-focus.md, «Запуск без окна»](session-focus.md#запуск-без-окна) | | Claude Code 2.1.293 | Claude Code answered it with exit 143 and its `SessionEnd` in under a second, measured on Claude Code 2.1.293; `SIGINT` did the same with exit 0. | `Sources/AgentWatchApp/HeadlessRun.swift` | | Claude Code 2.1.293 | Asked first, of the agent's own process and nothing above it: a run's parent is whatever program started it, and `claude -p` typed by a session's shell tool would otherwise take that session's kind — background under a pty host, desktop… | `Sources/AgentWatchLookup/ClaudeProcessRules.swift` | @@ -288,7 +288,7 @@ | Codex 0.153.4 | в терминале и у `codex exec` — ближайший `codex` над хуком; в ChatGPT.app не приходит | [agent-integration.md, «Чем два агента отличаются»](agent-integration.md#чем-два-агента-отличаются) | | Codex 0.153.4 | **Номер процесса у запуска есть и у Codex.** `codex exec` держит один тред и больше ничего, а его хук — дочерний процесс самого `codex exec` или его оболочки. | [agent-processes.md, «Запуски без окна»](agent-processes.md#запуски-без-окна) | | Codex 0.153.4 | Первая запись транскрипта `codex exec` говорит `source: "exec"` и `originator: "codex_exec"` при `thread_source: "user"` — «Приём сеансов Codex, и открытый вопрос про `/clear`». | [agent-processes.md, «Запуски без окна»](agent-processes.md#запуски-без-окна) | -| Codex 0.153.4 | Открыто: как `codex exec` отвечает на `SIGTERM` и `SIGINT` — на этой машине его запрос отклоняет один из хуков `UserPromptSubmit`. | [implementation-plan.md, «Десктопные клиенты — аудит 2026-10-07»](implementation-plan.md#десктопные-клиенты--аудит-2026-10-07) | +| Codex 0.153.4 | Прежнюю пробу остановил `UserPromptSubmit`. | [implementation-plan.md, «Открытые проверки настольных клиентов»](implementation-plan.md#открытые-проверки-настольных-клиентов) | | Codex 0.153.4 | Что делает `codex exec`, не замерено: на этой машине его запрос отклонил один из хуков `UserPromptSubmit`, и до работы запуск не дошёл. | [session-focus.md, «Запуск без окна»](session-focus.md#запуск-без-окна) | | Codex 0.153.4 | `hooks.json` in whichever folder Codex was started with — measured on Codex 0.153.4 and 0.161.0, a Codex started with `CODEX_HOME` reads this file there and no other. | `Sources/AgentWatchApp/ToolingInstaller.swift` | | Codex 0.153.4 | An agent started that way reads hooks only from its own folder (measured on Codex 0.153.4 and 0.161.0 and on Claude Code 2.1.294) and writes its transcripts there (measured on Codex 0.161.0 and Claude Code 2.1.294), so nothing in the… | `Sources/AgentWatchCore/AgentFolders.swift` | @@ -379,8 +379,6 @@ | 15.7.7 | Копия в папке, куда учётная запись не может писать, сразу после скачивания просит пароль администратора — это окно macOS, не приложения; `Cancel` молча прекращает обновление, копия цела. | [distribution.md, «Обновление»](distribution.md#обновление) | | 15.7.7 | Оборванное или зависшее скачивание оставляет недокачанный кусок `CFNetworkDownload_*.tmp` во временной папке учётной записи: его держит системный загрузчик, а не Sparkle. | [distribution.md, «Обновление»](distribution.md#обновление) | | 15.7.7 | Скачанное самим приложением такой пометки не получает и открывается без вопросов: замерено на настоящем релизе — бандл, загруженный не браузером, запустился без единого диалога, и копия, поставленная Sparkle 2.10.0 в чистой машине,… | [distribution.md, «Обновление»](distribution.md#обновление) | -| 15.7.7 | - **Карточка строки при спрятанном виджете.** После выбора сессии в меню над терминалом появилась карточка строки (`SessionHoverCard`) другой сессии, хотя виджет был спрятан, а показывает её только `HUDPanelController`. | [implementation-plan.md, «Сбои, которые не повторились»](implementation-plan.md#сбои-которые-не-повторились) | -| 15.7.7 | - **Клик по строке виджета пропал.** Нажатие и отпускание пришли на строку ждущей сессии, а вкладка не открылась, и обращения к Ghostty в системном журнале нет. | [implementation-plan.md, «Сбои, которые не повторились»](implementation-plan.md#сбои-которые-не-повторились) | | 15.7.7 | Вместе — потому что окно с вкладками или панелью инструментов на весь экран состоит из двух окон: полоса вкладок Ghostty — окно высотой 72 точки наверху, терминал — другое, от 28 точек вниз. | [menu-bar.md, «Маячок ожидающих чатов»](menu-bar.md#маячок-ожидающих-чатов) | | 15.7.7 | Every pause in a virtual machine lasted at least about 50 ms, whatever was asked: 45 steps of 14 ms took 2.8 s instead of 0.63 (measured on macOS 15.7.7 under Tart 2.40.1). | `.claude/skills/readme-media/scripts/aw-media.swift` | | 15.7.7 | No showMouseClicks: it drew nothing for the takes' posted clicks, measured on macOS 15.7.7 in the virtual machine, and the cut draws a ring of its own (zoom's taps). | `.claude/skills/readme-media/scripts/aw-media.swift` | diff --git a/docs/proposals/project-workspace.md b/docs/proposals/project-workspace.md index 1cefc06..ced328a 100644 --- a/docs/proposals/project-workspace.md +++ b/docs/proposals/project-workspace.md @@ -30,6 +30,11 @@ date: 19.11.2026 ## Правило Git на примере одной ветки +Ниже сохранён первоначальный вариант. В действующей реализации отдельное окно macOS запрашивает +подтверждение, а правила и значения по умолчанию меняются в настройках. Текущий порядок описан +в [git-protection.md](../git-protection.md). Проверки Windows и Связки ключей остаются в +[плане реализации](../implementation-plan.md#вехи-работы-с-проектами). + Предположим, Claude собирается удалить ветку `release` на сервере. Сегодня Mothership уже останавливает такую команду, если она требует подтверждения. Новая польза появляется **до запроса**: можно выбрать проект и увидеть, почему в нём сработает конкретное правило. 1. В разделе проекта «Защита» видно общее правило для Claude и Codex и исключения этого проекта. Например, для удаления обычной ветки достаточно подтверждения. Для ветки `release` дополнительно требуется ввести имя репозитория. diff --git a/docs/release-plan.md b/docs/release-plan.md index f8da199..a85ccbc 100644 --- a/docs/release-plan.md +++ b/docs/release-plan.md @@ -6,58 +6,8 @@ нет: этапы продукта и открытые продуктовые решения — в [плане реализации](implementation-plan.md); как сейчас собирается, подписывается и обновляется релиз — в [distribution.md](distribution.md). -## Что уже есть - -- Детерминированный мониторинг Claude Code и Codex, виджет, меню сессий, настройки оформления, - порядка и сочетания клавиш, сохранение истории, переход к сессии, самообновление. -- Установка и снятие интеграций со страницы Tooling в настройках; сохранение чужих хуков и - статусной команды. -- Новый мастер: выбор агента → подключение → проверка сигнала; доступ с пустого виджета и - `Tooling → Set Up Again…`. Повторение ничего не удаляет. Внешний вид и сессии сохраняются. -- Признаки найденной программы отдельно от состояния подключения. Ошибки записи видны в окне. -- README с настоящими AppKit-изображениями на вымышленных данных и роликами, снятыми в чистой - macOS внутри виртуальной машины. -- Плагин IDE: classic/reworked terminal, ping, тесты, verifier, CI подписи и публикации. -- Стабильные выпуски без пометки pre-release: 0.3.0 (2026-10-08), 0.4.0 (2026-10-10) и 0.5.0 - (2026-11-22), дальше - так же, на 0.x до 1.0. Релиз ведёт скилл `release`: раздел `CHANGELOG.md`, проверки, черновик, - публикация после «да». Обновление — Sparkle с подписью EdDSA и списком изменений - ([ADR-0023](adr/0023-the-update-goes-through-sparkle-signed-with-eddsa.md)). - -Это готовность отдельных частей, а не заявление о проверенной чистой установке всего продукта. - -## Состояние публикации - -Состояние на 2026-11-22. Проверить заново: `gh release list`, `gh secret list`, -`gh run list --workflow publish-plugin.yml`. - -| Факт | Следствие | -|---|---| -| `v0.5.0` опубликован 2026-11-22 как последний, `v0.4.0` — 2026-10-10, `v0.3.0` — 2026-10-08; `v0.1.0` — pre-release от 2026-09-11 | `/releases/latest` и фид отдают 0.5.0. Установленный 0.4.0 обновился до него в чистой машине через Sparkle; копия 0.5.0 под номером 0.4.0 обновилась так до самой себя с настоящего фида | -| У тега `v0.2.0` нет релиза | Версия 0.2.0 не дошла ни до кого; changelog не описывает её отдельно | -| В `v0.1.0` лежит `agent-watch-ide-0.1.3.zip`, в исходниках версия `0.1.4` | Нельзя считать опубликованный плагин проверкой текущего кода | -| Текущий ID — `com.glockbender.agentwatch`; прежние ID менялись | Проверить удаление старого ID перед установкой нового; иначе два обработчика URL | -| `CERTIFICATE_CHAIN`, `PRIVATE_KEY`, `PRIVATE_KEY_PASSWORD` добавлены 2026-09-11 | Наличие секретов подтверждено, пригодность ключа ещё нужно доказать запуском подписи | -| `PUBLISH_TOKEN` отсутствует; запусков `publish-plugin.yml` нет | Автопубликация ещё не доказана; состояние личного кабинета Marketplace не проверено | -| `release.yml` создаёт черновик с ZIP, DMG, их контрольными суммами и `appcast.xml`; Developer ID/notarization в нём не настроены | Нынешний путь установки требует команды в терминале | -| Секрет `SPARKLE_PRIVATE_KEY` заведён 2026-10-10, открытый ключ — в `SUPublicEDKey` | Что они пара, подтвердил релиз 0.4.0: подпись архива в фиде сходится с открытым ключом, и Sparkle в чистой машине её принял | - -Источники состояния: [GitHub Releases](https://github.com/glockbender/agentwatcher/releases), -[workflow плагина](../.github/workflows/publish-plugin.yml), -[workflow приложения](../.github/workflows/release.yml). - -## После 0.5.0 - -0.5.0 вышел 2026-11-22 по скиллу `release`, как и 0.4.0 (2026-10-10): changelog, окно -обновления со списком изменений, Sparkle. Как это устроено — [distribution.md](distribution.md), правила текста — в скилле. -Осталось: - -- [ ] `GUIDE.md` — гид по интерфейсу с роликами рядом с `TROUBLESHOOTING.md`, README ссылается - на него; скилл `readme-media` знает, что ролики стоят не только в README. - -**Открытое решение, с тем, что принято по умолчанию:** галочка Sparkle «скачивать и ставить -обновления самому» выключена (`SUAllowsAutomaticUpdates`): человек видит изменения и сам нажимает -`Install Update`. +История поставок — в [CHANGELOG.md](../CHANGELOG.md). Статус публикации и работоспособность +фида проверяются по [процедуре релиза](distribution.md#проверки-перед-публикацией). ## Что осталось до 1.0 @@ -134,17 +84,19 @@ ### 4. Проверить релизную матрицу -- [ ] Apple Silicon: macOS 14 и актуальная поддерживаемая версия; светлая/тёмная тема, - увеличенный текст/масштаб, небольшой экран, VoiceOver, Reduce Motion; на macOS 14 — что значок - в строке меню находит свои четыре символа SF (замер был на 15.3.1, без них значок остаётся - прежним). +Проверки запуска и интерфейса выполняются на macOS, установленной на машине разработчика. +Версию системы записываем вместе с результатом. + +- [ ] Запустить собранное приложение и проверить регистрацию расширения WidgetKit и переход + по ссылке виджета в окно проектов. +- [ ] Проверить светлую и тёмную темы, увеличенный текст, небольшой экран, VoiceOver и Reduce Motion. - [ ] Клавиатура в вопросе о завершении агента, заданном в меню; разделённые панели Ghostty и - вкладка `claude attach` в правиле трёх условий; стекло на экране macOS 26. + вкладка `claude attach` в правиле трёх условий; материал стекла. - [ ] Сфера и сетка из трёх состояний в настоящей строке меню на тёплых обоях: проба рисует голый градиент, а он хуже настоящей панели. - [ ] Claude и Codex: start, work, approval, choice, plan, subagent, background, limit, complete, закрытие терминала, перезапуск приложения. Версии и наблюдения записать в measurements.md. -- [ ] Hooks: установка, повторная установка, repair, removal; чужие записи и статусная команда сохраняются. +- [ ] Установка, повторная установка, восстановление и снятие хуков сохраняют чужие записи. - [ ] Приложение выключено / socket недоступен: агент продолжает работу, отправитель завершается быстро. - [ ] Обновление из опубликованного релиза в кандидат: настройки, история, разрешения и sender-ссылка остаются рабочими. Отмену и сетевые сбои проверяет прогон в машине перед каждым @@ -153,6 +105,11 @@ ## Что не блокирует 1.0 +- Гид по интерфейсу с роликами рядом с `TROUBLESHOOTING.md`. При его появлении сверка списка + роликов должна учитывать ссылки из обоих документов. +- Автоматическая установка обновлений. Сейчас Sparkle показывает изменения и ждёт, пока + человек нажмёт `Install Update`. + Watchdog зависаний, Ollama/LLM-функции, локальная статистика, Intel/universal. Это следующие продуктовые этапы, а не долг перед 1.0. Автоматически давать доверие хукам за пользователя не требуется: явный шаг и проверяемая доставка достаточны. diff --git a/docs/transcript-reader.md b/docs/transcript-reader.md index 6e43289..1b51a02 100644 --- a/docs/transcript-reader.md +++ b/docs/transcript-reader.md @@ -249,8 +249,10 @@ Codex (55 из 56 shell, 26 из 26 tool) (замер: Codex, версия не десять секунд до утра ради строки, которую человек уже может убрать сам; у работающей сессии такой границы нет, потому что её тишина и есть то, что ищется. Интервал задаётся настройкой `Read transcripts` на странице `General` окна настроек (по умолчанию 5 с) и там же выключается; при выключении снимаются и все сообщённые -читателем признаки сбоя, потому что предупреждение от остановленного читателя — утверждение -ни о чём. +читателем признаки сбоя. Приложение отменяет запланированные чтения и отбрасывает результаты +уже начатых. Если убрать профиль на странице `Tooling`, приложение перестаёт использовать +найденные пути из этого профиля. Чтение первых записей и заголовка отправителем хуков описано +выше, в разделе [«Что сессия рассказывает о себе»](#что-сессия-рассказывает-о-себе). Кнопка `×` появляется по собственному одноразовому таймеру виджета на границе получаса; события других сессий для этого не нужны. Новое свидетельство жизни переносит срок, скрытие diff --git a/native/devtool/src/documents.rs b/native/devtool/src/documents.rs index c43f07e..7457866 100644 --- a/native/devtool/src/documents.rs +++ b/native/devtool/src/documents.rs @@ -45,15 +45,15 @@ fn numbered_anchor(seen: &mut BTreeMap, title: &str) -> String { anchor } -fn tracked_files() -> Result { +fn source_files() -> Result { let mut git = Command::new("git"); + git.args(["ls-files", "-z", "--cached"]); if let Some(index) = std::env::var_os("AGENT_WATCH_VERIFY_INDEX") { git.env("GIT_INDEX_FILE", index); + } else { + git.args(["--others", "--exclude-standard"]); } - let list = git - .args(["ls-files", "-z"]) - .output() - .map_err(|e| e.to_string())?; + let list = git.output().map_err(|e| e.to_string())?; if !list.status.success() { return Err(String::from_utf8_lossy(&list.stderr).into_owned()); } @@ -96,13 +96,15 @@ fn finish(errors: Vec) -> Result<(), String> { pub fn run(command: &str, args: &[String]) -> Result<(), String> { match (command, args) { ("check-docs", []) => { - let files = tracked_files()?; - finish( - checks::CHECKS - .iter() - .flat_map(|check| check(&files)) - .collect(), - ) + let files = source_files()?; + let mut problems: Vec<_> = checks::CHECKS + .iter() + .flat_map(|check| check(&files)) + .collect(); + if let Err(problem) = crate::media::check_readme_assets(Path::new(".")) { + problems.push(problem); + } + finish(problems) } ("check-troubleshooting", []) => { let read = |p| fs::read_to_string(p).map_err(|e| format!("{p}: {e}")); @@ -114,7 +116,7 @@ pub fn run(command: &str, args: &[String]) -> Result<(), String> { ) } ("measurements", args) if args.is_empty() || args == ["--check"] => { - let (rows, mut errors) = measurements::collect(&tracked_files()?); + let (rows, mut errors) = measurements::collect(&source_files()?); let text = measurements::render(rows); if args.is_empty() { fs::write(measurements::OUTPUT, text).map_err(|e| e.to_string())?; diff --git a/native/devtool/src/media/cut.rs b/native/devtool/src/media/cut.rs index 4a8dd04..f1622cd 100644 --- a/native/devtool/src/media/cut.rs +++ b/native/devtool/src/media/cut.rs @@ -250,7 +250,27 @@ fn files(dir: &Path, prefix: &str, suffix: &str) -> Result> { Ok(out) } -fn check_published(root: &Path, listed: &BTreeSet<&str>) -> Result { +fn parse_manifest(text: &str) -> Result<(Vec>, BTreeSet<&str>)> { + let mut clips = Vec::new(); + let mut names = BTreeSet::new(); + for line in text.lines() { + if let Some(clip) = Clip::parse(line)? { + if !names.insert(clip.name) { + return Err("Duplicate clip names in clips.txt".into()); + } + clips.push(clip); + } + } + Ok((clips, names)) +} + +pub(crate) fn check_readme_assets(root: &Path) -> Result { + let manifest = read(&root.join(".claude/skills/readme-media/scripts/clips.txt"))?; + let (_, listed) = parse_manifest(&manifest)?; + check_manifest(root, &listed) +} + +fn check_manifest(root: &Path, listed: &BTreeSet<&str>) -> Result { let images = root.join("docs/images"); let doc = read(&root.join("README.md"))?; let links = Regex::new(r"docs/images/(clip-[\w-]+)\.avif").unwrap(); @@ -263,10 +283,15 @@ fn check_published(root: &Path, listed: &BTreeSet<&str>) -> Result { .iter() .filter_map(|p| p.file_stem()?.to_str()) .collect::>(); + let mut problems = Vec::new(); for (clips, message) in [ ( present.difference(listed), - "in docs/images but not in clips.txt: git rm it", + "in docs/images but missing from clips.txt", + ), + ( + listed.difference(&present), + "in clips.txt but missing from docs/images", ), ( listed.difference(&readme), @@ -278,18 +303,28 @@ fn check_published(root: &Path, listed: &BTreeSet<&str>) -> Result { ), ] { for clip in clips { - println!("{clip}: {message}"); + problems.push(format!("{clip}: {message}")); } } + if problems.is_empty() { + Ok(()) + } else { + Err(problems.join("\n")) + } +} + +fn check_published(root: &Path, listed: &BTreeSet<&str>) -> Result { + check_manifest(root, listed)?; + let images = root.join("docs/images"); let mut total = 0; - for clip in listed.intersection(&present) { + for clip in listed { total += fs::metadata(images.join(format!("{clip}.avif"))) .map_err(|e| e.to_string())? .len(); } println!( "all {} clips in docs/images: {} KB", - listed.intersection(&present).count(), + listed.len(), total / 1024 ); Ok(()) @@ -309,17 +344,7 @@ pub(super) fn run(root: &Path, work: &Path, args: &[String]) -> Result { } let scripts = root.join(".claude/skills/readme-media/scripts"); let spec = read(&scripts.join("clips.txt"))?; - let all = spec - .lines() - .map(Clip::parse) - .collect::>>()? - .into_iter() - .flatten() - .collect::>(); - let listed = all.iter().map(|clip| clip.name).collect::>(); - if listed.len() != all.len() { - return Err("Duplicate clip names in clips.txt".into()); - } + let (all, listed) = parse_manifest(&spec)?; if let Some(missing) = wanted.difference(&listed).next() { return Err(format!("Unknown clip: {missing}")); } @@ -368,6 +393,13 @@ pub(super) fn run(root: &Path, work: &Path, args: &[String]) -> Result { mod tests { use super::*; + #[test] + fn a_duplicate_name_cannot_be_checked_or_rendered() { + let clip = "clip-test take @a @b 32 32 clips/test.keys"; + assert!(parse_manifest(clip).is_ok()); + assert!(parse_manifest(&format!("{clip}\n{clip}")).is_err()); + } + #[test] fn reads_the_recording_manifest_and_camera_files() { let scripts = diff --git a/native/devtool/src/media/mod.rs b/native/devtool/src/media/mod.rs index 997efb0..9db976d 100644 --- a/native/devtool/src/media/mod.rs +++ b/native/devtool/src/media/mod.rs @@ -1,5 +1,6 @@ //! README recordings share a Swift screen driver and a disposable demo stage. mod cut; +pub(crate) use cut::check_readme_assets; mod first_start; mod frames; mod recording; diff --git a/native/devtool/src/media/vm.rs b/native/devtool/src/media/vm.rs index e84eb88..0c38239 100644 --- a/native/devtool/src/media/vm.rs +++ b/native/devtool/src/media/vm.rs @@ -17,17 +17,7 @@ const SHARE: &str = "/Volumes/My Shared Files/aw"; const TOOL: &str = "/Users/admin/.local/bin/agent-watch-devtool"; const USAGE: &str = "media vm stand | grant | up [bare] | sync | shoot [step] | run | fetch [take ...] | down | sh "; const STEPS: &[&str] = &[ - "setup", - "stage", - "start", - "menu", - "order", - "rows", - "look", - "folders", - "fullscreen", - "icon", - "counts", + "setup", "stage", "start", "menu", "order", "rows", "look", "folders", "icon", "counts", ]; fn io(r: std::io::Result) -> R { @@ -393,7 +383,7 @@ fn take_args<'a>(name: &'a str, extra: &'a [&'a str]) -> R> { } let name = name.strip_prefix("takes/").unwrap_or(name); let name = name.strip_suffix(".sh").unwrap_or(name); - if !STEPS.contains(&name) || name == "stage" || name == "counts" { + if !super::takes::NAMES.contains(&name) { return Err(format!("Unknown take: {name}")); } let mut args = vec!["take", name]; @@ -436,7 +426,7 @@ pub(super) fn run(args: &[String]) -> R { check(&mut media(&m.vm, &["stage", "up"]))?; continue; } - if ["order", "rows", "look", "folders", "fullscreen"].contains(&step) { + if ["order", "rows", "look", "folders"].contains(&step) { check(&mut media(&m.vm, &["stage", "reset-settings"]))? } let args = if step == "counts" { @@ -466,6 +456,10 @@ mod tests { take_args("./takes/icon.sh", &["counts"]).unwrap(), ["take", "icon", "counts"] ); + assert_eq!( + take_args("takes/fullscreen.sh", &[]).unwrap(), + ["take", "fullscreen"] + ); assert_eq!( take_args("aw-media", &["screen"]).unwrap(), ["aw", "screen"] diff --git a/native/git-protection/tests/git_guard.rs b/native/git-protection/tests/git_guard.rs index 04ba8c7..939dd4a 100644 --- a/native/git-protection/tests/git_guard.rs +++ b/native/git-protection/tests/git_guard.rs @@ -327,7 +327,9 @@ fn cancelling_the_hook_reaps_its_git_query() { .unwrap() .write_all(br#"{"tool_input":{"command":"git push"}}"#) .unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); + // Starting an ad-hoc-signed fixture can wait behind other tests. The hook's own + // deadline starts inside that process and still bounds the query. + let deadline = Instant::now() + Duration::from_secs(20); let query = loop { if let Some(pid) = std::fs::read_to_string(&marker) .ok() @@ -335,7 +337,22 @@ fn cancelling_the_hook_reaps_its_git_query() { { break Pid::from_raw(pid); } - assert!(Instant::now() < deadline, "Git inspection did not start"); + if child.try_wait().unwrap().is_some() { + let output = child.wait_with_output().unwrap(); + panic!( + "Git inspection did not start: {} ({})", + String::from_utf8_lossy(&output.stdout), + output.status + ); + } + if Instant::now() >= deadline { + let _ = kill( + Pid::from_raw(i32::try_from(child.id()).unwrap()), + Signal::SIGTERM, + ); + let _ = finish(child); + panic!("Git inspection did not start within 20 seconds"); + } std::thread::sleep(Duration::from_millis(10)); }; kill( diff --git a/scripts/build_native_git.py b/scripts/build_native_git.py deleted file mode 100644 index ecd9d03..0000000 --- a/scripts/build_native_git.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Build the Agent Watch executable from this checkout and its locked dependencies.""" - -import os -from pathlib import Path -import subprocess - - -def build_binary(): - root = Path(__file__).resolve().parents[1] - default_target = os.environ.get("CARGO_TARGET_DIR") or root / ".build" / "git-protection" - target = Path(default_target).resolve() - subprocess.run(["rustup", "run", "1.98.1", "cargo", "build", "--release", "--no-default-features", - "--locked", "--manifest-path", root / "native/git-protection/Cargo.toml", - "--target-dir", target], check=True, timeout=600) - return target / "release" / "agent-watch-git" - - -if __name__ == "__main__": - print(build_binary()) diff --git a/scripts/dev.sh b/scripts/dev.sh deleted file mode 100755 index dcdbf02..0000000 --- a/scripts/dev.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec "$(dirname "$0")/devtool" dev "$@" diff --git a/scripts/release-notes.sh b/scripts/release-notes.sh deleted file mode 100755 index 497b731..0000000 --- a/scripts/release-notes.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec "$(dirname "$0")/devtool" release-notes "$@" diff --git a/scripts/test-git-guard.py b/scripts/test-git-guard.py deleted file mode 100644 index 709eb94..0000000 --- a/scripts/test-git-guard.py +++ /dev/null @@ -1,305 +0,0 @@ -"""Check the installed hook's decisions against local synthetic Git repositories.""" - -import json -import importlib.util -import os -from pathlib import Path -import shlex -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -HOOKS = Path(__file__).resolve().parents[1] / "Resources/GitProtection/hooks" - - -COMMIT_FORM = ( - "git commit -m \"$(cat <<'EOF'\nDon't break the build\n\nCo-Authored-By: someone\nEOF\n)\"" -) - -GIT_CASES = [ - # false positives seen in transcripts -> allow - ("allow", "git push origin feature-x 2>&1 | tail -3", "feat"), - ("allow", "rm -f /tmp/s.log; git push 2>&1 | tail -3", "feat"), - ("allow", "docker rm -f pg; git push origin feature-x", "feat"), - ( - "allow", - "git commit -q -F - <<'MSG'\nmain carried both; see --force\nMSG\ngit push origin feature-x", - "feat", - ), - ( - "allow", - "git push -u origin feature-x && glab mr create --source-branch feature-x --target-branch main", - "feat", - ), - ("allow", 'git push 2>&1 | tail -2 && glab api -X POST notes -f "body=$(cat r.md)"', "feat"), - ("allow", "git push 2>&1 | tail -2; pkill -f sandbox", "feat"), - ("allow", "# To push without it: SKIP_E2E=1 git push --force\necho hi", "feat"), - ("allow", "git push --dry-run origin main 2>&1 | tail -18", "feat"), - ( - "allow", - "git push origin feature-x:feature-x 2>&1 | tail -1; git diff --shortstat origin/main...HEAD", - "feat", - ), - ("allow", "git checkout -b feature-y main && git push -u origin feature-y", "feat"), - ("allow", "cd {feat} && git push 2>&1 | tail -3", "main"), - ("allow", "git log --oneline -1 && git push origin feature-x", "feat"), - # mentions of a push, not pushes (first full review) - ("allow", 'grep -rn "git push --force" .', "feat"), - ("allow", 'echo "never run git push -f here"', "feat"), - ("allow", 'gh pr create --body "run git push -f later"', "feat"), - ("allow", 'git commit -m "first line\nsecond line: git push --force is not used"', "feat"), - ("allow", "pushd {feat} && git push", "main"), - ("allow", "git push origin --tags", "main"), - ("allow", "git push origin feature-x && git push origin --tags", "main"), - ("allow", "git push --no-prune origin", "feat"), - ("allow", "git push --prune --no-prune origin", "feat"), - ("allow", "git push --pru --no-pru origin", "feat"), - ("allow", "git push --prune --dry-run origin", "feat"), - ("allow", "git push -nf --prune origin", "feat"), - ("allow", "git push --no-dry-run -n --prune origin", "feat"), - ("allow", "git push --no-tags --ta origin", "main"), - # real risky pushes -> ask - ("deny", "git push --rep origin origin feature-x:main", "feat"), - ("deny", "git push --repo=origin origin feature-x:main", "feat"), - ("deny", "git push --rep=origin origin feature-x:main", "feat"), - ("deny", "git push --repo origin origin feature-x:main", "feat"), - ("deny", "git push --tags --no-tags origin", "main"), - ("deny", "git push --tags --no-ta origin", "main"), - ("deny", "git push --push-o --tags origin", "main"), - ("deny", "git push --m origin", "feat"), - ("deny", "git push --force-with-l=feature-x origin feature-x", "feat"), - ("deny", "git push --push-o --dry-run --prune origin", "feat"), - ("deny", "git push --push-o=--dry-run --prune origin", "feat"), - ("deny", "git push -o-n --prune origin", "feat"), - ("deny", "git push --force -- origin --dry-run", "feat"), - ("deny", "git push --prune origin", "feat"), - ("deny", "git push --no-prune --prune origin", "feat"), - ("deny", "git push --pru origin", "feat"), - ("deny", "git push --force origin feature-x", "feat"), - ("deny", "git push -f origin feature-x", "feat"), - ("deny", "git push --force-with-lease origin feature-x", "feat"), - ("deny", "git push -uf origin feature-x", "feat"), - ("deny", "git push origin +feature-x", "feat"), - ("deny", "git push origin main", "feat"), - ("deny", "SKIP_E2E=1 git push origin main 2>&1 | tail -25", "feat"), - ("deny", "git push -u origin main 2>&1 | tail -8", "feat"), - ("deny", "git push origin main > /tmp/push.log 2>&1", "feat"), - ("deny", "git push origin HEAD:main", "feat"), - ("deny", "git push origin feature-x:master", "feat"), - ("deny", "git push origin HEAD:refs/heads/main", "feat"), - ("deny", "git push origin --delete main", "feat"), - ("deny", "git push --all origin", "feat"), - ("deny", "git -C {feat} push --force", "feat"), - ("deny", "git push", "main"), - ("deny", "git push origin 2>&1 | tail -3", "main"), - ( - "deny", - "git checkout main 2>&1 | tail -2 && git merge --ff-only x && git push 2>&1 | tail -3", - "feat", - ), - ("deny", "git switch main && git merge --ff-only ci-green && git push origin", "feat"), - ("deny", "cd {main} && git push 2>&1 | tail -3", "feat"), - ("deny", "git -C {main} push", "feat"), - ("deny", "git push --force -u origin main; git push --force -u origin other", "feat"), - ("deny", "bash -c 'git push -f'", "feat"), - # the current branch written as HEAD, @ or a substitution (first full review) - ("deny", "git push -u origin HEAD", "main"), - ("deny", "git push origin HEAD", "main"), - ("deny", "git push origin @", "main"), - ("deny", "git push origin $(git branch --show-current)", "main"), - ("deny", "git push -o merge_request.create -u origin HEAD", "main"), - ("allow", "git push -u origin HEAD", "feat"), - # deleting on the remote: asked for main/master and for what may be a tag - ("deny", "git push origin --delete widget-row-redesign 2>&1 | tail -3", "feat"), - ("deny", "git push -d origin feature-x", "feat"), - ("deny", "git push origin :old-feature", "feat"), - ("allow", "git push origin v0.1.0 2>&1 | tail -3", "feat"), - ("deny", "git branch -d gone-branch && git push origin --delete gone-branch", "feat"), - ("deny", "git push origin :master", "feat"), - ("deny", "git push origin --delete v1.2.0", "feat"), - ("deny", "git push origin :refs/tags/nightly", "feat"), - ("deny", "git push --delete origin tag nightly", "feat"), - ("deny", "git tag -d nightly && git push origin :nightly", "feat"), - ("deny", "git push origin -d local-tag", "feat"), - ("deny", "git push origin --delete nightly", "feat"), - ("deny", "git push --delete origin latest", "feat"), - ("deny", "git push origin --delete v2", "feat"), - # a heredoc inside $(…), a reserved word or a group before the push (full review) - ("deny", COMMIT_FORM + " && git push origin main", "feat"), - ("deny", COMMIT_FORM + " && git push --force origin feature-x", "feat"), - ("deny", "if true; then git push --force origin x; fi", "feat"), - ("deny", "if git diff --quiet; then git push origin main; fi", "feat"), - ("deny", "{ git push -f origin x; }", "feat"), - ("deny", "! git push -f origin x", "feat"), - ("deny", "for r in a b; do git push origin main; done", "feat"), - ("deny", "if true; then git push; fi", "main"), - # a cd ends with its subshell; --git-dir and GIT_DIR name the repository (verification) - ("allow", "(cd {main} && git fetch); git push", "feat"), - ("deny", "sh -c 'cd {main} && git push'", "feat"), - ("deny", "(cd {main} && git push)", "feat"), - ("deny", "git --git-dir={main}/.git push", "feat"), - ("deny", "git --git-dir {main}/.git push", "feat"), - ("deny", "GIT_DIR={main}/.git git push", "feat"), - ("deny", "env GIT_DIR={main}/.git git push", "feat"), - ("deny", "git -C {main} --git-dir=.git push", "feat"), - ("allow", "git --git-dir={feat}/.git push", "main"), - # launchers, git's own options, matching refspecs, --track (full review) - ("deny", "docker run img sh -c 'git push -f'", "feat"), - ("deny", "env -S 'git push --force origin x'", "feat"), - ("deny", "fish -c 'git push -f'", "feat"), - ("deny", "ssh host bash -s <<'EOF'\ngit push --force origin x\nEOF", "feat"), - ("deny", "git submodule foreach git push origin main", "feat"), - ("deny", "git --git-dir {feat}/.git push origin main", "feat"), - ("deny", "git --work-tree /tmp push origin main", "feat"), - ("deny", "git push origin 'refs/heads/*:refs/heads/*'", "feat"), - ("deny", "git push origin :", "feat"), - ("deny", "git push origin HEAD:heads/main", "feat"), - ("deny", "git checkout --track origin/main && git push", "feat"), - ("deny", "git push origin --delete refs/heads/feature-y", "feat"), - # a tag deleted locally, then on the remote, under a name that is also a branch - ("deny", "git tag -d widget-row-redesign && git push origin :widget-row-redesign", "feat"), - # CRLF line ends: a carriage return must not hide the branch - ("deny", "git push origin main\r\necho done", "feat"), -] - -class GitGuardTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - root = Path(tempfile.mkdtemp(prefix="agent-watch-hook-")).resolve() - cls.addClassCleanup(subprocess.run, ["/usr/bin/trash", str(root)], check=True) - cls.env = {"HOME": str(root), "PATH": os.defpath, "GIT_CONFIG_NOSYSTEM": "1", - "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ALLOW_PROTOCOL": "file"} - contents = root / "Example Application.app/Contents" - hooks = contents / "Resources/GitProtection/hooks" - shutil.copytree(HOOKS, hooks, ignore=shutil.ignore_patterns("__pycache__")) - cls.hook = hooks / "git_guard.py" - spec = importlib.util.spec_from_file_location("git_guard", hooks / "git_guard.py") - cls.guard = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = cls.guard - cls.addClassCleanup(sys.modules.pop, spec.name) - spec.loader.exec_module(cls.guard) - cls.cli = contents / "MacOS/AgentWatchGit" - cls.folders = {"feat": root / "feat", "main": root / "main"} - def git(repo, *arguments): - subprocess.run(["git", "-C", str(repo), "-c", "user.name=Test", - "-c", "user.email=fixture@example.invalid", *arguments], - env=cls.env, capture_output=True, check=True, timeout=10) - for repo in cls.folders.values(): - repo.mkdir() - git(repo, "init", "--template=", "-b", "main") - git(repo, "commit", "--allow-empty", "-m", "Fixture") - feature = cls.folders["feat"] - git(feature, "switch", "-c", "feature-x") - git(feature, "tag", "local-tag") - for branch in ("widget-row-redesign", "old-feature", "feature-x"): - git(feature, "update-ref", "refs/remotes/origin/" + branch, "HEAD") - - def invoke(self, host, payload): - argv = [sys.executable, "-I", "-B", "-S", str(self.hook)] - if host == "codex": - argv += ["--host", "codex"] - return subprocess.run(argv, env=self.env, cwd=self.folders["feat"], input=payload, - text=True, capture_output=True, check=True, timeout=10).stdout - - def test_shell_decisions(self): - with patch.dict(os.environ, self.env, clear=True): - for want, command, folder in GIT_CASES: - for key, path in self.folders.items(): - command = command.replace("{" + key + "}", str(path)) - with self.subTest(command=command): - answer = self.guard.inspect({"cwd": str(self.folders[folder]), - "tool_input": {"command": command}}) - if want == "allow": - self.assertEqual(answer, "") - else: - verdict = json.loads(answer)["hookSpecificOutput"] - self.assertEqual(verdict["hookEventName"], "PreToolUse") - self.assertEqual(verdict["permissionDecision"], "deny") - - def test_both_hook_invocations_direct_deletion_to_the_bundled_cli(self): - for host in ("claude", "codex"): - with self.subTest(host=host): - answer = self.invoke(host, json.dumps({"tool_input": {"command": "git push origin --delete topic"}})) - verdict = json.loads(answer)["hookSpecificOutput"] - self.assertEqual(verdict["permissionDecision"], "deny") - self.assertIn(shlex.quote(str(self.cli)) + " push", verdict["permissionDecisionReason"]) - self.assertIn("delete to true", verdict["permissionDecisionReason"]) - self.assertEqual(self.invoke(host, json.dumps({"tool_input": {"command": "git branch topic"}})), "") - - def test_uses_shell_tool_working_folder(self): - payload = json.dumps({"cwd": str(self.folders["feat"]), "tool_input": { - "cmd": "git push", "workdir": str(self.folders["main"])}}) - self.assertEqual(json.loads(self.invoke("codex", payload))["hookSpecificOutput"]["permissionDecision"], "deny") - - def test_install_preflight_finishes_without_reading_stdin(self): - proc = subprocess.Popen([sys.executable, self.hook, "--check"], stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.env) - try: - self.assertEqual(proc.wait(timeout=3), 0) - self.assertEqual(proc.stdout.read(), b"agent-watch-git-hook-ok\n") - self.assertEqual(proc.stderr.read(), b"") - finally: - if proc.poll() is None: - proc.kill() - proc.communicate() - - def test_unreadable_input_fails_closed(self): - self.assertEqual(json.loads(self.invoke("claude", "invalid"))["hookSpecificOutput"]["permissionDecision"], "deny") - - def test_unknown_current_branch_blocks_implicit_push(self): - payload = json.dumps({"cwd": str(self.folders["feat"].parent), "tool_input": {"command": "git push"}}) - for host in ("claude", "codex"): - with self.subTest(host=host): - decision = json.loads(self.invoke(host, payload))["hookSpecificOutput"] - self.assertEqual(decision["permissionDecision"], "deny") - self.assertIn("current branch could not be determined", decision["permissionDecisionReason"]) - - def test_implicit_push_with_configured_destination_requires_confirmation(self): - folder = self.folders["feat"] - config = ["git", "-C", str(folder), "config"] - subprocess.run(config + ["--local", "remote.example.push", "HEAD:refs/heads/main"], - env=self.env, check=True, timeout=10) - try: - for command in ("git push", "git push example", "git push --repo=example", - "git push example feature-x", "git push --repo=origin example"): - with self.subTest(command=command): - payload = json.dumps({"cwd": str(folder), "tool_input": {"command": command}}) - decision = json.loads(self.invoke("codex", payload))["hookSpecificOutput"] - self.assertEqual(decision["permissionDecision"], "deny") - self.assertIn("depends on Git configuration", decision["permissionDecisionReason"]) - finally: - subprocess.run(config + ["--local", "--unset", "remote.example.push"], - env=self.env, check=True, timeout=10) - - def test_remote_mirror_setting_requires_confirmation(self): - folder = self.folders["feat"] - config = ["git", "-C", str(folder), "config"] - subprocess.run(config + ["--local", "remote.example.mirror", "true"], - env=self.env, check=True, timeout=10) - try: - payload = json.dumps({"cwd": str(folder), "tool_input": {"command": "git push example"}}) - decision = json.loads(self.invoke("claude", payload))["hookSpecificOutput"] - self.assertEqual(decision["permissionDecision"], "deny") - self.assertIn("mirror push", decision["permissionDecisionReason"]) - finally: - subprocess.run(config + ["--local", "--unset", "remote.example.mirror"], - env=self.env, check=True, timeout=10) - - def test_source_only_push_with_upstream_default_requires_confirmation(self): - folder = self.folders["feat"] - config = ["git", "-C", str(folder), "config", "--local"] - subprocess.run(config + ["push.default", "upstream"], env=self.env, check=True, timeout=10) - try: - payload = json.dumps({"cwd": str(folder), "tool_input": {"command": "git push origin feature-x"}}) - decision = json.loads(self.invoke("codex", payload))["hookSpecificOutput"] - self.assertEqual(decision["permissionDecision"], "deny") - self.assertIn("depends on Git configuration", decision["permissionDecisionReason"]) - finally: - subprocess.run(config + ["--unset", "push.default"], env=self.env, check=True, timeout=10) - - -if __name__ == "__main__": - unittest.main()