* test(cmd/bd): reset cobra flags between in-process runs; keep them out of parallel tests
runBDInProcess and runBDInProcessAllowError execute the package-level
rootCmd tree again and again in one process, and cobra never resets a
flag between Execute calls: a value one invocation parsed (create's
--title, --labels, list's --status, ...) and its Changed bit stayed on the
FlagSet, so the next invocation saw it, and a slice flag that had been
set appended to the stale value instead of replacing it. With a Dolt test
server (the only setup in which these tests run) that failed about 20
TestCLI_* tests depending on suite order.
TestMain now snapshots every flag of the tree (snapshotCommandFlags,
after all init()s registered them, before any test runs) and both runners
put the tree back before and after each run (resetCommandFlags): the
pointee of each flag.Value is restored (for pflag's scalar types that is
the bound variable; for slice types it also clears the internal "changed"
bit, so the next Set replaces), slice contents via SliceValue.Replace,
and Changed=false. TestResetCommandFlagsRestoresEveryFlag sets every flag
of the real tree and checks the reset. The ad-hoc --title reset in
TestCLI_CreateRejectsEmptyTitle_ProxiedServerMode is no longer needed.
Seven TestCLI_Comment* tests called t.Parallel() around the runners.
inProcessMutex serializes the runners only against each other, so their
chdir, stdio swap, env and config re-initialization raced every other
parallel test (data races on config globals; TestCobraParallelPolicyGuard
failing to read its own source files after a concurrent chdir). They run
serially now, and the guard treats the two runners like rootCmd.Execute.
Also two stale TestCLI_Create* cases: DryRunWithRigPrefix exercised a
create --prefix flag that no longer exists, and the flag-like-title cases
passed "--help" or "--foo-bar" where cobra parses them as flags; they now
pass the title after "--", the only way it reaches create's own guard.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix the ADO round-trip and bulk-delete tests that rotted unseen
Both need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd (BEADS_TEST_SKIP=dolt everywhere), so they failed unnoticed:
- TestADORoundTrip* stored ado.pat in the database. ado.pat is a secret
read only from config.yaml or AZURE_DEVOPS_PAT (config.IsYamlOnlyKey),
so the tracker found no PAT. The fixture sets AZURE_DEVOPS_PAT.
- TestBulkDeleteNoResurrection expected GetIssue to return (nil, nil) for
a deleted issue; the Dolt store reports storage.ErrNotFound.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix parity, completion and notion tests that only fail with a Dolt server
These are Dolt-gated (integration tag + test server), so no CI lane ran
them and they rotted:
- TestParityCreate*/TestParityReopenErrorExits1Silently: bd create
auto-routes via routing.DetectUserRole("."), which warns "beads.role
not configured (GH#2950)" on stderr when the working directory's git
config has no beads.role. The suite pins the configured case, so the
parity env now sets beads.role=maintainer in a test-owned global git
config ($XDG_CONFIG_HOME/git/config; the role lookup scrubs every
GIT_CONFIG_* variable, so those cannot be used).
- TestIssueIDCompletion: issueIDCompletion resolves a database path
before looking at the open store and returns nothing when there is
none; the test now sets dbPath to its store's path.
- TestIssueIDCompletion_UsesWorktreeFallbackWhenStoreNil and
TestGetNotionConfigReadsDBPathWhenStoreUnset: the code under test
reopens the store from metadata.json, which names a database but not
the per-test branch of the shared database that newTestStore uses, so
the reopened store saw none of the test's rows. They now use their own
database (newTestStoreIsolatedDB).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix stale doctor/e2e/autocommit/readonly Dolt-gated tests
These need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd, so they rotted unseen:
- TestE2E_DoctorFixMetadataRoundtrip, TestE2E_MigrateDoltMetadata,
TestDoctorCheckHealthReportsVersionMismatchOnRepoLocalPort: bd init now
defaults to embedded mode, where `bd sql` and `bd dolt start` are
refused. Init with --server on a repo-local server of their own
(repoLocalServerEnv: the suite's shared-server port vars cleared, server
stopped at cleanup) and start it explicitly, since BEADS_TEST_MODE=1 never
auto-starts one. MigrateDoltMetadata's DELETE also needed `key` quoted.
- TestDoctor{Conventions,Pollution}MaxRows_EnvOnly_Exits2: bdRunRaw drops
every BEADS_* variable, so the subprocess hit dolt.New's test-database
firewall (exit 1) before the row cap; pass BEADS_TEST_SERVER=1.
- TestDoltAutoCommit_On_WritesAdvanceHead: the embedded engine keeps its
data under .beads/embeddeddolt, not .beads/dolt; findDoltRepoDir looks
in both.
- TestValidateCheck_AllClean: bd doctor validate runs five checks since
the cross-table duplicates check was added.
- TestConfigValidateReadOnlyIsHermetic: readonly commands take a shared
workspace gate, whose lock file (.beads/dolt.gate.lock) workspacegate
creates on first use by design; compare the .beads tree without gate
lock files.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): undo each in-process execution's env and storage-mode leaks
Every in-process run of the bd command tree (runBDInProcess and the many
tests that call rootCmd.Execute directly) leaves process state behind:
PersistentPreRun exports the selected workspace as BEADS_DIR, loads its
.beads/.env, and records the workspace's mode in serverMode /
proxiedServerMode. With a Dolt test server, later tests in the same shard
then resolved a deleted fixture ("no active beads workspace found",
"migration sidecar is missing"), ran subprocess bd against the wrong
workspace ("recorded as proxied-server in .beads/metadata.json"), or took
the proxied path in RunE-level tests ("proxied-server UOW provider not
initialized", a nil-UOW panic in reopenProxiedResolve that killed a shard).
TestMain now registers a cobra initializer/finalizer pair
(installExecuteIsolation) that snapshots the environment and the two mode
globals when an execution starts and restores them when it ends; the
runners' restoreEnvSnapshot shares the helper. TestDoltConfigEnvironmentOverrides
used os.Setenv + defer os.Unsetenv, which deleted the suite's
BEADS_DOLT_SERVER_PORT (the test server's port) for every later test; it
uses t.Setenv now.
Full integration-tagged cmd/bd suite against a hermetic dolt (16 shards):
18 order-dependent failures and the shard panic gone; the 27 remaining
failures all fail alone too.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(init): keep --quiet quiet through the Claude/Codex/Cursor auto-setup
`bd init --quiet` ("Suppress output") still printed the project
integration installers' progress to stdout ("Installing Claude hooks for
this project...", "Claude Code integration installed", ...): the
installers write to os.Stdout unconditionally. Point stdout at the null
device around them while quiet; their failures keep going to stderr as
before. Found by TestInitCommand's quiet case, which asserts no output and
had not run in CI (Dolt-gated).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(init): bring the Dolt-gated init tests up to the current init contract
These tests need a Dolt test server, so no CI lane ran them and they
drifted from the product:
- Embedded is init's default mode, so the server-mode assertions
(.beads/dolt, opening the database on the test server, dolt_mode
"server" in metadata.json) now pass --server (TestInitCommand,
TestInitAlreadyInitialized, TestInitRedirect, TestInitBEADS_DIR,
TestInitDoltMetadata, TestInitDoltMetadataNoGit, TestInitDatabaseFlag's
metadata subtests). The in-process ones reset rootCmd's flags around
themselves so --server cannot leak into later in-process inits.
- Each server init gets its own --database: the suite shares one test
server, and a "test" database another test created belongs to another
project (init refuses: PROJECT IDENTITY MISMATCH).
- The marker tests seed a current-era version witness: the legacy-upgrade
guard refuses a non-empty .beads/dolt without one.
- The redirect test provisions the canonical target with config.yaml: bd
ignores a redirect to a directory with no project files (#4692).
- Shared-server inits get a free port of their own
(sharedServerTestEnv): the inherited BEADS_DOLT_SERVER_PORT is the
suite's test server, which a shared-server start refuses as another
project's, and the default shared port is 3308, a developer's live
server.
- --shared-server's config.yaml is now nested YAML (dolt: shared-server:
true); parse it instead of matching the old flat line.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): run the Dolt-gated tests that skipped on a bare dolt.New
setupTestDB (config, kv and Linear round-trip tests), setupGatedTestDB
(mol ready --gated) and the rename-prefix and bd sql tests opened stores
with dolt.New(&dolt.Config{Path: ...}): no server port, no
CreateIfMissing, so against a running test server they got "database ...
not found" and skipped as "Dolt server not available". They now use the
suite's newTestStore helpers (skip only when no test server runs), and
what that exposed is fixed test-side:
- TestCustomStatusConfig: custom_statuses is read back ORDER BY name;
look statuses up by name / expect name order.
- TestLinearRoundTripCoreFields, TestLinearPullMilestonesCreatesEpicHierarchy:
linear.api_key is a yaml-only secret (LINEAR_API_KEY), push now needs an
explicit linear.state_map, and batch push uses TeamLabels and
issueBatchCreate, which the mock server now answers.
- TestSqlCommand: bd sql refuses in the default embedded mode; set
serverMode for the server-backed store, and stop discarding RunE errors.
- TestE2E_AutoStartedRepoLocalServerPersistsAcrossCommands skipped on
this process's embedded mode although every bd it runs is a subprocess
on a --server workspace; gate on the dolt binary instead and stop the
auto-started server at cleanup.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): no fixed "unused" port, no swallowed JSON, no leaked front-door server
Three more things the Dolt-backed cmd/bd run exposed:
- TestTestServerConnection, TestSharedServerCfgNilHonorsSharedServer and
the two TestLegacyGuard* e2e tests pointed bd at 127.0.0.1:59999 as a
port nothing listens on. Any process on the host may hold it; a
listener that accepts and resets turns the expected "connection
refused" / "Dolt server unreachable" into another error. They take a
just-freed port from closedLoopbackPort (testutil.FindFreePort) now.
- TestDoltSetConfigJSONOutput and TestDoltSetConfigWithUpdateConfig
created .beads 0755, so bd's permissions warning landed in the JSON
under test and the tests skipped ("output not pure JSON") every run.
The fixture uses 0700, and non-JSON output fails instead of skipping.
- TestMigrateDoltModeFrontDoor's closing show/list auto-start a
repo-local server after the reverse migration; nothing stopped it, so
the suite's leak check failed (when the opt-in
BEADS_TEST_MIGRATION_FRONTDOOR suite runs). It stops it at cleanup.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): advisory cmd/bd Dolt-server tier (bazel-cmd-dolt)
No CI lane ran cmd/bd's Dolt-gated tests (TestCLI_*, the init and
store-backed suites, the doctor/e2e tests): main.yml's integration shards,
nightly's Full Test Suite, and Bazel's --config=prcore/ci and
--config=integration all pass BEADS_TEST_SKIP=dolt, so cmd/bd's TestMain
never starts a test server and those tests skip; the proxied and embedded
tiers run only their manifests' tests. They rotted unseen.
//cmd/bd:bd_dolt_server_test (tag dolt-server-cmd) runs the whole
integration-tagged cmd/bd suite, the integration build's bd_test, against
a hermetic dolt sql-server: BEADS_TEST_DOLT_SERVER=local starts it from
the pinned dolt in the test wrapper's runfiles, and
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 fails the target instead of skipping
into a cached pass. No test selection: the Go binary shards itself over
every top-level test (32 shards), so each runs exactly once, and
check_testcases.py fails a shard that ran none. --config=doltserver-cmd
has exactly --config=integration's build flags, so the two lanes share
bd_test's compile; prcore/ci and integration exclude the tag.
bazel.yml's new bazel-cmd-dolt job runs it exactly where bazel-integration
runs (same if: remotely on the farm for same-repo PRs, fork-ro/fork-rw,
and locally with the read-only cache in mode cache for forks). It is
advisory: job-level continue-on-error keeps a failure out of the call's
aggregate (BAZEL), and pr.yml's ci-gate reads its result (BAZEL_CMD_DOLT)
but requires it only while the committed top-level flag
BAZEL_CMD_DOLT_REQUIRED is "true" (now "false"; flipping it is the one
change needed). bazel-gate.sh accepts its skip in modes skip and local.
Policy tests: a third lane category in TestBazelLaneIsGatedAlongsideLegacy
(bazelFlagGatedLanes: gate env wired, never statically required, added by
the run script exactly when the pinned flag is "true"), the gate
simulation over every mode with the flag off (advisory: nothing it
reports reddens the gate) and on (exactly a gated lane), the cache-mode
and execution-mode checks, the tag taxonomy and prcore/integration
exclusions, and TestBazelCmdDoltJob (job steps, timeouts, .bazelrc
config equal to integration's build with no dolt skip or test selection,
the target's dolt-server rules, and bd_test's env repeated).
Measured locally (all fixes in this series, 32 shards, 16 at a time on a
shared host): 3267 top-level tests, all shards pass, max shard 313s (one
5001-issue export test, 214s, sets it), mean 100s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(init): hand the project installers a writer instead of swapping os.Stdout
The --quiet fix earlier in this series pointed the process-global
os.Stdout at the null device around the Claude/Codex/Cursor installers.
That works, but it mutates a global from inside a cobra Run: anything else
writing to stdout meanwhile (a goroutine, a future concurrent installer)
would vanish, and a concurrent read of os.Stdout is a data race.
The installers already write through env structs with stdout/stderr
fields. setup.ProjectInstallOutput carries the two writers, and
InstallClaudeProjectTo / InstallCodexProjectTo / InstallCursorProjectTo
use them (the old entry points keep the process streams). init passes
QuietProjectInstallOutput() under --quiet: progress discarded, error lines
still on stderr. The proxied-server init path (domain adapter
InstallClaudeProject now takes quiet) does the same, so its
"Installing Claude hooks..." is quiet too.
Consistent error policy under --quiet: errors still reach stderr. init's
own "Warning: failed to setup <installer>" lines were suppressed under
--quiet while the installers' "Error:" lines were not, and some installer
failures (Cursor rules) print nothing themselves; the warnings now print
whether or not quiet, like the installers' errors.
Coverage in required lanes: TestProjectInstallersReportToTheGivenOutput
(cmd/bd/setup) and TestEmbeddedInitA/basic, which now asserts that
`bd init --quiet` with agents enabled installs the Claude hooks and prints
none of the installers' progress (verified to fail with the quiet output
disabled).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(export): exercise the incremental-export fallback with a small threshold
TestTryIncrementalExport_ThresholdExceededFallsBack seeded
incrementalExportThreshold+1 = 5001 issues to cross the threshold. Batch
create is one transaction but still several statements per issue, so under
-race against the shared test server it took ~214 s, the longest test in
cmd/bd's Dolt-backed suite by far. The behaviour under test is only
"more changed issues than the threshold -> full export fallback".
incrementalExportThreshold becomes a var (same value), and the test, which
is not parallel, sets it to 20 and seeds 21 issues: 214 s -> 0.6 s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): tighten the flag-reset self-test, guards and canaries
Review follow-ups:
- TestResetCommandFlagsRestoresEveryFlag no longer skips a flag it cannot
set: a flag type without a sample value, a Set error, or a non-pointer
Value (which resetCommandFlags could not restore) is an error, so a new
flag type cannot go untested. resetCommandFlags documents that it also
resets flag-bound package globals.
- TestCobraParallelPolicyGuard treats .ExecuteC/.ExecuteContext/
.ExecuteContextC like .Execute (the per-execution isolation writes the
mode globals; a parallel execution would race).
- TestConfigValidateReadOnlyIsHermetic ignores only the gate a readonly
command takes (.beads/dolt.gate.lock and its .info sidecar), not any
"*.gate.lock*" file, so a new unexpected gate still trips the canary.
- TestCLI_CreateRejectsFlagLikeTitles: a bare `bd create --foo-bar` must
fail and create no issue (bd-2c0's intent), next to the "--" cases.
- TestCustomStatusConfig cites why statuses come back in name order: the
normalized custom_statuses table (#2961, 8537d943b) has no ordinal and is
read ORDER BY name, like custom_types; the test predates it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): run the cmd/bd Dolt-server tier in 16 shards
Each shard pays ~30-40 s of fixed cost (TestMain plus its own dolt
sql-server), so 32 shards spent roughly 40% of the lane's executor time on
setup and added 32 farm actions to every PR touching cmd/bd. With the
5001-issue export test cut to under a second, 16 shards measure (locally,
--nocache_test_results): max 186 s, mean 137 s, 2,187 executor-seconds
(vs ~2,800-3,200 at 32), all 3,267 top-level tests, every shard passing.
TestBazelCmdDoltJob pins the count; bazel.yml's timing comment is
restated (cache mode ~20-30 minutes).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
871 lines
25 KiB
Go
871 lines
25 KiB
Go
package setup
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/internal/templates/agents"
|
|
)
|
|
|
|
const (
|
|
codexInstructionMarker = "BEADS CODEX SETUP"
|
|
codexBeginMarker = "<!-- BEGIN " + codexInstructionMarker + ": generated by bd setup codex -->"
|
|
codexEndMarker = "<!-- END " + codexInstructionMarker + " -->"
|
|
codexInstructionsFile = "AGENTS.md"
|
|
codexConfigDir = ".codex"
|
|
codexConfigFile = "config.toml"
|
|
codexHooksFile = "hooks.json"
|
|
codexHomeEnvVar = "CODEX_HOME"
|
|
codexLegacySessionStartCommand = `bd prime --stealth | jq -Rs '{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:.}}'`
|
|
)
|
|
|
|
var (
|
|
codexEnvProvider = defaultCodexEnv
|
|
errCodexInstructionsMissing = errors.New("codex instructions not installed")
|
|
errCodexInstructionsStale = errors.New("codex instructions are stale")
|
|
errCodexInstructionsNoMarker = errors.New("codex instructions section missing")
|
|
errCodexHooksMissing = errors.New("codex hooks not installed")
|
|
errCodexHooksStale = errors.New("codex hooks are stale")
|
|
errCodexFeatureMissing = errors.New("codex hooks feature flag not enabled")
|
|
)
|
|
|
|
type codexEnv struct {
|
|
stdout io.Writer
|
|
stderr io.Writer
|
|
homeDir string
|
|
projectDir string
|
|
ensureDir func(string, os.FileMode) error
|
|
readFile func(string) ([]byte, error)
|
|
writeFile func(string, []byte) error
|
|
removeFile func(string) error
|
|
getenv func(string) string
|
|
}
|
|
|
|
func defaultCodexEnv() (codexEnv, error) {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return codexEnv{}, fmt.Errorf("home directory: %w", err)
|
|
}
|
|
workDir, err := os.Getwd()
|
|
if err != nil {
|
|
return codexEnv{}, fmt.Errorf("working directory: %w", err)
|
|
}
|
|
return codexEnv{
|
|
stdout: os.Stdout,
|
|
stderr: os.Stderr,
|
|
homeDir: home,
|
|
projectDir: workDir,
|
|
ensureDir: EnsureDir,
|
|
readFile: os.ReadFile,
|
|
writeFile: func(path string, data []byte) error {
|
|
return atomicWriteFile(path, data)
|
|
},
|
|
removeFile: os.Remove,
|
|
getenv: os.Getenv,
|
|
}, nil
|
|
}
|
|
|
|
func InstallCodex(global bool) error {
|
|
env, err := codexEnvProvider()
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
return installCodex(env, global)
|
|
}
|
|
|
|
// InstallCodexProject installs project-local Codex integration, returning an
|
|
// error instead of exiting. Used by bd init to integrate Codex setup
|
|
// automatically.
|
|
func InstallCodexProject() error {
|
|
return InstallCodexProjectTo(ProjectInstallOutput{})
|
|
}
|
|
|
|
// InstallCodexProjectTo is InstallCodexProject reporting to out.
|
|
func InstallCodexProjectTo(out ProjectInstallOutput) error {
|
|
env, err := codexEnvProvider()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
env.stdout, env.stderr = out.stdout(), out.stderr()
|
|
return installCodex(env, false)
|
|
}
|
|
|
|
func installCodex(env codexEnv, global bool) error {
|
|
if err := installAgentSkill(codexAgentSkillEnv(env, global)); err != nil {
|
|
return err
|
|
}
|
|
if err := installCodexNativeHooks(env, global); err != nil {
|
|
return err
|
|
}
|
|
return installCodexInstructions(env, global)
|
|
}
|
|
|
|
func CheckCodex(global bool) error {
|
|
env, err := codexEnvProvider()
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
return checkCodex(env, global)
|
|
}
|
|
|
|
func checkCodex(env codexEnv, global bool) error {
|
|
if err := checkAgentSkill(codexAgentSkillEnv(env, global), codexSetupCommand(global)); err != nil {
|
|
return err
|
|
}
|
|
if err := checkCodexNativeHooks(env, global); err != nil {
|
|
return err
|
|
}
|
|
return checkCodexInstructions(env, global)
|
|
}
|
|
|
|
func RemoveCodex(global bool) error {
|
|
env, err := codexEnvProvider()
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
return removeCodex(env, global)
|
|
}
|
|
|
|
func removeCodex(env codexEnv, global bool) error {
|
|
// The agent skill is shared with Cursor (same .agents/skills/beads path).
|
|
// Only remove it if Cursor isn't still relying on it.
|
|
if cursorIntegrationInstalledAt(env.readFile, codexRootDir(env, global), global) {
|
|
_, _ = fmt.Fprintln(env.stdout, "Keeping Beads agent skill (still used by Cursor integration)")
|
|
} else if err := removeAgentSkill(codexAgentSkillEnv(env, global)); err != nil {
|
|
return err
|
|
}
|
|
if err := removeCodexNativeHooks(env, global); err != nil {
|
|
return err
|
|
}
|
|
return removeCodexInstructions(env, global)
|
|
}
|
|
|
|
// cursorIntegrationInstalledAt reports whether Cursor's bd integration exists
|
|
// under root (projectDir for project scope, homeDir for global scope), using the
|
|
// provided readFile so the check stays hermetic in tests. Both Cursor and Codex
|
|
// install the shared .agents/skills/beads skill, so removing one must not delete
|
|
// the skill while the other still relies on it.
|
|
func cursorIntegrationInstalledAt(readFile func(string) ([]byte, error), root string, global bool) bool {
|
|
if data, err := readFile(filepath.Join(root, ".cursor", "hooks.json")); err == nil {
|
|
if config, perr := parseHooksJSON(data); perr == nil && cursorBeadsHooksPresent(config) {
|
|
return true
|
|
}
|
|
}
|
|
if !global {
|
|
if _, err := readFile(filepath.Join(root, cursorRulesPath)); err == nil {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func codexSetupCommand(global bool) string {
|
|
if global {
|
|
return "bd setup codex --global"
|
|
}
|
|
return "bd setup codex"
|
|
}
|
|
|
|
func codexRootDir(env codexEnv, global bool) string {
|
|
if global {
|
|
return env.homeDir
|
|
}
|
|
return env.projectDir
|
|
}
|
|
|
|
func codexHomeDir(env codexEnv) string {
|
|
if env.getenv != nil {
|
|
if path := env.getenv(codexHomeEnvVar); path != "" {
|
|
return path
|
|
}
|
|
}
|
|
return filepath.Join(env.homeDir, codexConfigDir)
|
|
}
|
|
|
|
func codexInstructionsPath(env codexEnv, global bool) string {
|
|
if global {
|
|
return filepath.Join(codexHomeDir(env), codexInstructionsFile)
|
|
}
|
|
return filepath.Join(env.projectDir, codexInstructionsFile)
|
|
}
|
|
|
|
func codexConfigRoot(env codexEnv, global bool) string {
|
|
if global {
|
|
return codexHomeDir(env)
|
|
}
|
|
return filepath.Join(env.projectDir, codexConfigDir)
|
|
}
|
|
|
|
func codexConfigPath(env codexEnv, global bool) string {
|
|
return filepath.Join(codexConfigRoot(env, global), codexConfigFile)
|
|
}
|
|
|
|
func codexHooksPath(env codexEnv, global bool) string {
|
|
return filepath.Join(codexConfigRoot(env, global), codexHooksFile)
|
|
}
|
|
|
|
func codexAgentSkillEnv(env codexEnv, global bool) agentSkillEnv {
|
|
return agentSkillEnv{
|
|
stdout: env.stdout,
|
|
stderr: env.stderr,
|
|
projectDir: codexRootDir(env, global),
|
|
ensureDir: env.ensureDir,
|
|
readFile: env.readFile,
|
|
writeFile: env.writeFile,
|
|
removeFile: env.removeFile,
|
|
}
|
|
}
|
|
|
|
func codexManagedSection() string {
|
|
return codexBeginMarker + "\n" + agents.CodexSectionBody() + "\n" + codexEndMarker
|
|
}
|
|
|
|
func installCodexInstructions(env codexEnv, global bool) error {
|
|
path := codexInstructionsPath(env, global)
|
|
if global {
|
|
_, _ = fmt.Fprintln(env.stdout, "Installing Codex instructions globally...")
|
|
} else {
|
|
_, _ = fmt.Fprintln(env.stdout, "Installing Codex instructions for this project...")
|
|
}
|
|
|
|
if err := env.ensureDir(filepath.Dir(path), 0o755); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: %v\n", err)
|
|
return err
|
|
}
|
|
|
|
var current string
|
|
data, err := env.readFile(path)
|
|
switch {
|
|
case err == nil:
|
|
current = string(data)
|
|
case os.IsNotExist(err):
|
|
default:
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
|
|
next := upsertCodexManagedSection(current)
|
|
if err := env.writeFile(path, []byte(next)); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
|
|
_, _ = fmt.Fprintln(env.stdout, "✓ Codex instructions installed")
|
|
_, _ = fmt.Fprintf(env.stdout, " File: %s\n", path)
|
|
_, _ = fmt.Fprintln(env.stdout, "Restart Codex if it is already running.")
|
|
return nil
|
|
}
|
|
|
|
func checkCodexInstructions(env codexEnv, global bool) error {
|
|
path := codexInstructionsPath(env, global)
|
|
data, err := env.readFile(path)
|
|
if os.IsNotExist(err) {
|
|
_, _ = fmt.Fprintf(env.stdout, "✗ Codex instructions not found: %s\n", path)
|
|
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
|
return errCodexInstructionsMissing
|
|
}
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
|
|
section, ok := extractCodexManagedSection(string(data))
|
|
if !ok {
|
|
_, _ = fmt.Fprintf(env.stdout, "⚠ Codex instructions exist but no beads section found: %s\n", path)
|
|
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
|
return errCodexInstructionsNoMarker
|
|
}
|
|
if section != codexManagedSection() {
|
|
_, _ = fmt.Fprintf(env.stdout, "⚠ Codex instructions installed but stale: %s\n", path)
|
|
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
|
return errCodexInstructionsStale
|
|
}
|
|
|
|
_, _ = fmt.Fprintf(env.stdout, "✓ Codex instructions installed: %s\n", path)
|
|
return nil
|
|
}
|
|
|
|
func removeCodexInstructions(env codexEnv, global bool) error {
|
|
path := codexInstructionsPath(env, global)
|
|
_, _ = fmt.Fprintln(env.stdout, "Removing Codex instructions...")
|
|
data, err := env.readFile(path)
|
|
if os.IsNotExist(err) {
|
|
_, _ = fmt.Fprintln(env.stdout, "No Codex instructions file found")
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
|
|
next, ok := removeCodexManagedSection(string(data))
|
|
if !ok {
|
|
_, _ = fmt.Fprintln(env.stdout, "No beads Codex section found")
|
|
return nil
|
|
}
|
|
if err := env.writeFile(path, []byte(next)); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
|
|
_, _ = fmt.Fprintln(env.stdout, "✓ Codex instructions removed")
|
|
return nil
|
|
}
|
|
|
|
func upsertCodexManagedSection(content string) string {
|
|
section := codexManagedSection()
|
|
if _, ok := extractCodexManagedSection(content); ok {
|
|
start := strings.Index(content, codexBeginMarker)
|
|
end := strings.Index(content, codexEndMarker)
|
|
end += len(codexEndMarker)
|
|
return content[:start] + section + content[end:]
|
|
}
|
|
if strings.TrimSpace(content) == "" {
|
|
return "# Codex Instructions\n\n" + section + "\n"
|
|
}
|
|
if !strings.HasSuffix(content, "\n") {
|
|
content += "\n"
|
|
}
|
|
return content + "\n" + section + "\n"
|
|
}
|
|
|
|
func extractCodexManagedSection(content string) (string, bool) {
|
|
start := strings.Index(content, codexBeginMarker)
|
|
end := strings.Index(content, codexEndMarker)
|
|
if start == -1 || end == -1 || start > end {
|
|
return "", false
|
|
}
|
|
end += len(codexEndMarker)
|
|
return content[start:end], true
|
|
}
|
|
|
|
func removeCodexManagedSection(content string) (string, bool) {
|
|
start := strings.Index(content, codexBeginMarker)
|
|
end := strings.Index(content, codexEndMarker)
|
|
if start == -1 || end == -1 || start > end {
|
|
return content, false
|
|
}
|
|
end += len(codexEndMarker)
|
|
if end < len(content) && content[end] == '\n' {
|
|
end++
|
|
}
|
|
return content[:start] + content[end:], true
|
|
}
|
|
|
|
func installCodexNativeHooks(env codexEnv, global bool) error {
|
|
if global {
|
|
_, _ = fmt.Fprintln(env.stdout, "Installing Codex native hooks globally...")
|
|
} else {
|
|
_, _ = fmt.Fprintln(env.stdout, "Installing Codex native hooks for this project...")
|
|
}
|
|
if err := installCodexFeatureFlag(env, global); err != nil {
|
|
return err
|
|
}
|
|
if codexBeadsPluginEnabled(env, global) {
|
|
_, _ = fmt.Fprintln(env.stdout, "✓ Beads Codex plugin detected — hooks are plugin-managed, skipping hooks.json fallback")
|
|
return nil
|
|
}
|
|
if err := installCodexHooksJSON(env, global); err != nil {
|
|
return err
|
|
}
|
|
_, _ = fmt.Fprintln(env.stdout, "✓ Codex native hooks installed")
|
|
return nil
|
|
}
|
|
|
|
func checkCodexNativeHooks(env codexEnv, global bool) error {
|
|
if !codexConfigHasHooksFeature(env, global) {
|
|
_, _ = fmt.Fprintf(env.stdout, "✗ Codex hooks feature flag not enabled: %s\n", codexConfigPath(env, global))
|
|
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
|
return errCodexFeatureMissing
|
|
}
|
|
if codexBeadsPluginEnabled(env, global) {
|
|
_, _ = fmt.Fprintln(env.stdout, "✓ Codex native hooks provided by beads plugin (plugin-managed)")
|
|
return nil
|
|
}
|
|
if !codexHooksJSONCurrent(env, global) {
|
|
_, _ = fmt.Fprintf(env.stdout, "⚠ Codex hooks missing or stale: %s\n", codexHooksPath(env, global))
|
|
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
|
return errCodexHooksStale
|
|
}
|
|
_, _ = fmt.Fprintf(env.stdout, "✓ Codex native hooks installed: %s\n", codexHooksPath(env, global))
|
|
return nil
|
|
}
|
|
|
|
func removeCodexNativeHooks(env codexEnv, global bool) error {
|
|
if err := removeCodexHooksJSON(env, global); err != nil {
|
|
return err
|
|
}
|
|
return removeCodexFeatureFlag(env, global)
|
|
}
|
|
|
|
func installCodexFeatureFlag(env codexEnv, global bool) error {
|
|
path := codexConfigPath(env, global)
|
|
if err := env.ensureDir(filepath.Dir(path), 0o755); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: %v\n", err)
|
|
return err
|
|
}
|
|
current := ""
|
|
if data, err := env.readFile(path); err == nil {
|
|
current = string(data)
|
|
} else if !os.IsNotExist(err) {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
next := upsertCodexHooksFeature(current)
|
|
if err := env.writeFile(path, []byte(next)); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func removeCodexFeatureFlag(env codexEnv, global bool) error {
|
|
path := codexConfigPath(env, global)
|
|
data, err := env.readFile(path)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
next := removeCodexHooksFeature(string(data))
|
|
if err := env.writeFile(path, []byte(next)); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func codexConfigHasHooksFeature(env codexEnv, global bool) bool {
|
|
data, err := env.readFile(codexConfigPath(env, global))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return codexHooksFeatureEnabled(string(data))
|
|
}
|
|
|
|
func codexBeadsPluginEnabled(env codexEnv, global bool) bool {
|
|
paths := []string{codexConfigPath(env, global)}
|
|
if !global {
|
|
paths = append(paths, codexConfigPath(env, true))
|
|
}
|
|
for _, path := range paths {
|
|
data, err := env.readFile(path)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if codexConfigEnablesBeadsPlugin(string(data)) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func codexConfigEnablesBeadsPlugin(content string) bool {
|
|
inBeadsPlugin := false
|
|
for _, line := range strings.Split(content, "\n") {
|
|
trimmed := strings.TrimSpace(line)
|
|
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
|
table := strings.Trim(trimmed, "[]")
|
|
// Plugin tables are [plugins.<name>] or [plugins."<name>@<marketplace>"]
|
|
// (TOML quotes a key containing "@"). Match the <name> segment
|
|
// exactly: a substring test (GH#4244) mistakes any "*beads*" plugin
|
|
// (e.g. design-to-beads) for the beads hook plugin and wrongly skips
|
|
// the hooks write.
|
|
inBeadsPlugin = false
|
|
if rest, ok := strings.CutPrefix(table, "plugins."); ok {
|
|
name, _, _ := strings.Cut(strings.ToLower(strings.Trim(rest, "\"'")), "@")
|
|
inBeadsPlugin = name == "beads"
|
|
}
|
|
continue
|
|
}
|
|
if inBeadsPlugin && codexConfigLineKey(trimmed) == "enabled" {
|
|
parts := strings.SplitN(trimmed, "=", 2)
|
|
return len(parts) == 2 && strings.TrimSpace(parts[1]) == "true"
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func installCodexHooksJSON(env codexEnv, global bool) error {
|
|
path := codexHooksPath(env, global)
|
|
if err := env.ensureDir(filepath.Dir(path), 0o755); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: %v\n", err)
|
|
return err
|
|
}
|
|
current := map[string]interface{}{}
|
|
data, err := env.readFile(path)
|
|
if err != nil && !os.IsNotExist(err) {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
if err == nil {
|
|
if current, err = parseHooksJSON(data); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
}
|
|
upsertCodexManagedHooks(current)
|
|
out, err := marshalHooksJSON(current)
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: marshal %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
if err := env.writeFile(path, out); err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func removeCodexHooksJSON(env codexEnv, global bool) error {
|
|
path := codexHooksPath(env, global)
|
|
data, err := env.readFile(path)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
current, err := parseHooksJSON(data)
|
|
if err != nil {
|
|
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
|
|
return err
|
|
}
|
|
removeCodexManagedHooks(current)
|
|
if len(current) == 0 {
|
|
if err := env.removeFile(path); err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
next, err := marshalHooksJSON(current)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return env.writeFile(path, next)
|
|
}
|
|
|
|
func codexHooksJSONCurrent(env codexEnv, global bool) bool {
|
|
data, err := env.readFile(codexHooksPath(env, global))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
current, err := parseHooksJSON(data)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return codexManagedHooksCurrent(current)
|
|
}
|
|
|
|
func upsertCodexHooksFeature(content string) string {
|
|
lines := strings.Split(content, "\n")
|
|
inFeatures := false
|
|
featuresSeen := false
|
|
flagSeen := false
|
|
for i, line := range lines {
|
|
trimmed := strings.TrimSpace(line)
|
|
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
|
inFeatures = trimmed == "[features]"
|
|
if inFeatures {
|
|
featuresSeen = true
|
|
}
|
|
continue
|
|
}
|
|
key := codexConfigLineKey(trimmed)
|
|
if inFeatures && key == "codex_hooks" {
|
|
lines[i] = ""
|
|
continue
|
|
}
|
|
if inFeatures && key == "hooks" {
|
|
lines[i] = "hooks = true"
|
|
flagSeen = true
|
|
}
|
|
}
|
|
if featuresSeen && !flagSeen {
|
|
out := make([]string, 0, len(lines)+1)
|
|
inserted := false
|
|
inFeatures = false
|
|
for _, line := range lines {
|
|
trimmed := strings.TrimSpace(line)
|
|
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
|
if inFeatures && !inserted {
|
|
out = append(out, "hooks = true")
|
|
inserted = true
|
|
}
|
|
inFeatures = trimmed == "[features]"
|
|
}
|
|
if strings.TrimSpace(line) != "" {
|
|
out = append(out, line)
|
|
}
|
|
}
|
|
if inFeatures && !inserted {
|
|
out = append(out, "hooks = true")
|
|
}
|
|
lines = out
|
|
}
|
|
next := strings.TrimRight(strings.Join(lines, "\n"), "\n")
|
|
if !featuresSeen {
|
|
if strings.TrimSpace(next) != "" {
|
|
next += "\n\n"
|
|
}
|
|
next += "[features]\nhooks = true"
|
|
}
|
|
return next + "\n"
|
|
}
|
|
|
|
func removeCodexHooksFeature(content string) string {
|
|
lines := strings.Split(content, "\n")
|
|
out := make([]string, 0, len(lines))
|
|
inFeatures := false
|
|
for _, line := range lines {
|
|
trimmed := strings.TrimSpace(line)
|
|
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
|
inFeatures = trimmed == "[features]"
|
|
out = append(out, line)
|
|
continue
|
|
}
|
|
key := codexConfigLineKey(trimmed)
|
|
if inFeatures && (key == "hooks" || key == "codex_hooks") {
|
|
continue
|
|
}
|
|
out = append(out, line)
|
|
}
|
|
return strings.TrimRight(strings.Join(out, "\n"), "\n") + "\n"
|
|
}
|
|
|
|
func codexHooksFeatureEnabled(content string) bool {
|
|
inFeatures := false
|
|
for _, line := range strings.Split(content, "\n") {
|
|
trimmed := strings.TrimSpace(line)
|
|
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
|
inFeatures = trimmed == "[features]"
|
|
continue
|
|
}
|
|
if inFeatures && codexConfigLineKey(trimmed) == "hooks" {
|
|
parts := strings.SplitN(trimmed, "=", 2)
|
|
return len(parts) == 2 && strings.TrimSpace(parts[1]) == "true"
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func codexConfigLineKey(trimmed string) string {
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
|
return ""
|
|
}
|
|
parts := strings.SplitN(trimmed, "=", 2)
|
|
if len(parts) != 2 {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(parts[0])
|
|
}
|
|
|
|
func codexManagedHooks() map[string]interface{} {
|
|
return map[string]interface{}{
|
|
"SessionStart": []interface{}{codexHookEntry("startup|resume|clear", "bd codex-hook SessionStart", "Loading Beads context")},
|
|
"PreCompact": []interface{}{codexHookEntry("manual|auto", "bd codex-hook PreCompact", "Checking Beads context")},
|
|
"PostCompact": []interface{}{codexHookEntry("manual|auto", "bd codex-hook PostCompact", "Scheduling Beads context refresh")},
|
|
"UserPromptSubmit": []interface{}{codexHookEntry("", "bd codex-hook UserPromptSubmit", "Refreshing Beads context")},
|
|
}
|
|
}
|
|
|
|
func codexHookEntry(matcher, command, status string) map[string]interface{} {
|
|
entry := map[string]interface{}{
|
|
"hooks": []interface{}{
|
|
map[string]interface{}{
|
|
"type": "command",
|
|
"command": command,
|
|
"statusMessage": status,
|
|
},
|
|
},
|
|
}
|
|
if matcher != "" {
|
|
entry["matcher"] = matcher
|
|
}
|
|
return entry
|
|
}
|
|
|
|
func upsertCodexManagedHooks(config map[string]interface{}) {
|
|
hooks, ok := config["hooks"].(map[string]interface{})
|
|
if !ok {
|
|
hooks = map[string]interface{}{}
|
|
config["hooks"] = hooks
|
|
}
|
|
for event, entries := range codexManagedHooks() {
|
|
removeCodexManagedHookEvent(hooks, event)
|
|
hooks[event] = append(toInterfaceSlice(hooks[event]), entries.([]interface{})...)
|
|
}
|
|
}
|
|
|
|
func removeCodexManagedHooks(config map[string]interface{}) {
|
|
hooks, ok := config["hooks"].(map[string]interface{})
|
|
if !ok {
|
|
return
|
|
}
|
|
for event := range codexManagedHooks() {
|
|
removeCodexManagedHookEvent(hooks, event)
|
|
}
|
|
if len(hooks) == 0 {
|
|
delete(config, "hooks")
|
|
}
|
|
}
|
|
|
|
func codexManagedHooksCurrent(config map[string]interface{}) bool {
|
|
hooks, ok := config["hooks"].(map[string]interface{})
|
|
if !ok {
|
|
return false
|
|
}
|
|
for _, entry := range toInterfaceSlice(hooks["SessionStart"]) {
|
|
if codexHookEntryHasLegacySessionStart(entry) {
|
|
return false
|
|
}
|
|
}
|
|
for event, wantEntries := range codexManagedHooks() {
|
|
want, _ := wantEntries.([]interface{})
|
|
for _, wantEntry := range want {
|
|
if !codexHookEntriesContain(toInterfaceSlice(hooks[event]), wantEntry) {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// codexBeadsHooksPresent reports whether a parsed hooks.json config contains any
|
|
// bd-managed Codex hook entry ("bd codex-hook " command) or the exact legacy
|
|
// SessionStart pipeline. It mirrors
|
|
// cursorBeadsHooksPresent so codexIntegrationInstalled can detect a hooks-only
|
|
// Codex install (no AGENTS.md section) the same way cursorIntegrationInstalledAt
|
|
// detects a hooks-only Cursor install.
|
|
func codexBeadsHooksPresent(config map[string]interface{}) bool {
|
|
hooks, ok := config["hooks"].(map[string]interface{})
|
|
if !ok {
|
|
return false
|
|
}
|
|
for event := range codexManagedHooks() {
|
|
for _, entry := range toInterfaceSlice(hooks[event]) {
|
|
if codexHookEntryManaged(entry) || (event == "SessionStart" && codexHookEntryHasLegacySessionStart(entry)) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func removeCodexManagedHookEvent(hooks map[string]interface{}, event string) {
|
|
entries := toInterfaceSlice(hooks[event])
|
|
filtered := entries[:0]
|
|
for _, entry := range entries {
|
|
if codexHookEntryManaged(entry) {
|
|
continue
|
|
}
|
|
if event == "SessionStart" && !removeCodexLegacySessionStartCommand(entry) {
|
|
continue
|
|
}
|
|
filtered = append(filtered, entry)
|
|
}
|
|
if len(filtered) == 0 {
|
|
delete(hooks, event)
|
|
} else {
|
|
hooks[event] = filtered
|
|
}
|
|
}
|
|
|
|
func codexHookEntriesContain(entries []interface{}, want interface{}) bool {
|
|
wantJSON, _ := json.Marshal(want)
|
|
for _, entry := range entries {
|
|
gotJSON, _ := json.Marshal(entry)
|
|
if string(gotJSON) == string(wantJSON) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func codexHookEntryManaged(entry interface{}) bool {
|
|
entryMap, ok := entry.(map[string]interface{})
|
|
if !ok {
|
|
return false
|
|
}
|
|
commands := toInterfaceSlice(entryMap["hooks"])
|
|
for _, command := range commands {
|
|
commandMap, ok := command.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
if commandString, _ := commandMap["command"].(string); strings.HasPrefix(commandString, "bd codex-hook ") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func codexHookEntryHasLegacySessionStart(entry interface{}) bool {
|
|
entryMap, ok := entry.(map[string]interface{})
|
|
if !ok {
|
|
return false
|
|
}
|
|
for _, hook := range toInterfaceSlice(entryMap["hooks"]) {
|
|
hookMap, ok := hook.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
command, _ := hookMap["command"].(string)
|
|
if strings.TrimSpace(command) == codexLegacySessionStartCommand {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// removeCodexLegacySessionStartCommand removes only the exact historical
|
|
// SessionStart pipeline from an entry. It reports whether the entry still has
|
|
// hooks and should be preserved.
|
|
func removeCodexLegacySessionStartCommand(entry interface{}) bool {
|
|
entryMap, ok := entry.(map[string]interface{})
|
|
if !ok {
|
|
return true
|
|
}
|
|
hooks := toInterfaceSlice(entryMap["hooks"])
|
|
if hooks == nil {
|
|
return true
|
|
}
|
|
filtered := hooks[:0]
|
|
removed := false
|
|
for _, hook := range hooks {
|
|
hookMap, ok := hook.(map[string]interface{})
|
|
if ok {
|
|
command, _ := hookMap["command"].(string)
|
|
if strings.TrimSpace(command) == codexLegacySessionStartCommand {
|
|
removed = true
|
|
continue
|
|
}
|
|
}
|
|
filtered = append(filtered, hook)
|
|
}
|
|
if !removed {
|
|
return true
|
|
}
|
|
if len(filtered) == 0 {
|
|
return false
|
|
}
|
|
entryMap["hooks"] = filtered
|
|
return true
|
|
}
|
|
|
|
func toInterfaceSlice(value interface{}) []interface{} {
|
|
switch typed := value.(type) {
|
|
case []interface{}:
|
|
return typed
|
|
default:
|
|
return nil
|
|
}
|
|
}
|