From 4d39996910f573c8e9faa9a79ceb62846aea1df1 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 06:49:55 +1000 Subject: [PATCH 01/10] feat: add scoped agent commit attribution --- bin/fm-git-attribution.py | 125 ++++++++++++++++++++++++ bin/fm-git-strip-ai-trailers.sh | 23 ++++- bin/fm-spawn.sh | 18 +++- docs/configuration.md | 33 +++++-- tests/fm-git-strip-ai-trailers.test.sh | 77 +++++++++++++++ tests/fm-spawn-dispatch-profile.test.sh | 34 +++++++ 6 files changed, 299 insertions(+), 11 deletions(-) create mode 100755 bin/fm-git-attribution.py diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py new file mode 100755 index 00000000000..88a8dea968d --- /dev/null +++ b/bin/fm-git-attribution.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Scoped commit attribution. + +Usage: fm-git-attribution.py mode + fm-git-attribution.py stamp + +An empty legacy config means keep; nonempty configs list host/owner[/repo] +(one per line, # comments). Invalid entries refuse the launch/commit. +Stamp runs in Git's hook cwd and rechecks origin, so another repository cannot +inherit an attribution opt-in. Only UUID session IDs and Claude's public session +URL shape are publishable; arbitrary environment values are never copied. +""" +import os +import re +import subprocess +import sys +from pathlib import Path +from urllib.parse import urlsplit + +SCOPE = re.compile(r"[a-z0-9.-]+/[a-z0-9_.-]+(?:/[a-z0-9_.-]+)?", re.I) +UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", re.I) + + +def remote(project): + result = subprocess.run(["git", "-C", project, "config", "--get", "remote.origin.url"], + capture_output=True, text=True, check=False) + url = result.stdout.strip() + if "://" in url: + parsed = urlsplit(url) + if parsed.scheme not in ("ssh", "https", "http", "git"): + return "" + host, path = parsed.hostname or "", parsed.path.lstrip("/") + else: + match = re.fullmatch(r"(?:[^/@:]+@)?([^/:]+):([^\s]+)", url) + if not match: + return "" + host, path = match.groups() + value = f"{host}/{path.removesuffix('.git')}".lower() + return value if SCOPE.fullmatch(value) and value.count("/") == 2 else "" + + +def mode(config, project): + path = Path(config) + if not path.exists(): + return "strip" + content = path.read_text() + if not content.strip(): + return "keep" + scopes = [] + for line in content.splitlines(): + line = line.split("#", 1)[0].strip().lower().removesuffix("/") + if not line: + continue + if not SCOPE.fullmatch(line) or any(p in (".", "..") for p in line.split("/")): + raise ValueError("invalid keep-ai-trailers scope (expected host/owner[/repo])") + scopes.append(line.removesuffix(".git")) + target = remote(project) + return "add" if any(target == s or target.startswith(s + "/") for s in scopes) else "strip" + + +def session(runtime, lines): + # This variable is supplied to shell tools by Codex, not a parent endpoint ID. + if runtime == "codex": + value = os.environ.get("CODEX_THREAD_ID", "") + return value if UUID.fullmatch(value) else "" + if runtime.startswith("claude"): + for line in lines: + if line.lower().startswith("claude-session:"): + value = line.split(":", 1)[1].strip() + if UUID.fullmatch(value) or re.fullmatch( + r"https://claude\.ai/code/session_[a-zA-Z0-9]+", value): + return value + return "" + + +def stamp(config, runtime, model, message): + current = mode(config, ".") + if current != "add": + if current == "strip": + subprocess.run([str(Path(__file__).with_name("fm-git-strip-ai-trailers.sh")), message], check=True) + return + # Runtime/model are launch metadata, never free-form trailer contents. + if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", runtime) or not re.fullmatch( + r"[a-zA-Z0-9][a-zA-Z0-9_.:/+-]*", model) or "://" in model: + raise ValueError("unsafe runtime/model for Agent-Platform") + path = Path(message) + lines = path.read_text().splitlines() + sid = session(runtime, lines) + # Replace our fields on amend/retry; retain existing co-authors. + lines = [line for line in lines if not re.match( + r"(?i)^(agent-system|agent-platform|agent-session):", line)] + coauthors = [line for line in lines if re.match( + rf"(?i)^co-authored-by:\s*{re.escape(runtime)}(?:\s|<|$)", line)] + if not coauthors: + # A stable system identity covers runtimes that emit no co-author. + lines += ["", f"Co-authored-by: {runtime} "] + # Claude Code omits model IDs from commit attribution. A default model is + # unresolved launch metadata, so it must not be presented as a model ID. + platform = runtime + if not runtime.startswith("claude") and model not in ("default", "auto"): + platform += f"/{model}" + args = ["git", "interpret-trailers", "--in-place", "--if-exists", "replace", + "--trailer", "Agent-System: fac:firstmate", + "--trailer", f"Agent-Platform: {platform}"] + native_session = any( + re.fullmatch(r"[a-z0-9-]+-session", line.split(":", 1)[0], re.I) + and line.split(":", 1)[1].strip() == sid + for line in lines if ":" in line + ) + if sid and not native_session: + args += ["--trailer", f"Agent-Session: {sid}"] + path.write_text("\n".join(lines).rstrip() + "\n") + subprocess.run(args + [message], check=True) + + +if __name__ == "__main__": + try: + if len(sys.argv) == 4 and sys.argv[1] == "mode": + print(mode(*sys.argv[2:])) + elif len(sys.argv) == 6 and sys.argv[1] == "stamp": + stamp(*sys.argv[2:]) + else: + raise ValueError(__doc__) + except (OSError, ValueError, subprocess.CalledProcessError) as exc: + sys.exit(f"fm-git-attribution: {exc}") diff --git a/bin/fm-git-strip-ai-trailers.sh b/bin/fm-git-strip-ai-trailers.sh index 76fb0ec005d..6d73044b9db 100755 --- a/bin/fm-git-strip-ai-trailers.sh +++ b/bin/fm-git-strip-ai-trailers.sh @@ -6,7 +6,7 @@ # fm-git-strip-ai-trailers.sh # Commit-msg hook mode. Git passes the proposed message file as $1. # Rewrites that file in place, then exits 0 so the commit proceeds. -# fm-git-strip-ai-trailers.sh install [--no-strip] [--push-guard ] +# fm-git-strip-ai-trailers.sh install [--no-strip] [--attribution ] [--push-guard ] # Recreate as a core.hooksPath for this launch: a commit-msg # hook that runs this strip, plus one wrapper per client-side hook name # git documents except reference-transaction and post-index-change, @@ -31,6 +31,9 @@ # the pre-push wrapper run bin/fm-git-push-guard.sh on it first, with # git's arguments and ref lines, chaining to the repository's pre-push # hook only when the guard passes (that script owns the rules). +# --attribution keeps and adds scoped +# attribution through fm-git-attribution.py, rechecking the commit repo. +# The scope list is frozen read-only alongside the task hooks. # fm-git-strip-ai-trailers.sh env-file # Write as one plain export statement that appends # core.hooksPath= after the GIT_CONFIG_COUNT entries this @@ -86,7 +89,7 @@ usage() { cat >&2 <<'EOF' usage: fm-git-strip-ai-trailers.sh - fm-git-strip-ai-trailers.sh install [--no-strip] [--push-guard ] [ [...]] + fm-git-strip-ai-trailers.sh install [--no-strip] [--attribution ] [--push-guard ] [ [...]] fm-git-strip-ai-trailers.sh env-file EOF exit 2 @@ -119,6 +122,7 @@ fm_is_ai_attribution_line() { 'generated with [cortex code](https://docs.snowflake.com/'*')') return 0 ;; + agent-system:* | agent-platform:* | agent-session:*) return 0 ;; co-authored-by:*) ;; *) return 1 ;; esac @@ -135,7 +139,7 @@ fm_is_ai_attribution_line() { esac name=$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]') case "$email" in - noreply@anthropic.com | cursoragent@* | noreply@openai.com | copilot@github.com | noreply@commandcode.ai | noreply@snowflake.com) + noreply@firstmate.invalid | noreply@anthropic.com | cursoragent@* | noreply@openai.com | copilot@github.com | noreply@commandcode.ai | noreply@snowflake.com) return 0 ;; esac @@ -313,6 +317,11 @@ install_hooks() { strip_line= [ "$strip" = 0 ] || strip_line="$(quote_for_hook "$SELF") \"\$1\" || exit \$?" + if [ -n "${attribution_config:-}" ]; then + cp "$attribution_config" "$hooks_dir/attribution-scopes" || return 1 + chmod 400 "$hooks_dir/attribution-scopes" || return 1 + strip_line="python3 $(quote_for_hook "${SELF%/*}/fm-git-attribution.py") stamp $(quote_for_hook "$hooks_dir/attribution-scopes") $(quote_for_hook "$attribution_runtime") $(quote_for_hook "$attribution_model") \"\$1\" || exit \$?" + fi write_executable "$hooks_dir/commit-msg" <&2 exit 1 fi +# Resolve the legacy presence flag or scoped keep-and-add list before any +# runtime-specific attribution settings are built. +AI_ATTRIBUTION_MODE=$(python3 "$SCRIPT_DIR/fm-git-attribution.py" mode "$CONFIG/keep-ai-trailers" "$PROJ_ABS") || exit 1 +KEEP_AI_TRAILERS=0 +[ "$AI_ATTRIBUTION_MODE" = strip ] || KEEP_AI_TRAILERS=1 + # Project capacity admission (bin/fm-project-capacity-lib.sh owns the # declaration, what holds a place, and why this is race-safe). A fresh worker # for a project whose declared capacity is already held is deferred here, before @@ -4097,6 +4103,10 @@ if [ "$KIND" = ship ] || [ "$KIND" = scout ]; then cat "$SOURCE_BRIEF" && if [ "$KIND" = ship ] && [ "$MODE" = no-mistakes ]; then fm_brief_intent_overlay "$CAPTAIN_INTENT" + fi && + if [ "$AI_ATTRIBUTION_MODE" = add ]; then + # shellcheck disable=SC2016 # Markdown backticks, not command substitution. + printf '\n# Scoped attribution\nInclude the visible attribution line `Agent-System: fac:firstmate` in the pull request description, preserving any pipeline attestation.\n' fi } >"$BRIEF_TMP" || { rm -f -- "$BRIEF_TMP" @@ -6838,6 +6848,9 @@ if [ "$EXTERNAL_REVIEW" = 1 ]; then [ -z "$EXTERNAL_BACKUP_REMOTE" ] || guard_args+=("$EXTERNAL_BACKUP_REMOTE" "$EXTERNAL_BACKUP_PREFIX") strip_args=() [ "$KEEP_AI_TRAILERS" = 0 ] || strip_args=(--no-strip) + if [ "$AI_ATTRIBUTION_MODE" = add ]; then + strip_args+=(--attribution "$CONFIG/keep-ai-trailers" "$HARNESS" "${MODEL:-default}") + fi { "$FM_ROOT/bin/fm-git-push-guard.sh" write "${guard_args[@]}" \ && "$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install "${strip_args[@]+"${strip_args[@]}"}" \ --push-guard "$PUSH_GUARD_FILE" "$GIT_HOOKS_DIR" "$WT"; } || { @@ -6845,8 +6858,11 @@ if [ "$EXTERNAL_REVIEW" = 1 ]; then exit 1 } GIT_HOOKS_INSTALLED=1 -elif [ "$KEEP_AI_TRAILERS" = 0 ]; then +elif [ "$KEEP_AI_TRAILERS" = 0 ] || [ "$AI_ATTRIBUTION_MODE" = add ]; then STRIP_INSTALL=("$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install "$GIT_HOOKS_DIR" "$WT") + if [ "$AI_ATTRIBUTION_MODE" = add ]; then + STRIP_INSTALL=("$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install --attribution "$CONFIG/keep-ai-trailers" "$HARNESS" "${MODEL:-default}" "$GIT_HOOKS_DIR" "$WT") + fi if [ "$KIND" = ship ] && [ "$MODE" != local-only ]; then STRIP_INSTALL+=("$FM_ROOT/bin/fm-upstream-push-guard.sh" "$FM_ROOT" "$TASK_TMP/prior-art.json") fi diff --git a/docs/configuration.md b/docs/configuration.md index 410aceea09b..5eff556a663 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1349,7 +1349,7 @@ rovo is likewise verified for crewmate and scout launches ONLY, refused for a se An agy secondmate or primary runs the tracked project-scope `.agents/hooks.json` in its own home, and `bin/fm-spawn.sh` pre-registers a secondmate home in agy's workspace trust store through `bin/fm-agy-trust.sh`; [`docs/supervision-protocols/agy.md`](supervision-protocols/agy.md) owns its supervision protocol and [`docs/verification/agy.md`](verification/agy.md) owns the evidence. devin is verified for crewmate and scout launches only; a secondmate is refused because Devin has no verified primary supervision protocol. -Its private worker config disables Claude Code imports (including the captain's hooks) and, unless the home sets `config/keep-ai-trailers` (see "Commit attribution"), Devin commit attribution without editing user or project config; [`fm-devin-config.sh`](../bin/fm-devin-config.sh) owns these enforced settings and [Devin verification](verification/devin.md) owns the live evidence and observed model availability. +Its private worker config disables Claude Code imports (including the captain's hooks) and, when the resolved [commit attribution policy](#commit-attribution) strips trailers, Devin commit attribution without editing user or project config; [`fm-devin-config.sh`](../bin/fm-devin-config.sh) owns these enforced settings and [Devin verification](verification/devin.md) owns the live evidence and observed model availability. cortex (Snowflake's Cortex Code) is likewise verified for crewmate and scout launches only; a secondmate is refused because Cortex has no verified primary supervision protocol. It runs only on the tmux and Herdr backends; a zellij, cmux, orca, paseo, rex, or t3code launch is refused because those backends supply no Cortex pane identity to prove its titled composer empty. @@ -1459,7 +1459,7 @@ Pi-family secondmates can start unattended in Firstmate-seeded homes without acc For omp secondmate launches, `fm-spawn.sh` names only the parent home's `state/.omp-ext.ts` busy extension with `-e`: omp auto-discovers the home's tracked `.omp/extensions/` with no trust gate, and naming a discovered file with `-e` as well loads it twice; every omp launch also carries the tracked `.omp/fm-worker-overlay.yml` posture overlay through `--config`, which [`fm-spawn.sh --help`](../bin/fm-spawn.sh) owns. For a Claude secondmate, `fm-spawn.sh` writes the busy hooks into the parent home's `state/.claude-settings.json` and passes that file as Claude Code's one `--settings` value. -The same file carries `feedbackDrafts` and, unless `config/keep-ai-trailers` is present, the attribution policy every other Claude launch puts in its inline `--settings` JSON. +The same file carries `feedbackDrafts` and the resolved [commit attribution policy](#commit-attribution) that every other Claude launch puts in its inline `--settings` JSON. Claude Code applies `--settings` for that session and does not write the file into the mate home. A key the file sets overrides the same key in user, project, and local settings. A key it omits keeps the file-based value, so a `.claude/settings.local.json` already in the home is left untouched. @@ -1819,17 +1819,38 @@ This applies only to agents Firstmate launches; the captain's own primary Firstm ### Commit attribution -The optional local, gitignored `config/keep-ai-trailers` presence flag opts this home into keeping AI co-author trailers on its launched workers. +The optional local, gitignored `config/keep-ai-trailers` selects attribution for launched workers. +An empty file retains the legacy home-wide keep behavior described below. +A nonempty file instead lists one forge scope per line, `host/owner` or `host/owner/repo`, with optional blank lines and `#` comments: + +```text +# Keep and add attribution only for this owner +github.com/t27sol +``` + +Scopes match the project's `origin` remote over HTTPS, SSH URL or SCP syntax, case insensitively at owner/repository boundaries; no wildcard or local path matching is supported. +Malformed scopes refuse the launch. +A matching task keeps existing AI co-authors and installs a commit hook that adds a runtime co-author when absent, `Agent-System: fac:firstmate`, and `Agent-Platform: [/]`. +The runtime is always included; a known model selected from the runtime's catalog is included only when permitted, with Claude Code model IDs and unresolved `default`/`auto` model choices omitted. +The hook adds `Agent-Session` from a UUID `CODEX_THREAD_ID` for Codex when no native session trailer already carries the same reference. +A UUID/public Claude session URL in the runtime's existing `Claude-Session` trailer already satisfies session attribution and is retained without adding a duplicate `Agent-Session`. +Unavailable sessions are omitted, and no local path, arbitrary hostname, credential, or guessed session is copied into the added fields. +Other runtimes receive system, platform and co-author attribution with no inferred session identity. +Amending a message replaces the shared fields rather than duplicating them; no trailer order is required and native runtime trailers retain their order. +The task's scope list is frozen in its hooks directory, and the hook rechecks the repository's origin for each commit, so an unrelated repository reached from the same pane still strips AI co-authors. +Matching workers' launch briefs also require the visible PR attribution line `Agent-System: fac:firstmate`. +Focused synthetic regression coverage is in [`fm-git-strip-ai-trailers.test.sh`](../tests/fm-git-strip-ai-trailers.test.sh) and [`fm-spawn-dispatch-profile.test.sh`](../tests/fm-spawn-dispatch-profile.test.sh). +The following home-wide behavior applies to an empty flag; nonmatching repositories in scope-list mode use the absent-flag stripping behavior. With the flag absent, every Claude launch's session `--settings` value carries `"attribution":{"commit":"","pr":"","sessionUrl":false}`, every Devin worker config sets `"attribution": false`, and every fleet launch appends a worker-scoped `GIT_CONFIG` `core.hooksPath` entry pointing at `state/.git-hooks`, where git's `commit-msg` hook strips known AI trailers even when a runtime injects them after the typed message. The entry follows any `GIT_CONFIG_*` entries the worker inherits, so an inherited scoped `credential.helper` still applies to the worker and to the repository's own hooks, such as a git-lfs `pre-push`; an inherited `GIT_CONFIG_COUNT` that is not a decimal number, or that leaves no room for another entry within Git's signed int, stops the launch before the worker runs. T3 Code owns its provider command and cannot carry Claude's inline setting, but its per-worktree environment overlay selects the same Git hook; [`t3code-backend.md`](t3code-backend.md#active-limits) owns that backend limit. -When the flag is present, Claude launches omit those attribution-off settings, Devin worker configs keep the user config's `attribution` setting (Devin's default is on), and fleet launches do not install or select the strip hooks, so Git uses the repository's configured hooks directly. -Because the upstream prior-art push guard is installed only through those pane hooks, a shipping worker in a home with the flag present also skips that guard. +When the flag is empty, Claude launches omit those attribution-off settings, Devin worker configs keep the user config's `attribution` setting (Devin's default is on), and fleet launches do not install or select the strip hooks, so Git uses the repository's configured hooks directly. +Because the upstream prior-art push guard is installed only through those pane hooks, a shipping worker in a home with an empty flag also skips that guard. Cortex Code has no attribution switch and its model writes a `Generated with Snowflake CoCo` line and a `Co-authored-by: Snowflake CoCo` trailer itself, so the strip hooks are the only mechanism that removes them from a Cortex worker's commits. `bin/fm-git-strip-ai-trailers.sh` owns the identities, the install, and chaining the hooks of whichever repository git is running in, including when `git -c core.hooksPath` supplies the pane's hook override, so a project hook such as husky still runs when stripping is enabled. A repository whose config sets `core.hooksPath` to the empty string runs no project hook, as in plain git; if the wrapper otherwise cannot resolve that repository's hooks directory, the git operation fails rather than silently skipping a project hook such as a pre-push guard. When stripping is enabled, the hooks directory is read-only, so a hook manager run inside a fleet pane (lefthook's npm postinstall, `pre-commit install`) fails instead of displacing the strip; install a project's hooks from outside the pane, where the wrappers chain them. -The flag is a home-wide attribution choice, so it is inherited into secondmate homes under the [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md) inherited-local-material contract and a secondmate's own workers keep AI trailers too. +The file is inherited into secondmate homes under the [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md) inherited-local-material contract, so its scope selection applies to a secondmate's own workers too. Per-machine Cursor `cli-config.json` attribution-off is not this contract: it does not travel with Firstmate, defaults back to on when unset, and only feeds the CLI's request to the server, so it suppresses the trailer rather than preventing it. ## Project capacity (config/project-capacity) diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index ea1f744289b..3f8b87dd47f 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -30,6 +30,81 @@ make_repo() { fm_git_init_commit "$dir" } +test_scoped_keep_and_add() { + local runtime repo hooks config body session model + config="$TMP_ROOT/scopes" + printf '%s\n' '# selected owner and exact repository' 'github.com/t27sol' 'gitlab.com/team/one' >"$config" + for runtime in codex claude pi pi-signed omp opencode grok kimi cursor agy muse gemini rovo devin commandcode polytoken cortex; do + repo="$TMP_ROOT/scoped-$runtime" hooks="$TMP_ROOT/scoped-hooks-$runtime" + make_repo "$repo" + git -C "$repo" remote add origin git@github.com:t27sol/sample.git + model=fixture-model + "$STRIP" install --attribution "$config" "$runtime" "$model" "$hooks" "$repo" || fail 'scoped install failed' + session=11111111-2222-3333-4444-555555555555 + CODEX_THREAD_ID=$session with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty \ + -m 'fix: scoped attribution' -m 'Co-authored-by: Jane Doe ' \ + -m "Claude-Session: $session" + body=$(git -C "$repo" log -1 --format=%B) + assert_contains "$body" 'Agent-System: fac:firstmate' 'missing system' + if [ "$runtime" = claude ]; then + assert_contains "$body" 'Agent-Platform: claude' 'missing Claude platform' + assert_not_contains "$body" "claude/$model" 'Claude model must be omitted' + else + assert_contains "$body" "Agent-Platform: $runtime/$model" 'missing platform' + fi + assert_contains "$body" "Co-authored-by: $runtime " 'missing agent coauthor' + assert_contains "$body" 'Co-authored-by: Jane Doe' 'lost human coauthor' + case "$runtime" in + codex | claude) assert_not_contains "$body" 'Agent-Session:' 'native session was duplicated' ;; + *) assert_not_contains "$body" 'Agent-Session:' 'guessed session for another runtime' ;; + esac + if [ "$runtime" = codex ]; then + CODEX_THREAD_ID=$session with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: no native session' + body=$(git -C "$repo" log -1 --format=%B) + assert_contains "$body" "Agent-Session: $session" 'Codex UUID missing without native session' + fi + CODEX_THREAD_ID=/private/session with_hooks_env "$hooks" git -C "$repo" commit -q --amend --allow-empty \ + -m 'fix: amended attribution' -m 'Co-authored-by: Claude ' + body=$(git -C "$repo" log -1 --format=%B) + assert_not_contains "$body" 'Agent-Session:' 'unsafe or stale session published' + assert_contains "$body" 'Co-authored-by: Claude ' 'native coauthor lost' + # The same pane committing in another repo must still strip. + git -C "$repo" remote set-url origin https://github.com/t27sol-other/sample.git + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty \ + -m 'fix: outside scope' --trailer 'Co-authored-by: Claude ' + body=$(git -C "$repo" log -1 --format=%B) + assert_not_contains "$body" 'noreply@anthropic.com' 'outside scope kept AI trailer' + assert_not_contains "$body" 'Agent-System:' 'outside scope gained attribution' + done + pass 'scoped hooks keep and add across runtimes; other owners strip and unsafe sessions are omitted' +} + +test_scope_matching() { + local config repo mode url + config="$TMP_ROOT/scope-matching" repo="$TMP_ROOT/scope-repo" + make_repo "$repo" + git -C "$repo" remote add origin https://github.com/t27sol/repo.git + for url in https://github.com/t27sol/repo.git ssh://git@github.com/t27sol/repo.git git@github.com:t27sol/repo.git; do + git -C "$repo" remote set-url origin "$url" + printf '%s\n' 'github.com/t27sol/repo' >"$config" + mode=$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo") || fail 'scope resolution failed' + [ "$mode" = add ] || fail 'exact repository did not match' + done + printf '%s\n' 'github.com/t27sol/other' >"$config" + [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = strip ] || fail 'sibling repo matched' + printf '%s\n' 'https://github.com/t27sol' >"$config" + if python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo" 2>/dev/null; then fail 'invalid scope accepted'; fi + : >"$config" + [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = keep ] || fail 'legacy flag changed' + printf '%s\n' github.com/t27sol >"$config" + "$STRIP" install --attribution "$config" codex default "$TMP_ROOT/default-model-hooks" "$repo" || fail 'default-model install failed' + with_hooks_env "$TMP_ROOT/default-model-hooks" git -C "$repo" commit -q --allow-empty -m 'fix: unresolved model' + mode=$(git -C "$repo" log -1 --format=%B) + assert_contains "$mode" 'Agent-Platform: codex' 'runtime missing without model' + assert_not_contains "$mode" 'Agent-Platform: codex/' 'unreported model emitted' + pass 'scope resolution accepts forge transports, bounds repository scopes, rejects malformed config and keeps legacy flag' +} + test_cursor_trailer_does_not_reach_the_commit_object() { local repo hooks body author repo="$TMP_ROOT/cursor-object" @@ -555,6 +630,8 @@ test_push_guard_install_runs_the_guard_before_chaining() { pass "install --push-guard writes a read-only pre-push that runs the guard before chaining" } +test_scoped_keep_and_add +test_scope_matching test_cursor_trailer_does_not_reach_the_commit_object test_commandcode_trailer_is_stripped test_human_coauthor_is_kept diff --git a/tests/fm-spawn-dispatch-profile.test.sh b/tests/fm-spawn-dispatch-profile.test.sh index 776e1aa552d..2f84568bb57 100755 --- a/tests/fm-spawn-dispatch-profile.test.sh +++ b/tests/fm-spawn-dispatch-profile.test.sh @@ -2384,6 +2384,39 @@ test_claude_crewmate_launch_carries_the_attribution_policy() { pass "a claude crewmate launch carries the attribution-off policy in its own settings" } +test_scoped_attribution_launches() { + local runtime owner rec id out status body hooks + for runtime in codex claude; do + for owner in t27sol another-owner; do + id="scoped-$runtime-$owner" + rec=$(make_spawn_case "$id" "$runtime" "$id") + read_case_record "$rec" + printf '%s\n' github.com/t27sol >"$HOME_DIR/config/keep-ai-trailers" + git -C "$PROJ_DIR" remote set-url origin "git@github.com:$owner/example.git" + # Keep fetch local while exposing the forge URL to scope resolution. + git -C "$PROJ_DIR" config "url.file://$PROJ_DIR.origin.git.insteadOf" "git@github.com:$owner/example.git" + out=$(run_ship_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$id" "$PROJ_DIR") + status=$? + expect_code 0 "$status" "scoped $runtime spawn failed"$'\n'"$out" + hooks="$HOME_DIR/state/$id.git-hooks" + GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0="$hooks" \ + git -C "$WT_DIR" -c user.name=Fixture -c user.email=fixture@example.invalid commit -q --allow-empty -m 'fix: scope launch' \ + --trailer 'Co-authored-by: Claude ' || fail 'scoped launch commit failed' + body=$(git -C "$WT_DIR" log -1 --format=%B) + if [ "$owner" = t27sol ]; then + assert_contains "$body" "Agent-Platform: $runtime" 'scoped launch did not add platform' + assert_contains "$(cat "$HOME_DIR/data/$id/launch-brief.md")" 'Agent-System: fac:firstmate' 'missing PR attribution instruction' + [ "$runtime" != claude ] || assert_attribution_policy_absent "$(cat "$LAUNCH_LOG")" 'scoped claude' + else + assert_not_contains "$body" 'noreply@anthropic.com' 'unlisted owner kept AI trailer' + assert_not_contains "$body" 'Agent-System:' 'unlisted owner gained shared attribution' + [ "$runtime" != claude ] || assert_attribution_policy "$(cat "$LAUNCH_LOG")" 'unscoped claude' + fi + done + done + pass 'Codex and Claude scoped launches add attribution only for listed owners' +} + test_keep_ai_trailers_omits_attribution_settings_and_strip_hooks() { local rec id out status launch id=profile-claude-keep-attribution-z25 @@ -3093,6 +3126,7 @@ test_codex_permission_does_not_change_other_harnesses() { pass "Codex restricted mode leaves other harness launch flags unchanged" } +test_scoped_attribution_launches test_codex_permission_modes test_codex_permission_invalid_refuses_before_mutation test_codex_permission_does_not_change_other_harnesses From 19d0dcb03158c1daba56997d921adb69bee3cd6f Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:01:45 +1000 Subject: [PATCH 02/10] no-mistakes(review): Fix t27sol attribution defaults, trailer preservation, and session references --- bin/fm-git-attribution.py | 84 ++++++++--------- bin/fm-git-strip-ai-trailers.sh | 17 ++-- bin/fm-spawn.sh | 60 ++++++------- docs/configuration.md | 33 +++---- tests/fm-git-strip-ai-trailers.test.sh | 115 +++++++++++++++--------- tests/fm-spawn-dispatch-profile.test.sh | 62 ++++++++++++- 6 files changed, 218 insertions(+), 153 deletions(-) diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index 88a8dea968d..5c7edab646c 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -2,13 +2,12 @@ """Scoped commit attribution. Usage: fm-git-attribution.py mode - fm-git-attribution.py stamp + fm-git-attribution.py stamp -An empty legacy config means keep; nonempty configs list host/owner[/repo] -(one per line, # comments). Invalid entries refuse the launch/commit. -Stamp runs in Git's hook cwd and rechecks origin, so another repository cannot -inherit an attribution opt-in. Only UUID session IDs and Claude's public session -URL shape are publishable; arbitrary environment values are never copied. +t27sol GitHub repositories always receive attribution; elsewhere the legacy +config presence flag means keep, and absence means strip. +Stamp runs in Git's hook cwd and rechecks origin. Session references come from +runtime context or existing task metadata, never a new persistent record. """ import os import re @@ -17,48 +16,34 @@ from pathlib import Path from urllib.parse import urlsplit -SCOPE = re.compile(r"[a-z0-9.-]+/[a-z0-9_.-]+(?:/[a-z0-9_.-]+)?", re.I) UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", re.I) -def remote(project): +def t27sol(project): result = subprocess.run(["git", "-C", project, "config", "--get", "remote.origin.url"], capture_output=True, text=True, check=False) url = result.stdout.strip() if "://" in url: parsed = urlsplit(url) - if parsed.scheme not in ("ssh", "https", "http", "git"): - return "" + if parsed.scheme not in ("ssh", "https"): + return False host, path = parsed.hostname or "", parsed.path.lstrip("/") else: match = re.fullmatch(r"(?:[^/@:]+@)?([^/:]+):([^\s]+)", url) if not match: - return "" + return False host, path = match.groups() - value = f"{host}/{path.removesuffix('.git')}".lower() - return value if SCOPE.fullmatch(value) and value.count("/") == 2 else "" + return host.lower() == "github.com" and bool(re.fullmatch( + r"t27sol/[a-z0-9_.-]+", path.lower().removesuffix(".git"))) def mode(config, project): - path = Path(config) - if not path.exists(): - return "strip" - content = path.read_text() - if not content.strip(): - return "keep" - scopes = [] - for line in content.splitlines(): - line = line.split("#", 1)[0].strip().lower().removesuffix("/") - if not line: - continue - if not SCOPE.fullmatch(line) or any(p in (".", "..") for p in line.split("/")): - raise ValueError("invalid keep-ai-trailers scope (expected host/owner[/repo])") - scopes.append(line.removesuffix(".git")) - target = remote(project) - return "add" if any(target == s or target.startswith(s + "/") for s in scopes) else "strip" + if t27sol(project): + return "add" + return "keep" if Path(config).exists() else "strip" -def session(runtime, lines): +def session(runtime, lines, task_meta): # This variable is supplied to shell tools by Codex, not a parent endpoint ID. if runtime == "codex": value = os.environ.get("CODEX_THREAD_ID", "") @@ -70,14 +55,20 @@ def session(runtime, lines): if UUID.fullmatch(value) or re.fullmatch( r"https://claude\.ai/code/session_[a-zA-Z0-9]+", value): return value + if runtime.startswith("opencode"): + value = os.environ.get("OPENCODE_SESSION_ID", "") + return value if re.fullmatch(r"ses_[a-zA-Z0-9]+", value) else "" + if runtime == "polytoken" and task_meta and Path(task_meta).is_file(): + for line in Path(task_meta).read_text().splitlines(): + if line.startswith("polytoken_session="): + value = line.split("=", 1)[1] + return value if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}", value) else "" return "" -def stamp(config, runtime, model, message): - current = mode(config, ".") - if current != "add": - if current == "strip": - subprocess.run([str(Path(__file__).with_name("fm-git-strip-ai-trailers.sh")), message], check=True) +def stamp(task_meta, runtime, model, message): + if not t27sol("."): + subprocess.run([str(Path(__file__).with_name("fm-git-strip-ai-trailers.sh")), message], check=True) return # Runtime/model are launch metadata, never free-form trailer contents. if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", runtime) or not re.fullmatch( @@ -85,31 +76,34 @@ def stamp(config, runtime, model, message): raise ValueError("unsafe runtime/model for Agent-Platform") path = Path(message) lines = path.read_text().splitlines() - sid = session(runtime, lines) # Replace our fields on amend/retry; retain existing co-authors. lines = [line for line in lines if not re.match( r"(?i)^(agent-system|agent-platform|agent-session):", line)] - coauthors = [line for line in lines if re.match( + content = "\n".join(lines).rstrip() + "\n" + trailers = subprocess.run(["git", "interpret-trailers", "--parse"], input=content, + capture_output=True, text=True, check=True).stdout.splitlines() + sid = session(runtime, trailers, task_meta) + coauthors = [line for line in trailers if re.match( rf"(?i)^co-authored-by:\s*{re.escape(runtime)}(?:\s|<|$)", line)] - if not coauthors: - # A stable system identity covers runtimes that emit no co-author. - lines += ["", f"Co-authored-by: {runtime} "] # Claude Code omits model IDs from commit attribution. A default model is # unresolved launch metadata, so it must not be presented as a model ID. platform = runtime if not runtime.startswith("claude") and model not in ("default", "auto"): platform += f"/{model}" - args = ["git", "interpret-trailers", "--in-place", "--if-exists", "replace", - "--trailer", "Agent-System: fac:firstmate", - "--trailer", f"Agent-Platform: {platform}"] + args = ["git", "interpret-trailers", "--in-place"] + if not coauthors: + args += ["--if-exists", "addIfDifferent", "--trailer", + f"Co-authored-by: {runtime} "] + args += ["--if-exists", "replace", "--trailer", "Agent-System: fac:firstmate", + "--trailer", f"Agent-Platform: {platform}"] native_session = any( re.fullmatch(r"[a-z0-9-]+-session", line.split(":", 1)[0], re.I) and line.split(":", 1)[1].strip() == sid - for line in lines if ":" in line + for line in trailers if ":" in line ) if sid and not native_session: args += ["--trailer", f"Agent-Session: {sid}"] - path.write_text("\n".join(lines).rstrip() + "\n") + path.write_text(content) subprocess.run(args + [message], check=True) diff --git a/bin/fm-git-strip-ai-trailers.sh b/bin/fm-git-strip-ai-trailers.sh index 6d73044b9db..7f45f4619a2 100755 --- a/bin/fm-git-strip-ai-trailers.sh +++ b/bin/fm-git-strip-ai-trailers.sh @@ -6,7 +6,7 @@ # fm-git-strip-ai-trailers.sh # Commit-msg hook mode. Git passes the proposed message file as $1. # Rewrites that file in place, then exits 0 so the commit proceeds. -# fm-git-strip-ai-trailers.sh install [--no-strip] [--attribution ] [--push-guard ] +# fm-git-strip-ai-trailers.sh install [--no-strip] [--attribution ] [--push-guard ] # Recreate as a core.hooksPath for this launch: a commit-msg # hook that runs this strip, plus one wrapper per client-side hook name # git documents except reference-transaction and post-index-change, @@ -31,9 +31,8 @@ # the pre-push wrapper run bin/fm-git-push-guard.sh on it first, with # git's arguments and ref lines, chaining to the repository's pre-push # hook only when the guard passes (that script owns the rules). -# --attribution keeps and adds scoped +# --attribution keeps and adds scoped # attribution through fm-git-attribution.py, rechecking the commit repo. -# The scope list is frozen read-only alongside the task hooks. # fm-git-strip-ai-trailers.sh env-file # Write as one plain export statement that appends # core.hooksPath= after the GIT_CONFIG_COUNT entries this @@ -89,7 +88,7 @@ usage() { cat >&2 <<'EOF' usage: fm-git-strip-ai-trailers.sh - fm-git-strip-ai-trailers.sh install [--no-strip] [--attribution ] [--push-guard ] [ [...]] + fm-git-strip-ai-trailers.sh install [--no-strip] [--attribution ] [--push-guard ] [ [...]] fm-git-strip-ai-trailers.sh env-file EOF exit 2 @@ -317,10 +316,8 @@ install_hooks() { strip_line= [ "$strip" = 0 ] || strip_line="$(quote_for_hook "$SELF") \"\$1\" || exit \$?" - if [ -n "${attribution_config:-}" ]; then - cp "$attribution_config" "$hooks_dir/attribution-scopes" || return 1 - chmod 400 "$hooks_dir/attribution-scopes" || return 1 - strip_line="python3 $(quote_for_hook "${SELF%/*}/fm-git-attribution.py") stamp $(quote_for_hook "$hooks_dir/attribution-scopes") $(quote_for_hook "$attribution_runtime") $(quote_for_hook "$attribution_model") \"\$1\" || exit \$?" + if [ -n "${attribution_meta:-}" ]; then + strip_line="python3 $(quote_for_hook "${SELF%/*}/fm-git-attribution.py") stamp $(quote_for_hook "$attribution_meta") $(quote_for_hook "$attribution_runtime") $(quote_for_hook "$attribution_model") \"\$1\" || exit \$?" fi write_executable "$hooks_dir/commit-msg" <.git-hooks as an appended GIT_CONFIG core.hooksPath entry for the pane, so git # commit-msg strips known AI trailers at the commit object for every launched # runtime, Claude included as defense in depth. bin/fm-git-strip-ai-trailers.sh @@ -880,9 +877,6 @@ if [ "$LAVISH_AXI_HOST_CONFIG_PRESENT" = 1 ]; then ;; esac fi -if ! KEEP_AI_TRAILERS=$(fm_config_source_present "$CONFIG/keep-ai-trailers"); then - exit 1 -fi # Set by the forge agreement below for a forge=external ship. EXTERNAL_REVIEW=0 EXTERNAL_BACKUP_REMOTE= @@ -3978,8 +3972,6 @@ if [ "$RELAUNCH" -eq 0 ] && [ "$KIND" != secondmate ] && echo "error: spawn refused: project $PROJ_ABS has no commit yet (unborn HEAD), so there is nothing to branch a worktree from; make one commit in the project, for example 'git -C $PROJ_ABS commit --allow-empty -m \"chore: initial commit\"', then spawn again" >&2 exit 1 fi -# Resolve the legacy presence flag or scoped keep-and-add list before any -# runtime-specific attribution settings are built. AI_ATTRIBUTION_MODE=$(python3 "$SCRIPT_DIR/fm-git-attribution.py" mode "$CONFIG/keep-ai-trailers" "$PROJ_ABS") || exit 1 KEEP_AI_TRAILERS=0 [ "$AI_ATTRIBUTION_MODE" = strip ] || KEEP_AI_TRAILERS=1 @@ -4103,10 +4095,6 @@ if [ "$KIND" = ship ] || [ "$KIND" = scout ]; then cat "$SOURCE_BRIEF" && if [ "$KIND" = ship ] && [ "$MODE" = no-mistakes ]; then fm_brief_intent_overlay "$CAPTAIN_INTENT" - fi && - if [ "$AI_ATTRIBUTION_MODE" = add ]; then - # shellcheck disable=SC2016 # Markdown backticks, not command substitution. - printf '\n# Scoped attribution\nInclude the visible attribution line `Agent-System: fac:firstmate` in the pull request description, preserving any pipeline attestation.\n' fi } >"$BRIEF_TMP" || { rm -f -- "$BRIEF_TMP" @@ -6450,19 +6438,18 @@ const setupEventSubscription = (ctx, handler) => { })(); return true; }; -const makeHandler = () => { - let activeSession = null; +const makeHandler = (state) => { return async (event) => { const type = eventType(event); const id = sessionID(event); if (type === "session.execution.started") { - if (activeSession === null) activeSession = id; - if (id === activeSession) await busyEvent("busy", "session-execution-started"); + if (state.activeSession === null) state.activeSession = id; + if (id === state.activeSession) await busyEvent("busy", "session-execution-started"); return; } if (type === "session.execution.succeeded" || type === "session.execution.interrupted" || type === "session.execution.failed") { - if (id === activeSession) { - activeSession = null; + if (id === state.activeSession) { + state.activeSession = null; await busyEvent("idle", type.replace(/\./g, "-")); } if (notifyTurnEnd) await touchTurnEnded(); @@ -6472,19 +6459,19 @@ const makeHandler = () => { const properties = eventProperties(event); const statusType = properties.status && properties.status.type; if (statusType === "busy" || statusType === "retry") { - if (activeSession === null) activeSession = id; - if (id === activeSession) await busyEvent("busy", "session-" + statusType); + if (state.activeSession === null) state.activeSession = id; + if (id === state.activeSession) await busyEvent("busy", "session-" + statusType); return; } - if (statusType === "idle" && id === activeSession) { - activeSession = null; + if (statusType === "idle" && id === state.activeSession) { + state.activeSession = null; await busyEvent("idle", "session-status-idle"); } return; } if (type === "session.idle") { - if (id === activeSession) { - activeSession = null; + if (id === state.activeSession) { + state.activeSession = null; await busyEvent("idle", "session-idle"); } if (notifyTurnEnd) await touchTurnEnded(); @@ -6492,9 +6479,13 @@ const makeHandler = () => { }; }; export const FmBusyState = async () => { - const handleEvent = makeHandler(); + const state = { activeSession: null }; + const handleEvent = makeHandler(state); return { event: async ({ event }) => handleEvent(event), + "shell.env": async (input, output) => { + output.env.OPENCODE_SESSION_ID = input.sessionID || state.activeSession || ""; + }, }; }; @@ -6502,7 +6493,11 @@ export default { id: "fm.busy-state", server: FmBusyState, setup(ctx) { - setupEventSubscription(ctx, makeHandler()); + const state = { activeSession: null }; + setupEventSubscription(ctx, makeHandler(state)); + ctx.shell.hook("create.before", (event) => { + event.env.OPENCODE_SESSION_ID = state.activeSession || ""; + }); }, }; EOF @@ -6529,6 +6524,9 @@ const busyEvent = (state, event) => export const FmBusyState = async () => { let activeSession = null; return { + "shell.env": async (input, output) => { + output.env.OPENCODE_SESSION_ID = input.sessionID || activeSession || ""; + }, event: async ({ event }) => { if (event.type === "session.status") { const sessionID = event.properties.sessionID; @@ -6849,7 +6847,7 @@ if [ "$EXTERNAL_REVIEW" = 1 ]; then strip_args=() [ "$KEEP_AI_TRAILERS" = 0 ] || strip_args=(--no-strip) if [ "$AI_ATTRIBUTION_MODE" = add ]; then - strip_args+=(--attribution "$CONFIG/keep-ai-trailers" "$HARNESS" "${MODEL:-default}") + strip_args+=(--attribution "$STATE_REAL/$ID.meta" "$HARNESS" "${MODEL:-default}") fi { "$FM_ROOT/bin/fm-git-push-guard.sh" write "${guard_args[@]}" \ && "$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install "${strip_args[@]+"${strip_args[@]}"}" \ @@ -6861,7 +6859,7 @@ if [ "$EXTERNAL_REVIEW" = 1 ]; then elif [ "$KEEP_AI_TRAILERS" = 0 ] || [ "$AI_ATTRIBUTION_MODE" = add ]; then STRIP_INSTALL=("$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install "$GIT_HOOKS_DIR" "$WT") if [ "$AI_ATTRIBUTION_MODE" = add ]; then - STRIP_INSTALL=("$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install --attribution "$CONFIG/keep-ai-trailers" "$HARNESS" "${MODEL:-default}" "$GIT_HOOKS_DIR" "$WT") + STRIP_INSTALL=("$FM_ROOT/bin/fm-git-strip-ai-trailers.sh" install --attribution "$STATE_REAL/$ID.meta" "$HARNESS" "${MODEL:-default}" "$GIT_HOOKS_DIR" "$WT") fi if [ "$KIND" = ship ] && [ "$MODE" != local-only ]; then STRIP_INSTALL+=("$FM_ROOT/bin/fm-upstream-push-guard.sh" "$FM_ROOT" "$TASK_TMP/prior-art.json") diff --git a/docs/configuration.md b/docs/configuration.md index 5eff556a663..bd11469d7c0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1819,38 +1819,29 @@ This applies only to agents Firstmate launches; the captain's own primary Firstm ### Commit attribution -The optional local, gitignored `config/keep-ai-trailers` selects attribution for launched workers. -An empty file retains the legacy home-wide keep behavior described below. -A nonempty file instead lists one forge scope per line, `host/owner` or `host/owner/repo`, with optional blank lines and `#` comments: - -```text -# Keep and add attribution only for this owner -github.com/t27sol -``` - -Scopes match the project's `origin` remote over HTTPS, SSH URL or SCP syntax, case insensitively at owner/repository boundaries; no wildcard or local path matching is supported. -Malformed scopes refuse the launch. +Workers in GitHub repositories owned by `t27sol` keep and receive commit attribution by default, even when `config/keep-ai-trailers` is absent. +The owner match uses the project's `origin` remote over HTTPS, SSH URL or SCP syntax, case insensitively at the owner boundary. A matching task keeps existing AI co-authors and installs a commit hook that adds a runtime co-author when absent, `Agent-System: fac:firstmate`, and `Agent-Platform: [/]`. The runtime is always included; a known model selected from the runtime's catalog is included only when permitted, with Claude Code model IDs and unresolved `default`/`auto` model choices omitted. The hook adds `Agent-Session` from a UUID `CODEX_THREAD_ID` for Codex when no native session trailer already carries the same reference. A UUID/public Claude session URL in the runtime's existing `Claude-Session` trailer already satisfies session attribution and is retained without adding a duplicate `Agent-Session`. -Unavailable sessions are omitted, and no local path, arbitrary hostname, credential, or guessed session is copied into the added fields. -Other runtimes receive system, platform and co-author attribution with no inferred session identity. -Amending a message replaces the shared fields rather than duplicating them; no trailer order is required and native runtime trailers retain their order. -The task's scope list is frozen in its hooks directory, and the hook rechecks the repository's origin for each commit, so an unrelated repository reached from the same pane still strips AI co-authors. -Matching workers' launch briefs also require the visible PR attribution line `Agent-System: fac:firstmate`. +OpenCode passes its existing plugin session identity to shell commands in memory, and Polytoken uses the existing task metadata's `polytoken_session` field. +A session not yet available at commit time is omitted; other runtimes have no connected session source and omit it too. +No additional persistent session record is created, and no local path, arbitrary hostname, credential, or guessed session is copied into the added fields. +Amending a message replaces the shared fields rather than duplicating them; no trailer order is required and native runtime trailers retain their order within Git's parsed trailer block. +The hook rechecks the repository's origin for each commit, so an unrelated repository reached from the same pane still strips AI co-authors. Focused synthetic regression coverage is in [`fm-git-strip-ai-trailers.test.sh`](../tests/fm-git-strip-ai-trailers.test.sh) and [`fm-spawn-dispatch-profile.test.sh`](../tests/fm-spawn-dispatch-profile.test.sh). -The following home-wide behavior applies to an empty flag; nonmatching repositories in scope-list mode use the absent-flag stripping behavior. -With the flag absent, every Claude launch's session `--settings` value carries `"attribution":{"commit":"","pr":"","sessionUrl":false}`, every Devin worker config sets `"attribution": false`, and every fleet launch appends a worker-scoped `GIT_CONFIG` `core.hooksPath` entry pointing at `state/.git-hooks`, where git's `commit-msg` hook strips known AI trailers even when a runtime injects them after the typed message. +Outside t27sol, the optional local, gitignored `config/keep-ai-trailers` retains its legacy home-wide presence-flag behavior; its contents do not select owners or repositories. +With that flag absent outside t27sol, every Claude launch's session `--settings` value carries `"attribution":{"commit":"","pr":"","sessionUrl":false}`, every Devin worker config sets `"attribution": false`, and every fleet launch appends a worker-scoped `GIT_CONFIG` `core.hooksPath` entry pointing at `state/.git-hooks`, where git's `commit-msg` hook strips known AI trailers even when a runtime injects them after the typed message. The entry follows any `GIT_CONFIG_*` entries the worker inherits, so an inherited scoped `credential.helper` still applies to the worker and to the repository's own hooks, such as a git-lfs `pre-push`; an inherited `GIT_CONFIG_COUNT` that is not a decimal number, or that leaves no room for another entry within Git's signed int, stops the launch before the worker runs. T3 Code owns its provider command and cannot carry Claude's inline setting, but its per-worktree environment overlay selects the same Git hook; [`t3code-backend.md`](t3code-backend.md#active-limits) owns that backend limit. -When the flag is empty, Claude launches omit those attribution-off settings, Devin worker configs keep the user config's `attribution` setting (Devin's default is on), and fleet launches do not install or select the strip hooks, so Git uses the repository's configured hooks directly. -Because the upstream prior-art push guard is installed only through those pane hooks, a shipping worker in a home with an empty flag also skips that guard. +When the flag is present outside t27sol, Claude launches omit those attribution-off settings, Devin worker configs keep the user config's `attribution` setting (Devin's default is on), and fleet launches do not install or select the strip hooks, so Git uses the repository's configured hooks directly. +Because the upstream prior-art push guard is installed only through those pane hooks, a shipping worker in a home with the flag present outside t27sol also skips that guard. Cortex Code has no attribution switch and its model writes a `Generated with Snowflake CoCo` line and a `Co-authored-by: Snowflake CoCo` trailer itself, so the strip hooks are the only mechanism that removes them from a Cortex worker's commits. `bin/fm-git-strip-ai-trailers.sh` owns the identities, the install, and chaining the hooks of whichever repository git is running in, including when `git -c core.hooksPath` supplies the pane's hook override, so a project hook such as husky still runs when stripping is enabled. A repository whose config sets `core.hooksPath` to the empty string runs no project hook, as in plain git; if the wrapper otherwise cannot resolve that repository's hooks directory, the git operation fails rather than silently skipping a project hook such as a pre-push guard. When stripping is enabled, the hooks directory is read-only, so a hook manager run inside a fleet pane (lefthook's npm postinstall, `pre-commit install`) fails instead of displacing the strip; install a project's hooks from outside the pane, where the wrappers chain them. -The file is inherited into secondmate homes under the [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md) inherited-local-material contract, so its scope selection applies to a secondmate's own workers too. +The file is inherited into secondmate homes under the [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md) inherited-local-material contract, so its legacy keep behavior applies to a secondmate's own workers too. Per-machine Cursor `cli-config.json` attribution-off is not this contract: it does not travel with Firstmate, defaults back to on when unset, and only feeds the CLI's request to the server, so it suppresses the trailer rather than preventing it. ## Project capacity (config/project-capacity) diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index 3f8b87dd47f..1d916448a12 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -10,6 +10,7 @@ set -u # A fleet pane already carries GIT_CONFIG core.hooksPath. These cases set that # override themselves, so drop the inherited one before any git command. unset GIT_CONFIG_COUNT GIT_CONFIG_KEY_0 GIT_CONFIG_VALUE_0 GIT_CONFIG_PARAMETERS +unset CODEX_THREAD_ID OPENCODE_SESSION_ID # shellcheck source=tests/lib.sh . "$(dirname "${BASH_SOURCE[0]}")/lib.sh" @@ -31,78 +32,105 @@ make_repo() { } test_scoped_keep_and_add() { - local runtime repo hooks config body session model - config="$TMP_ROOT/scopes" - printf '%s\n' '# selected owner and exact repository' 'github.com/t27sol' 'gitlab.com/team/one' >"$config" + local runtime repo hooks meta body session model native expected platform for runtime in codex claude pi pi-signed omp opencode grok kimi cursor agy muse gemini rovo devin commandcode polytoken cortex; do repo="$TMP_ROOT/scoped-$runtime" hooks="$TMP_ROOT/scoped-hooks-$runtime" + meta="$TMP_ROOT/$runtime.meta" make_repo "$repo" git -C "$repo" remote add origin git@github.com:t27sol/sample.git model=fixture-model - "$STRIP" install --attribution "$config" "$runtime" "$model" "$hooks" "$repo" || fail 'scoped install failed' + "$STRIP" install --attribution "$meta" "$runtime" "$model" "$hooks" "$repo" || fail 'scoped install failed' session=11111111-2222-3333-4444-555555555555 + native=$(printf 'Co-authored-by: Jane Doe \nSigned-off-by: Jane Doe \nClaude-Session: %s' "$session") CODEX_THREAD_ID=$session with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty \ - -m 'fix: scoped attribution' -m 'Co-authored-by: Jane Doe ' \ - -m "Claude-Session: $session" - body=$(git -C "$repo" log -1 --format=%B) - assert_contains "$body" 'Agent-System: fac:firstmate' 'missing system' - if [ "$runtime" = claude ]; then - assert_contains "$body" 'Agent-Platform: claude' 'missing Claude platform' - assert_not_contains "$body" "claude/$model" 'Claude model must be omitted' - else - assert_contains "$body" "Agent-Platform: $runtime/$model" 'missing platform' - fi - assert_contains "$body" "Co-authored-by: $runtime " 'missing agent coauthor' - assert_contains "$body" 'Co-authored-by: Jane Doe' 'lost human coauthor' - case "$runtime" in - codex | claude) assert_not_contains "$body" 'Agent-Session:' 'native session was duplicated' ;; - *) assert_not_contains "$body" 'Agent-Session:' 'guessed session for another runtime' ;; - esac + -m 'fix: scoped attribution' -m "$native" || fail 'attributed commit failed' + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + platform=$runtime/$model + [ "$runtime" != claude ] || platform=claude + expected=$(printf '%s\nCo-authored-by: %s \nAgent-System: fac:firstmate\nAgent-Platform: %s' "$native" "$runtime" "$platform") + [ "$body" = "$expected" ] || fail "$runtime lost or reordered parsed trailers: $body" + CODEX_THREAD_ID=$session with_hooks_env "$hooks" git -C "$repo" commit -q --amend --no-edit --allow-empty || fail 'repeat stamping failed' + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$body" = "$expected" ] || fail "$runtime repeat stamping changed parsed trailers: $body" if [ "$runtime" = codex ]; then CODEX_THREAD_ID=$session with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: no native session' - body=$(git -C "$repo" log -1 --format=%B) + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) assert_contains "$body" "Agent-Session: $session" 'Codex UUID missing without native session' fi CODEX_THREAD_ID=/private/session with_hooks_env "$hooks" git -C "$repo" commit -q --amend --allow-empty \ -m 'fix: amended attribution' -m 'Co-authored-by: Claude ' - body=$(git -C "$repo" log -1 --format=%B) + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) assert_not_contains "$body" 'Agent-Session:' 'unsafe or stale session published' assert_contains "$body" 'Co-authored-by: Claude ' 'native coauthor lost' - # The same pane committing in another repo must still strip. git -C "$repo" remote set-url origin https://github.com/t27sol-other/sample.git with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty \ - -m 'fix: outside scope' --trailer 'Co-authored-by: Claude ' + -m 'fix: outside scope' --trailer "Co-authored-by: $runtime " \ + --trailer 'Co-authored-by: Claude ' body=$(git -C "$repo" log -1 --format=%B) - assert_not_contains "$body" 'noreply@anthropic.com' 'outside scope kept AI trailer' + assert_not_contains "$body" 'Co-authored-by:' 'outside scope kept AI trailer' assert_not_contains "$body" 'Agent-System:' 'outside scope gained attribution' done - pass 'scoped hooks keep and add across runtimes; other owners strip and unsafe sessions are omitted' + pass 'Git parses preserved native trailers and idempotent attribution across all runtimes' } test_scope_matching() { - local config repo mode url - config="$TMP_ROOT/scope-matching" repo="$TMP_ROOT/scope-repo" + local config repo mode url model + config="$TMP_ROOT/legacy-flag" repo="$TMP_ROOT/scope-repo" make_repo "$repo" git -C "$repo" remote add origin https://github.com/t27sol/repo.git - for url in https://github.com/t27sol/repo.git ssh://git@github.com/t27sol/repo.git git@github.com:t27sol/repo.git; do + for url in https://github.com/t27sol/repo.git ssh://git@github.com/t27sol/repo.git git@github.com:t27sol/repo.git https://github.com/T27SOL/Another.GIT; do + git -C "$repo" remote set-url origin "$url" + mode=$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo") || fail 'owner resolution failed' + [ "$mode" = add ] || fail 't27sol owner did not match without configuration' + done + for url in https://github.com/t27sol-other/repo.git https://gitlab.com/t27sol/repo.git https://github.com/other/t27sol.git "$repo"; do git -C "$repo" remote set-url origin "$url" - printf '%s\n' 'github.com/t27sol/repo' >"$config" - mode=$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo") || fail 'scope resolution failed' - [ "$mode" = add ] || fail 'exact repository did not match' + [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = strip ] || fail 'unrelated repository matched' done - printf '%s\n' 'github.com/t27sol/other' >"$config" - [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = strip ] || fail 'sibling repo matched' - printf '%s\n' 'https://github.com/t27sol' >"$config" - if python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo" 2>/dev/null; then fail 'invalid scope accepted'; fi : >"$config" [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = keep ] || fail 'legacy flag changed' - printf '%s\n' github.com/t27sol >"$config" - "$STRIP" install --attribution "$config" codex default "$TMP_ROOT/default-model-hooks" "$repo" || fail 'default-model install failed' - with_hooks_env "$TMP_ROOT/default-model-hooks" git -C "$repo" commit -q --allow-empty -m 'fix: unresolved model' - mode=$(git -C "$repo" log -1 --format=%B) - assert_contains "$mode" 'Agent-Platform: codex' 'runtime missing without model' - assert_not_contains "$mode" 'Agent-Platform: codex/' 'unreported model emitted' - pass 'scope resolution accepts forge transports, bounds repository scopes, rejects malformed config and keeps legacy flag' + printf '%s\n' 'gitlab.com/arbitrary/selection' >"$config" + [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = keep ] || fail 'legacy flag contents became a scope list' + git -C "$repo" remote set-url origin git@github.com:t27sol/repo.git + [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = add ] || fail 'legacy flag bypassed t27sol attribution' + for model in default auto; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" codex "$model" "$TMP_ROOT/default-model-hooks" "$repo" || fail 'default-model install failed' + with_hooks_env "$TMP_ROOT/default-model-hooks" git -C "$repo" commit -q --allow-empty -m 'fix: unresolved model' + mode=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + assert_contains "$mode" 'Agent-Platform: codex' 'runtime missing without model' + assert_not_contains "$mode" 'Agent-Platform: codex/' 'unreported model emitted' + done + pass 't27sol policy needs no configuration and preserves the legacy presence flag elsewhere' +} + +test_recorded_sessions() { + local runtime repo hooks meta sid body native + for runtime in opencode polytoken; do + repo="$TMP_ROOT/session-$runtime" hooks="$TMP_ROOT/session-hooks-$runtime" meta="$TMP_ROOT/session-$runtime.meta" + make_repo "$repo" + git -C "$repo" remote add origin https://github.com/t27sol/sample.git + "$STRIP" install --attribution "$meta" "$runtime" default "$hooks" "$repo" || fail 'session hook install failed' + if [ "$runtime" = opencode ]; then sid=ses_abc123; else sid=0czfake-echo; fi + printf 'polytoken_session=%s\npolytoken_credential=/private/credential\n' "$sid" >"$meta" + OPENCODE_SESSION_ID=$sid with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: recorded session' || fail 'session commit failed' + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + assert_contains "$body" "Agent-Session: $sid" "$runtime recorded session missing" + assert_not_contains "$body" credential 'credential leaked' + native="$runtime-session: $sid" + OPENCODE_SESSION_ID=$sid with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: native session' --trailer "$native" || fail 'native session commit failed' + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + assert_contains "$body" "$native" 'native recorded session lost' + assert_not_contains "$body" 'Agent-Session:' 'native recorded session duplicated' + printf 'polytoken_session=/private/secret\n' >"$meta" + OPENCODE_SESSION_ID=/private/secret with_hooks_env "$hooks" git -C "$repo" commit -q --amend --allow-empty -m 'fix: unsafe session' || fail 'unsafe session commit failed' + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + assert_not_contains "$body" 'Agent-Session:' 'unsafe session published' + rm "$meta" + OPENCODE_SESSION_ID= with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: absent session' || fail 'absent session commit failed' + body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + assert_not_contains "$body" 'Agent-Session:' 'absent session guessed' + done + pass 'OpenCode context and existing Polytoken metadata supply safe session references' } test_cursor_trailer_does_not_reach_the_commit_object() { @@ -632,6 +660,7 @@ test_push_guard_install_runs_the_guard_before_chaining() { test_scoped_keep_and_add test_scope_matching +test_recorded_sessions test_cursor_trailer_does_not_reach_the_commit_object test_commandcode_trailer_is_stripped test_human_coauthor_is_kept diff --git a/tests/fm-spawn-dispatch-profile.test.sh b/tests/fm-spawn-dispatch-profile.test.sh index 2f84568bb57..4628ce9e1b9 100755 --- a/tests/fm-spawn-dispatch-profile.test.sh +++ b/tests/fm-spawn-dispatch-profile.test.sh @@ -2391,7 +2391,6 @@ test_scoped_attribution_launches() { id="scoped-$runtime-$owner" rec=$(make_spawn_case "$id" "$runtime" "$id") read_case_record "$rec" - printf '%s\n' github.com/t27sol >"$HOME_DIR/config/keep-ai-trailers" git -C "$PROJ_DIR" remote set-url origin "git@github.com:$owner/example.git" # Keep fetch local while exposing the forge URL to scope resolution. git -C "$PROJ_DIR" config "url.file://$PROJ_DIR.origin.git.insteadOf" "git@github.com:$owner/example.git" @@ -2405,7 +2404,6 @@ test_scoped_attribution_launches() { body=$(git -C "$WT_DIR" log -1 --format=%B) if [ "$owner" = t27sol ]; then assert_contains "$body" "Agent-Platform: $runtime" 'scoped launch did not add platform' - assert_contains "$(cat "$HOME_DIR/data/$id/launch-brief.md")" 'Agent-System: fac:firstmate' 'missing PR attribution instruction' [ "$runtime" != claude ] || assert_attribution_policy_absent "$(cat "$LAUNCH_LOG")" 'scoped claude' else assert_not_contains "$body" 'noreply@anthropic.com' 'unlisted owner kept AI trailer' @@ -2414,7 +2412,64 @@ test_scoped_attribution_launches() { fi done done - pass 'Codex and Claude scoped launches add attribution only for listed owners' + pass 'Codex and Claude launches add t27sol attribution without a configuration file' +} + +test_opencode_session_attribution() { + local version rec id out status hooks + for version in 1.18.32 2.0.21; do + id="session-opencode-$version" + rec=$(make_spawn_case "$id" opencode "$id") + read_case_record "$rec" + git -C "$PROJ_DIR" remote set-url origin git@github.com:t27sol/example.git + git -C "$PROJ_DIR" config "url.file://$PROJ_DIR.origin.git.insteadOf" git@github.com:t27sol/example.git + out=$(FM_TEST_OPENCODE_VERSION=$version run_ship_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$id" "$PROJ_DIR") + status=$? + expect_code 0 "$status" "OpenCode $version spawn failed: $out" + hooks="$HOME_DIR/state/$id.git-hooks" + out=$(PLUGIN_PATH="$WT_DIR/.opencode/plugins/fm-busy-state.js" HOOKS_PATH="$hooks" WORKTREE="$WT_DIR" \ + OPENCODE_MAJOR=${version%%.*} node --input-type=module 2>&1 <<'JS' +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; +const mod = await import(pathToFileURL(process.env.PLUGIN_PATH).href); +const sid = "ses_abc123"; +const env = {}; +if (process.env.OPENCODE_MAJOR === "1") { + const hooks = await mod.FmBusyState({}); + await hooks.event({ event: { type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } } }); + await hooks["shell.env"]({ cwd: process.env.WORKTREE }, { env }); +} else { + let shellHook; + let deliver; + let delivered; + const consumed = new Promise(resolve => { delivered = resolve; }); + const stream = { + async *[Symbol.asyncIterator]() { + await new Promise(resolve => { deliver = resolve; }); + yield { type: "session.execution.started", properties: { sessionID: sid } }; + delivered(); + }, + }; + mod.default.setup({ + event: { subscribe: async () => stream }, + shell: { hook: (name, callback) => { assert.equal(name, "create.before"); shellHook = callback; } }, + }); + await new Promise(resolve => setImmediate(resolve)); + deliver(); + await consumed; + shellHook({ env }); +} +assert.equal(env.OPENCODE_SESSION_ID, sid); +const gitEnv = { ...process.env, ...env, GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "core.hooksPath", GIT_CONFIG_VALUE_0: process.env.HOOKS_PATH }; +execFileSync("git", ["-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-q", "--allow-empty", "-m", "fix: OpenCode session"], { cwd: process.env.WORKTREE, env: gitEnv }); +const message = execFileSync("git", ["log", "-1", "--format=%B"], { cwd: process.env.WORKTREE }); +const trailers = execFileSync("git", ["interpret-trailers", "--parse"], { input: message }).toString(); +assert.ok(trailers.split("\n").includes("Agent-Session: " + sid), trailers); +JS + ) || fail "OpenCode $version session attribution failed: $out" + done + pass 'OpenCode 1 and 2 plugin session contexts reach actual commit trailers' } test_keep_ai_trailers_omits_attribution_settings_and_strip_hooks() { @@ -3127,6 +3182,7 @@ test_codex_permission_does_not_change_other_harnesses() { } test_scoped_attribution_launches +test_opencode_session_attribution test_codex_permission_modes test_codex_permission_invalid_refuses_before_mutation test_codex_permission_does_not_change_other_harnesses From 9259b60db0a90ec42ecc1f6f60acd30ea47ed130 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:09:27 +1000 Subject: [PATCH 03/10] no-mistakes(review): Respect Git trailer boundaries when removing attribution --- bin/fm-git-attribution.py | 32 +++++++-- bin/fm-git-strip-ai-trailers.sh | 2 +- tests/fm-git-strip-ai-trailers.test.sh | 91 +++++++++++++++++++++++++- 3 files changed, 119 insertions(+), 6 deletions(-) diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index 5c7edab646c..8ac92cc5862 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -3,6 +3,7 @@ Usage: fm-git-attribution.py mode fm-git-attribution.py stamp + fm-git-attribution.py strip-fields t27sol GitHub repositories always receive attribution; elsewhere the legacy config presence flag means keep, and absence means strip. @@ -17,6 +18,28 @@ from urllib.parse import urlsplit UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", re.I) +SHARED_FIELDS = {"agent-system", "agent-platform", "agent-session"} + + +def remove_trailers(content, keys): + args = ["git", "interpret-trailers", "--only-input"] + block = subprocess.run(args + ["--only-trailers"], input=content, + capture_output=True, text=True, check=True).stdout + if not block: + return content + formatted = subprocess.run(args, input=content, capture_output=True, + text=True, check=True).stdout + divider = re.search(r"(?m)^---(?:[ \t]|\r?$)", formatted) + cursor = divider.start() if divider else len(formatted) + entries = re.findall(r"(?m)^[^\s][^\n]*(?:\n[ \t][^\n]*)*\n?", block) + for entry in reversed(entries): + start = formatted.rfind(entry, 0, cursor) + if start < 0: + raise ValueError("cannot locate Git-parsed trailer in message") + if entry.split(":", 1)[0].strip().lower() in keys: + formatted = formatted[:start] + formatted[start + len(entry):] + cursor = start + return formatted def t27sol(project): @@ -75,11 +98,8 @@ def stamp(task_meta, runtime, model, message): r"[a-zA-Z0-9][a-zA-Z0-9_.:/+-]*", model) or "://" in model: raise ValueError("unsafe runtime/model for Agent-Platform") path = Path(message) - lines = path.read_text().splitlines() # Replace our fields on amend/retry; retain existing co-authors. - lines = [line for line in lines if not re.match( - r"(?i)^(agent-system|agent-platform|agent-session):", line)] - content = "\n".join(lines).rstrip() + "\n" + content = remove_trailers(path.read_text(), SHARED_FIELDS) trailers = subprocess.run(["git", "interpret-trailers", "--parse"], input=content, capture_output=True, text=True, check=True).stdout.splitlines() sid = session(runtime, trailers, task_meta) @@ -113,6 +133,10 @@ def stamp(task_meta, runtime, model, message): print(mode(*sys.argv[2:])) elif len(sys.argv) == 6 and sys.argv[1] == "stamp": stamp(*sys.argv[2:]) + elif len(sys.argv) == 3 and sys.argv[1] == "strip-fields": + message = Path(sys.argv[2]) + message.write_text(remove_trailers( + message.read_text(), SHARED_FIELDS | {"claude-session"})) else: raise ValueError(__doc__) except (OSError, ValueError, subprocess.CalledProcessError) as exc: diff --git a/bin/fm-git-strip-ai-trailers.sh b/bin/fm-git-strip-ai-trailers.sh index 7f45f4619a2..fe6863fe0d8 100755 --- a/bin/fm-git-strip-ai-trailers.sh +++ b/bin/fm-git-strip-ai-trailers.sh @@ -121,7 +121,6 @@ fm_is_ai_attribution_line() { 'generated with [cortex code](https://docs.snowflake.com/'*')') return 0 ;; - agent-system:* | agent-platform:* | agent-session:*) return 0 ;; co-authored-by:*) ;; *) return 1 ;; esac @@ -156,6 +155,7 @@ strip_msgfile() { echo "error: commit message file not found: $src" >&2 return 1 } + python3 "${SELF%/*}/fm-git-attribution.py" strip-fields "$src" || return 1 tmp=$(mktemp "${TMPDIR:-/tmp}/fm-git-strip-ai-trailers.XXXXXX") || return 1 while IFS= read -r line || [ -n "$line" ]; do if fm_is_ai_attribution_line "$line"; then diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index 1d916448a12..3d797ff4afd 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -65,8 +65,10 @@ test_scoped_keep_and_add() { git -C "$repo" remote set-url origin https://github.com/t27sol-other/sample.git with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty \ -m 'fix: outside scope' --trailer "Co-authored-by: $runtime " \ - --trailer 'Co-authored-by: Claude ' + --trailer 'Co-authored-by: Claude ' \ + --trailer "Claude-Session: $session" body=$(git -C "$repo" log -1 --format=%B) + assert_not_contains "$body" 'Claude-Session:' 'outside scope kept native session' assert_not_contains "$body" 'Co-authored-by:' 'outside scope kept AI trailer' assert_not_contains "$body" 'Agent-System:' 'outside scope gained attribution' done @@ -133,6 +135,91 @@ test_recorded_sessions() { pass 'OpenCode context and existing Polytoken metadata supply safe session references' } +test_git_trailer_removal_preserves_message_body() { + local mode shape repo hooks msg prose native body parsed expected sid human + sid=11111111-2222-3333-4444-555555555555 + prose=$(printf '%s\n' 'fix: document attribution' '' \ + 'Agent-System: fac:example' 'Agent-Platform: codex/example' \ + 'Agent-Session: example-session' 'Claude-Session: example-native-session' \ + 'These are body examples followed by explanatory prose.') + human=$(printf '%s\n' 'Signed-off-by: Jane Doe ' \ + 'Co-authored-by: Jane Doe ' 'Reviewed-by: Review Team' 'Empty-Key: ') + native=$(printf '%s\n' 'Signed-off-by: Jane Doe ' \ + 'Co-authored-by: Jane Doe ' \ + 'Co-authored-by: Claude ' \ + 'Reviewed-by: Review' ' Team' 'Empty-Key:' \ + 'aGeNt-System : stale-system' ' stale-system-continuation' \ + 'Agent-Platform: stale-platform' ' stale-platform-continuation' \ + 'Agent-Session: stale-session' ' stale-session-continuation' "Claude-Session: $sid") + for mode in add strip fallback direct keep; do + for shape in trailered body-only; do + repo="$TMP_ROOT/body-$mode-$shape" hooks="$TMP_ROOT/body-hooks-$mode-$shape" + make_repo "$repo" + git -C "$repo" remote add origin https://github.com/t27sol/sample.git + case "$mode" in + add | fallback) "$STRIP" install --attribution "$TMP_ROOT/body.meta" codex fixture-model "$hooks" "$repo" || fail 'body attribution install failed' ;; + strip) "$STRIP" install "$hooks" "$repo" || fail 'body strip install failed' ;; + keep) "$STRIP" install --no-strip "$hooks" "$repo" || fail 'body keep install failed' ;; + esac + [ "$mode" = add ] || git -C "$repo" remote set-url origin https://github.com/another-owner/sample.git + msg="$repo/message" + printf '%s\n' "$prose" >"$msg" + [ "$shape" != trailered ] || printf '\n%s\n' "$native" >>"$msg" + if [ "$mode" = direct ]; then + "$STRIP" "$msg" || fail 'direct body strip failed' + git -C "$repo" commit -q --allow-empty -F "$msg" || fail 'direct body commit failed' + else + CODEX_THREAD_ID=$sid with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -F "$msg" || fail "$mode body commit failed" + fi + body=$(git -C "$repo" log -1 --format=%B) + assert_contains "$body" "$prose" "$mode $shape changed body examples" + parsed=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + if [ "$mode" = keep ]; then + if [ "$shape" = trailered ]; then + assert_contains "$parsed" "Claude-Session: $sid" 'keep removed native session' + assert_contains "$parsed" 'Agent-Session: stale-session stale-session-continuation' 'keep removed shared fields' + else + [ -z "$parsed" ] || fail 'body-only examples became trailers' + fi + continue + fi + expected= + if [ "$shape" = trailered ]; then + expected=$human + if [ "$mode" = add ]; then + expected=$(printf '%s\n' 'Signed-off-by: Jane Doe ' \ + 'Co-authored-by: Jane Doe ' \ + 'Co-authored-by: Claude ' \ + 'Reviewed-by: Review Team' 'Empty-Key: ' "Claude-Session: $sid") + fi + fi + if [ "$mode" = add ]; then + [ -z "$expected" ] || expected="$expected"$'\n' + expected="$expected"$(printf '%s\n' 'Co-authored-by: codex ' \ + 'Agent-System: fac:firstmate' 'Agent-Platform: codex/fixture-model') + [ "$shape" != body-only ] || expected="$expected"$'\n'"Agent-Session: $sid" + fi + [ "$parsed" = "$expected" ] || fail "$mode $shape changed parsed trailer meaning or order: $parsed" + CODEX_THREAD_ID=$sid with_hooks_env "$hooks" git -C "$repo" commit -q --amend --allow-empty --no-edit || fail "$mode amendment failed" + body=$(git -C "$repo" log -1 --format=%B) + assert_contains "$body" "$prose" "$mode amendment changed body examples" + done + done + pass 'Git trailer removal preserves body examples, folded native fields, empty fields and native order' +} + +test_strip_fields_preserves_patch_content() { + local msg patch expected + msg="$TMP_ROOT/patch-message" + patch=$(printf '%s\n' '---' 'Agent-System: patch-system' 'Agent-Platform: patch-platform' \ + 'Agent-Session: patch-session' 'Claude-Session: patch-session') + printf 'fix: patch message\n\nSigned-off-by: Jane Doe \nAgent-System: stale-system\nAgent-Platform: stale-platform\nAgent-Session: stale-session\nClaude-Session: stale-session\n\n%s\n' "$patch" >"$msg" + "$STRIP" "$msg" || fail 'patch message strip failed' + expected=$(printf 'fix: patch message\n\nSigned-off-by: Jane Doe \n\n%s' "$patch") + [ "$(cat "$msg")" = "$expected" ] || fail 'strip changed patch content or retained real attribution' + pass 'stripping respects Git trailer boundaries before a patch divider' +} + test_cursor_trailer_does_not_reach_the_commit_object() { local repo hooks body author repo="$TMP_ROOT/cursor-object" @@ -658,6 +745,8 @@ test_push_guard_install_runs_the_guard_before_chaining() { pass "install --push-guard writes a read-only pre-push that runs the guard before chaining" } +test_git_trailer_removal_preserves_message_body +test_strip_fields_preserves_patch_content test_scoped_keep_and_add test_scope_matching test_recorded_sessions From f4a446e68b1887a07a979240a71709be30dbf299 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:13:55 +1000 Subject: [PATCH 04/10] no-mistakes(review): Normalize trailing slashes before matching t27sol origins --- bin/fm-git-attribution.py | 2 +- tests/fm-git-strip-ai-trailers.test.sh | 30 ++++++++++++++++++++++---- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index 8ac92cc5862..f01b4826236 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -57,7 +57,7 @@ def t27sol(project): return False host, path = match.groups() return host.lower() == "github.com" and bool(re.fullmatch( - r"t27sol/[a-z0-9_.-]+", path.lower().removesuffix(".git"))) + r"t27sol/[a-z0-9_.-]+", path.lower().rstrip("/").removesuffix(".git"))) def mode(config, project): diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index 3d797ff4afd..b0748afd43c 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -76,18 +76,40 @@ test_scoped_keep_and_add() { } test_scope_matching() { - local config repo mode url model + local config repo mode url model hooks trailers expected config="$TMP_ROOT/legacy-flag" repo="$TMP_ROOT/scope-repo" make_repo "$repo" git -C "$repo" remote add origin https://github.com/t27sol/repo.git - for url in https://github.com/t27sol/repo.git ssh://git@github.com/t27sol/repo.git git@github.com:t27sol/repo.git https://github.com/T27SOL/Another.GIT; do + hooks="$TMP_ROOT/scope-matching-hooks" + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" codex default "$hooks" "$repo" || fail 'owner-matching hook install failed' + expected=$(printf '%s\n' 'Co-authored-by: Jane Doe ' \ + 'Co-authored-by: codex ' 'Agent-System: fac:firstmate' 'Agent-Platform: codex') + for url in https://github.com/t27sol/repo https://github.com/t27sol/repo/ \ + https://github.com/t27sol/repo.git https://github.com/t27sol/repo.git/ \ + ssh://git@github.com/t27sol/repo ssh://git@github.com/t27sol/repo/ \ + ssh://git@github.com/t27sol/repo.git ssh://git@github.com/t27sol/repo.git/ \ + git@github.com:t27sol/repo git@github.com:t27sol/repo/ \ + git@github.com:t27sol/repo.git git@github.com:t27sol/repo.git/ \ + https://github.com/T27SOL/Another.GIT https://github.com/T27SOL/Another.GIT///; do git -C "$repo" remote set-url origin "$url" mode=$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo") || fail 'owner resolution failed' - [ "$mode" = add ] || fail 't27sol owner did not match without configuration' + [ "$mode" = add ] || fail "t27sol owner did not match without configuration: $url" + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: equivalent origin' \ + --trailer 'Co-authored-by: Jane Doe ' || fail "commit failed for origin: $url" + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$trailers" = "$expected" ] || fail "equivalent origin changed committed attribution: $url" done - for url in https://github.com/t27sol-other/repo.git https://gitlab.com/t27sol/repo.git https://github.com/other/t27sol.git "$repo"; do + for url in https://github.com/t27sol-other/repo.git https://github.com/t27sol-other/repo.git/ \ + ssh://git@github.com/t27sol-other/repo.git/ git@github.com:t27sol-other/repo.git/ \ + https://gitlab.com/t27sol/repo.git https://gitlab.com/t27sol/repo.git/ \ + https://github.com/other/t27sol.git "$repo"; do git -C "$repo" remote set-url origin "$url" [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = strip ] || fail 'unrelated repository matched' + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: unrelated origin' \ + --trailer 'Co-authored-by: Claude ' \ + --trailer 'Co-authored-by: Jane Doe ' || fail 'unrelated origin commit failed' + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$trailers" = 'Co-authored-by: Jane Doe ' ] || fail "unrelated origin kept attribution: $url" done : >"$config" [ "$(python3 "$ROOT/bin/fm-git-attribution.py" mode "$config" "$repo")" = keep ] || fail 'legacy flag changed' From 414dd91188f58c72bad0cd25b511e5364c377cbe Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:19:34 +1000 Subject: [PATCH 05/10] no-mistakes(review): Validate models only when emitting attribution --- bin/fm-git-attribution.py | 7 ++-- tests/fm-git-strip-ai-trailers.test.sh | 52 ++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index f01b4826236..04f741f0630 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -94,9 +94,8 @@ def stamp(task_meta, runtime, model, message): subprocess.run([str(Path(__file__).with_name("fm-git-strip-ai-trailers.sh")), message], check=True) return # Runtime/model are launch metadata, never free-form trailer contents. - if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", runtime) or not re.fullmatch( - r"[a-zA-Z0-9][a-zA-Z0-9_.:/+-]*", model) or "://" in model: - raise ValueError("unsafe runtime/model for Agent-Platform") + if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", runtime): + raise ValueError("unsafe runtime for Agent-Platform") path = Path(message) # Replace our fields on amend/retry; retain existing co-authors. content = remove_trailers(path.read_text(), SHARED_FIELDS) @@ -109,6 +108,8 @@ def stamp(task_meta, runtime, model, message): # unresolved launch metadata, so it must not be presented as a model ID. platform = runtime if not runtime.startswith("claude") and model not in ("default", "auto"): + if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.:/+-]*", model) or "://" in model: + raise ValueError("unsafe model for Agent-Platform") platform += f"/{model}" args = ["git", "interpret-trailers", "--in-place"] if not coauthors: diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index b0748afd43c..4d173a17068 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -127,6 +127,57 @@ test_scope_matching() { pass 't27sol policy needs no configuration and preserves the legacy presence flag elsewhere' } +test_model_validation_follows_platform_emission() { + local repo hooks runtime model native expected trailers before + repo="$TMP_ROOT/model-emission" hooks="$TMP_ROOT/model-emission-hooks" + make_repo "$repo" + git -C "$repo" remote add origin https://github.com/t27sol/sample.git + native=$(printf '%s\n' 'Co-authored-by: Claude ' \ + 'Claude-Session: https://claude.ai/code/session_test123') + expected=$(printf '%s\nAgent-System: fac:firstmate\nAgent-Platform: claude' "$native") + for model in 'sonnet[1m]' 'opus[1m]' 'claude-sonnet-4-5@20250929' \ + 'claude-sonnet-4-5@20250929[1m]' sonnet default auto; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" claude "$model" "$hooks" "$repo" || fail 'Claude model hook install failed' + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: Claude model omission' -m "$native" \ + || fail "omitted Claude model blocked commit: $model" + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$trailers" = "$expected" ] || fail "Claude model changed trailer semantics: $model" + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty --amend --no-edit \ + || fail "omitted Claude model blocked amendment: $model" + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$trailers" = "$expected" ] || fail 'Claude amendment changed trailer semantics' + done + for model in fixture-model default auto; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" codex "$model" "$hooks" "$repo" || fail 'Codex model hook install failed' + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: platform model' || fail 'Codex model blocked commit' + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + expected=$(printf '%s\n' 'Co-authored-by: codex ' 'Agent-System: fac:firstmate') + if [ "$model" = fixture-model ]; then + expected="$expected"$'\n''Agent-Platform: codex/fixture-model' + else + expected="$expected"$'\n''Agent-Platform: codex' + fi + [ "$trailers" = "$expected" ] || fail 'known or unresolved model emission changed' + done + for model in 'unsafe model' 'https://provider.invalid/model' $'model\nAgent-System: injected'; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" codex "$model" "$hooks" "$repo" || fail 'unsafe-model hook install failed' + before=$(git -C "$repo" rev-parse HEAD) + if with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: refused model' >"$repo/refusal" 2>&1; then + fail 'unsafe emitted model was accepted' + fi + [ "$(git -C "$repo" rev-parse HEAD)" = "$before" ] || fail 'unsafe model created a commit' + done + for runtime in 'claude invalid' $'claude\nAgent-System: injected'; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" "$runtime" 'sonnet[1m]' "$hooks" "$repo" || fail 'unsafe-runtime hook install failed' + before=$(git -C "$repo" rev-parse HEAD) + if with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: refused runtime' >"$repo/refusal" 2>&1; then + fail 'Claude model omission bypassed runtime validation' + fi + [ "$(git -C "$repo" rev-parse HEAD)" = "$before" ] || fail 'unsafe runtime created a commit' + done + pass 'hook commits omit supported Claude model spellings while validating emitted models and runtimes' +} + test_recorded_sessions() { local runtime repo hooks meta sid body native for runtime in opencode polytoken; do @@ -771,6 +822,7 @@ test_git_trailer_removal_preserves_message_body test_strip_fields_preserves_patch_content test_scoped_keep_and_add test_scope_matching +test_model_validation_follows_platform_emission test_recorded_sessions test_cursor_trailer_does_not_reach_the_commit_object test_commandcode_trailer_is_stripped From 7199672d3b37a5a22f68bc3f4fbcb308ca715c53 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:29:51 +1000 Subject: [PATCH 06/10] no-mistakes(review): Preserve supported model selectors in attribution trailers --- bin/fm-git-attribution.py | 5 ++- docs/configuration.md | 3 +- tests/fm-git-strip-ai-trailers.test.sh | 57 ++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index 04f741f0630..39a44d269b4 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -108,7 +108,10 @@ def stamp(task_meta, runtime, model, message): # unresolved launch metadata, so it must not be presented as a model ID. platform = runtime if not runtime.startswith("claude") and model not in ("default", "auto"): - if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.:/+-]*", model) or "://" in model: + if (not model or any(c.isspace() or not c.isprintable() for c in model) + or model.startswith(("/", ".", "~")) or "\\" in model + or re.match(r"^[a-zA-Z]:/", model) or "://" in model + or any(part in (".", "..") for part in model.split("/"))): raise ValueError("unsafe model for Agent-Platform") platform += f"/{model}" args = ["git", "interpret-trailers", "--in-place"] diff --git a/docs/configuration.md b/docs/configuration.md index bd11469d7c0..978acbd1a19 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1822,7 +1822,8 @@ This applies only to agents Firstmate launches; the captain's own primary Firstm Workers in GitHub repositories owned by `t27sol` keep and receive commit attribution by default, even when `config/keep-ai-trailers` is absent. The owner match uses the project's `origin` remote over HTTPS, SSH URL or SCP syntax, case insensitively at the owner boundary. A matching task keeps existing AI co-authors and installs a commit hook that adds a runtime co-author when absent, `Agent-System: fac:firstmate`, and `Agent-Platform: [/]`. -The runtime is always included; a known model selected from the runtime's catalog is included only when permitted, with Claude Code model IDs and unresolved `default`/`auto` model choices omitted. +The runtime is always included; the selected launch model reference is included only when permitted, with Claude Code model IDs and unresolved `default`/`auto` model choices omitted. +Each runtime's existing selector and catalog contracts own model syntax and availability; attribution preserves safe references, including variant suffixes, while rejecting controls, whitespace, local paths, and URLs. The hook adds `Agent-Session` from a UUID `CODEX_THREAD_ID` for Codex when no native session trailer already carries the same reference. A UUID/public Claude session URL in the runtime's existing `Claude-Session` trailer already satisfies session attribution and is retained without adding a duplicate `Agent-Session`. OpenCode passes its existing plugin session identity to shell commands in memory, and Polytoken uses the existing task metadata's `polytoken_session` field. diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index 4d173a17068..98a87b6d961 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -178,6 +178,62 @@ test_model_validation_follows_platform_emission() { pass 'hook commits omit supported Claude model spellings while validating emitted models and runtimes' } +test_model_selectors_reach_commit_attribution() { + local repo hooks runtime model trailers expected native before + repo="$TMP_ROOT/model-selectors" hooks="$TMP_ROOT/model-selector-hooks" + make_repo "$repo" + git -C "$repo" remote add origin https://github.com/t27sol/sample.git + native='Co-authored-by: Jane Doe ' + while IFS='|' read -r runtime model; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" "$runtime" "$model" "$hooks" "$repo" || fail 'selector hook install failed' + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: model selector attribution' -m "$native" \ + || fail "safe launch selector blocked commit: $runtime $model" + expected=$(printf '%s\nCo-authored-by: %s \nAgent-System: fac:firstmate\nAgent-Platform: %s/%s' "$native" "$runtime" "$runtime" "$model") + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$trailers" = "$expected" ] || fail "selector changed committed trailer semantics: $runtime $model" + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty --amend --no-edit || fail 'selector amendment failed' + trailers=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$trailers" = "$expected" ] || fail 'selector amendment changed trailer semantics' + done <<'CASES' +opencode|openai/gpt-6.1-sol#high +opencode|fixture/native#proof +opencode|vertex/claude-sonnet-4-5@20250929[1m]#high +codex|gpt-6.1-sol +pi|codex-native/gpt-6.1-sol +pi-signed|codex-native/gpt-6.1-sol +omp|claude-bridge/claude-opus-4-7 +omp|*sonnet* +grok|grok-4 +kimi|kimi-code/k3-256k +cursor|cursor-grok-4.5-high-fast +agy|gemini-3.8-flash-high +muse|muse-spark-1.2-contributor +gemini|gemini-2.5-pro +rovo|gpt-5.6-sol +devin|swe-2-medium +commandcode|deepseek/deepseek-v4.1-flash +polytoken|zai/glm-5.3-flash +cortex|claude-sonnet-5-5 +CASES + for runtime in opencode codex; do + for model in '' 'unsafe model' $'model\nAgent-System: injected' $'model\rAgent-System: injected' \ + $'model\tvariant' $'model\001variant' $'model\033variant' $'model\177variant' \ + "model$(printf '\302\205')variant" "model$(printf '\342\200\250')variant" \ + '/private/secret' './secret' '../secret' '~/secret' 'provider/../../secret' \ + 'C:/Users/private/secret' 'C:\Users\private\secret' \ + 'https://private.invalid/model' 'file:///private/secret'; do + "$STRIP" install --attribution "$TMP_ROOT/absent.meta" "$runtime" "$model" "$hooks" "$repo" || fail 'unsafe-selector hook install failed' + before=$(git -C "$repo" rev-parse HEAD) + if with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: refused selector' >"$repo/refusal" 2>&1; then + fail 'unsafe or private selector was published' + fi + assert_contains "$(cat "$repo/refusal")" 'unsafe model' 'selector was refused for an unrelated reason' + [ "$(git -C "$repo" rev-parse HEAD)" = "$before" ] || fail 'unsafe selector created a commit' + done + done + pass 'runtime model references survive hook commits while controls, paths and URLs are refused' +} + test_recorded_sessions() { local runtime repo hooks meta sid body native for runtime in opencode polytoken; do @@ -823,6 +879,7 @@ test_strip_fields_preserves_patch_content test_scoped_keep_and_add test_scope_matching test_model_validation_follows_platform_emission +test_model_selectors_reach_commit_attribution test_recorded_sessions test_cursor_trailer_does_not_reach_the_commit_object test_commandcode_trailer_is_stripped From 28f588b011068e0e587864630980b5c7dab4a2c5 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:44:38 +1000 Subject: [PATCH 07/10] no-mistakes(review): Restrict coauthor removal to Git trailer blocks --- bin/fm-git-attribution.py | 33 +++++++++-- bin/fm-git-strip-ai-trailers.sh | 70 +---------------------- docs/configuration.md | 6 +- tests/fm-git-strip-ai-trailers.test.sh | 79 +++++++++++++++++++++++--- 4 files changed, 107 insertions(+), 81 deletions(-) diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index 39a44d269b4..79981846540 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -21,7 +21,24 @@ SHARED_FIELDS = {"agent-system", "agent-platform", "agent-session"} -def remove_trailers(content, keys): +def is_ai_coauthor(value): + name = value.strip().lower() + email = "" + if "<" in name and ">" in name.split("<", 1)[1]: + name, email = name.split("<", 1) + name = name.strip() + email = email.split(">", 1)[0].strip() + return (email.startswith("cursoragent@") or email in { + "noreply@firstmate.invalid", "noreply@anthropic.com", "noreply@openai.com", + "copilot@github.com", "noreply@commandcode.ai", "noreply@snowflake.com", + } or name in { + "cursor", "cursor agent", "claude", "claude code", "github copilot", "copilot", + "codex", "chatgpt", "gemini", "google gemini", "grok", "openai", "commandcodebot", + "snowflake coco", "cortex code", + }) + + +def remove_trailers(content, keys, strip_ai=False): args = ["git", "interpret-trailers", "--only-input"] block = subprocess.run(args + ["--only-trailers"], input=content, capture_output=True, text=True, check=True).stdout @@ -36,7 +53,11 @@ def remove_trailers(content, keys): start = formatted.rfind(entry, 0, cursor) if start < 0: raise ValueError("cannot locate Git-parsed trailer in message") - if entry.split(":", 1)[0].strip().lower() in keys: + key, _, value = entry.partition(":") + key = key.strip().lower() + value = " ".join(line.strip() for line in value.splitlines()) + if (key in keys or strip_ai and key == "co-authored-by" + and is_ai_coauthor(value)): formatted = formatted[:start] + formatted[start + len(entry):] cursor = start return formatted @@ -139,8 +160,12 @@ def stamp(task_meta, runtime, model, message): stamp(*sys.argv[2:]) elif len(sys.argv) == 3 and sys.argv[1] == "strip-fields": message = Path(sys.argv[2]) - message.write_text(remove_trailers( - message.read_text(), SHARED_FIELDS | {"claude-session"})) + content = remove_trailers( + message.read_text(), SHARED_FIELDS | {"claude-session"}, strip_ai=True) + message.write_text("".join(line for line in content.splitlines(keepends=True) + if not re.fullmatch( + r"generated with \[(?:snowflake coco|cortex code)\]" + r"\(https://docs\.snowflake\.com/.*\)", line.strip(), re.I))) else: raise ValueError(__doc__) except (OSError, ValueError, subprocess.CalledProcessError) as exc: diff --git a/bin/fm-git-strip-ai-trailers.sh b/bin/fm-git-strip-ai-trailers.sh index fe6863fe0d8..bcb51af9346 100755 --- a/bin/fm-git-strip-ai-trailers.sh +++ b/bin/fm-git-strip-ai-trailers.sh @@ -94,79 +94,13 @@ EOF exit 2 } -trim_space() { - local s=$1 - s=${s#"${s%%[![:space:]]*}"} - s=${s%"${s##*[![:space:]]}"} - printf '%s' "$s" -} - -# True when this line is an AI Co-Authored-By trailer that must not reach a -# commit object. Matches known product names and exact observed bot addresses only; an -# address is added when a runtime is seen emitting it, never guessed from a -# vendor domain, so a human co-author who works at a vendor is kept. A human -# whose name or address merely contains a substring such as "ai" is kept. -fm_is_ai_attribution_line() { - local raw=$1 lowered rest name email - raw=${raw%$'\r'} - raw=$(trim_space "$raw") - [ -n "$raw" ] || return 1 - lowered=$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]') - # Cortex Code (verified live, cortex 1.1.104) writes a `Generated with` line - # beside its Co-authored-by trailer, and its built-in /commit command writes - # the same line naming `Cortex Code`. Only these two exact link shapes are - # attribution; any other `Generated with` text is the author's own. - case "$lowered" in - 'generated with [snowflake coco](https://docs.snowflake.com/'*')' | \ - 'generated with [cortex code](https://docs.snowflake.com/'*')') - return 0 - ;; - co-authored-by:*) ;; - *) return 1 ;; - esac - rest=$(trim_space "${raw#*:}") - name=$rest - email= - case "$rest" in - *'<'*'>'*) - email=$(printf '%s' "$rest" | tr '[:upper:]' '[:lower:]') - email=${email#*'<'} - email=${email%%'>'*} - name=$(trim_space "${rest%%'<'*}") - ;; - esac - name=$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]') - case "$email" in - noreply@firstmate.invalid | noreply@anthropic.com | cursoragent@* | noreply@openai.com | copilot@github.com | noreply@commandcode.ai | noreply@snowflake.com) - return 0 - ;; - esac - case "$name" in - cursor | 'cursor agent' | claude | 'claude code' | 'github copilot' | copilot | codex | chatgpt | gemini | 'google gemini' | grok | openai | commandcodebot | 'snowflake coco' | 'cortex code') - return 0 - ;; - esac - return 1 -} - strip_msgfile() { - local src=$1 tmp + local src=$1 [ -f "$src" ] || { echo "error: commit message file not found: $src" >&2 return 1 } - python3 "${SELF%/*}/fm-git-attribution.py" strip-fields "$src" || return 1 - tmp=$(mktemp "${TMPDIR:-/tmp}/fm-git-strip-ai-trailers.XXXXXX") || return 1 - while IFS= read -r line || [ -n "$line" ]; do - if fm_is_ai_attribution_line "$line"; then - continue - fi - printf '%s\n' "$line" - done <"$src" >"$tmp" || { - rm -f "$tmp" - return 1 - } - mv "$tmp" "$src" + python3 "${SELF%/*}/fm-git-attribution.py" strip-fields "$src" } quote_for_hook() { diff --git a/docs/configuration.md b/docs/configuration.md index 978acbd1a19..374b18fcc61 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1830,7 +1830,8 @@ OpenCode passes its existing plugin session identity to shell commands in memory A session not yet available at commit time is omitted; other runtimes have no connected session source and omit it too. No additional persistent session record is created, and no local path, arbitrary hostname, credential, or guessed session is copied into the added fields. Amending a message replaces the shared fields rather than duplicating them; no trailer order is required and native runtime trailers retain their order within Git's parsed trailer block. -The hook rechecks the repository's origin for each commit, so an unrelated repository reached from the same pane still strips AI co-authors. +Hook selection is scoped to the launch repository; an attribution-enabled hook rechecks the commit repository's origin and strips attribution outside t27sol. +A worker launched outside t27sol that later commits in a t27sol submodule retains its launch repository's policy; adding attribution in that direction is an accepted limitation deferred to follow-up work. Focused synthetic regression coverage is in [`fm-git-strip-ai-trailers.test.sh`](../tests/fm-git-strip-ai-trailers.test.sh) and [`fm-spawn-dispatch-profile.test.sh`](../tests/fm-spawn-dispatch-profile.test.sh). Outside t27sol, the optional local, gitignored `config/keep-ai-trailers` retains its legacy home-wide presence-flag behavior; its contents do not select owners or repositories. With that flag absent outside t27sol, every Claude launch's session `--settings` value carries `"attribution":{"commit":"","pr":"","sessionUrl":false}`, every Devin worker config sets `"attribution": false`, and every fleet launch appends a worker-scoped `GIT_CONFIG` `core.hooksPath` entry pointing at `state/.git-hooks`, where git's `commit-msg` hook strips known AI trailers even when a runtime injects them after the typed message. @@ -1839,7 +1840,8 @@ T3 Code owns its provider command and cannot carry Claude's inline setting, but When the flag is present outside t27sol, Claude launches omit those attribution-off settings, Devin worker configs keep the user config's `attribution` setting (Devin's default is on), and fleet launches do not install or select the strip hooks, so Git uses the repository's configured hooks directly. Because the upstream prior-art push guard is installed only through those pane hooks, a shipping worker in a home with the flag present outside t27sol also skips that guard. Cortex Code has no attribution switch and its model writes a `Generated with Snowflake CoCo` line and a `Co-authored-by: Snowflake CoCo` trailer itself, so the strip hooks are the only mechanism that removes them from a Cortex worker's commits. -`bin/fm-git-strip-ai-trailers.sh` owns the identities, the install, and chaining the hooks of whichever repository git is running in, including when `git -c core.hooksPath` supplies the pane's hook override, so a project hook such as husky still runs when stripping is enabled. +`bin/fm-git-attribution.py` owns message filtering and stamping; known AI co-authors are removed only from Git's parsed trailer block, preserving body examples and human co-authors. +`bin/fm-git-strip-ai-trailers.sh` owns the install and chaining the hooks of whichever repository git is running in, including when `git -c core.hooksPath` supplies the pane's hook override, so a project hook such as husky still runs when stripping is enabled. A repository whose config sets `core.hooksPath` to the empty string runs no project hook, as in plain git; if the wrapper otherwise cannot resolve that repository's hooks directory, the git operation fails rather than silently skipping a project hook such as a pre-push guard. When stripping is enabled, the hooks directory is read-only, so a hook manager run inside a fleet pane (lefthook's npm postinstall, `pre-commit install`) fails instead of displacing the strip; install a project's hooks from outside the pane, where the wrappers chain them. The file is inherited into secondmate homes under the [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md) inherited-local-material contract, so its legacy keep behavior applies to a secondmate's own workers too. diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index 98a87b6d961..36ea5ad0310 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -270,6 +270,8 @@ test_git_trailer_removal_preserves_message_body() { prose=$(printf '%s\n' 'fix: document attribution' '' \ 'Agent-System: fac:example' 'Agent-Platform: codex/example' \ 'Agent-Session: example-session' 'Claude-Session: example-native-session' \ + 'Co-authored-by: pi ' \ + 'Co-authored-by: Jane Doe ' \ 'These are body examples followed by explanatory prose.') human=$(printf '%s\n' 'Signed-off-by: Jane Doe ' \ 'Co-authored-by: Jane Doe ' 'Reviewed-by: Review Team' 'Empty-Key: ') @@ -337,12 +339,77 @@ test_git_trailer_removal_preserves_message_body() { pass 'Git trailer removal preserves body examples, folded native fields, empty fields and native order' } +test_known_coauthors_respect_git_trailer_boundary() { + local mode repo hooks msg ai humans prose footer body parsed + ai=$(printf '%s\n' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Fixture ' \ + 'Co-authored-by: Cursor ' \ + 'Co-authored-by: Cursor Agent ' \ + 'Co-authored-by: Claude ' \ + 'Co-authored-by: Claude Code ' \ + 'Co-authored-by: GitHub Copilot ' \ + 'Co-authored-by: Copilot ' \ + 'Co-authored-by: Codex ' \ + 'Co-authored-by: ChatGPT ' \ + 'Co-authored-by: Gemini ' \ + 'Co-authored-by: Google Gemini ' \ + 'Co-authored-by: Grok ' \ + 'Co-authored-by: OpenAI ' \ + 'Co-authored-by: CommandCodeBot ' \ + 'Co-authored-by: Snowflake CoCo ' \ + 'Co-authored-by: Cortex Code ' \ + 'cO-AuThOrEd-By : pi' ' ') + humans=$(printf '%s\n' 'Co-authored-by: Jane Doe ' \ + 'Co-authored-by: Jane Doe ' \ + 'Co-authored-by: Sam Roe ' \ + 'Co-authored-by: Daisy ') + prose=$(printf 'fix: document co-authors\n\n%s\n%s\nThese are body examples followed by explanatory prose.' "$ai" "$humans") + footer=$(printf 'Signed-off-by: Jane Doe \n%s\n%s' "$ai" "$humans") + for mode in direct strip fallback; do + repo="$TMP_ROOT/coauthor-body-$mode" hooks="$TMP_ROOT/coauthor-hooks-$mode" + make_repo "$repo" + git -C "$repo" remote add origin https://github.com/t27sol/sample.git + case "$mode" in + strip) "$STRIP" install "$hooks" "$repo" || fail 'coauthor strip hook install failed' ;; + fallback) "$STRIP" install --attribution "$TMP_ROOT/coauthor.meta" claude default "$hooks" "$repo" || fail 'coauthor fallback hook install failed' ;; + esac + git -C "$repo" remote set-url origin https://github.com/another-owner/sample.git + msg="$repo/message" + printf '%s\n\n%s\n' "$prose" "$footer" >"$msg" + if [ "$mode" = direct ]; then + "$STRIP" "$msg" || fail 'direct coauthor strip failed' + git -C "$repo" commit -q --allow-empty -F "$msg" || fail 'direct coauthor commit failed' + else + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -F "$msg" || fail 'coauthor hook commit failed' + fi + body=$(git -C "$repo" log -1 --format=%B) + assert_contains "$body" "$prose" "$mode stripped a body coauthor example" + parsed=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$parsed" = "Signed-off-by: Jane Doe "$'\n'"$humans" ] || fail "$mode lost human coauthors or kept AI trailers: $parsed" + if [ "$mode" != direct ]; then + with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty --amend --no-edit || fail 'coauthor amendment failed' + body=$(git -C "$repo" log -1 --format=%B) + assert_contains "$body" "$prose" 'amendment stripped body coauthor examples' + parsed=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) + [ "$parsed" = "Signed-off-by: Jane Doe "$'\n'"$humans" ] || fail 'amendment changed human trailer semantics' + fi + done + pass 'known AI coauthors strip only from parsed trailers while body examples and human coauthors survive' +} + test_strip_fields_preserves_patch_content() { local msg patch expected msg="$TMP_ROOT/patch-message" patch=$(printf '%s\n' '---' 'Agent-System: patch-system' 'Agent-Platform: patch-platform' \ - 'Agent-Session: patch-session' 'Claude-Session: patch-session') - printf 'fix: patch message\n\nSigned-off-by: Jane Doe \nAgent-System: stale-system\nAgent-Platform: stale-platform\nAgent-Session: stale-session\nClaude-Session: stale-session\n\n%s\n' "$patch" >"$msg" + 'Agent-Session: patch-session' 'Claude-Session: patch-session' \ + 'Co-authored-by: pi ') + printf 'fix: patch message\n\nSigned-off-by: Jane Doe \nAgent-System: stale-system\nAgent-Platform: stale-platform\nAgent-Session: stale-session\nClaude-Session: stale-session\nCo-authored-by: pi \n\n%s\n' "$patch" >"$msg" "$STRIP" "$msg" || fail 'patch message strip failed' expected=$(printf 'fix: patch message\n\nSigned-off-by: Jane Doe \n\n%s' "$patch") [ "$(cat "$msg")" = "$expected" ] || fail 'strip changed patch content or retained real attribution' @@ -793,14 +860,11 @@ test_cortex_attribution_does_not_reach_the_commit_object() { "$STRIP" install "$hooks" "$repo" || fail "install should succeed" printf 'note\n' >>"$repo/README.md" git -C "$repo" add README.md - # The exact message Cortex Code 1.1.104 produced live: its typed -m body, - # a Generated with link line, then the Co-authored-by trailer. with_hooks_env "$hooks" git -C "$repo" commit -q \ -m 'probe commit' \ -m 'Generated with [Snowflake CoCo](https://docs.snowflake.com/en/user-guide/cortex-code/cortex-code)' \ - -m 'Co-authored-by: Snowflake CoCo ' \ - -m 'Co-authored-by: Jane Doe ' \ - -m 'Generated with care by a human, no link' + -m 'Generated with care by a human, no link' \ + -m $'Co-authored-by: Snowflake CoCo \nCo-authored-by: Jane Doe ' body=$(git -C "$repo" log -1 --format=%B) assert_not_contains "$body" "Snowflake CoCo" "Cortex attribution reached the commit object" assert_not_contains "$body" "noreply@snowflake.com" "Cortex bot address reached the commit object" @@ -874,6 +938,7 @@ test_push_guard_install_runs_the_guard_before_chaining() { pass "install --push-guard writes a read-only pre-push that runs the guard before chaining" } +test_known_coauthors_respect_git_trailer_boundary test_git_trailer_removal_preserves_message_body test_strip_fields_preserves_patch_content test_scoped_keep_and_add From 54e3da6cc04822cc4cd3f4faa79349894f668d03 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 07:57:45 +1000 Subject: [PATCH 08/10] no-mistakes(test): Fix OpenCode 2 native shell session attribution --- bin/fm-spawn.sh | 20 ++++- docs/verification/runtime-backends.md | 6 ++ tests/fm-opencode-primary-live-e2e.test.sh | 10 ++- tests/fm-spawn-dispatch-profile.test.sh | 29 +++++-- tests/opencode-v2-live-fixture.py | 88 +++++++++++++++++++++- 5 files changed, 141 insertions(+), 12 deletions(-) diff --git a/bin/fm-spawn.sh b/bin/fm-spawn.sh index b1e618bdae7..0bb260835ec 100755 --- a/bin/fm-spawn.sh +++ b/bin/fm-spawn.sh @@ -6442,6 +6442,14 @@ const makeHandler = (state) => { return async (event) => { const type = eventType(event); const id = sessionID(event); + if (type === "session.created") { + if (id) state.sessions.add(id); + return; + } + if (type === "session.deleted") { + state.sessions.delete(id); + return; + } if (type === "session.execution.started") { if (state.activeSession === null) state.activeSession = id; if (id === state.activeSession) await busyEvent("busy", "session-execution-started"); @@ -6478,13 +6486,17 @@ const makeHandler = (state) => { } }; }; +// Native session shell commands have no execution.started event. Use the +// sole known session when idle; do not guess between multiple sessions. +const shellSession = (state) => state.activeSession || + (state.sessions.size === 1 ? state.sessions.values().next().value : ""); export const FmBusyState = async () => { - const state = { activeSession: null }; + const state = { activeSession: null, sessions: new Set() }; const handleEvent = makeHandler(state); return { event: async ({ event }) => handleEvent(event), "shell.env": async (input, output) => { - output.env.OPENCODE_SESSION_ID = input.sessionID || state.activeSession || ""; + output.env.OPENCODE_SESSION_ID = input.sessionID || shellSession(state); }, }; }; @@ -6493,10 +6505,10 @@ export default { id: "fm.busy-state", server: FmBusyState, setup(ctx) { - const state = { activeSession: null }; + const state = { activeSession: null, sessions: new Set() }; setupEventSubscription(ctx, makeHandler(state)); ctx.shell.hook("create.before", (event) => { - event.env.OPENCODE_SESSION_ID = state.activeSession || ""; + event.env.OPENCODE_SESSION_ID = shellSession(state); }); }, }; diff --git a/docs/verification/runtime-backends.md b/docs/verification/runtime-backends.md index 1a558337f14..932ef4564bc 100644 --- a/docs/verification/runtime-backends.md +++ b/docs/verification/runtime-backends.md @@ -3564,6 +3564,12 @@ Repeat the hooked-worker check above before publication if watcher or task-inbox ## OpenCode 2 launch and brief delivery +Worker shell-session attribution verified on 2026-10-31 on macOS arm64 with OpenCode 2.0.21 using `FM_OPENCODE_WORKER_ATTRIBUTION_LIVE=1 bash tests/fm-opencode-primary-live-e2e.test.sh`, with that release on `PATH` and an isolated `TMPDIR`. +The native `/api/session/{id}/shell` endpoint made two commits without a model turn; Git's trailer parser confirmed each carried exactly the server-created session ID. +The run reported `ok - OpenCode 2.0.21 native shell commits retain session ses_e712f5450ffeETCOmls06wBpSJ without a model turn`. +The generated worker plugin retains known sessions in memory independently of busy-state tracking; an idle shell receives the sole known session, while ambiguous idle sessions omit the reference. +`tests/fm-spawn-dispatch-profile.test.sh` also covers active-turn identity, terminal-event clearing, ambiguous idle sessions and session deletion through the generated plugin and installed commit hook. + Verified on 2026-10-15 on Linux x86_64 against OpenCode 2.0.11 and 2.0.22, each installed into a scratch npm prefix with scratch `HOME`, XDG directories, and `OPENCODE_DB`, while the host's global OpenCode 1.18 stayed in place. The token-free native plugin fixture passed on both releases: diff --git a/tests/fm-opencode-primary-live-e2e.test.sh b/tests/fm-opencode-primary-live-e2e.test.sh index 66d79d93dd1..7f2eca2bb09 100755 --- a/tests/fm-opencode-primary-live-e2e.test.sh +++ b/tests/fm-opencode-primary-live-e2e.test.sh @@ -8,6 +8,8 @@ # named in FM_OPENCODE_LIVE_BINS (space-separated paths), or the `opencode` on # PATH when that is unset. An OpenCode 1.x executable is reported and skipped, # because the fixture exercises only the OpenCode 2 plugin surface. +# FM_OPENCODE_WORKER_ATTRIBUTION_LIVE=1 selects only native worker shell-session +# attribution, without the primary-plugin cases or model-provider fixture. # FM_OPENCODE_LIVE_E2E=1 selects the credentialed TUI half instead, against the # `opencode` on PATH, with the launch flags and session database queries of its # detected major. @@ -33,7 +35,13 @@ if [ "${FM_OPENCODE_LIVE_E2E:-0}" != 1 ]; then printf 'skip: %s reports %s, not OpenCode 2\n' "$bin" "$("$bin" --version 2>/dev/null || printf unknown)" continue fi - PATH="$(dirname "$bin"):$PATH" python3 "$fixture" || { + if [ "${FM_OPENCODE_WORKER_ATTRIBUTION_LIVE:-0}" != 1 ]; then + PATH="$(dirname "$bin"):$PATH" python3 "$fixture" || { + printf 'not ok - OpenCode %s native fixture failed\n' "$("$bin" --version)" >&2 + exit 1 + } + fi + PATH="$(dirname "$bin"):$PATH" python3 "$fixture" --worker-attribution || { printf 'not ok - OpenCode %s native fixture failed\n' "$("$bin" --version)" >&2 exit 1 } diff --git a/tests/fm-spawn-dispatch-profile.test.sh b/tests/fm-spawn-dispatch-profile.test.sh index 4628ce9e1b9..93cc85f2b72 100755 --- a/tests/fm-spawn-dispatch-profile.test.sh +++ b/tests/fm-spawn-dispatch-profile.test.sh @@ -2443,12 +2443,17 @@ if (process.env.OPENCODE_MAJOR === "1") { let shellHook; let deliver; let delivered; - const consumed = new Promise(resolve => { delivered = resolve; }); + const emit = async (event) => { + const consumed = new Promise(resolve => { delivered = resolve; }); + deliver(event); + await consumed; + }; const stream = { async *[Symbol.asyncIterator]() { - await new Promise(resolve => { deliver = resolve; }); - yield { type: "session.execution.started", properties: { sessionID: sid } }; - delivered(); + while (true) { + yield await new Promise(resolve => { deliver = resolve; }); + delivered(); + } }, }; mod.default.setup({ @@ -2456,8 +2461,20 @@ if (process.env.OPENCODE_MAJOR === "1") { shell: { hook: (name, callback) => { assert.equal(name, "create.before"); shellHook = callback; } }, }); await new Promise(resolve => setImmediate(resolve)); - deliver(); - await consumed; + // Native V2 session shell commands do not start a model turn. + await emit({ type: "session.created", data: { sessionID: sid } }); + shellHook({ env }); + assert.equal(env.OPENCODE_SESSION_ID, sid); + await emit({ type: "session.created", data: { sessionID: "ses_other" } }); + shellHook({ env }); + assert.equal(env.OPENCODE_SESSION_ID, "", "idle multi-session shells must not guess an identity"); + await emit({ type: "session.execution.started", data: { sessionID: sid } }); + shellHook({ env }); + assert.equal(env.OPENCODE_SESSION_ID, sid, "active-turn identity remains available"); + await emit({ type: "session.execution.succeeded", data: { sessionID: sid } }); + shellHook({ env }); + assert.equal(env.OPENCODE_SESSION_ID, "", "the completed turn must not leave a stale active identity"); + await emit({ type: "session.deleted", data: { sessionID: "ses_other" } }); shellHook({ env }); } assert.equal(env.OPENCODE_SESSION_ID, sid); diff --git a/tests/opencode-v2-live-fixture.py b/tests/opencode-v2-live-fixture.py index e4ecb425c4b..2519bdd0b7b 100644 --- a/tests/opencode-v2-live-fixture.py +++ b/tests/opencode-v2-live-fixture.py @@ -9,6 +9,7 @@ import shutil import socket import subprocess +import sys import tempfile import threading import time @@ -17,6 +18,88 @@ import urllib.request +def run_worker_attribution(lab): + """AGT-006: native shell commits carry their server-created session ID. + + The oracle is the session returned by the real HTTP API, compared with + Git-parsed trailers. No model-turn event is supplied to mask a missing ID. + """ + repo = Path(__file__).resolve().parent.parent + project = lab / "worker" + fmhome = lab / "fmhome" + hooks = fmhome / "state/native-session.git-hooks" + # Only the pane is simulated to obtain the actual generated worker plugin + # and installed hooks; shell execution below uses the native server. + subprocess.run(["bash", "-c", ''' +set -eu +. "$1/tests/fixtures.sh" +fm_test_spawn_home "$2/fmhome" opencode +fm_test_spawn_brief "$2/fmhome" native-session +fm_git_worktree "$2/project" "$2/worker" native-session +git -C "$2/project" remote set-url origin git@github.com:t27sol/example.git +git -C "$2/project" config "url.file://$2/project.origin.git.insteadOf" git@github.com:t27sol/example.git +fakebin=$(fm_test_make_spawn_fakebin "$2/fake") +FM_FAKE_LAUNCH_LOG="$2/launch.log" fm_test_run_spawn "$2/fmhome" "$2/worker" "$fakebin" \ + native-session "$2/project" --mode no-mistakes --yolo off +''', "worker-attribution", str(repo), str(lab)], check=True) + home = lab / "home" + home.mkdir() + env = {k: v for k, v in os.environ.items() if not k.startswith(("OPENCODE_", "FM_", "XDG_"))} + env.update(HOME=str(home), TMPDIR=str(lab), OPENCODE_DB=str(lab / "native.db"), OPENCODE_DISABLE_MODELS_FETCH="1", OPENCODE_DISABLE_AUTOUPDATE="1", OPENCODE_DISABLE_LSP_DOWNLOAD="1", GIT_CONFIG_COUNT="1", GIT_CONFIG_KEY_0="core.hooksPath", GIT_CONFIG_VALUE_0=str(hooks)) + for kind in ("CONFIG", "DATA", "CACHE", "STATE"): + path = home / kind.lower() + path.mkdir() + env[f"XDG_{kind}_HOME"] = str(path) + (project / "opencode.json").write_text(json.dumps({"snapshots": False, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}]})) + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + logpath = lab / "server.log" + headers = {"Content-Type": "application/json"} + + def api(path, body=None): + request = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=json.dumps(body).encode() if body is not None else None, headers=headers) + with urllib.request.urlopen(request, timeout=20) as response: + data = response.read() + return json.loads(data) if data else None + + def until(check, label): + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + value = check() + if value: + return value + time.sleep(0.1) + raise RuntimeError(f"Timed out: {label}\n{logpath.read_text()}") + + with logpath.open("w") as log: + process = subprocess.Popen(["opencode", "serve", "--hostname", "127.0.0.1", "--port", str(port)], cwd=project, env=env, stdout=log, stderr=log) + try: + password = until(lambda: next((s.removeprefix("server password ") for s in logpath.read_text().splitlines() if s.startswith("server password ")), None), "server readiness") + headers["Authorization"] = "Basic " + base64.b64encode(f"opencode:{password}".encode()).decode() + version = api("/api/info")["version"] + query = urllib.parse.urlencode({"location[directory]": str(project)}) + until(lambda: any(p["id"] == "fm.busy-state" and p["state"]["status"] == "active" for p in api("/api/plugin?" + query)["data"]), "generated worker plugin readiness") + sid = api("/api/session", {"location": {"directory": str(project)}, "agent": "build"})["data"]["id"] + for attempt in range(2): + before = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=project) + api(f"/api/session/{sid}/shell", {"command": f'git -c user.name=Fixture -c user.email=fixture@example.invalid commit -q --allow-empty -m "fix: native shell attribution {attempt}"'}) + until(lambda: subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=project) != before, "native shell commit") + message = subprocess.check_output(["git", "log", "-1", "--format=%B"], cwd=project) + trailers = subprocess.check_output(["git", "interpret-trailers", "--parse"], input=message).decode().splitlines() + assert trailers.count(f"Agent-Session: {sid}") == 1, (sid, trailers) + assert "Co-authored-by: opencode " in trailers, trailers + assert "Agent-Platform: opencode" in trailers, trailers + print(f"ok - OpenCode {version} native shell commits retain session {sid} without a model turn") + finally: + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + def run(lab): repo = Path(__file__).resolve().parent.parent project = lab / "project" @@ -207,5 +290,8 @@ def completed_context(): if __name__ == "__main__": with tempfile.TemporaryDirectory(prefix="fm-opencode-v2-live-") as directory: - run(Path(directory).resolve()) + if sys.argv[1:] == ["--worker-attribution"]: + run_worker_attribution(Path(directory).resolve()) + else: + run(Path(directory).resolve()) print("ok - private OpenCode server, provider, watcher, configuration and database cleaned") From cd583bcb00b87810934873ceac0bcb23848c2867 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 08:05:31 +1000 Subject: [PATCH 09/10] no-mistakes(document): Align commit attribution documentation with repository policy --- .../references/harness/commandcode.md | 2 +- .../harness-adapters/references/harness/cortex.md | 2 +- .../harness-adapters/references/harness/cursor.md | 2 +- .../harness-adapters/references/harness/devin.md | 2 +- .../harness-adapters/references/harness/polytoken.md | 2 +- .agents/skills/operational-home-layout/SKILL.md | 4 ++-- bin/fm-config-inherit-lib.sh | 4 ++-- bin/fm-devin-config.sh | 5 +++-- bin/fm-git-attribution.py | 8 ++++++-- bin/fm-git-strip-ai-trailers.sh | 11 ++++++----- bin/fm-spawn.sh | 12 ++++++------ docs/configuration.md | 7 ++++--- docs/scripts.md | 3 ++- docs/t3code-backend.md | 6 +++--- 14 files changed, 39 insertions(+), 31 deletions(-) diff --git a/.agents/skills/harness-adapters/references/harness/commandcode.md b/.agents/skills/harness-adapters/references/harness/commandcode.md index 3d0023aef29..a795d3d0859 100644 --- a/.agents/skills/harness-adapters/references/harness/commandcode.md +++ b/.agents/skills/harness-adapters/references/harness/commandcode.md @@ -19,7 +19,7 @@ The router owns the crewmate/scout-only boundary; primary and secondmate integra | Model discovery | `commandcode --list-models`; authentication preflight is `commandcode status`. | | Marker | None; the process title is the anchored name `command-code`, which identifies the adapter and outranks foreign inherited markers. | | Trust dialogs | `--trust` skips the fresh-worktree folder-trust prompt and `--yolo` bypasses permission prompts. | -| Commit attribution | Command Code adds `Co-authored-by: CommandCodeBot ` by default and only its settings files can turn that off, so the fleet commit-msg strip removes it unless the home sets `config/keep-ai-trailers` (`../../../docs/configuration.md` "Commit attribution"). | +| Commit attribution | Command Code adds `Co-authored-by: CommandCodeBot ` by default and only its settings files can turn that off; Firstmate applies the [commit attribution policy](../../../../../docs/configuration.md#commit-attribution) through Git hooks. | ## Per-process wiring limits diff --git a/.agents/skills/harness-adapters/references/harness/cortex.md b/.agents/skills/harness-adapters/references/harness/cortex.md index b7449a292cf..094bcfc3e71 100644 --- a/.agents/skills/harness-adapters/references/harness/cortex.md +++ b/.agents/skills/harness-adapters/references/harness/cortex.md @@ -21,7 +21,7 @@ The router owns the crewmate/scout-only boundary; primary and secondmate integra | Marker | None; anchored native `cortex` ancestry identifies the adapter and outranks foreign inherited markers. | | Trust dialogs | `--dangerously-allow-all-tool-calls` (alias `--bypass`) also skips the `Do you trust this project?` dialog and writes nothing to `~/.snowflake/cortex/cortex.json`; project hooks and settings still load. | | Imported config | Cortex loads Claude-compatible `~/.claude/settings.json` and project `.claude/settings.json` and `settings.local.json` hooks as well as its own `.cortex/` files, so a worker in a project with Claude hooks runs them; there is no switch to disable the import. | -| Commit attribution | The model, not a client setting, writes a `Generated with Snowflake CoCo` line and a `Co-authored-by: Snowflake CoCo ` trailer; the spawn-owned commit-msg strip (`../../../../../bin/fm-git-strip-ai-trailers.sh`) removes both unless the home sets `config/keep-ai-trailers`. | +| Commit attribution | The model, not a client setting, writes a `Generated with Snowflake CoCo` line and a `Co-authored-by: Snowflake CoCo ` trailer; Firstmate applies the [commit attribution policy](../../../../../docs/configuration.md#commit-attribution) through Git hooks. | ## Worker lifecycle limits diff --git a/.agents/skills/harness-adapters/references/harness/cursor.md b/.agents/skills/harness-adapters/references/harness/cursor.md index e6d20245981..2e91f702034 100644 --- a/.agents/skills/harness-adapters/references/harness/cursor.md +++ b/.agents/skills/harness-adapters/references/harness/cursor.md @@ -9,7 +9,7 @@ Cross-harness provider and credential identity is owned by `references/common/mo |---|---| | Binary | `fm_cursor_resolve_binary` in `../../../bin/fm-cursor-lib.sh` resolves stable launcher `cursor-agent` or legacy `agent`, never `cursor`, and accepts each candidate only after that owner's bounded launch probe (via `fm_run_timed`, so coreutils `timeout` is not required) so a broken preferred name falls through; both names normally symlink into `~/.local/share/cursor-agent/versions//cursor-agent`, whose target auto-update replaces. | | Launch | Positional instructions with `--trust`, `--yolo`, optional `--model `, and `--workspace `, after clearing foreign primary markers. | -| Attribution | Cursor can append a Co-authored-by trailer after the typed message. Unless the home sets `config/keep-ai-trailers` (`../../../../../docs/configuration.md` "Commit attribution"), every fleet launch installs the pane-scoped commit-msg strip in `../../../bin/fm-git-strip-ai-trailers.sh`, which removes known AI trailers and leaves human co-authors and the author identity untouched. | +| Attribution | Cursor can append a Co-authored-by trailer after the typed message; Firstmate applies the [commit attribution policy](../../../../../docs/configuration.md#commit-attribution). | | Models | Use current-account `cursor-agent --list-models` or legacy `agent --list-models`; the drifting observed list had only `cursor-grok-4.5-high` and `cursor-grok-4.5-high-fast` for Grok plus several `xhigh` ids, so choose a returned reasoning id and never assume low or medium Grok. | | Busy state | `../../../bin/fm-busy-lib.sh` folds the per-conversation transcript as `cursor-transcript`: `role:user` opens and typed `turn_ended` closes success or abort, covering manual interrupt; nothing is armed or seeded, and this backend-agnostic source was identical on tmux and Herdr. | | Exit command | `/exit`. | diff --git a/.agents/skills/harness-adapters/references/harness/devin.md b/.agents/skills/harness-adapters/references/harness/devin.md index c90e3e93364..ab0bbc58c9c 100644 --- a/.agents/skills/harness-adapters/references/harness/devin.md +++ b/.agents/skills/harness-adapters/references/harness/devin.md @@ -19,7 +19,7 @@ The router owns the crewmate/scout-only boundary; primary and secondmate integra | Marker | None; anchored native `devin` ancestry identifies the adapter and outranks foreign inherited markers. | | Trust dialogs | The launch skips workspace trust for this run; the spawn owner carries the exact flags. | | Imported config | The worker config sets `read_config_from.claude` false, so no Claude Code hook, `CLAUDE.md` rule, `.claude/skills`, or Claude MCP entry is imported; `AGENTS.md` and `.agents/skills` still load. | -| Commit attribution | Unless the home sets `config/keep-ai-trailers` (`../../../../../docs/configuration.md` "Commit attribution"), the worker config sets `attribution` false, Devin's switch for its `Co-Authored-By` trailer and `Generated with Devin` line; with the flag, the user config's setting (default on) is kept. | +| Commit attribution | The private worker config applies the [commit attribution policy](../../../../../docs/configuration.md#commit-attribution); `fm-devin-config.sh` owns the enforced settings. | ## Worker lifecycle limits diff --git a/.agents/skills/harness-adapters/references/harness/polytoken.md b/.agents/skills/harness-adapters/references/harness/polytoken.md index 137adff6e2d..71f3191a67b 100644 --- a/.agents/skills/harness-adapters/references/harness/polytoken.md +++ b/.agents/skills/harness-adapters/references/harness/polytoken.md @@ -20,7 +20,7 @@ The router owns the crewmate/scout-only boundary; primary and secondmate integra | Marker | None; the daemon's anchored `polytoken` comm in tool-subprocess ancestry identifies the adapter (a tool subprocess's parent IS the daemon, verified live), and a structural polytoken ancestor outranks foreign inherited markers. | | Trust dialogs | None at launch: the permission posture comes from the generated config dir under [`fm_polytoken_write_config`'s policy](../../../../../bin/fm-polytoken-lib.sh), and the first-start license dialog requires an operator decision - `--accept-license-terms` is never passed, and the readiness gate fails loudly on a pane that never starts processing its brief. | | Imported config | The worktree `.polytoken/` project layer (hooks and facets) plus the generated per-task config dir, which fully replaces the global config (verified live: a `version: 4`-only project config.yaml fails startup with zero providers, and no `--global-config-dir` reaches the daemon). | -| Commit attribution | The shared `state/.git-hooks` commit-msg strip covers polytoken like every launched runtime. | +| Commit attribution | The shared Git hooks apply the [commit attribution policy](../../../../../docs/configuration.md#commit-attribution). | ## Worker lifecycle limits diff --git a/.agents/skills/operational-home-layout/SKILL.md b/.agents/skills/operational-home-layout/SKILL.md index 0270091258f..ffe330f6f34 100644 --- a/.agents/skills/operational-home-layout/SKILL.md +++ b/.agents/skills/operational-home-layout/SKILL.md @@ -35,7 +35,7 @@ config/backend runtime session-provider backend override for new tasks; LOCAL, config/t3code-token LOCAL, gitignored T3 Code mcp-client credential; docs/t3code-backend.md "Sign-in" owns minting, expiry, and secondmate linking config/t3code-instances LOCAL, gitignored, inherited T3 provider-instance map; docs/t3code-backend.md "Provider instances and models" owns schema and catalog validation config/calm Calm presentation preference shared by the Pi extension and the Claude Code mod; LOCAL, gitignored, and not inherited; see docs/configuration.md "Calm preference" -config/keep-ai-trailers optional presence flag to keep AI co-author trailers in this home's fleet commits; LOCAL, gitignored; inherited by secondmate homes; see docs/configuration.md "Commit attribution" +config/keep-ai-trailers optional commit-attribution flag; LOCAL, gitignored; inherited by secondmate homes; docs/configuration.md "Commit attribution" owns its policy config/supervision-branch-model config/supervision-branch-effort Pi supervision-branch model and reasoning-effort pins written by /supervision-model; LOCAL, gitignored, independently settable, and not inherited; see docs/configuration.md "Pi supervision branch model and effort" config/supervision-host optional supervision-host engine setting: the host runs the supervision branch's contract on a headless engine beside a non-Pi primary, away and, on a Claude or Cursor primary, attended; absent runs it on a Claude primary and nowhere else; LOCAL, gitignored, not inherited; see docs/configuration.md "Supervision host" config/supervision-host-off optional presence flag opting this home out of the supervision host on every primary; LOCAL, gitignored; inherited by secondmate homes under the primary-authoritative contract; see docs/configuration.md "Supervision host" @@ -98,7 +98,7 @@ state/ runtime records and signals; gitignored .cortex-plugin/ firstmate-owned per-task Cortex Code plugin directory (mode 700; busy-state hooks and Herdr pane registration) passed through --plugin-dir so no user or project config is edited; bin/fm-cortex-plugin.sh owns it; removed by teardown .muse-session muse busy-source binding (sessions root plus task worktree) written by fm-spawn; removed by teardown .cursor-session cursor busy-source binding (projects root, task worktree, prior conversations) written by fm-spawn; removed by teardown - .git-hooks/ per-task git hooksPath that strips AI commit trailers at the commit object unless config/keep-ai-trailers is present; written by fm-spawn, removed by teardown (bin/fm-git-strip-ai-trailers.sh) + .git-hooks/ per-task git hooksPath for the commit attribution policy and push guards; written by fm-spawn, removed by teardown (bin/fm-git-strip-ai-trailers.sh); docs/configuration.md "Commit attribution" owns selection .reconcile-nudged epoch second of the last inventory-reconcile nudge sent to this secondmate; bin/fm-secondmate-reconcile.sh owns its per-home cooldown window .ready-timeout durable record that the opt-in ready-session timeout stopped (or failed to stop) this ship worker's idle agent while its PR awaited merge; while a `stopped` record names the current spawn_gen and crew state still reads done the worker is deliberately stopped, not stuck, and relaunches on demand; bin/fm-ready-timeout-lib.sh owns it; removed by teardown .backlog-close the exact backlog transition a teardown recorded before removing the task's record, so an interrupted cleanup can still be finished at the next session start; bin/fm-backlog-transition-lib.sh owns its format and replay, and a landed transition removes it diff --git a/bin/fm-config-inherit-lib.sh b/bin/fm-config-inherit-lib.sh index e129bf9a6db..1cc3c13cd0c 100644 --- a/bin/fm-config-inherit-lib.sh +++ b/bin/fm-config-inherit-lib.sh @@ -28,8 +28,8 @@ # declared configuration. # Primary config/t3code-instances selects the T3 provider account for each # harness, so secondmates inherit it rather than falling back to a default. -# Primary config/keep-ai-trailers is a home-wide commit-attribution choice, so -# a secondmate's own crewmates keep AI co-author trailers too. +# Primary config/keep-ai-trailers propagates the legacy attribution preference; +# docs/configuration.md "Commit attribution" owns its policy. # Primary config/supervision-host-off is the fleet's supervision-host opt-out, # so a primary that opts out opts every secondmate home out too, while each # home's config/supervision-host engine line stays its own. diff --git a/bin/fm-devin-config.sh b/bin/fm-devin-config.sh index db43e7e3637..16b34117fe8 100755 --- a/bin/fm-devin-config.sh +++ b/bin/fm-devin-config.sh @@ -12,8 +12,9 @@ # and Claude MCP imports, while AGENTS.md and .agents/skills still load. # attribution=false is forced too, because Devin otherwise adds a # Co-Authored-By: Devin trailer and a Generated with Devin line to commits -# and PRs, unless FM_KEEP_AI_TRAILERS=1 (fm-spawn sets it when the home has -# config/keep-ai-trailers); then the source's attribution setting is kept. +# and PRs, unless FM_KEEP_AI_TRAILERS=1; then the source's attribution setting +# is kept. fm-spawn resolves that value under docs/configuration.md's +# "Commit attribution" policy. # UserPromptSubmit opens a turn; Stop and SessionEnd close it. Devin 3000.11.1 # emits no Stop on double-Escape cancellation, so fm-control invalidates its # state to unknown after delivering that interrupt, never fabricating idle. diff --git a/bin/fm-git-attribution.py b/bin/fm-git-attribution.py index 79981846540..ae81999df4d 100755 --- a/bin/fm-git-attribution.py +++ b/bin/fm-git-attribution.py @@ -5,8 +5,8 @@ fm-git-attribution.py stamp fm-git-attribution.py strip-fields -t27sol GitHub repositories always receive attribution; elsewhere the legacy -config presence flag means keep, and absence means strip. +docs/configuration.md "Commit attribution" owns launch-repository selection +and its accepted cross-repository limitation. Stamp runs in Git's hook cwd and rechecks origin. Session references come from runtime context or existing task metadata, never a new persistent record. """ @@ -22,6 +22,8 @@ def is_ai_coauthor(value): + # Match known product names and observed bot addresses, never vendor domains + # or name substrings, so human co-authors employed by vendors remain. name = value.strip().lower() email = "" if "<" in name and ">" in name.split("<", 1)[1]: @@ -162,6 +164,8 @@ def stamp(task_meta, runtime, model, message): message = Path(sys.argv[2]) content = remove_trailers( message.read_text(), SHARED_FIELDS | {"claude-session"}, strip_ai=True) + # Only the observed Cortex link forms count as generated attribution; + # other "Generated with" prose belongs to the author. message.write_text("".join(line for line in content.splitlines(keepends=True) if not re.fullmatch( r"generated with \[(?:snowflake coco|cortex code)\]" diff --git a/bin/fm-git-strip-ai-trailers.sh b/bin/fm-git-strip-ai-trailers.sh index bcb51af9346..b20a9e728c9 100755 --- a/bin/fm-git-strip-ai-trailers.sh +++ b/bin/fm-git-strip-ai-trailers.sh @@ -46,9 +46,10 @@ # git's pre-push arguments and stdin; a refusal stops the push, and a # pass chains to the repository's own pre-push with the same stdin. # -# WHY THIS EXISTS. Claude launches already carry attribution-off in their -# per-launch --settings JSON. Cursor and other non-Claude runtimes inject a -# Co-Authored-By trailer at the tooling layer AFTER the worker types a clean +# WHY THIS EXISTS. When stripping is selected under docs/configuration.md's +# "Commit attribution" policy, Claude launches already carry attribution-off +# in their per-launch --settings JSON. Cursor and other non-Claude runtimes +# inject a Co-Authored-By trailer at the tooling layer AFTER the worker types a clean # message, so the typed message is not the commit object. # A prior per-machine ~/.cursor/cli-config.json attribution-off is not durable: # it does not travel with Firstmate, it defaults back to on when unset, and it @@ -68,8 +69,8 @@ # writes the commit object without running git. Both incidents that motivated # this strip came through an ordinary hook-running commit, so the ruling is to # accept that gap rather than add a push-side rewrite or a push-side check. A -# trailer found on a fleet commit therefore points at one of those two paths, -# not at an unnoticed hole in the matcher. +# trailer found on a stripping worker's commit therefore points at one of +# those two paths, not at an unnoticed hole in the matcher. # # ACCEPTED RESIDUAL, ruled 2026-09-17. Inside a fleet pane git reports this # directory as the repository's hooks directory, so a hook manager run there diff --git a/bin/fm-spawn.sh b/bin/fm-spawn.sh index 0bb260835ec..ef10f61c751 100755 --- a/bin/fm-spawn.sh +++ b/bin/fm-spawn.sh @@ -664,7 +664,7 @@ # state/.git-hooks as an appended GIT_CONFIG core.hooksPath entry for the pane, so git # commit-msg strips known AI trailers at the commit object for every launched # runtime, Claude included as defense in depth. bin/fm-git-strip-ai-trailers.sh -# owns the identities, the hook install, and chaining the repository git is +# owns the hook install and chaining the repository git is # actually running in so a project husky hook still runs. Author identity is # not rewritten. A forge=external ship installs that directory even under # config/keep-ai-trailers, because its pre-push wrapper carries the push guard. @@ -6838,18 +6838,18 @@ EOF ;; esac -# Per-task git hooksPath that strips AI commit trailers at the commit object. -# Installed for every kind, including secondmate, unless the home opts in to -# keeping trailers. Cursor and other non-Claude runtimes inject the trailer +# Per-task git hooksPath selected by docs/configuration.md's "Commit attribution" +# policy, for every kind including secondmate. +# Cursor and other non-Claude runtimes inject the trailer # after the typed message, so the typed message is not the object. When # installed, the pane receives this directory via GIT_CONFIG_* below, which # overrides a project's husky core.hooksPath without rewriting it; the installer # chains the previous hooks so they still run. Real secondmate # homes are firstmate clones; a launch whose worktree is not git fails closed -# rather than shipping a runtime that cannot strip. +# rather than shipping a runtime without its required hooks. # A forge=external ship always gets this directory, because its pre-push # wrapper carries the guard that keeps task branches off the shared origin; a -# home that keeps trailers gets a commit-msg wrapper that only chains. +# legacy keep launch gets a commit-msg wrapper that only chains. GIT_HOOKS_DIR="$STATE_REAL/$ID.git-hooks" GIT_HOOKS_INSTALLED=0 if [ "$EXTERNAL_REVIEW" = 1 ]; then diff --git a/docs/configuration.md b/docs/configuration.md index 374b18fcc61..55d3542a804 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1837,13 +1837,14 @@ Outside t27sol, the optional local, gitignored `config/keep-ai-trailers` retains With that flag absent outside t27sol, every Claude launch's session `--settings` value carries `"attribution":{"commit":"","pr":"","sessionUrl":false}`, every Devin worker config sets `"attribution": false`, and every fleet launch appends a worker-scoped `GIT_CONFIG` `core.hooksPath` entry pointing at `state/.git-hooks`, where git's `commit-msg` hook strips known AI trailers even when a runtime injects them after the typed message. The entry follows any `GIT_CONFIG_*` entries the worker inherits, so an inherited scoped `credential.helper` still applies to the worker and to the repository's own hooks, such as a git-lfs `pre-push`; an inherited `GIT_CONFIG_COUNT` that is not a decimal number, or that leaves no room for another entry within Git's signed int, stops the launch before the worker runs. T3 Code owns its provider command and cannot carry Claude's inline setting, but its per-worktree environment overlay selects the same Git hook; [`t3code-backend.md`](t3code-backend.md#active-limits) owns that backend limit. -When the flag is present outside t27sol, Claude launches omit those attribution-off settings, Devin worker configs keep the user config's `attribution` setting (Devin's default is on), and fleet launches do not install or select the strip hooks, so Git uses the repository's configured hooks directly. -Because the upstream prior-art push guard is installed only through those pane hooks, a shipping worker in a home with the flag present outside t27sol also skips that guard. +When the flag is present outside t27sol, Claude launches omit those attribution-off settings and Devin worker configs keep the user config's `attribution` setting (Devin's default is on). +Fleet launches then use the repository's configured hooks directly, except that a [`forge=external`](external-review-forge.md) ship still installs the wrappers for its push guard without stripping attribution. +Because the upstream prior-art push guard is installed only through those pane hooks, a non-external shipping worker in a home with the flag present outside t27sol also skips that guard. Cortex Code has no attribution switch and its model writes a `Generated with Snowflake CoCo` line and a `Co-authored-by: Snowflake CoCo` trailer itself, so the strip hooks are the only mechanism that removes them from a Cortex worker's commits. `bin/fm-git-attribution.py` owns message filtering and stamping; known AI co-authors are removed only from Git's parsed trailer block, preserving body examples and human co-authors. `bin/fm-git-strip-ai-trailers.sh` owns the install and chaining the hooks of whichever repository git is running in, including when `git -c core.hooksPath` supplies the pane's hook override, so a project hook such as husky still runs when stripping is enabled. A repository whose config sets `core.hooksPath` to the empty string runs no project hook, as in plain git; if the wrapper otherwise cannot resolve that repository's hooks directory, the git operation fails rather than silently skipping a project hook such as a pre-push guard. -When stripping is enabled, the hooks directory is read-only, so a hook manager run inside a fleet pane (lefthook's npm postinstall, `pre-commit install`) fails instead of displacing the strip; install a project's hooks from outside the pane, where the wrappers chain them. +Whenever installed, the hooks directory is read-only, so a hook manager run inside a fleet pane (lefthook's npm postinstall, `pre-commit install`) fails instead of displacing the wrappers; install a project's hooks from outside the pane, where the wrappers chain them. The file is inherited into secondmate homes under the [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md) inherited-local-material contract, so its legacy keep behavior applies to a secondmate's own workers too. Per-machine Cursor `cli-config.json` attribution-off is not this contract: it does not travel with Firstmate, defaults back to on when unset, and only feeds the CLI's request to the server, so it suppresses the trailer rather than preventing it. diff --git a/docs/scripts.md b/docs/scripts.md index e6183016586..e7d5d479ff3 100644 --- a/docs/scripts.md +++ b/docs/scripts.md @@ -74,7 +74,8 @@ The shared no-mistakes gate lifecycle boundary is summarized in [architecture.md | [`fm-project-origin-lib.sh`](../bin/fm-project-origin-lib.sh) | Accepted origin-form owner shared by both remote provisioning boundaries | | `fm-spawn.sh` | Spawn crewmates, scouts, `id=repo` batches, and secondmates on the resolved harness and runtime backend | | [`fm-approval-failover.sh`](../bin/fm-approval-failover.sh) | Save a captain-approved managed-approval fallback and recover a worker after observed defeated bypass | -| `fm-git-strip-ai-trailers.sh` | Strip known AI commit trailers at commit-msg time and install that hook, plus any forge=external push guard, for a fleet launch | +| `fm-git-attribution.py` | Resolve commit attribution policy and filter or stamp Git-parsed trailers | +| `fm-git-strip-ai-trailers.sh` | Install commit attribution hooks and push guards for a fleet launch | | `fm-git-push-guard.sh` | Refuse a forge=external task's pushes to the shared origin and of task-prefixed branches, and write its per-task guard record ([design](external-review-forge.md)) | | `fm-backend.sh` | Runtime-backend selection, meta helpers, selector resolution, and operation dispatch | | `fm-backend-hometag-lib.sh` | Shared per-installation home-tag derivation for zellij tab, cmux workspace, and tern session titles | diff --git a/docs/t3code-backend.md b/docs/t3code-backend.md index 05a142791d9..9889185d5cd 100644 --- a/docs/t3code-backend.md +++ b/docs/t3code-backend.md @@ -97,10 +97,10 @@ The normal isolation and unlanded-work refusal rules still apply. T3 sets environment variables per provider instance, never per thread, so nothing can be typed into a pane before launch. Each harness reads its own configuration from the thread's working directory instead, and Firstmate writes the facts a pane would have exported into that directory before the launch turn. For `claude` that is an `env` block in the directory's `.claude/settings.local.json`, merged alongside the busy hooks a worker already carries there; for `codex` it is a `.codex/config.toml` holding a `[shell_environment_policy]` `set` table. -Codex applies that file only in a project it [trusts](#setup); in an untrusted project a Codex thread runs without any of these values, so its Git hook entry, and with it the AI-trailer strip and a `forge=external` ship's push guard, does not apply; Firstmate warns at spawn when it cannot confirm that trust, but never grants it. +Codex applies that file only in a project it [trusts](#setup); in an untrusted project a Codex thread runs without any of these values, so its Git hook entry, and with it the [commit attribution policy](configuration.md#commit-attribution) and a `forge=external` ship's push guard, does not apply; Firstmate warns at spawn when it cannot confirm that trust, but never grants it. The Claude `env` block keeps entries Firstmate did not write, such as a secondmate home's own, and lists the keys Firstmate wrote in `FM_T3CODE_ENV_KEYS` so a respawn replaces exactly those; a symlinked `.claude/settings.local.json` is refused. The thread's `GIT_CONFIG_*` entries are Firstmate's own `core.hooksPath` hook entry only: inherited `GIT_CONFIG_*` values, or any other inherited environment value, are never written to these files, because they can carry credentials. -That entry sets `GIT_CONFIG_COUNT=1` and index 0, so numbered `GIT_CONFIG_KEY_`/`GIT_CONFIG_VALUE_` entries in the T3 server's environment do not apply in the thread; with `config/keep-ai-trailers` no hook entry is written and they apply unchanged, except on a [`forge=external`](external-review-forge.md) ship, whose push guard always installs the hook entry. +That entry sets `GIT_CONFIG_COUNT=1` and index 0, so numbered `GIT_CONFIG_KEY_`/`GIT_CONFIG_VALUE_` entries in the T3 server's environment do not apply in the thread; when neither the [commit attribution policy](configuration.md#commit-attribution) nor a [`forge=external`](external-review-forge.md) push guard requires a hook entry, those inherited entries apply unchanged. A T3 server whose agents need extra Git config, such as a `credential.helper`, supplies it through Git config files, which the hook entry leaves alone: for example the service user's global config, or `GIT_CONFIG_GLOBAL` in its service environment. Firstmate-created untracked environment files are git-excluded and removed at teardown; in a secondmate home, teardown removes only the keys `FM_T3CODE_ENV_KEYS` lists from the home's own `.claude/settings.local.json`. An existing untracked `.codex/config.toml` without Firstmate's marker is preserved and refused. @@ -262,7 +262,7 @@ If a task's thread no longer reads back, release the task by hand: - T3 Code remains experimental and runs only `claude` and `codex`. - T3 starts the agent at `full-access` with its provider instance's account and environment, so a spawn refuses `config/claude-permission-mode=auto` for `claude`, `config/codex-approval-mode=approve-for-me` or `config/codex-permission-mode=restricted` for `codex`, `config/launch-env-allowlist`, a worker account pin, `--seat`, and a raw launch command; select the account through `config/t3code-instances` instead. - T3 owns the Claude provider command, so Firstmate cannot add its command-line prompt-suggestion, feedback-draft, or attribution controls; configure equivalent provider-instance settings in T3 when those policies are required. - Unless `config/keep-ai-trailers` is present, the per-worktree environment selects Firstmate's Git commit hook to strip known AI trailers, including on T3 workers. + The per-worktree environment carries Firstmate's [commit attribution policy](configuration.md#commit-attribution) through Git hooks. - T3 also owns the Codex provider command, so Firstmate cannot apply the pane-backed worker's hook-disable or turn-end notify options. Firstmate's pane-backed hook-trust workaround therefore does not apply; supervision uses T3's [thread status table](#restart-and-liveness-behavior). - `fm-control.sh exit` is refused because the V2 `/mcp` tools have no session stop, and `relaunch` is refused because a thread keeps its conversation, so no fresh agent can replace it. From e2fbd08fa6d7291268474108087377a804f8e910 Mon Sep 17 00:00:00 2001 From: jazz127 Date: Sat, 31 Oct 2026 08:11:44 +1000 Subject: [PATCH 10/10] no-mistakes(lint): Fix ShellCheck warnings in attribution fixtures --- tests/fm-git-strip-ai-trailers.test.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/fm-git-strip-ai-trailers.test.sh b/tests/fm-git-strip-ai-trailers.test.sh index 36ea5ad0310..e9fac52678b 100644 --- a/tests/fm-git-strip-ai-trailers.test.sh +++ b/tests/fm-git-strip-ai-trailers.test.sh @@ -216,6 +216,7 @@ polytoken|zai/glm-5.3-flash cortex|claude-sonnet-5-5 CASES for runtime in opencode codex; do + # shellcheck disable=SC2088 # The literal tilde path is an intentionally unsafe selector. for model in '' 'unsafe model' $'model\nAgent-System: injected' $'model\rAgent-System: injected' \ $'model\tvariant' $'model\001variant' $'model\033variant' $'model\177variant' \ "model$(printf '\302\205')variant" "model$(printf '\342\200\250')variant" \ @@ -257,7 +258,7 @@ test_recorded_sessions() { body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) assert_not_contains "$body" 'Agent-Session:' 'unsafe session published' rm "$meta" - OPENCODE_SESSION_ID= with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: absent session' || fail 'absent session commit failed' + OPENCODE_SESSION_ID='' with_hooks_env "$hooks" git -C "$repo" commit -q --allow-empty -m 'fix: absent session' || fail 'absent session commit failed' body=$(git -C "$repo" log -1 --format=%B | git -C "$repo" interpret-trailers --parse) assert_not_contains "$body" 'Agent-Session:' 'absent session guessed' done