gitgram/aitimemachine/beads/cmd/bd/hooks_exec_composition_test.go
caelum0x 49b183818c Unify gitgram + aitimemachine into the monorepo (de-submodule) and merge vendored engines
Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as
opaque submodule gitlinks on GitHub) into fully-tracked first-party content.

AITM now merges its 7 vendored repos as first-party engines:
- memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts
- git: vendored C git (bundled binary) + gitnexus (in-process code intelligence)
- agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess)

Includes the full session's product build: Gitgram web/mobile/backend features,
AITM website/CLI/MCP, the unified memory layer, engine build tooling
(scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md),
and extensive test suites.

Build artifacts, node_modules, external/, and gemini-cli are gitignored.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 14:14:09 +03:00

353 lines
11 KiB
Go

package main
import (
"strings"
"testing"
)
// section is a stand-in BEADS INTEGRATION block used in these tests; the
// real generator is generateHookSection but the injection logic doesn't care
// about the contents — it only cares about marker presence and placement.
const testBeadsSection = `# --- BEGIN BEADS INTEGRATION v1.2.3 ---
if command -v bd >/dev/null 2>&1; then
bd hooks run pre-commit "$@"
fi
# --- END BEADS INTEGRATION v1.2.3 ---
`
// TestInjectHookSection_PrecommitTemplatedHook reproduces GH#3537: bd's
// section must NOT be appended below pre-commit's templated hook (which ends
// in `exec`), because exec replaces the running shell — anything below it
// is unreachable. The bd section must be injected ABOVE the exec block so
// it actually runs on every commit.
func TestInjectHookSection_PrecommitTemplatedHook(t *testing.T) {
// Faithful reproduction of pre-commit init-templatedir's hook output.
existing := `#!/usr/bin/env bash
# File generated by pre-commit: https://pre-commit.com
# ID: 138fd403232d2ddd5efb44317e38bf03
# start templated
INSTALL_PYTHON='/opt/homebrew/Cellar/pre-commit/4.6.0/libexec/bin/python'
ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit)
# end templated
HERE="$(cd "$(dirname "$0")" && pwd)"
ARGS+=(--hook-dir "$HERE" -- "$@")
if [ -x "$INSTALL_PYTHON" ]; then
exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}"
elif command -v pre-commit > /dev/null; then
exec pre-commit "${ARGS[@]}"
else
echo '` + "`pre-commit`" + ` not found. Did you forget to activate your virtualenv?' 1>&2
exit 1
fi
`
out := injectHookSection(existing, testBeadsSection)
beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION")
if beadsIdx == -1 {
t.Fatalf("bd section not present in result:\n%s", out)
}
ifIdx := strings.Index(out, `if [ -x "$INSTALL_PYTHON" ]`)
if ifIdx == -1 {
t.Fatalf("expected pre-commit's `if` block to remain, got:\n%s", out)
}
if beadsIdx >= ifIdx {
t.Errorf("bd section was injected BELOW the exec block (unreachable). "+
"beads at byte %d, if-block at byte %d. Full output:\n%s",
beadsIdx, ifIdx, out)
}
if !strings.Contains(out, `exec "$INSTALL_PYTHON" -mpre_commit`) ||
!strings.Contains(out, `exec pre-commit "${ARGS[@]}"`) {
t.Errorf("expected both exec lines to be preserved, got:\n%s", out)
}
}
// TestInjectHookSection_StandaloneTrailingExec covers a hook that simply ends
// in a bare `exec <cmd>` with no enclosing if/case. The section should be
// injected directly above the exec line.
func TestInjectHookSection_StandaloneTrailingExec(t *testing.T) {
existing := `#!/bin/sh
echo "user setup"
exec /usr/local/bin/some-tool "$@"
`
out := injectHookSection(existing, testBeadsSection)
beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION")
execIdx := strings.Index(out, "exec /usr/local/bin/some-tool")
if beadsIdx == -1 || execIdx == -1 {
t.Fatalf("missing markers in output:\n%s", out)
}
if beadsIdx >= execIdx {
t.Errorf("bd section was injected BELOW exec (unreachable):\n%s", out)
}
if !strings.Contains(out, `echo "user setup"`) {
t.Errorf("expected user setup line preserved, got:\n%s", out)
}
}
// TestInjectHookSection_NonExecHookAppendsAtEnd is the regression guard:
// hooks that don't end in exec must keep the existing append-at-bottom
// behaviour so we don't change semantics for the common case.
func TestInjectHookSection_NonExecHookAppendsAtEnd(t *testing.T) {
existing := `#!/bin/sh
echo "user hook"
some-other-command
`
out := injectHookSection(existing, testBeadsSection)
// User content must come before the bd section.
userIdx := strings.Index(out, "some-other-command")
beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION")
if userIdx == -1 || beadsIdx == -1 {
t.Fatalf("missing markers:\n%s", out)
}
if userIdx >= beadsIdx {
t.Errorf("expected bd section appended after user content, got:\n%s", out)
}
}
// TestInjectHookSection_ExecInMiddleStillAppends covers the case where a hook
// has an exec call somewhere in the middle but real code follows. We should
// NOT rewrite that — falling back to append is correct.
func TestInjectHookSection_ExecInMiddleStillAppends(t *testing.T) {
existing := `#!/bin/sh
if [ "$1" = "--reload" ]; then
exec "$0"
fi
echo "running normal commit checks"
some-other-command "$@"
`
out := injectHookSection(existing, testBeadsSection)
beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION")
echoIdx := strings.Index(out, `echo "running normal commit checks"`)
if beadsIdx == -1 || echoIdx == -1 {
t.Fatalf("missing markers:\n%s", out)
}
if beadsIdx <= echoIdx {
t.Errorf("bd section should be appended after non-trivial trailing code, got:\n%s", out)
}
}
// TestFindExecBlockInjectionPoint_TableDriven exercises the helper directly
// with a small set of representative inputs.
func TestFindExecBlockInjectionPoint_TableDriven(t *testing.T) {
tests := []struct {
name string
content string
// wantInject is the substring expected at (or just after) the returned
// byte offset; -1 sentinel via wantNegative=true.
wantPrefix string
wantNegative bool
}{
{
name: "empty file",
// no exec at all
content: "",
wantNegative: true,
},
{
name: "just shebang and echo",
content: "#!/bin/sh\necho hi\n",
wantNegative: true,
},
{
name: "bare trailing exec",
content: "#!/bin/sh\necho before\nexec /bin/something\n",
wantPrefix: "exec /bin/something",
},
{
name: "if-elif-else-exec ladder",
content: `#!/usr/bin/env bash
echo top
if [ -x /a ]; then
exec /a
elif command -v b > /dev/null; then
exec b
else
echo missing 1>&2
exit 1
fi
`,
wantPrefix: "if [ -x /a ]",
},
{
name: "exec in middle, normal code follows",
content: `#!/bin/sh
if [ "$1" = "x" ]; then exec "$0"; fi
echo continues
do-stuff
`,
wantNegative: true,
},
{
// Two disjoint exec blocks with real code after both. The scan
// walks back from EOF, hits `do-stuff` (real code), bails with -1
// and the caller appends as normal. (review nit on PR #3556)
name: "two disjoint exec blocks, real code after both",
content: `#!/bin/sh
if [ -x /a ]; then exec /a; fi
echo middle
if [ -x /b ]; then exec /b; fi
do-stuff
`,
wantNegative: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := findExecBlockInjectionPoint(tt.content)
if tt.wantNegative {
if got != -1 {
t.Fatalf("want -1, got %d (content slice from offset: %q)",
got, snippet(tt.content, got, 60))
}
return
}
if got < 0 || got > len(tt.content) {
t.Fatalf("offset %d out of bounds (len %d)", got, len(tt.content))
}
tail := tt.content[got:]
if !strings.HasPrefix(tail, tt.wantPrefix) {
t.Errorf("want offset at prefix %q, got offset %d → %q",
tt.wantPrefix, got, snippet(tt.content, got, 80))
}
})
}
}
// TestInjectHookSection_IfBlockWithCommentInBody covers the backward-walk
// branch in findExecBlockInjectionPoint where the if-body contains a blank
// line or a comment between the `if ...` opener and the `exec` line. Without
// this fixture the comment/blank skip-and-continue branch is unexercised.
func TestInjectHookSection_IfBlockWithCommentInBody(t *testing.T) {
existing := `#!/bin/sh
echo "before"
if [ -x /usr/local/bin/foo ]; then
# Why we use foo: documented elsewhere.
exec /usr/local/bin/foo "$@"
fi
`
out := injectHookSection(existing, testBeadsSection)
beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION")
ifIdx := strings.Index(out, "if [ -x /usr/local/bin/foo ]")
if beadsIdx == -1 || ifIdx == -1 {
t.Fatalf("missing markers:\n%s", out)
}
if beadsIdx >= ifIdx {
t.Errorf("bd section should be injected above the if-block (not between if and exec); got:\n%s", out)
}
if !strings.Contains(out, "# Why we use foo") {
t.Errorf("body comment was lost:\n%s", out)
}
}
// TestInjectHookSection_Idempotent_PrecommitTemplate confirms that running
// injectHookSection twice on a pre-commit-templated hook is idempotent: the
// first run takes Case 3 (no markers → inject above the exec block); the
// second run takes Case 1 (markers present → replace between markers) and
// reuses the same injection point. The output of run 2 must equal run 1.
// (review nit on PR #3556 — guards against a future refactor regressing
// the idempotency that the marker logic currently provides for free.)
func TestInjectHookSection_Idempotent_PrecommitTemplate(t *testing.T) {
existing := `#!/usr/bin/env bash
HERE="$(cd "$(dirname "$0")" && pwd)"
if [ -x "$INSTALL_PYTHON" ]; then
exec "$INSTALL_PYTHON" -mpre_commit "$@"
elif command -v pre-commit > /dev/null; then
exec pre-commit "$@"
else
echo 'not found' 1>&2
exit 1
fi
`
once := injectHookSection(existing, testBeadsSection)
twice := injectHookSection(once, testBeadsSection)
if once != twice {
t.Errorf("injectHookSection is not idempotent.\nrun 1:\n%s\nrun 2:\n%s", once, twice)
}
// Sanity: the bd block must still be above the exec block after both runs.
beadsIdx := strings.Index(twice, "BEGIN BEADS INTEGRATION")
ifIdx := strings.Index(twice, `if [ -x "$INSTALL_PYTHON" ]`)
if beadsIdx == -1 || ifIdx == -1 || beadsIdx >= ifIdx {
t.Errorf("after two runs the bd block should still sit above the if-block:\n%s", twice)
}
}
// TestIsAllowedAfterExec_TableDriven directly exercises every branch of the
// helper, including `elif <args>` and `else <args>` (with arguments rather
// than the bare keyword which is handled by the switch above).
func TestIsAllowedAfterExec_TableDriven(t *testing.T) {
tests := []struct {
name string
trimmed string
want bool
}{
{name: "empty", trimmed: "", want: true},
{name: "comment", trimmed: "# a comment", want: true},
{name: "fi", trimmed: "fi", want: true},
{name: "bare else", trimmed: "else", want: true},
{name: "done", trimmed: "done", want: true},
{name: "esac", trimmed: "esac", want: true},
{name: "close brace", trimmed: "}", want: true},
{name: "case fallthrough", trimmed: ";;", want: true},
{name: "elif with cond", trimmed: "elif command -v foo > /dev/null; then", want: true},
{name: "else with stuff", trimmed: "else stuff-on-same-line", want: true},
{name: "exit 0", trimmed: "exit 0", want: true},
{name: "exit no arg", trimmed: "exit", want: true},
{name: "echo space", trimmed: "echo 'msg'", want: true},
{name: "real code", trimmed: "do-real-thing arg", want: false},
{name: "assignment", trimmed: "FOO=bar", want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isAllowedAfterExec(tt.trimmed); got != tt.want {
t.Errorf("isAllowedAfterExec(%q) = %v, want %v", tt.trimmed, got, tt.want)
}
})
}
}
// TestIsExecLine_TableDriven covers the helper's tab-prefix branch and a
// few negatives for completeness.
func TestIsExecLine_TableDriven(t *testing.T) {
tests := []struct {
trimmed string
want bool
}{
{trimmed: "exec /bin/foo", want: true},
{trimmed: "exec", want: true},
{trimmed: "exec\t/bin/foo", want: true},
{trimmed: "execute foo", want: false},
{trimmed: "echo exec", want: false},
{trimmed: "", want: false},
}
for _, tt := range tests {
t.Run(tt.trimmed, func(t *testing.T) {
if got := isExecLine(tt.trimmed); got != tt.want {
t.Errorf("isExecLine(%q) = %v, want %v", tt.trimmed, got, tt.want)
}
})
}
}
func snippet(s string, from, n int) string {
if from < 0 || from >= len(s) {
return ""
}
end := from + n
if end > len(s) {
end = len(s)
}
return s[from:end]
}