返回 last30days-skill
sync_contract_test.go
根目录 / mcp / internal / engine / sync_contract_test.go
1 package engine
2
3 import (
4 "crypto/sha256"
5 "fmt"
6 "io/fs"
7 "os"
8 "path/filepath"
9 "regexp"
10 "runtime"
11 "strings"
12 "testing"
13 )
14
15 // engineSourceDir resolves the git source of truth for the vendored engine
16 // (skills/last30days/scripts/) from this test file's location, independent
17 // of the caller's working directory.
18 func engineSourceDir(t *testing.T) string {
19 t.Helper()
20 _, thisFile, _, ok := runtime.Caller(0)
21 if !ok {
22 t.Fatal("runtime.Caller: cannot locate test file")
23 }
24 // This file lives in mcp/internal/engine/; the repo root is three levels up.
25 dir := filepath.Join(filepath.Dir(thisFile), "..", "..", "..",
26 "skills", "last30days", "scripts")
27 abs, err := filepath.Abs(dir)
28 if err != nil {
29 t.Fatalf("resolve engine source dir: %v", err)
30 }
31 if _, err := os.Stat(filepath.Join(abs, "last30days.py")); err != nil {
32 t.Fatalf("engine source not found at %s: %v", abs, err)
33 }
34 return abs
35 }
36
37 var (
38 importStmtRe = regexp.MustCompile(`(?m)^[ \t]*import[ \t]+([^#\n]+)`)
39 fromStmtRe = regexp.MustCompile(`(?m)^[ \t]*from[ \t]+([A-Za-z_]\w*)`)
40 importNameRe = regexp.MustCompile(`^[A-Za-z_]\w*`)
41 )
42
43 // importedModules returns the first dotted component of every absolute
44 // import statement in a Python source, including in-function imports.
45 // Relative imports (from . import x) are skipped: they resolve inside a
46 // package, never to a top-level script module.
47 func importedModules(src []byte) []string {
48 var names []string
49 for _, m := range importStmtRe.FindAllSubmatch(src, -1) {
50 for _, part := range strings.Split(string(m[1]), ",") {
51 if name := importNameRe.FindString(strings.TrimSpace(part)); name != "" {
52 names = append(names, name)
53 }
54 }
55 }
56 for _, m := range fromStmtRe.FindAllSubmatch(src, -1) {
57 names = append(names, string(m[1]))
58 }
59 return names
60 }
61
62 // runtimeTopLevelModules derives, from the engine's own import statements,
63 // which top-level scripts/<name>.py files the engine loads at runtime.
64 // last30days.py puts its directory on sys.path, so any import that names a
65 // sibling .py file resolves to that file. The scan starts from the entry
66 // point and every lib/ module, then follows the discovered top-level modules
67 // transitively, so the contract tracks the code instead of repeating the
68 // sync script's file list.
69 func runtimeTopLevelModules(t *testing.T, srcDir string) map[string]bool {
70 t.Helper()
71 queue := []string{"last30days.py"}
72 if err := filepath.WalkDir(filepath.Join(srcDir, "lib"), func(path string, d fs.DirEntry, err error) error {
73 if err != nil {
74 return err
75 }
76 if !d.IsDir() && strings.HasSuffix(path, ".py") {
77 rel, err := filepath.Rel(srcDir, path)
78 if err != nil {
79 return err
80 }
81 queue = append(queue, filepath.ToSlash(rel))
82 }
83 return nil
84 }); err != nil {
85 t.Fatalf("walk engine lib: %v", err)
86 }
87
88 modules := map[string]bool{"last30days.py": true}
89 for len(queue) > 0 {
90 rel := queue[0]
91 queue = queue[1:]
92 src, err := os.ReadFile(filepath.Join(srcDir, filepath.FromSlash(rel)))
93 if err != nil {
94 t.Fatalf("read engine module %s: %v", rel, err)
95 }
96 for _, name := range importedModules(src) {
97 file := name + ".py"
98 if modules[file] {
99 continue
100 }
101 if st, err := os.Stat(filepath.Join(srcDir, file)); err == nil && !st.IsDir() {
102 modules[file] = true
103 queue = append(queue, file)
104 }
105 }
106 }
107 return modules
108 }
109
110 // wantFile reports whether a source-tree relative path must be embedded: the
111 // last30days.py entry point, every top-level module it imports at runtime,
112 // and the lib/ tree, minus interpreter caches the sync script strips for
113 // determinism.
114 func wantFile(rel string, topLevel map[string]bool) bool {
115 if topLevel[rel] {
116 return true
117 }
118 if rel != "lib" && !strings.HasPrefix(rel, "lib/") {
119 return false
120 }
121 if strings.Contains(rel, "__pycache__") || strings.HasSuffix(rel, ".pyc") {
122 return false
123 }
124 return true
125 }
126
127 func TestImportedModules(t *testing.T) {
128 src := []byte(`import os, sys as system
129 from lib import schema
130 from . import sibling
131 from .pkg import thing
132
133 def persist():
134 import store
135 from watchlist import run # trailing comment
136 x = "import notamodule"
137 `)
138 got := strings.Join(importedModules(src), ",")
139 want := "os,sys,store,lib,watchlist"
140 if got != want {
141 t.Fatalf("importedModules = %q, want %q", got, want)
142 }
143 }
144
145 func hashFileFS(fsys fs.FS, name string) (string, error) {
146 data, err := fs.ReadFile(fsys, name)
147 if err != nil {
148 return "", err
149 }
150 sum := sha256.Sum256(data)
151 return fmt.Sprintf("%x", sum), nil
152 }
153
154 // TestVendoredMatchesSource guards the sync-engine.sh contract: the embedded
155 // engine must be byte-identical to the git source it mirrors, and must carry
156 // every top-level module the engine imports at runtime. A developer who
157 // edits skills/last30days/scripts/ and runs `go test` without re-syncing gets
158 // a failure naming the fix; CI runs scripts/sync-engine.sh before go test so
159 // the check also fails loudly if that step ever goes missing or silently
160 // no-ops (a fresh checkout embeds only the .gitkeep anchor).
161 func TestVendoredMatchesSource(t *testing.T) {
162 srcDir := engineSourceDir(t)
163 topLevel := runtimeTopLevelModules(t, srcDir)
164
165 embedded, err := EngineFS()
166 if err != nil {
167 t.Fatalf("EngineFS: %v", err)
168 }
169 const resync = "run `bash scripts/sync-engine.sh` from mcp/ to resync " +
170 "(source of truth: skills/last30days/scripts/, see mcp/README.md)"
171
172 embeddedHashes := map[string]string{}
173 if err := fs.WalkDir(embedded, ".", func(path string, d fs.DirEntry, err error) error {
174 if err != nil {
175 return err
176 }
177 if d.IsDir() || path == ".gitkeep" {
178 return nil
179 }
180 h, err := hashFileFS(embedded, path)
181 if err != nil {
182 return err
183 }
184 embeddedHashes[path] = h
185 return nil
186 }); err != nil {
187 t.Fatalf("walk embedded engine: %v", err)
188 }
189
190 sourceHashes := map[string]string{}
191 if err := filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, err error) error {
192 if err != nil {
193 return err
194 }
195 if d.IsDir() {
196 return nil
197 }
198 rel, err := filepath.Rel(srcDir, path)
199 if err != nil {
200 return err
201 }
202 rel = filepath.ToSlash(rel)
203 if !wantFile(rel, topLevel) {
204 return nil
205 }
206 data, err := os.ReadFile(path)
207 if err != nil {
208 return err
209 }
210 sum := sha256.Sum256(data)
211 sourceHashes[rel] = fmt.Sprintf("%x", sum)
212 return nil
213 }); err != nil {
214 t.Fatalf("walk engine source: %v", err)
215 }
216
217 var problems []string
218 for rel, want := range sourceHashes {
219 got, ok := embeddedHashes[rel]
220 if !ok {
221 if topLevel[rel] {
222 problems = append(problems, "missing from embed: "+rel+
223 " (imported at runtime; add it to the module list in scripts/sync-engine.sh if resync does not copy it)")
224 } else {
225 problems = append(problems, "missing from embed: "+rel)
226 }
227 continue
228 }
229 if got != want {
230 problems = append(problems, "stale content in embed: "+rel)
231 }
232 }
233 for rel := range embeddedHashes {
234 if _, ok := sourceHashes[rel]; !ok {
235 problems = append(problems, "embed has file with no source: "+rel)
236 }
237 }
238 if len(problems) > 0 {
239 t.Fatalf("vendored engine differs from git source (%d file(s)):\n %s\n%s",
240 len(problems), strings.Join(problems, "\n "), resync)
241 }
242 }
243
244 var minPythonRe = regexp.MustCompile(`(?m)^MIN_PYTHON\s*=\s*\((\d+),\s*(\d+)\)`)
245
246 // TestMinPythonVersionMatchesEngine keeps the Go duplicate of the engine's
247 // MIN_PYTHON floor honest without hardcoding the value: the expected version
248 // is parsed out of skills/last30days/scripts/last30days.py itself, so an
249 // engine-side bump fails here with the exact file and line to mirror instead
250 // of drifting silently.
251 func TestMinPythonVersionMatchesEngine(t *testing.T) {
252 src, err := os.ReadFile(filepath.Join(engineSourceDir(t), "last30days.py"))
253 if err != nil {
254 t.Fatalf("read engine entry point: %v", err)
255 }
256 m := minPythonRe.FindSubmatch(src)
257 if m == nil {
258 t.Fatal("MIN_PYTHON = (major, minor) not found in last30days.py; " +
259 "update minPythonRe in sync_contract_test.go")
260 }
261 want := string(m[1]) + "." + string(m[2])
262 if MinPythonVersion != want {
263 t.Fatalf("MinPythonVersion = %q, engine MIN_PYTHON = %q; "+
264 "update the Go constant to match last30days.py",
265 MinPythonVersion, want)
266 }
267 }
268
268 lines GO