From 3996681d54109487fdd1f157510e22d488c1baa4 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 10:18:44 -0500 Subject: [PATCH 1/3] refactor(codex): use the authoritative plugin source [[tasks/harmony-2016]] --- .agents/plugins/marketplace.json | 6 +- .github/workflows/ci.yml | 21 ++- .gitignore | 6 + Makefile | 12 +- README.md | 87 ++++++--- plugins/gitkb/.codex-plugin/plugin.json | 36 ---- plugins/gitkb/.mcp.json | 20 -- plugins/gitkb/LICENSE | 21 --- plugins/gitkb/README.md | 86 --------- plugins/gitkb/hooks/hooks.json | 58 ------ .../skills/gitkb-code-intelligence/SKILL.md | 28 --- tests/catalog-policy.py | 105 +++++++++++ tests/mcp-contract.py | 42 ----- tests/mcp-startup.py | 171 ------------------ tests/package-policy.sh | 56 +++--- tests/verify-source.py | 68 +++++++ 16 files changed, 289 insertions(+), 534 deletions(-) delete mode 100644 plugins/gitkb/.codex-plugin/plugin.json delete mode 100644 plugins/gitkb/.mcp.json delete mode 100644 plugins/gitkb/LICENSE delete mode 100644 plugins/gitkb/README.md delete mode 100644 plugins/gitkb/hooks/hooks.json delete mode 100644 plugins/gitkb/skills/gitkb-code-intelligence/SKILL.md create mode 100644 tests/catalog-policy.py delete mode 100644 tests/mcp-contract.py delete mode 100644 tests/mcp-startup.py create mode 100644 tests/verify-source.py diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index 5534b60..10b4d36 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -7,8 +7,10 @@ { "name": "gitkb", "source": { - "source": "local", - "path": "./plugins/gitkb" + "source": "git-subdir", + "url": "https://github.com/gitkb/gitkb-codex-plugin.git", + "path": "./plugin", + "sha": "3c30820e97bcb3f6eb4f9648c8d07b8784bbb930" }, "policy": { "installation": "AVAILABLE", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1312dd4..49609a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,16 +9,29 @@ on: jobs: validate: runs-on: ubuntu-latest + timeout-minutes: 5 steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - name: Install jq run: sudo apt-get update && sudo apt-get install -y jq - - name: Run release checks + - name: Run catalog release checks run: make release-check + - name: Read approved canonical source + id: source + run: echo "sha=$(jq -r '.plugins[] | select(.name == "gitkb") | .source.sha' .agents/plugins/marketplace.json)" >> "$GITHUB_OUTPUT" + - name: Checkout exact canonical plugin and tests + uses: actions/checkout@v4 + with: + repository: gitkb/gitkb-codex-plugin + ref: ${{ steps.source.outputs.sha }} + path: .canonical + persist-credentials: false - uses: actions/setup-node@v4 with: node-version: '22' - - name: Install Codex for MCP launch regression + - name: Install Codex for source and MCP launch regression run: npm install --prefix "$RUNNER_TEMP/codex" @openai/codex@0.159.2 - - name: Test packaged MCP launch through Codex - run: make test-integration CODEX_TEST_BINARY="$RUNNER_TEMP/codex/node_modules/.bin/codex" + - name: Verify canonical package and actual Git-backed installation + run: make test-integration CANONICAL_SOURCE_DIR="$GITHUB_WORKSPACE/.canonical" CODEX_TEST_BINARY="$RUNNER_TEMP/codex/node_modules/.bin/codex" diff --git a/.gitignore b/.gitignore index e43b0f9..ad074b3 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ .DS_Store + +# Temporary source checkout used by CI; never a maintained plugin copy. +.canonical/ + +# Python regression-test import cache. +__pycache__/ diff --git a/Makefile b/Makefile index 73c7a55..cc5cc46 100644 --- a/Makefile +++ b/Makefile @@ -4,23 +4,17 @@ all: lint test test: @tests/package-policy.sh - @python3 tests/mcp-contract.py plugins/gitkb + @python3 tests/catalog-policy.py test-integration: - @python3 tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" + @python3 tests/verify-source.py --codex "$(CODEX_TEST_BINARY)" $(if $(CANONICAL_SOURCE_DIR),--source-checkout "$(CANONICAL_SOURCE_DIR)") lint: lint-json lint-policy @echo "All checks passed." lint-json: - @echo "Checking marketplace.json is valid JSON..." + @echo "Checking marketplace catalog is valid JSON..." @jq empty .agents/plugins/marketplace.json - @echo "Checking bundled plugin manifest is valid JSON..." - @jq empty plugins/gitkb/.codex-plugin/plugin.json - @echo "Checking bundled hooks config is valid JSON..." - @jq empty plugins/gitkb/hooks/hooks.json - @echo "Checking bundled MCP config is valid JSON..." - @jq empty plugins/gitkb/.mcp.json lint-policy: @tests/package-policy.sh diff --git a/README.md b/README.md index c4f09a1..998b3a3 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,85 @@ # GitKB Codex Plugins -A private Codex plugin marketplace by GitKB. +The Codex plugin marketplace by GitKB. ## Available Plugins -| Plugin | Description | -|--------|-------------| -| [gitkb](https://github.com/gitkb/gitkb-codex-plugin) | Knowledge base and code intelligence for AI-native development. | +| Plugin | Authoritative source | +|--------|----------------------| +| gitkb | [gitkb/gitkb-codex-plugin](https://github.com/gitkb/gitkb-codex-plugin) — knowledge base and code intelligence | -The Claude marketplace also includes [`meta`](https://github.com/gitkb/meta). Add the Codex `meta` plugin here after `gitkb/meta` has a `codex-plugin` payload that mirrors its Claude plugin. +This repository owns the catalog, installation policies and approved source +selectors. The standalone repository owns the plugin payload, hooks, skills, +MCP configuration, package version and behavior tests. Changes to those components +belong there; there is no bundled GitKB payload or sync workflow here. -## Repository Layout +The GitKB entry uses Codex's supported `git-subdir` source, selecting `./plugin` +from the standalone repository by a full immutable commit SHA. See the +[OpenAI packaging documentation](https://developers.openai.com/plugins/build/plugins). -```text -.agents/plugins/marketplace.json # Codex marketplace manifest -plugins/gitkb/ # Installable GitKB Codex plugin payload -``` - -Codex marketplace entries resolve plugin paths relative to this marketplace repo. The `plugins/gitkb` payload mirrors the private `gitkb-codex-plugin` package while both are under review. +The Claude marketplace also includes [`meta`](https://github.com/gitkb/meta). +Add a Codex entry here once its authoritative repository has a supported payload. ## Usage ```bash -# Add this private marketplace when you have repository access codex plugin marketplace add gitkb/codex-plugins - -# Install a plugin codex plugin add gitkb@gitkb ``` -## License +The installation identity remains `gitkb@gitkb`. Codex fetches the declared +Git source and installs its package; a Harmony meta checkout is not required. +The reference is pinned rather than rolling with `main`, so changes upstream +only reach this catalog after a reviewed pin update. -MIT +For an existing Git-backed marketplace installation: + +```bash +codex plugin marketplace upgrade gitkb +codex plugin add gitkb@gitkb +``` -## MCP Launch Regression Tests +Then start a new Codex session, or resume through the ATC shim, to launch a new +MCP process. Refreshing a marketplace or installing binaries alone does not +change an already running MCP child's environment. Missing historical activity +is not backfilled. -`make test` checks the packaged environment allowlist and cache version. The -installation test exercises the actual Codex MCP launch boundary with synthetic -sessions, custom registry settings, paths with spaces and Unicode, and credential -canaries. It reuses an isolated plugin installation across two sessions and a -launch without activity context. It does not start a model turn or run an activity -sink, and it does not use your Codex home or credentials. +## Development and Release Promotion ```bash +make release-check make test-integration CODEX_TEST_BINARY=/absolute/path/to/provider/codex ``` -Pass the provider binary, rather than an ATC shim. CI runs this test with Codex -`0.159.2`, in addition to the release checks. +Catalog tests reject duplicate GitKB entries, unexpected sources, mutable or +malformed selectors, escaping package paths, and a reintroduced local payload +or copy of the MCP behavior tests. + +The integration command fetches the exact catalog commit into a temporary +checkout and runs its package-owned policy, MCP contract and startup tests. The +startup test installs this catalog's actual Git-backed entry with Codex, compares +every installed package file against the referenced source, and verifies session +and credential isolation. It uses an isolated Codex home and synthetic context, +without model turns or real activity sinks. Pass the provider binary, not an ATC +shim. Source fetches need network access to the public standalone repository; +`make release-check` remains offline. + +CI checks out the same source selector and passes it as `CANONICAL_SOURCE_DIR` +to avoid fetching that verification checkout again. Codex still resolves and +fetches the actual Git-backed plugin entry. CI uses Codex `0.159.2`. + +To promote a new plugin release: + +1. Implement and test the change in `gitkb/gitkb-codex-plugin`, bumping its plugin + version when the installed payload changes. +2. Update only the GitKB entry's `source.sha` to the approved full commit SHA. +3. Run the catalog and delegated source checks, then review and merge the pin PR. + +The initial selector contains the tested `0.1.2` payload from standalone +[PR #7](https://github.com/gitkb/gitkb-codex-plugin/pull/7), matching the payload +previously bundled by marketplace PR #5. It is immutable and published, so the +catalog cannot fall back to the pre-fix standalone `main` while that PR is open. + +## License + +MIT diff --git a/plugins/gitkb/.codex-plugin/plugin.json b/plugins/gitkb/.codex-plugin/plugin.json deleted file mode 100644 index feb0065..0000000 --- a/plugins/gitkb/.codex-plugin/plugin.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "gitkb", - "version": "0.1.2", - "description": "Codex hooks, skills, and MCP config for GitKB code-intelligence guidance.", - "author": { - "name": "GitKB", - "url": "https://gitkb.com" - }, - "homepage": "https://gitkb.com/docs", - "repository": "https://github.com/gitkb/gitkb-codex-plugin", - "license": "MIT", - "keywords": [ - "gitkb", - "codex", - "hooks", - "mcp", - "code-intelligence" - ], - "skills": "./skills/", - "mcpServers": "./.mcp.json", - "interface": { - "displayName": "GitKB", - "shortDescription": "GitKB code-intelligence guidance for Codex sessions.", - "longDescription": "Installs Codex hooks, a GitKB code-intelligence skill, and MCP configuration so Codex can prefer GitKB's AST-backed callers, callees, symbols, impact, and semantic tools when exploring code relationships.", - "developerName": "GitKB", - "category": "Productivity", - "capabilities": [ - "Write" - ], - "defaultPrompt": [ - "Find callers of this function with GitKB.", - "Assess this file's blast radius.", - "Find definitions and references for this symbol." - ] - } -} diff --git a/plugins/gitkb/.mcp.json b/plugins/gitkb/.mcp.json deleted file mode 100644 index 6c0cc04..0000000 --- a/plugins/gitkb/.mcp.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "mcpServers": { - "gitkb": { - "command": "git-kb", - "args": [ - "mcp" - ], - "env_vars": [ - "SESSION_ACTIVITY_RESOURCE_ID", - "SESSION_ACTIVITY_RESOURCE_KIND", - "SESSION_ACTIVITY_PROVIDER", - "SESSION_ACTIVITY_CONTEXT_FILE", - "SESSION_ACTIVITY_SINK_COMMAND", - "SESSION_ACTIVITY_SINK_ARGS_JSON", - "ATC_ROOT", - "ATC_CONFIG" - ] - } - } -} diff --git a/plugins/gitkb/LICENSE b/plugins/gitkb/LICENSE deleted file mode 100644 index ebc742f..0000000 --- a/plugins/gitkb/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 GitKB - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/plugins/gitkb/README.md b/plugins/gitkb/README.md deleted file mode 100644 index 1b0e7d7..0000000 --- a/plugins/gitkb/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# GitKB for Codex - -GitKB gives Codex local code intelligence first: symbols, callers, callees, impact analysis, dead-code detection, semantic search, and service-edge queries through the `git-kb` CLI and MCP tools. Full GitKB setup adds the persistent knowledge graph for tasks, specs, decisions, architecture, and team sync. - -## First Value - -Install the plugin, open a Git repo, and ask Codex about the code: - -- "What calls `authenticate()`?" -- "What's the blast radius of changing `src/auth.rs`?" -- "Find likely dead code in this project." -- "Index this repo with GitKB and summarize language support." - -Codex should prefer local commands such as: - -```bash -git-kb code doctor --json -git-kb code index -git-kb code symbols --json -git-kb code callers "" --json -git-kb code callees "" --json -git-kb code impact path/to/file --json -git-kb code dead --json -git-kb ai semantic "query" --json -``` - -Raw text search remains appropriate for exact strings, logs, config, docs, generated output, snapshots, and one-off file checks. - -## Prerequisites - -Install GitKB: - -```bash -brew install gitkb/tap/gitkb -# or -curl -fsSL https://get.gitkb.com/install.sh | bash -``` - -If `git-kb` is missing, the plugin hooks fail open. Codex can still guide installation from the bundled skill. - -## Optional Full KB Setup - -When you want persistent tasks, project knowledge, sync, or the full repo-local Codex assets, initialize GitKB in the repo: - -```bash -git-kb init -git-kb init codex -``` - -`git-kb init codex` remains the source of truth for canonical repo-local GitKB Codex assets. This marketplace plugin is a thin wrapper that delegates hooks to `git-kb hook codex`. - -## What This Plugin Ships - -- one focused code-intelligence skill; -- Codex lifecycle hooks that call `git-kb hook codex`; -- MCP configuration for `git-kb mcp`; -- inherited session activity context for the MCP process; -- no vendored copy of the full canonical `git-kb init codex` skill set. - -## ATC Session Activity - -When Codex runs through an ATC shim, the plugin forwards the parent's six -`SESSION_ACTIVITY_*` settings to `git-kb mcp`. It also forwards `ATC_ROOT` and -`ATC_CONFIG` when set, so the activity sink uses the same registry as the shim. -Codex filters the MCP environment; installing a newer `git-kb` or `atc` binary -alone does not update this plugin launch configuration. - -Install the updated plugin (`0.1.2`) from your marketplace and restart or resume -Codex through the ATC shim to start a new MCP process. Existing MCP processes keep -the environment with which they started. Previously omitted activity records -are not backfilled by this update. - -The configuration forwards variable names rather than fixed session values. -Without parent activity context, GitKB keeps its normal behavior. The plugin does -not forward API credentials, generic provider thread IDs, or a global ATC session -ID as a substitute for the activity contract. - -## Documentation - -- [Getting Started](https://gitkb.com/docs/getting-started/quick-start/) -- [Code Intelligence](https://gitkb.com/docs/core-concepts/code-intelligence/) -- [MCP Setup](https://gitkb.com/docs/getting-started/mcp-setup/) - -## License - -MIT diff --git a/plugins/gitkb/hooks/hooks.json b/plugins/gitkb/hooks/hooks.json deleted file mode 100644 index af03e6f..0000000 --- a/plugins/gitkb/hooks/hooks.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "hooks": { - "SessionStart": [ - { - "matcher": "startup|resume|compact|clear", - "hooks": [ - { - "type": "command", - "command": "git-kb hook codex" - } - ] - } - ], - "UserPromptSubmit": [ - { - "hooks": [ - { - "type": "command", - "command": "git-kb hook codex" - } - ] - } - ], - "PreToolUse": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "command": "git-kb hook codex" - } - ] - } - ], - "PermissionRequest": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "command": "git-kb hook codex" - } - ] - } - ], - "PostToolUse": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "command": "git-kb hook codex" - } - ] - } - ] - } -} diff --git a/plugins/gitkb/skills/gitkb-code-intelligence/SKILL.md b/plugins/gitkb/skills/gitkb-code-intelligence/SKILL.md deleted file mode 100644 index a0a5840..0000000 --- a/plugins/gitkb/skills/gitkb-code-intelligence/SKILL.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: gitkb-code-intelligence -description: Use when Codex or a GitKB hook points you at GitKB for callers, definitions, references, usage analysis, blast radius, or symbol search. ---- - -# GitKB Code Intelligence - -Use GitKB's AST-backed code intelligence for code relationships: - -```bash -git-kb code symbols "" --json -git-kb code symbols --file --json -git-kb code callers "" --json -git-kb code callees "" --json -git-kb code impact --json -git-kb ai semantic "" --json -``` - -When MCP tools are enabled, prefer the matching GitKB MCP tools for structured output. - -Raw `rg`, `grep`, `find`, and file reads are still appropriate for exact strings, logs, config, docs, generated output, snapshots, and one-off content checks. - -If code intelligence returns no results for code that exists, run: - -```bash -git-kb code doctor --json -git-kb code index -``` diff --git a/tests/catalog-policy.py b/tests/catalog-policy.py new file mode 100644 index 0000000..9e4c0c3 --- /dev/null +++ b/tests/catalog-policy.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Exercise catalog source selection and guard against reintroducing a plugin copy.""" +import copy +import json +import importlib.util +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +POLICY = ROOT / "tests/package-policy.sh" + + +class CatalogPolicy(unittest.TestCase): + def check(self, change=None, artifact=None, success=False, symlink=False): + """Check a temporary catalog without touching the repository under test.""" + manifest = json.loads((ROOT / ".agents/plugins/marketplace.json").read_text()) + if change: + change(manifest) + with tempfile.TemporaryDirectory(prefix="gitkb-catalog-policy-") as directory: + root = Path(directory) + target = root / ".agents/plugins/marketplace.json" + target.parent.mkdir(parents=True) + target.write_text(json.dumps(manifest)) + if artifact: + path = root / artifact + path.parent.mkdir(parents=True, exist_ok=True) + if symlink: + path.symlink_to("missing-target") + else: + path.write_text("a second maintained copy") + result = subprocess.run([str(POLICY), str(root)], capture_output=True, + text=True, timeout=10) + self.assertEqual(result.returncode == 0, success, result.stdout + result.stderr) + + def test_catalog_is_valid(self): + """Accept the maintained immutable canonical source.""" + self.check(success=True) + + def test_source_cannot_switch_authority_or_escape_the_package(self): + """Reject local copies, alternate repositories, and unsafe subdirectory paths.""" + for field, value in (("source", "local"), ("url", "file:///tmp/plugin"), + ("url", "https://github.com/other/plugin.git"), + ("path", "../plugin"), ("path", "/tmp/plugin")): + with self.subTest(field=field, value=value): + self.check(lambda doc: doc["plugins"][0]["source"].update({field: value})) + + def test_selector_is_an_immutable_commit(self): + """Reject missing, malformed, mutable, and shell-like selectors.""" + for value in (None, "", "main", "v0.1.2", "a" * 39, "g" * 40, "$(touch sentinel)"): + with self.subTest(value=value): + self.check(lambda doc: doc["plugins"][0]["source"].update(sha=value)) + self.check(lambda doc: doc["plugins"][0]["source"].pop("sha")) + + def test_no_ambiguous_or_extra_source_fields(self): + """Reject a competing mutable ref or embedded environment settings.""" + for field, value in (("ref", "main"), ("env", {"ATC_SESSION_ID": "fixed"})): + with self.subTest(field=field): + self.check(lambda doc: doc["plugins"][0]["source"].update({field: value})) + + def test_one_gitkb_entry(self): + """Reject duplicate entries with the same installation identity.""" + self.check(lambda doc: doc["plugins"].append(copy.deepcopy(doc["plugins"][0]))) + + def test_no_local_payload_or_copied_behavior_tests(self): + """Reject renewed payload and test mirroring even when the source stays correct.""" + for path in ("plugins/gitkb/.mcp.json", "plugin/.mcp.json", + "tests/mcp-contract.py", "tests/mcp-startup.py"): + with self.subTest(path=path): + self.check(artifact=path) + + def test_broken_payload_symlink_is_rejected(self): + """Reject dangling aliases that existence checks alone would miss.""" + self.check(artifact="plugin", symlink=True) + + +class SourceCheckout(unittest.TestCase): + def test_wrong_or_dirty_checkout_cannot_run_package_code(self): + """Use real Git state to reject stale or modified checkouts before executing their tests.""" + spec = importlib.util.spec_from_file_location("source_checks", ROOT / "tests/verify-source.py") + checks = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checks) + with tempfile.TemporaryDirectory(prefix="gitkb-source-policy-") as directory: + root = Path(directory) + env = checks.git_environment() + env.update(GIT_AUTHOR_NAME="Fixture", GIT_AUTHOR_EMAIL="fixture@example.test", + GIT_COMMITTER_NAME="Fixture", GIT_COMMITTER_EMAIL="fixture@example.test") + subprocess.run(["git", "-c", "init.templateDir=", "init", "--quiet", str(root)], + check=True, env=env, timeout=10) + (root / "tracked").write_text("approved") + subprocess.run(["git", "-C", str(root), "add", "tracked"], check=True, env=env, timeout=10) + subprocess.run(["git", "-C", str(root), "-c", "commit.gpgsign=false", + "commit", "--quiet", "-m", "fixture"], check=True, env=env, timeout=10) + sha = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], + text=True, env=env, timeout=10).strip() + with self.assertRaisesRegex(RuntimeError, "does not match catalog"): + checks.verify(root, {"sha": "0" * 40}, "unused") + (root / "tracked").write_text("unreviewed") + with self.assertRaisesRegex(RuntimeError, "local changes"): + checks.verify(root, {"sha": sha}, "unused") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/mcp-contract.py b/tests/mcp-contract.py deleted file mode 100644 index 02f70d4..0000000 --- a/tests/mcp-contract.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python3 -"""Guard the packaged MCP launch contract, including its credential boundary.""" -import json -import sys -import unittest -from pathlib import Path - -FORWARDED = { - "SESSION_ACTIVITY_RESOURCE_ID", "SESSION_ACTIVITY_RESOURCE_KIND", - "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", - "SESSION_ACTIVITY_SINK_COMMAND", "SESSION_ACTIVITY_SINK_ARGS_JSON", - "ATC_ROOT", "ATC_CONFIG", -} -PLUGIN_ROOT = Path(sys.argv.pop(1)) - - -class LaunchContract(unittest.TestCase): - def test_parent_context_is_forwarded_by_name_only(self): - """Require the activity/registry allowlist while rejecting fixed environment values.""" - config = json.loads((PLUGIN_ROOT / ".mcp.json").read_text()) - self.assertEqual(set(config["mcpServers"]), {"gitkb"}) - server = config["mcpServers"]["gitkb"] - names = server["env_vars"] - self.assertIsInstance(names, list) - self.assertTrue(all(isinstance(name, str) for name in names)) - self.assertEqual(set(names), FORWARDED) - self.assertEqual(len(names), len(FORWARDED), "duplicate forwarding names") - self.assertNotIn("env", server, "do not bake session identity into the plugin") - self.assertEqual(server["command"], "git-kb") - self.assertEqual(server["args"], ["mcp"]) - - def test_cache_version_changes_with_launch_contract(self): - """Ensure the installable version cannot reuse either pre-fix cache entry.""" - manifest = json.loads((PLUGIN_ROOT / ".codex-plugin/plugin.json").read_text()) - version = tuple(int(part) for part in manifest["version"].split(".")) - self.assertEqual(len(version), 3) - self.assertGreaterEqual(version, (0, 1, 2), "old cache versions lack this contract") - self.assertEqual(manifest["mcpServers"], "./.mcp.json") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py deleted file mode 100644 index e04426a..0000000 --- a/tests/mcp-startup.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python3 -"""Install the real package in an isolated Codex home and inspect its MCP child. - -Uses only initialize and mcpServerStatus/list; never starts a thread or model turn. -The fake GitKB server captures synthetic context without running an activity sink. -""" -import argparse -import json -import os -import selectors -import shlex -import shutil -import signal -import subprocess -import sys -import tempfile -import time -from pathlib import Path - -NAMES = ( - "SESSION_ACTIVITY_RESOURCE_ID", "SESSION_ACTIVITY_RESOURCE_KIND", - "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", - "SESSION_ACTIVITY_SINK_COMMAND", "SESSION_ACTIVITY_SINK_ARGS_JSON", - "ATC_ROOT", "ATC_CONFIG", -) -FORBIDDEN = ("MCP_ENV_UNRELATED_SECRET", "OPENAI_API_KEY", "ATC_SESSION_ID", "CODEX_THREAD_ID") - - -def run(codex, args, env, cwd): - """Run a bounded plugin installation command with only the fixture environment.""" - result = subprocess.run([codex, *args], env=env, cwd=cwd, - stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30) - if result.returncode: - raise AssertionError(f"Codex {args} failed: {result.stdout} {result.stderr}") - - -def inspect_child(codex, env, root, capture): - """Negotiate packaged MCP tools, capture context, and clean up the owned process group.""" - capture.unlink(missing_ok=True) - with (root / "stderr.log").open("w+") as stderr: - process = subprocess.Popen([codex, "app-server"], env=env, cwd=root, - stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=stderr, start_new_session=True) - selector = selectors.DefaultSelector() - selector.register(process.stdout, selectors.EVENT_READ) - pending = bytearray() - - def send(message): - """Write one newline-delimited app-server request or notification.""" - process.stdin.write((json.dumps(message) + "\n").encode()) - process.stdin.flush() - - def response(request_id): - """Read the matching reply with a deadline, ignoring asynchronous notifications.""" - deadline = time.monotonic() + 15 - while time.monotonic() < deadline: - while b"\n" in pending: - line, _, rest = pending.partition(b"\n") - pending[:] = rest - message = json.loads(line) - if message.get("id") == request_id: - if "error" in message: - raise AssertionError(message["error"]) - return message["result"] - if selector.select(timeout=0.1): - chunk = os.read(process.stdout.fileno(), 65536) - if not chunk: - break - pending.extend(chunk) - stderr.flush() - stderr.seek(0) - raise AssertionError(f"No response to {request_id}: {stderr.read()[-4000:]}") - - try: - send({"id": 1, "method": "initialize", "params": { - "clientInfo": {"name": "gitkb-package-test", "version": "1"}, - "capabilities": {"experimentalApi": True}}}) - response(1) - send({"method": "initialized"}) - send({"id": 2, "method": "mcpServerStatus/list", "params": {}}) - servers = response(2)["data"] - server = next(item for item in servers if item["name"] == "gitkb") - assert server["pluginId"] == "gitkb@gitkb", server - assert "context_probe" in server["tools"], server - assert capture.exists(), "packaged MCP child did not start" - return json.loads(capture.read_text()) - finally: - selector.close() - try: - os.killpg(process.pid, signal.SIGTERM) - except ProcessLookupError: - pass - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGKILL) - process.wait(timeout=5) - process.stdin.close() - process.stdout.close() - - -def main(): - """Verify session isolation and the credential boundary through a real package install.""" - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--codex", required=True, help="Provider Codex binary, not an ATC shim") - parser.add_argument("--marketplace", default=".") - args = parser.parse_args() - codex = shutil.which(args.codex) - if not codex: - parser.error("Codex binary not found") - codex = str(Path(codex).resolve()) - marketplace = str(Path(args.marketplace).resolve()) - with tempfile.TemporaryDirectory(prefix="gitkb-mcp-context-") as directory: - root = Path(directory) - (root / "bin").mkdir() - (root / "codex").mkdir() - capture = root / "context.json" - fixture = root / "mcp_fixture.py" - fixture.write_text('''import json, os, sys -if sys.argv[1:] != ["mcp"]: - sys.exit(0) -''' + f"names = {NAMES + FORBIDDEN!r}\n" + - f"with open({str(capture)!r}, 'w') as output:\n" + - " json.dump({name: os.environ[name] for name in names if name in os.environ}, output)\n" + '''for line in sys.stdin: - message = json.loads(line) - if "id" not in message: - continue - method = message["method"] - if method == "initialize": - result = {"protocolVersion": message["params"]["protocolVersion"], - "capabilities": {"tools": {}}, "serverInfo": {"name": "gitkb-fixture", "version": "1"}} - elif method == "tools/list": - result = {"tools": [{"name": "context_probe", "description": "Launch boundary probe", - "inputSchema": {"type": "object", "properties": {}}}]} - elif method == "resources/list": - result = {"resources": []} - elif method == "resources/templates/list": - result = {"resourceTemplates": []} - else: - print(json.dumps({"jsonrpc": "2.0", "id": message["id"], - "error": {"code": -32601, "message": "Method not found"}}), flush=True) - continue - print(json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}), flush=True) -''') - shim = root / "bin/git-kb" - shim.write_text(f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(fixture))} \"$@\"\n") - shim.chmod(0o755) - # Construct the environment: never inherit the developer's keys, session or home. - base_env = {"HOME": directory, "CODEX_HOME": str(root / "codex"), - "PATH": str(root / "bin") + os.pathsep + os.defpath, - "TMPDIR": directory} - node = shutil.which("node") - if node: - # npm Codex launchers use /usr/bin/env node; keep that interpreter reachable. - base_env["PATH"] += os.pathsep + str(Path(node).parent) - run(codex, ["plugin", "marketplace", "add", marketplace, "--json"], base_env, root) - run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root) - for session in ("alpha", "beta", None): - expected = {} if session is None else dict(zip(NAMES, ( - f"xses-{session}", "external", "codex", - str(root / f"{session} path 'quoted' ü.json"), - str(root / "sink path"), json.dumps(["activity", "record", "--json"]), - str(root / f"{session} registry"), str(root / f"{session} config.toml")))) - env = dict(base_env, **expected, **{name: "synthetic-canary" for name in FORBIDDEN}) - observed = inspect_child(codex, env, root, capture) - assert observed == expected, f"{session or 'unshimmed'}: expected {expected}, got {observed}" - print(f"PASS: {session or 'unshimmed'} MCP context and credential isolation") - - -if __name__ == "__main__": - main() diff --git a/tests/package-policy.sh b/tests/package-policy.sh index b6a47d2..725a0d4 100755 --- a/tests/package-policy.sh +++ b/tests/package-policy.sh @@ -6,34 +6,28 @@ fail() { exit 1 } -test -f .agents/plugins/marketplace.json || fail "missing marketplace" -test -f plugins/gitkb/.codex-plugin/plugin.json || fail "missing bundled gitkb plugin" - -marketplace_name=$(jq -r '.name' .agents/plugins/marketplace.json) -test "$marketplace_name" = "gitkb" || fail "marketplace name must be gitkb" - -source_kind=$(jq -r '.plugins[] | select(.name == "gitkb") | .source.source' .agents/plugins/marketplace.json) -source_path=$(jq -r '.plugins[] | select(.name == "gitkb") | .source.path' .agents/plugins/marketplace.json) -test "$source_kind" = "local" || fail "Codex marketplace plugin source must be local" -test "$source_path" = "./plugins/gitkb" || fail "gitkb source path must be ./plugins/gitkb" - -plugin_name=$(jq -r '.name' plugins/gitkb/.codex-plugin/plugin.json) -test "$plugin_name" = "gitkb" || fail "bundled plugin name must be gitkb" - -if jq -e 'has("hooks")' plugins/gitkb/.codex-plugin/plugin.json >/dev/null; then - fail "plugin manifest must not use unsupported hooks field" -fi - -hook_commands=$(jq -r '.. | objects | select(.type? == "command") | .command' plugins/gitkb/hooks/hooks.json) -test -n "$hook_commands" || fail "expected command hooks" -if echo "$hook_commands" | grep -v '^git-kb hook codex$' >/dev/null; then - fail "all hooks must delegate to git-kb hook codex" -fi - -if grep -R "gitkb-a[t]c\\|@personal" . \ - --exclude-dir=.git \ - --exclude=package-policy.sh >/dev/null; then - fail "marketplace must not contain old plugin or personal-marketplace identity" -fi - -echo "Marketplace policy checks passed." +repo_root=${1:-.} +manifest="$repo_root/.agents/plugins/marketplace.json" +test -f "$manifest" || fail "missing marketplace" + +jq -e ' + .name == "gitkb" and + ([.plugins[] | select(.name == "gitkb")] | length == 1) and + ([.plugins[] | select(.name == "gitkb")][0] | + .policy == {"installation": "AVAILABLE", "authentication": "ON_INSTALL"} and + .category == "Productivity" and + (.source | + keys == ["path", "sha", "source", "url"] and + .source == "git-subdir" and + .url == "https://github.com/gitkb/gitkb-codex-plugin.git" and + .path == "./plugin" and + (.sha | type == "string" and test("^[0-9a-f]{40}$")))) +' "$manifest" >/dev/null || fail "gitkb must select exactly one canonical package by immutable SHA" + +for path in plugins/gitkb plugin tests/mcp-contract.py tests/mcp-startup.py; do + if [ -e "$repo_root/$path" ] || [ -L "$repo_root/$path" ]; then + fail "catalog must not vendor the canonical payload or behavior tests: $path" + fi +done + +echo "Catalog policy checks passed." diff --git a/tests/verify-source.py b/tests/verify-source.py new file mode 100644 index 0000000..9039fc3 --- /dev/null +++ b/tests/verify-source.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Run package-owned checks against the exact source selected by this catalog.""" +import argparse +import json +import os +import subprocess +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def run(args, **kwargs): + """Run a bounded command and propagate failures without executing shell text.""" + return subprocess.run(args, check=True, timeout=60, **kwargs) + + +def git_environment(): + """Keep source verification independent of developer Git configuration and credentials.""" + env = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")} + env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0") + return env + + +def verify(source_dir, source, codex): + """Verify the checkout identity and reuse its package and real Codex startup tests.""" + env = git_environment() + actual = subprocess.check_output(["git", "-C", str(source_dir), "rev-parse", "HEAD"], + text=True, timeout=10, env=env).strip() + if actual != source["sha"]: + raise RuntimeError(f"Source checkout {actual} does not match catalog {source['sha']}") + dirty = subprocess.check_output(["git", "-C", str(source_dir), "status", "--porcelain"], + text=True, timeout=10, env=env).strip() + if dirty: + raise RuntimeError(f"Canonical source checkout has local changes: {dirty[:4000]}") + run(["make", "-C", str(source_dir), "release-check"], env=env) + run(["python3", str(source_dir / "tests/mcp-startup.py"), "--codex", codex, + "--marketplace", str(ROOT), "--expected-plugin-root", str(source_dir / "plugin")]) + + +def main(): + """Fetch the declared source or verify a provided CI checkout before using its tests.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--codex", required=True) + parser.add_argument("--source-checkout", type=Path) + args = parser.parse_args() + if not args.codex: + parser.error("pass the provider binary via CODEX_TEST_BINARY") + run([str(ROOT / "tests/package-policy.sh"), str(ROOT)]) + manifest = json.loads((ROOT / ".agents/plugins/marketplace.json").read_text()) + source = next(item["source"] for item in manifest["plugins"] if item["name"] == "gitkb") + print(f"Verifying {source['url']} at {source['sha']}", flush=True) + if args.source_checkout: + verify(args.source_checkout.resolve(), source, args.codex) + return + with tempfile.TemporaryDirectory(prefix="gitkb-canonical-source-") as directory: + source_dir = Path(directory) + # Public immutable source: avoid developer Git credentials, templates and URL rewrites. + env = git_environment() + run(["git", "-c", "init.templateDir=", "init", "--quiet", str(source_dir)], env=env) + run(["git", "-C", str(source_dir), "fetch", "--quiet", "--depth=1", + source["url"], source["sha"]], env=env) + run(["git", "-C", str(source_dir), "checkout", "--quiet", "--detach", "FETCH_HEAD"], env=env) + verify(source_dir, source, args.codex) + + +if __name__ == "__main__": + main() From 062feddcde2674043b1d76283a70ac307d3c4773 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 11:06:37 -0500 Subject: [PATCH 2/3] test: verify pinned source bytes before delegation [[tasks/harmony-2016]] --- .agents/plugins/marketplace.json | 2 +- .github/workflows/ci.yml | 5 +- Makefile | 4 +- README.md | 12 +++ tests/catalog-policy.py | 145 ++++++++++++++++++++++++++----- tests/verify-source.py | 80 ++++++++++++++--- 6 files changed, 209 insertions(+), 39 deletions(-) diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index 10b4d36..fcb4b9c 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -10,7 +10,7 @@ "source": "git-subdir", "url": "https://github.com/gitkb/gitkb-codex-plugin.git", "path": "./plugin", - "sha": "3c30820e97bcb3f6eb4f9648c8d07b8784bbb930" + "sha": "3a6c6ecc6fa6e79a5170151209f565dda5e153d8" }, "policy": { "installation": "AVAILABLE", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49609a7..74f00be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,10 +6,13 @@ on: branches: - main +permissions: + contents: read + jobs: validate: runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 15 steps: - uses: actions/checkout@v4 with: diff --git a/Makefile b/Makefile index cc5cc46..32feea8 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,10 @@ all: lint test test: @tests/package-policy.sh - @python3 tests/catalog-policy.py + @python3 -B tests/catalog-policy.py test-integration: - @python3 tests/verify-source.py --codex "$(CODEX_TEST_BINARY)" $(if $(CANONICAL_SOURCE_DIR),--source-checkout "$(CANONICAL_SOURCE_DIR)") + @python3 -B tests/verify-source.py --codex "$(CODEX_TEST_BINARY)" $(if $(CANONICAL_SOURCE_DIR),--source-checkout "$(CANONICAL_SOURCE_DIR)") lint: lint-json lint-policy @echo "All checks passed." diff --git a/README.md b/README.md index 998b3a3..1833116 100644 --- a/README.md +++ b/README.md @@ -83,3 +83,15 @@ catalog cannot fall back to the pre-fix standalone `main` while that PR is open. ## License MIT + +Source verification compares every file's bytes and executable mode with the +pinned Git tree, independently of the index, ignore rules, replacement refs, +and fsmonitor hooks. Unexpected files (including ignored import shadows), +symlinks, and special files fail before package tests execute. Provided checkouts +must be pristine; use the default temporary checkout when a developer checkout +contains generated files. Delegated checks use a temporary home and omit parent +credentials, Python/shell startup overrides, and ATC session settings. The shared +canonical driver covers both fresh installation and upgrade from a bundled +`0.1.0` fixture. These checks validate catalog selection and the MCP launch +boundary; they are not a sandbox for arbitrary package code or a live ATC +registry acceptance test. Python 3.11 or newer is required. diff --git a/tests/catalog-policy.py b/tests/catalog-policy.py index 9e4c0c3..1f990d1 100644 --- a/tests/catalog-policy.py +++ b/tests/catalog-policy.py @@ -2,10 +2,12 @@ """Exercise catalog source selection and guard against reintroducing a plugin copy.""" import copy import json +import os import importlib.util import subprocess import tempfile import unittest +from unittest import mock from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -76,29 +78,128 @@ def test_broken_payload_symlink_is_rejected(self): class SourceCheckout(unittest.TestCase): - def test_wrong_or_dirty_checkout_cannot_run_package_code(self): - """Use real Git state to reject stale or modified checkouts before executing their tests.""" + def setUp(self): + """Prepare a real, small source tree without developer Git hooks or configuration.""" spec = importlib.util.spec_from_file_location("source_checks", ROOT / "tests/verify-source.py") - checks = importlib.util.module_from_spec(spec) - spec.loader.exec_module(checks) - with tempfile.TemporaryDirectory(prefix="gitkb-source-policy-") as directory: - root = Path(directory) - env = checks.git_environment() - env.update(GIT_AUTHOR_NAME="Fixture", GIT_AUTHOR_EMAIL="fixture@example.test", - GIT_COMMITTER_NAME="Fixture", GIT_COMMITTER_EMAIL="fixture@example.test") - subprocess.run(["git", "-c", "init.templateDir=", "init", "--quiet", str(root)], - check=True, env=env, timeout=10) - (root / "tracked").write_text("approved") - subprocess.run(["git", "-C", str(root), "add", "tracked"], check=True, env=env, timeout=10) - subprocess.run(["git", "-C", str(root), "-c", "commit.gpgsign=false", - "commit", "--quiet", "-m", "fixture"], check=True, env=env, timeout=10) - sha = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], - text=True, env=env, timeout=10).strip() - with self.assertRaisesRegex(RuntimeError, "does not match catalog"): - checks.verify(root, {"sha": "0" * 40}, "unused") - (root / "tracked").write_text("unreviewed") - with self.assertRaisesRegex(RuntimeError, "local changes"): - checks.verify(root, {"sha": sha}, "unused") + self.checks = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.checks) + self.directory = tempfile.TemporaryDirectory(prefix="gitkb-source-policy-") + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.env = self.checks.git_environment() + self.env.update(GIT_AUTHOR_NAME="Fixture", GIT_AUTHOR_EMAIL="fixture@example.test", + GIT_COMMITTER_NAME="Fixture", GIT_COMMITTER_EMAIL="fixture@example.test") + subprocess.run(["git", "-c", "init.templateDir=", "init", "--quiet", str(self.root)], + check=True, env=self.env, timeout=10) + (self.root / "tracked").write_text("approved") + self.git("add", "tracked") + self.git("-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "fixture") + self.source = {"sha": self.git("rev-parse", "HEAD").strip()} + + def git(self, *args): + """Use the fixture Git repository without inheriting session-specific Git variables.""" + return subprocess.check_output(["git", "-C", str(self.root), *args], + text=True, env=self.env, timeout=10) + + def reject(self, source=None): + """Rejection must happen before any package-owned executable is launched.""" + with mock.patch.object(self.checks, "run") as execute: + with self.assertRaises(RuntimeError): + self.checks.verify(self.root, source or self.source, "unused") + execute.assert_not_called() + + def test_wrong_or_dirty_checkout_cannot_run_package_code(self): + """Reject stale identity and changed bytes before package execution.""" + self.reject({"sha": "0" * 40}) + (self.root / "tracked").write_text("tampered") + self.reject() + + def test_index_flags_cannot_hide_modified_source(self): + """Raw committed bytes must win over assume-unchanged and skip-worktree flags.""" + for flag in ("--assume-unchanged", "--skip-worktree"): + with self.subTest(flag=flag): + self.git("update-index", flag, "tracked") + (self.root / "tracked").write_text("tampered") + self.reject() + (self.root / "tracked").write_text("approved") + self.git("update-index", "--no-assume-unchanged", "--no-skip-worktree", "tracked") + + def test_ignored_shadow_module_is_rejected(self): + """Ignored Python import shadows cannot execute inside a supposedly clean source tree.""" + (self.root / ".git/info").mkdir(exist_ok=True) + (self.root / ".git/info/exclude").write_text("sitecustomize.py\n") + (self.root / "sitecustomize.py").write_text("raise RuntimeError('unreviewed')") + self.assertEqual(self.git("status", "--porcelain"), "") + self.reject() + + def test_links_special_files_and_modes_are_rejected(self): + """Reject changes to file type and executable permissions without following links.""" + tracked = self.root / "tracked" + for kind in ("symlink", "fifo", "executable"): + with self.subTest(kind=kind): + tracked.unlink() + if kind == "symlink": + tracked.symlink_to("missing-target") + elif kind == "fifo": + os.mkfifo(tracked) + else: + tracked.write_text("approved") + tracked.chmod(0o755) + self.reject() + + def test_local_fsmonitor_is_never_executed(self): + """Source validation must not invoke a repository-configured Git status hook.""" + hook = self.root / ".git/fsmonitor" + marker = self.root / ".git/executed" + hook.write_text("#!/bin/sh\ntouch " + str(marker) + "\n") + hook.chmod(0o755) + self.git("config", "core.fsmonitor", str(hook)) + with mock.patch.object(self.checks, "run"): + self.checks.verify(self.root, self.source, "unused") + self.assertFalse(marker.exists(), "verification executed an unreviewed fsmonitor hook") + + def test_replace_refs_cannot_substitute_unapproved_tree(self): + """A local Git replacement must not change which committed bytes are approved.""" + (self.root / "tracked").write_text("tampered") + self.git("add", "tracked") + self.git("-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "unreviewed") + substitute = self.git("rev-parse", "HEAD").strip() + self.git("update-ref", "HEAD", self.source["sha"]) + self.git("replace", self.source["sha"], substitute) + self.reject() + + def test_committed_links_are_not_executable_source(self): + """Even a tracked symlink may not make package checks read outside the approved tree.""" + (self.root / "alias").symlink_to("tracked") + self.git("add", "alias") + self.git("-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "symlink fixture") + self.source["sha"] = self.git("rev-parse", "HEAD").strip() + self.reject() + + def test_valid_source_with_unusual_paths(self): + """NUL-delimited tree parsing preserves tabs, newlines, spaces, and Unicode filenames.""" + path = self.root / "nested" / "quoted ' ü\tline\nfile" + path.parent.mkdir() + path.write_text("approved") + self.git("add", "nested") + self.git("-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "path fixture") + self.source["sha"] = self.git("rev-parse", "HEAD").strip() + with mock.patch.object(self.checks, "run") as execute: + self.checks.verify(self.root, self.source, "unused") + self.assertEqual(execute.call_count, 3) + + def test_valid_source_runs_without_parent_credentials_or_hooks(self): + """Delegate both checks with an owned home and a minimal environment.""" + canaries = {name: "synthetic-canary" for name in + ("OPENAI_API_KEY", "SESSION_ACTIVITY_RESOURCE_ID", "ATC_ROOT", "PYTHONPATH", "BASH_ENV")} + with mock.patch.dict(os.environ, canaries), mock.patch.object(self.checks, "run") as execute: + self.checks.verify(self.root, self.source, "/provider/codex") + self.assertEqual(execute.call_count, 3) + for call in execute.call_args_list: + env = call.kwargs["env"] + self.assertTrue(set(canaries).isdisjoint(env)) + self.assertNotEqual(env["HOME"], os.environ["HOME"]) + self.assertEqual(env["CODEX_HOME"], str(Path(env["HOME"]) / "codex")) if __name__ == "__main__": diff --git a/tests/verify-source.py b/tests/verify-source.py index 9039fc3..e8e08c3 100644 --- a/tests/verify-source.py +++ b/tests/verify-source.py @@ -1,8 +1,10 @@ #!/usr/bin/env python3 """Run package-owned checks against the exact source selected by this catalog.""" import argparse +import hashlib import json import os +import stat import subprocess import tempfile from pathlib import Path @@ -10,9 +12,9 @@ ROOT = Path(__file__).resolve().parents[1] -def run(args, **kwargs): +def run(args, *, timeout=60, **kwargs): """Run a bounded command and propagate failures without executing shell text.""" - return subprocess.run(args, check=True, timeout=60, **kwargs) + return subprocess.run(args, check=True, timeout=timeout, **kwargs) def git_environment(): @@ -22,20 +24,72 @@ def git_environment(): return env -def verify(source_dir, source, codex): - """Verify the checkout identity and reuse its package and real Codex startup tests.""" - env = git_environment() - actual = subprocess.check_output(["git", "-C", str(source_dir), "rev-parse", "HEAD"], +def check_tree(source_dir, source, env): + """Compare bytes and modes to the committed tree, bypassing index flags and status hooks.""" + git = ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(source_dir)] + actual = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True, timeout=10, env=env).strip() if actual != source["sha"]: raise RuntimeError(f"Source checkout {actual} does not match catalog {source['sha']}") - dirty = subprocess.check_output(["git", "-C", str(source_dir), "status", "--porcelain"], - text=True, timeout=10, env=env).strip() - if dirty: - raise RuntimeError(f"Canonical source checkout has local changes: {dirty[:4000]}") - run(["make", "-C", str(source_dir), "release-check"], env=env) - run(["python3", str(source_dir / "tests/mcp-startup.py"), "--codex", codex, - "--marketplace", str(ROOT), "--expected-plugin-root", str(source_dir / "plugin")]) + tree = subprocess.check_output([*git, "ls-tree", "-rzl", "--full-tree", source["sha"]], + timeout=10, env=env) + expected = {} + for entry in tree.split(b"\0"): + if not entry: + continue + metadata, name = entry.split(b"\t", 1) + mode, kind, digest, size = metadata.decode("ascii").split() + if kind != "blob" or mode not in ("100644", "100755"): + raise RuntimeError(f"Canonical source must contain regular files: {os.fsdecode(name)}") + expected[os.fsdecode(name)] = (mode == "100755", digest, int(size)) + seen = {} + directories = {str(parent) for name in expected for parent in Path(name).parents} + for parent, dirs, files in os.walk(source_dir, followlinks=False): + if Path(parent) == source_dir: + dirs[:] = [name for name in dirs if name != ".git"] + files = [name for name in files if name != ".git"] + for name in dirs + files: + path = Path(parent) / name + relative = str(path.relative_to(source_dir)) + mode = path.lstat().st_mode + if stat.S_ISDIR(mode): + if relative not in directories: + raise RuntimeError(f"Canonical source has unexpected directory: {relative}") + continue + if not stat.S_ISREG(mode): + raise RuntimeError(f"Canonical source has non-regular file: {relative}") + if relative not in expected or path.stat().st_size != expected[relative][2]: + raise RuntimeError(f"Canonical source checkout has local changes: {relative}") + # Git's blob identity includes its header; do not apply repository clean filters. + with path.open("rb") as stream: + size = os.fstat(stream.fileno()).st_size + digest = hashlib.sha1(b"blob " + str(size).encode() + b"\0", usedforsecurity=False) + while chunk := stream.read(65536): + digest.update(chunk) + seen[relative] = (bool(mode & 0o111), digest.hexdigest(), size) + changed = sorted(name for name in seen.keys() | expected.keys() + if seen.get(name) != expected.get(name)) + if changed: + raise RuntimeError(f"Canonical source checkout has local changes: {changed[:20]}") + + +def verify(source_dir, source, codex): + """Validate the entire checkout before delegating checks without parent credentials.""" + check_tree(source_dir, source, git_environment()) + with tempfile.TemporaryDirectory(prefix="gitkb-source-check-home-") as directory: + (Path(directory) / "codex").mkdir() + env = {"HOME": directory, "CODEX_HOME": str(Path(directory) / "codex"), + "XDG_CONFIG_HOME": str(Path(directory) / "config"), "TMPDIR": directory, + "PATH": os.environ.get("PATH", os.defpath), "CODEX_TEST_BINARY": codex, + "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "core.fsmonitor", "GIT_CONFIG_VALUE_0": "false"} + run(["make", "-C", str(source_dir), "release-check"], env=env) + # Allow the shared driver's bounded installs, three launches, and cleanup to finish. + for mode in ([], ["--legacy-first"]): + run(["python3", "-B", str(source_dir / "tests/mcp-startup.py"), "--codex", codex, + "--marketplace", str(ROOT), "--expected-plugin-root", str(source_dir / "plugin"), *mode], + env=env, timeout=300) def main(): From 5293e7f23677a21565f7134b02654e5c0171fc25 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 11:12:18 -0500 Subject: [PATCH 3/3] chore: promote reviewed canonical test revision [[tasks/harmony-2016]] --- .agents/plugins/marketplace.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index fcb4b9c..de21faa 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -10,7 +10,7 @@ "source": "git-subdir", "url": "https://github.com/gitkb/gitkb-codex-plugin.git", "path": "./plugin", - "sha": "3a6c6ecc6fa6e79a5170151209f565dda5e153d8" + "sha": "d6b67ba8b244a9072996d63636bb8bf614ffc207" }, "policy": { "installation": "AVAILABLE",