Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,25 @@ on:
branches:
- main

permissions:
contents: read

jobs:
validate:
runs-on: ubuntu-latest
timeout-minutes: 10
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
run: make release-check
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install Codex for 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"
13 changes: 10 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
.PHONY: all test lint lint-json lint-policy lint-codex diff-check release-check clean
.PHONY: all test test-integration lint lint-json lint-policy lint-codex diff-check release-check clean

all: lint test

test:
@tests/package-policy.sh
@python3 -B tests/mcp-contract.py plugin
@python3 -B tests/mcp-startup-unit.py

test-integration:
@python3 -B tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)"
@python3 -B tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" --legacy-first

lint: lint-json lint-policy lint-codex
@echo "All checks passed."
Expand All @@ -23,8 +29,9 @@ lint-policy:
@tests/package-policy.sh

lint-codex:
@if command -v codex >/dev/null 2>&1; then \
echo "Checking Codex CLI is available for marketplace install testing"; \
@if [ -n "$(CODEX_TEST_BINARY)" ]; then \
"$(CODEX_TEST_BINARY)" plugin --help >/dev/null; \
elif command -v codex >/dev/null 2>&1; then \
codex plugin --help >/dev/null; \
else \
echo "Skipping Codex CLI check (codex not available)"; \
Expand Down
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# GitKB Codex Plugin

This repository contains the GitKB marketplace plugin for Codex.
This repository is the authoritative source for the GitKB Codex plugin payload
and its package/MCP regression tests. The `gitkb/codex-plugins` marketplace references
`./plugin` here through a Git-backed source; it does not maintain a plugin copy.
Plugin behavior changes belong in this repository. Catalog release promotion only
updates the marketplace's approved commit selector.

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.

Expand Down Expand Up @@ -87,3 +91,25 @@ The plugin version is declared in:
- `plugin/.codex-plugin/plugin.json`

Keep the marketplace and plugin docs aligned when preparing a release.

## MCP Launch Regression Tests

`make test` checks the packaged environment allowlist and cache version, and
runs negative controls for cache symlinks, special files, executable modes,
receipt path escapes, optimized Python, protocol failures, output limits, and
process cleanup. Python 3.11 or newer is required for these test tools. 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. A second isolated run first installs a bundled
`0.1.0` fixture, reproduces its missing context, then upgrades the same
`gitkb@gitkb` installation and repeats those checks. The harness bounds protocol
buffers and diagnostic reads, and terminates its own app-server process group.
It does not start a model turn or run an activity sink, and it does not use your Codex home or credentials.

```bash
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.
2 changes: 1 addition & 1 deletion plugin/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gitkb",
"version": "0.1.0",
"version": "0.1.2",
"description": "Codex hooks, skills, and MCP config for GitKB code-intelligence guidance.",
"author": {
"name": "GitKB",
Expand Down
10 changes: 10 additions & 0 deletions plugin/.mcp.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@
"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"
]
}
}
Expand Down
20 changes: 19 additions & 1 deletion plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,27 @@ git-kb init codex
- one focused code-intelligence skill;
- Codex lifecycle hooks that call `git-kb hook codex`;
- MCP configuration for `git-kb mcp`;
- no external harness-specific behavior;
- 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/)
Expand Down
42 changes: 42 additions & 0 deletions tests/mcp-contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/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()
196 changes: 196 additions & 0 deletions tests/mcp-startup-unit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Negative controls for the shared real-Codex launch harness."""
import importlib.util
import os
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path

SCRIPT = Path(__file__).with_name('mcp-startup.py')
spec = importlib.util.spec_from_file_location('startup', SCRIPT)
startup = importlib.util.module_from_spec(spec)
spec.loader.exec_module(startup)


class PayloadTests(unittest.TestCase):
def test_payload_rejects_links_and_special_files(self):
"""Never follow external links or block reading FIFOs in a package cache."""
for kind in ('file', 'directory', 'dangling', 'fifo'):
with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
payload = root / 'plugin'
payload.mkdir()
(payload / 'manifest').write_text('approved')
if kind == 'fifo':
os.mkfifo(payload / 'escape')
else:
target = root / 'outside'
if kind == 'file':
target.write_text('outside')
elif kind == 'directory':
target.mkdir()
(target / 'secret').write_text('outside')
(payload / 'escape').symlink_to(target)
with self.assertRaisesRegex(AssertionError, 'regular|symlink'):
startup.payload_fingerprint(payload)

def test_payload_includes_executable_mode(self):
"""Cache equality must detect a lost hook executable bit as well as changed bytes."""
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
path = root / 'hook'
path.write_text('hook')
path.chmod(0o644)
before = startup.payload_fingerprint(root)
path.chmod(0o755)
self.assertNotEqual(before, startup.payload_fingerprint(root))

def test_missing_or_empty_payload_is_not_valid(self):
"""Two absent trees must not pass as matching installations."""
with tempfile.TemporaryDirectory() as directory:
for root in (Path(directory), Path(directory) / 'missing'):
with self.subTest(root=root), self.assertRaises(AssertionError):
startup.payload_fingerprint(root)

def test_receipt_must_stay_inside_isolated_cache(self):
"""Reject external paths, relative paths, and symlink escapes before reading a cache."""
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
outside = root / "outside"
outside.mkdir()
(outside / "payload").write_text("external")
cache = root / "codex/plugins/cache"
cache.mkdir(parents=True)
(cache / "link").symlink_to(outside, target_is_directory=True)
for path in (outside, Path("outside"), cache / "link"):
with self.subTest(path=path), self.assertRaisesRegex(AssertionError, "escapes"):
startup.installed_payload({"installedPath": str(path)}, root)
valid = cache / "gitkb/gitkb/0.1.2"
valid.mkdir(parents=True)
(valid / "payload").write_text("approved")
self.assertEqual(startup.installed_payload({"installedPath": str(valid)}, root),
startup.payload_fingerprint(valid))

def test_optimized_context_check_rejects_missing_or_leaked_values(self):
"""Exercise context mismatch and secret leakage checks in an actual -O interpreter."""
for observed, expected in (({}, {"SESSION_ACTIVITY_RESOURCE_ID": "alpha"}),
({"OPENAI_API_KEY": "synthetic-canary"}, {})):
with self.subTest(observed=observed):
code = ("import importlib.util; "
f"s=importlib.util.spec_from_file_location('startup', {str(SCRIPT)!r}); "
"m=importlib.util.module_from_spec(s); s.loader.exec_module(m); "
f"m.check_context({observed!r}, {expected!r}, 'negative control')")
result = subprocess.run([sys.executable, "-O", "-B", "-c", code],
capture_output=True, text=True, timeout=10)
self.assertNotEqual(result.returncode, 0)
self.assertIn("AssertionError", result.stderr)

def test_legacy_fixture_selects_one_entry_by_name(self):
"""Adding another catalog entry must not silently change the upgrade control's target."""
other = {"name": "other", "source": {"source": "local", "path": "./other"}}
catalog = {"plugins": [other, {"name": "gitkb", "source": {"source": "git-subdir"}}]}
startup.use_legacy_source(catalog)
self.assertEqual(catalog["plugins"][0]["source"], {"source": "local", "path": "./other"})
self.assertEqual(catalog["plugins"][1]["source"], {"source": "local", "path": "./plugin"})
for entries in ([], [other], [{"name": "gitkb"}, {"name": "gitkb"}]):
with self.subTest(entries=entries), self.assertRaises(AssertionError):
startup.use_legacy_source({"plugins": entries})


class ProtocolTests(unittest.TestCase):
def exercise(self, mode, optimized=False):
"""Exercise faults in an owned fake app-server; its PID must be gone on return."""
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
fake = root / 'fake-codex'
capture = root / 'context.json'
fake.write_text('#!' + sys.executable + '\n' + '''import json, os, signal, subprocess, sys, time
from pathlib import Path
root = Path(__file__).parent
(root / 'pid').write_text(str(os.getpid()))
mode = ''' + repr(mode) + '''
if mode == 'descendant':
code = 'import os, signal, time; from pathlib import Path; signal.signal(signal.SIGTERM, signal.SIG_IGN); Path(' + repr(str(root / 'child-pid')) + ').write_text(str(os.getpid())); time.sleep(30)'
subprocess.Popen([sys.executable, '-c', code])
deadline = time.monotonic() + 5
while not (root / 'child-pid').exists() and time.monotonic() < deadline:
time.sleep(0.01)
print('{invalid json', flush=True)
time.sleep(30)
elif mode == 'timeout':
time.sleep(30)
elif mode == 'eof':
sys.stderr.write('synthetic diagnostic\\n')
sys.exit(0)
elif mode == 'flood':
sys.stdout.write('x' * (2 * 1024 * 1024))
sys.stdout.flush()
time.sleep(30)
elif mode == 'malformed':
print('{invalid json', flush=True)
time.sleep(30)
else:
for line in sys.stdin:
request = json.loads(line)
if 'id' not in request:
continue
result = {} if request['id'] == 1 else {'data': [
{'name': 'gitkb', 'pluginId': 'wrong' if mode == 'identity' else 'gitkb@gitkb',
'tools': {} if mode == 'tools' else {'context_probe': {}}}]}
if mode != 'capture':
(root / 'context.json').write_text('{}')
print(json.dumps({'id': request['id'], 'result': result}), flush=True)
''')
fake.chmod(0o755)
env = {'PATH': os.defpath, 'HOME': directory}
if optimized:
probe = root / 'probe.py'
probe.write_text('import importlib.util\nfrom pathlib import Path\n'
f'spec = importlib.util.spec_from_file_location("startup", {str(SCRIPT)!r})\n'
'module = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\n'
f'module.inspect_child({str(fake)!r}, {env!r}, Path({directory!r}), '
f'Path({str(capture)!r}), response_timeout=1)\n')
result = subprocess.run([sys.executable, '-O', '-B', str(probe)],
env=env, capture_output=True, text=True, timeout=10)
self.assertNotEqual(result.returncode, 0, 'optimized Python accepted invalid MCP state')
self.assertIn('AssertionError', result.stderr)
else:
with self.assertRaises(AssertionError) as failure:
startup.inspect_child(str(fake), env, root, capture, response_timeout=1)
if mode == 'eof':
self.assertIn('synthetic diagnostic', str(failure.exception))
if mode == 'flood':
self.assertIn('limit', str(failure.exception))
pid = int((root / 'pid').read_text())
with self.assertRaises(ProcessLookupError):
os.kill(pid, 0)
if mode == 'descendant':
child = int((root / 'child-pid').read_text())
deadline = time.monotonic() + 2
while time.monotonic() < deadline:
state = subprocess.run(['ps', '-p', str(child), '-o', 'stat='],
capture_output=True, text=True, timeout=5).stdout.strip()
if not state or state.startswith('Z'):
break # A zombie is stopped; the host's init process owns its reaping.
time.sleep(0.05)
else:
self.fail('TERM-resistant owned descendant survived cleanup')

def test_faults_fail_and_reap_the_app_server(self):
"""Fail closed on timeout, EOF, malformed/flooding output, wrong identity/tools, or no child."""
for mode in ('timeout', 'eof', 'flood', 'malformed', 'identity', 'tools', 'capture', 'descendant'):
with self.subTest(mode=mode):
self.exercise(mode)

def test_optimized_python_keeps_security_checks(self):
"""Python -O must not disable installed identity/tool/child checks."""
for mode in ('identity', 'tools', 'capture'):
with self.subTest(mode=mode):
self.exercise(mode, optimized=True)


if __name__ == '__main__':
unittest.main()
Loading
Loading