AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(ci): tighten coverage source and engine sync guards (#1167)
Ilia Alshanetskyce5cd4ea4363
diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.ymlindex 0240470c..d3d175f8 100644--- a/.github/workflows/validate.yml+++ b/.github/workflows/validate.yml@@ -63,6 +63,9 @@ jobs:go-version: "1.25.5"cache-dependency-path: mcp/go.sum+ - name: Sync vendored engine+ run: bash mcp/scripts/sync-engine.sh+- name: Run MCP Go testsrun: go test -race ./...working-directory: mcpdiff --git a/changelog.d/+skill-flag-docs.added.md b/changelog.d/+skill-flag-docs.added.mdnew file mode 100644index 00000000..a6f5997c--- /dev/null+++ b/changelog.d/+skill-flag-docs.added.md@@ -0,0 +1 @@+Document previously-undocumented engine flags in SKILL.md; add CLI-flag and engine-sync contract tests.diff --git a/mcp/internal/engine/sync_contract_test.go b/mcp/internal/engine/sync_contract_test.gonew file mode 100644index 00000000..86fe85a2--- /dev/null+++ b/mcp/internal/engine/sync_contract_test.go@@ -0,0 +1,267 @@+package engine++import (+ "crypto/sha256"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "testing"+)++// engineSourceDir resolves the git source of truth for the vendored engine+// (skills/last30days/scripts/) from this test file's location, independent+// of the caller's working directory.+func engineSourceDir(t *testing.T) string {+ t.Helper()+ _, thisFile, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("runtime.Caller: cannot locate test file")+ }+ // This file lives in mcp/internal/engine/; the repo root is three levels up.+ dir := filepath.Join(filepath.Dir(thisFile), "..", "..", "..",+ "skills", "last30days", "scripts")+ abs, err := filepath.Abs(dir)+ if err != nil {+ t.Fatalf("resolve engine source dir: %v", err)+ }+ if _, err := os.Stat(filepath.Join(abs, "last30days.py")); err != nil {+ t.Fatalf("engine source not found at %s: %v", abs, err)+ }+ return abs+}++var (+ importStmtRe = regexp.MustCompile(`(?m)^[ \t]*import[ \t]+([^#\n]+)`)+ fromStmtRe = regexp.MustCompile(`(?m)^[ \t]*from[ \t]+([A-Za-z_]\w*)`)+ importNameRe = regexp.MustCompile(`^[A-Za-z_]\w*`)+)++// importedModules returns the first dotted component of every absolute+// import statement in a Python source, including in-function imports.+// Relative imports (from . import x) are skipped: they resolve inside a+// package, never to a top-level script module.+func importedModules(src []byte) []string {+ var names []string+ for _, m := range importStmtRe.FindAllSubmatch(src, -1) {+ for _, part := range strings.Split(string(m[1]), ",") {+ if name := importNameRe.FindString(strings.TrimSpace(part)); name != "" {+ names = append(names, name)+ }+ }+ }+ for _, m := range fromStmtRe.FindAllSubmatch(src, -1) {+ names = append(names, string(m[1]))+ }+ return names+}++// runtimeTopLevelModules derives, from the engine's own import statements,+// which top-level scripts/<name>.py files the engine loads at runtime.+// last30days.py puts its directory on sys.path, so any import that names a+// sibling .py file resolves to that file. The scan starts from the entry+// point and every lib/ module, then follows the discovered top-level modules+// transitively, so the contract tracks the code instead of repeating the+// sync script's file list.+func runtimeTopLevelModules(t *testing.T, srcDir string) map[string]bool {+ t.Helper()+ queue := []string{"last30days.py"}+ if err := filepath.WalkDir(filepath.Join(srcDir, "lib"), func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if !d.IsDir() && strings.HasSuffix(path, ".py") {+ rel, err := filepath.Rel(srcDir, path)+ if err != nil {+ return err+ }+ queue = append(queue, filepath.ToSlash(rel))+ }+ return nil+ }); err != nil {+ t.Fatalf("walk engine lib: %v", err)+ }++ modules := map[string]bool{"last30days.py": true}+ for len(queue) > 0 {+ rel := queue[0]+ queue = queue[1:]+ src, err := os.ReadFile(filepath.Join(srcDir, filepath.FromSlash(rel)))+ if err != nil {+ t.Fatalf("read engine module %s: %v", rel, err)+ }+ for _, name := range importedModules(src) {+ file := name + ".py"+ if modules[file] {+ continue+ }+ if st, err := os.Stat(filepath.Join(srcDir, file)); err == nil && !st.IsDir() {+ modules[file] = true+ queue = append(queue, file)+ }+ }+ }+ return modules+}++// wantFile reports whether a source-tree relative path must be embedded: the+// last30days.py entry point, every top-level module it imports at runtime,+// and the lib/ tree, minus interpreter caches the sync script strips for+// determinism.+func wantFile(rel string, topLevel map[string]bool) bool {+ if topLevel[rel] {+ return true+ }+ if rel != "lib" && !strings.HasPrefix(rel, "lib/") {+ return false+ }+ if strings.Contains(rel, "__pycache__") || strings.HasSuffix(rel, ".pyc") {+ return false+ }+ return true+}++func TestImportedModules(t *testing.T) {+ src := []byte(`import os, sys as system+from lib import schema+from . import sibling+from .pkg import thing++def persist():+ import store+ from watchlist import run # trailing comment+x = "import notamodule"+`)+ got := strings.Join(importedModules(src), ",")+ want := "os,sys,store,lib,watchlist"+ if got != want {+ t.Fatalf("importedModules = %q, want %q", got, want)+ }+}++func hashFileFS(fsys fs.FS, name string) (string, error) {+ data, err := fs.ReadFile(fsys, name)+ if err != nil {+ return "", err+ }+ sum := sha256.Sum256(data)+ return fmt.Sprintf("%x", sum), nil+}++// TestVendoredMatchesSource guards the sync-engine.sh contract: the embedded+// engine must be byte-identical to the git source it mirrors, and must carry+// every top-level module the engine imports at runtime. A developer who+// edits skills/last30days/scripts/ and runs `go test` without re-syncing gets+// a failure naming the fix; CI runs scripts/sync-engine.sh before go test so+// the check also fails loudly if that step ever goes missing or silently+// no-ops (a fresh checkout embeds only the .gitkeep anchor).+func TestVendoredMatchesSource(t *testing.T) {+ srcDir := engineSourceDir(t)+ topLevel := runtimeTopLevelModules(t, srcDir)++ embedded, err := EngineFS()+ if err != nil {+ t.Fatalf("EngineFS: %v", err)+ }+ const resync = "run `bash scripts/sync-engine.sh` from mcp/ to resync " ++ "(source of truth: skills/last30days/scripts/, see mcp/README.md)"++ embeddedHashes := map[string]string{}+ if err := fs.WalkDir(embedded, ".", func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if d.IsDir() || path == ".gitkeep" {+ return nil+ }+ h, err := hashFileFS(embedded, path)+ if err != nil {+ return err+ }+ embeddedHashes[path] = h+ return nil+ }); err != nil {+ t.Fatalf("walk embedded engine: %v", err)+ }++ sourceHashes := map[string]string{}+ if err := filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if d.IsDir() {+ return nil+ }+ rel, err := filepath.Rel(srcDir, path)+ if err != nil {+ return err+ }+ rel = filepath.ToSlash(rel)+ if !wantFile(rel, topLevel) {+ return nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ sum := sha256.Sum256(data)+ sourceHashes[rel] = fmt.Sprintf("%x", sum)+ return nil+ }); err != nil {+ t.Fatalf("walk engine source: %v", err)+ }++ var problems []string+ for rel, want := range sourceHashes {+ got, ok := embeddedHashes[rel]+ if !ok {+ if topLevel[rel] {+ problems = append(problems, "missing from embed: "+rel++ " (imported at runtime; add it to the module list in scripts/sync-engine.sh if resync does not copy it)")+ } else {+ problems = append(problems, "missing from embed: "+rel)+ }+ continue+ }+ if got != want {+ problems = append(problems, "stale content in embed: "+rel)+ }+ }+ for rel := range embeddedHashes {+ if _, ok := sourceHashes[rel]; !ok {+ problems = append(problems, "embed has file with no source: "+rel)+ }+ }+ if len(problems) > 0 {+ t.Fatalf("vendored engine differs from git source (%d file(s)):\n %s\n%s",+ len(problems), strings.Join(problems, "\n "), resync)+ }+}++var minPythonRe = regexp.MustCompile(`(?m)^MIN_PYTHON\s*=\s*\((\d+),\s*(\d+)\)`)++// TestMinPythonVersionMatchesEngine keeps the Go duplicate of the engine's+// MIN_PYTHON floor honest without hardcoding the value: the expected version+// is parsed out of skills/last30days/scripts/last30days.py itself, so an+// engine-side bump fails here with the exact file and line to mirror instead+// of drifting silently.+func TestMinPythonVersionMatchesEngine(t *testing.T) {+ src, err := os.ReadFile(filepath.Join(engineSourceDir(t), "last30days.py"))+ if err != nil {+ t.Fatalf("read engine entry point: %v", err)+ }+ m := minPythonRe.FindSubmatch(src)+ if m == nil {+ t.Fatal("MIN_PYTHON = (major, minor) not found in last30days.py; " ++ "update minPythonRe in sync_contract_test.go")+ }+ want := string(m[1]) + "." + string(m[2])+ if MinPythonVersion != want {+ t.Fatalf("MinPythonVersion = %q, engine MIN_PYTHON = %q; "++ "update the Go constant to match last30days.py",+ MinPythonVersion, want)+ }+}diff --git a/mcp/scripts/sync-engine.sh b/mcp/scripts/sync-engine.shindex 30d178d7..92cbba85 100755--- a/mcp/scripts/sync-engine.sh+++ b/mcp/scripts/sync-engine.sh@@ -3,7 +3,7 @@# mcp/internal/engine/vendored/# so the Go binary's embed.FS captures the engine at build time.#-# Source of truth: skills/last30days/scripts/. Never edit the mirror directly.+# Source of truth: skills/last30days/scripts/. Never edit mcp/internal/engine/vendored/ directly.# Run before `go build` locally and in CI before `printing-press bundle`.set -euo pipefail@@ -25,8 +25,12 @@ mkdir -p "${VENDORED}"# Clear stale content while keeping the .gitkeep that anchors the embed path.find "${VENDORED}" -mindepth 1 -not -name ".gitkeep" -delete-# Copy the entry script, persistence module, and lib/ tree (modules + lib/vendor/).-cp "${ENGINE_SRC}/last30days.py" "${ENGINE_SRC}/store.py" "${VENDORED}/"+# Copy the entry script, the top-level modules it imports at runtime, and the+# lib/ tree (modules + lib/vendor/). sync_contract_test.go fails if the engine+# imports a top-level module missing from this list.+for module in last30days.py store.py; do+ cp "${ENGINE_SRC}/${module}" "${VENDORED}/${module}"+donecp -R "${ENGINE_SRC}/lib" "${VENDORED}/lib"# Strip caches so the embed.FS stays deterministic.diff --git a/pyproject.toml b/pyproject.tomlindex 98ad03db..e6da95bc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -63,7 +63,7 @@ addopts = [[tool.coverage.run]branch = true-source = ["skills/last30days/scripts", "tests"]+source = ["skills/last30days/scripts"]omit = ["skills/last30days/scripts/lib/vendor/*","dist/*",@@ -73,10 +73,14 @@ omit = [skip_empty = trueshow_missing = true# Coverage gate (issue #254). Floor intended to rise over time, not a ceiling.-# Baseline measured 2026-07-03 on main before feat/hosted-api-mode-# (source = scripts + tests): TOTAL 84.06%. Gate pinned at that baseline.+# Baseline measured 2026-09-23 on the full suite with scripts-tree source+# (tests/ excluded): TOTAL 82.28%. The previous 84 floor was measured with+# source = scripts + tests, where well-tested test code inflated the number;+# excluding tests/ lowers the honest baseline, which is why the floor moves+# 84 -> 81. Pinned at 81 (not 82) for ~1.3pp headroom against the measured+# 82.28; raise back toward 82+ as coverage grows.# Do not lower without documenting why in the PR (see AGENTS.md Rules).-fail_under = 84+fail_under = 81omit = ["skills/last30days/scripts/lib/vendor/*","dist/*",diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex bf5d73df..2d915ae9 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -1711,11 +1711,18 @@ For ALL query types:- **Meet higher-priority host/tool requirements and user instructions for citations.** Include required inline links or a separate `Sources:` block when applicable. Otherwise use the engine's π Web: footer without adding a duplicate source list.**Options** (passed through from user's command):-- `--days=N` β Look back N days instead of 30 (e.g., `--days=7` for weekly roundup)+- `--days=N` β Look back N days instead of 30 (e.g., `--days=7` for weekly roundup). `--lookback-days=N` is the same flag under its explicit name+- `--as-of=YYYY-MM-DD` β End date for the lookback window; `--days` counts back from this date instead of today- `--quick` β Faster, fewer sources (8-12 each)- (default) β Balanced (20-30 each)- `--deep` β Comprehensive (50-70 Reddit, 40-60 X)- `--register={default,exec,dev,creator,eli5}` β Apply a named audience template to the standard single-topic brief. Pass the flag through to the engine; do not treat its value as topic text. Registers do not apply to JSON, discover, drill, library, or comparison output.+- `--max-results=N`, `--max-per-source=N`, `--max-source-fetches=N` β Raise the ranked-pool, per-stream, and per-source fetch caps on high-volume topics where the defaults under-cover (see issue #716)+- `--verify-freshness` / `--no-verify-freshness` β Re-check source-grounded claims after research / explicitly disable that check+- `--synthesis-file=PATH` β Markdown synthesis to embed in `--emit=html` output (HTML-as-deliverable flow)+- `--publish-password=PASS` β Shared password for `--publish-html` / `--publish`; prefer `LAST30DAYS_PUBLISH_PASSWORD` in the environment so the secret never appears in process lists+- `--debug` β Enable HTTP debug logging (troubleshooting only)+- `--store` β Persist ranked findings to the SQLite research store**Leaving Step 2 - LAW 1 reminder:** honor higher-priority host/tool requirements and user instructions for visible citations. The `π Web:` footer and saved-raw-file appendix do not substitute for required links or source sections. When no additional citation form is required, keep the default ending at the invitation without a duplicate source list.diff --git a/tests/test_jobs_fusion_render.py b/tests/test_jobs_fusion_render.pyindex 94bf2ff9..8c0b114e 100644--- a/tests/test_jobs_fusion_render.py+++ b/tests/test_jobs_fusion_render.py@@ -1,4 +1,5 @@import copy+from urllib.parse import urlsplitimport pytest@@ -205,7 +206,11 @@ def test_hiring_analysis_uses_canonical_job_urls(rejected):original = jobs[-1]variant = copy.deepcopy(original)variant.item_id = "other-stream-id"- variant.url = original.url.upper() + "/?utm_source=jobs"+ parts = urlsplit(original.url)+ variant.url = parts._replace(+ scheme=parts.scheme.upper(), netloc=parts.netloc.upper(),+ path=parts.path + "/", query="utm_source=jobs",+ ).geturl()report.items_by_source["jobs"] = [*jobs[:-1], variant]assert fusion.candidate_key(original) == fusion.candidate_key(variant)if rejected:@@ -221,3 +226,20 @@ def test_hiring_analysis_uses_canonical_job_urls(rejected):assert f"evidence: {4 if rejected else 5} roles" in textif rejected:assert original.title not in text+++def test_hiring_analysis_keeps_case_sensitive_job_paths_distinct():+ jobs = _jobs(5)+ original = jobs[-1]+ distinct = copy.deepcopy(original)+ distinct.item_id = "case-sensitive-role"+ distinct.title = "Software Engineer, Infrastructure"+ parts = urlsplit(original.url)+ distinct.url = parts._replace(path=parts.path.upper()).geturl()+ report = _report([*jobs, distinct], pool_limit=6)++ assert len(report.ranked_candidates) == 6+ assert {original.url, distinct.url} <= {+ candidate.url for candidate in report.ranked_candidates+ }+ assert "evidence: 6 roles" in render.render_compact(report)diff --git a/tests/test_skill_flag_contract.py b/tests/test_skill_flag_contract.pynew file mode 100644index 00000000..8126379d--- /dev/null+++ b/tests/test_skill_flag_contract.py@@ -0,0 +1,45 @@+"""Every engine CLI flag must be reachable from SKILL.md.++AGENTS.md: "A new engine flag with no SKILL.md integration is incomplete."+This test enforces that rule: each non-suppressed long option registered by+build_parser() must appear literally in skills/last30days/SKILL.md, so the+model invoking the skill can discover every flag a user might pass through.++Suppressed (argparse.SUPPRESS-help) flags are exempt: they are hidden from+--help on purpose and must never be promoted into the runtime spec.+"""+import re+from pathlib import Path++import last30days as cli++REPO_ROOT = Path(__file__).resolve().parents[1]+SKILL_MD = REPO_ROOT / "skills" / "last30days" / "SKILL.md"+++def _documented_flags():+ """Long options from the parser, minus hidden (--help) and suppressed."""+ flags = set()+ for action in cli.build_parser()._actions:+ if action.help == "==SUPPRESS==":+ continue+ for opt in action.option_strings:+ if opt.startswith("--") and opt != "--help":+ flags.add(opt)+ return flags+++def test_all_parser_flags_documented_in_skill_md():+ skill = SKILL_MD.read_text(encoding="utf-8")+ missing = [+ flag+ for flag in sorted(_documented_flags())+ # A trailing [^-\w] lookahead keeps --deep from matching+ # --deep-research (and --days from --days-suffix style collisions)+ # while still matching --flag=value, --flag`, --flag , etc.+ if not re.search(re.escape(flag) + r"(?![-\w])", skill)+ ]+ assert not missing, (+ "engine flags missing from SKILL.md (document them or suppress "+ f"with reason in build_parser): {', '.join(missing)}"+ )