machina-cli 0.5.2__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. {machina_cli-0.5.2 → machina_cli-0.6.0}/CHANGELOG.md +36 -0
  2. {machina_cli-0.5.2 → machina_cli-0.6.0}/PKG-INFO +1 -1
  3. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/harness-loop-kit/context-verify.py +333 -27
  4. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/harness-loop-kit/surface-verify.py +80 -11
  5. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/context-graph.md +39 -4
  6. machina_cli-0.6.0/docs-site/commands/update.md +35 -0
  7. {machina_cli-0.5.2 → machina_cli-0.6.0}/pyproject.toml +2 -2
  8. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/__init__.py +1 -1
  9. machina_cli-0.6.0/src/machina_cli/commands/context_graph.py +346 -0
  10. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/main.py +100 -39
  11. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/repl.py +4 -0
  12. machina_cli-0.6.0/src/machina_cli/update_check.py +113 -0
  13. machina_cli-0.6.0/tests/test_context_graph_timeline.py +114 -0
  14. machina_cli-0.5.2/docs-site/commands/update.md +0 -21
  15. machina_cli-0.5.2/src/machina_cli/commands/context_graph.py +0 -171
  16. {machina_cli-0.5.2 → machina_cli-0.6.0}/.github/workflows/ci.yml +0 -0
  17. {machina_cli-0.5.2 → machina_cli-0.6.0}/.github/workflows/release.yml +0 -0
  18. {machina_cli-0.5.2 → machina_cli-0.6.0}/.gitignore +0 -0
  19. {machina_cli-0.5.2 → machina_cli-0.6.0}/CLAUDE.md +0 -0
  20. {machina_cli-0.5.2 → machina_cli-0.6.0}/README.md +0 -0
  21. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/agentic-harness-loop.md +0 -0
  22. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/credentials.md +0 -0
  23. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/harness-loop-kit/PLAYBOOK-SCORECARD.md +0 -0
  24. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/harness-loop-kit/README.md +0 -0
  25. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/harness-loop-kit/VALIDATION.md +0 -0
  26. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/harness-loop-kit/provision.py +0 -0
  27. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs/loop-tools-connector.py +0 -0
  28. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/.gitignore +0 -0
  29. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/.vitepress/config.mts +0 -0
  30. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/.vitepress/theme/custom.css +0 -0
  31. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/.vitepress/theme/index.ts +0 -0
  32. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/README.md +0 -0
  33. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/agent.md +0 -0
  34. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/config.md +0 -0
  35. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/connect.md +0 -0
  36. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/connector.md +0 -0
  37. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/credentials.md +0 -0
  38. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/deploy.md +0 -0
  39. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/document.md +0 -0
  40. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/execution.md +0 -0
  41. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/factory.md +0 -0
  42. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/login.md +0 -0
  43. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/loop.md +0 -0
  44. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/mapping.md +0 -0
  45. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/mcp.md +0 -0
  46. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/org.md +0 -0
  47. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/project.md +0 -0
  48. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/prompt.md +0 -0
  49. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/skills.md +0 -0
  50. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/sports.md +0 -0
  51. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/template.md +0 -0
  52. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/commands/workflow.md +0 -0
  53. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/guide/authentication.md +0 -0
  54. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/guide/configuration.md +0 -0
  55. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/guide/installation.md +0 -0
  56. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/guide/quickstart.md +0 -0
  57. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/guide/repl.md +0 -0
  58. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/guide/running.md +0 -0
  59. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/index.md +0 -0
  60. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/package-lock.json +0 -0
  61. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/package.json +0 -0
  62. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/public/favicon.ico +0 -0
  63. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/public/machina-logo-dark.png +0 -0
  64. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/public/machina-logo-light.png +0 -0
  65. {machina_cli-0.5.2 → machina_cli-0.6.0}/docs-site/vercel.json +0 -0
  66. {machina_cli-0.5.2 → machina_cli-0.6.0}/install.ps1 +0 -0
  67. {machina_cli-0.5.2 → machina_cli-0.6.0}/install.sh +0 -0
  68. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/browser_auth.py +0 -0
  69. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/client.py +0 -0
  70. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/__init__.py +0 -0
  71. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/agent.py +0 -0
  72. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/auth.py +0 -0
  73. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/config_cmd.py +0 -0
  74. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/connect.py +0 -0
  75. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/connector.py +0 -0
  76. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/credentials.py +0 -0
  77. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/deploy.py +0 -0
  78. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/document.py +0 -0
  79. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/execution.py +0 -0
  80. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/factory.py +0 -0
  81. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/loop.py +0 -0
  82. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/mapping.py +0 -0
  83. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/mcp.py +0 -0
  84. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/org.py +0 -0
  85. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/project.py +0 -0
  86. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/prompt.py +0 -0
  87. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/skills.py +0 -0
  88. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/sports.py +0 -0
  89. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/template.py +0 -0
  90. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/commands/workflow.py +0 -0
  91. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/config.py +0 -0
  92. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/factory_client.py +0 -0
  93. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/loop_client.py +0 -0
  94. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/models/__init__.py +0 -0
  95. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/project_client.py +0 -0
  96. {machina_cli-0.5.2 → machina_cli-0.6.0}/src/machina_cli/updater.py +0 -0
  97. {machina_cli-0.5.2 → machina_cli-0.6.0}/tests/__init__.py +0 -0
  98. {machina_cli-0.5.2 → machina_cli-0.6.0}/tests/test_cli_output.py +0 -0
  99. {machina_cli-0.5.2 → machina_cli-0.6.0}/tests/test_connect.py +0 -0
  100. {machina_cli-0.5.2 → machina_cli-0.6.0}/tests/test_mcp_url.py +0 -0
  101. {machina_cli-0.5.2 → machina_cli-0.6.0}/tests/test_org_usage.py +0 -0
  102. {machina_cli-0.5.2 → machina_cli-0.6.0}/tests/test_sports_integration.py +0 -0
@@ -2,6 +2,42 @@
2
2
 
3
3
  All notable changes to machina-cli are documented here.
4
4
 
5
+ ## [0.6.0] - 2026-07-01
6
+
7
+ ### Added
8
+ - **Auto-heal for the `analysis<->fixture` edge** (opt-in via `ANALYSIS_HEAL_WORKFLOW` at provision time). When `context-verify` finds fixtures sharing an identical pre-match analysis (the misattribution class), each affected fixture now gets one **async** `context-heal-runner` dispatch that runs the pod's own per-fixture research workflow (fresh web search + LLM extract + doc update) — regenerating the misattributed analyses instead of just flagging them. Async by design: a dozen sequential researches inside one connector execution is the silent-death failure mode `scan_link` hit at enterprise scale. Bounded twice: `max_fixtures_per_run` (default 5) caps cost per scan with the backlog draining across scheduled scans, and a **no-progress budget** (`max_heal_attempts`, default 3) stops re-dispatching when healing isn't working — a draining backlog (13→10→7) never trips it; a stuck one (13→13→13) escalates to Slack ("could NOT self-heal") instead. Slack messages now distinguish *found + self-healing* from *found, needs a human*.
9
+ - **`machina context-graph timeline [--org] [--days N]`** — the self-healing event history: every `detected` → `heal` → `heal-paused`/`recovered` event, reconstructed from the persisted graph-health trail (works retroactively on any pod with history; no new state). The summary line is the ROI number: how many times the loop found and fixed a problem before a human had to. `--org` merges all projects into one chronological stream.
10
+
11
+ ## [0.5.8] - 2026-07-01
12
+
13
+ ### Fixed
14
+ - **`context-verify`'s new Slack notify (0.5.7) used the rounded `broken_rate_pct` as its broken/clean signal — `round(100 * 1/500)` is `0`, so a single genuine broken record could round down to a "clean" 0% and never alert.** Found immediately while deploying 0.5.7 to SBOT Prd, on the exact real record it should have caught. Switched to the raw broken-count field per edge (`broken_edges` for `analysis<->fixture`, `misattributed` for `odd<->market<->fixture`) — exact, never rounds away a real finding. The percentage is still shown in messages, just no longer used as the decision signal.
15
+
16
+ ## [0.5.7] - 2026-07-01
17
+
18
+ ### Added
19
+ - **`context-verify` posts to Slack on a data-integrity transition.** The two edges with a `broken_rate_pct` verdict (`analysis<->fixture`, `odd<->market<->fixture`) now post when that edge goes from clean to broken, or back — reusing the eval prompt's own assessment text as the message body (already a specific, human-written summary — e.g. "an analysis regarding Vitória vs Flamengo being incorrectly attributed to..."). Silent while an already-flagged issue stays open. Shares the same `slack-notify-config` webhook as `surface-verify.py` — one webhook per pod covers both. The linkability edge (`market->fixture(link)`) has no `broken_rate_pct` and isn't wired to this — its link-rate isn't inherently good/bad the same way (many markets are structurally unlinkable outrights).
20
+
21
+ ## [0.5.6] - 2026-07-01
22
+
23
+ ### Fixed
24
+ - **`context-verify`'s linkability edge silently died on enterprise-scale data.** `scan_link` pulls the full fixture + market universe, paginated at 50 docs/request — fine at hundreds of documents, but SBOT Prd (sportingbot.com) has ~4k fixtures + ~1.8k markets, meaning ~116 sequential round-trips inside one connector execution. Long enough to die mid-run server-side with no health doc and no error — not a crash, just silence. Bumped pagination to 500/request (confirmed the same data pulls in ~30s either way; ~116 round-trips → ~12). Also fixed a second, unrelated truncation in the same function: the markets pull was capped at 500 regardless of how many existed (sized for when "markets are few" — not true at 1.8k), silently dropping candidates from the join *before* any of the function's own reported drop-counts could see them.
25
+
26
+ ## [0.5.5] - 2026-07-01
27
+
28
+ ### Added
29
+ - **`context-verify` supports per-tenant document names** (`FIXTURE_DOC_NAME` / `MARKETS_DOC_NAME`, default `sportradar-fixture` / `entain-markets-tier3` — unchanged, so existing deployments are unaffected). Needed to provision it on SBOT Prd (sportingbot.com): same underlying fixture/markets schema (`bwin_fixture_id`, `markets_tier3`, `pre_match_research`, ...), verified field-identical, but stored under `sportingbot-fixture` / `sportingbot-markets-tier3` instead of the entain-branded names — running unmodified would have silently audited zero documents.
30
+
31
+ ## [0.5.4] - 2026-07-01
32
+
33
+ ### Fixed
34
+ - **`surface-verify`'s odds-heal now has a retry budget.** `trigger_odds_heal` re-runs `entain-coverage-fut-refresh-markets` — a real 15-step workflow that calls the live bwin API — on every `degraded:odds` scan, with no limit on how many times a stuck incident could re-trigger it. It now stops after `max_heal_attempts` (default 3) **consecutive** `degraded:odds` scans, read from the persisted health-doc history (each scan is a fresh, memory-less process), and hands off to a human via Slack ("could NOT self-heal ... needs a human") instead of continuing to re-trigger the workflow. A prior recovery resets the count, so an old resolved incident never counts against a new one. Investigated 2026-07-01: `heal_needed` had never actually fired in `enrichment-production`'s history (0/39 scans) — the gap was latent, not yet a real incident.
35
+
36
+ ## [0.5.3] - 2026-07-01
37
+
38
+ ### Added
39
+ - **A "new version available" notice, shown automatically.** Any `machina` command now checks (at most once a day, cached in `~/.machina/update_check.json`) whether a newer release exists, and prints a one-line notice after the command's own output if so — pointing at `machina update`. Zero added latency on ~everything: a fresh cache is a local file read; a stale one kicks off the real GitHub check in a background thread with a 1.5s budget, so a slow network degrades to "check again next time" instead of a hang. Never blocks, never raises, never shows twice in one process, and is suppressed for `--json` output and piped/non-tty stdout so it can never corrupt a script. The REPL shows it once at startup too.
40
+
5
41
  ## [0.5.2] - 2026-07-01
6
42
 
7
43
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: machina-cli
3
- Version: 0.5.2
3
+ Version: 0.6.0
4
4
  Summary: CLI for the Machina AI Agent platform
5
5
  Project-URL: Homepage, https://machina.gg
6
6
  Project-URL: Repository, https://github.com/machina-sports/machina-cli
@@ -26,6 +26,25 @@ RESOLVES the cross-language links a deterministic join misses and PERSISTS them
26
26
  `context-verify-beat` agent runs the whole sweep on a schedule (self-evolving) — the
27
27
  harness loop's verify + self-repair (Cap 8/8.2) applied to the data graph.
28
28
 
29
+ Slack awareness (analysis<->fixture, odd<->market<->fixture only -- these are the two
30
+ edges with a broken_rate_pct verdict; linkability's link-rate isn't inherently good/bad
31
+ the same way): posts on a broken-rate TRANSITION for that edge -- clean->broken or
32
+ broken->clean -- reusing the eval prompt's own assessment text as the message body (it's
33
+ already a specific, human-written summary). Silent while an already-flagged issue stays
34
+ open, so it doesn't re-page every scan. Shares the same `slack-notify-config` document /
35
+ SLACK_WEBHOOK_URL as surface-verify.py -- one webhook per pod covers both.
36
+
37
+ Auto-heal for analysis<->fixture (opt-in via ANALYSIS_HEAL_WORKFLOW): when a scan finds
38
+ collapsed analysis groups, each affected fixture gets ONE async `context-heal-runner`
39
+ dispatch that runs this pod's per-fixture research workflow (fresh web search + LLM
40
+ extract + doc update) -- regenerating the misattributed analyses. Async on purpose: a
41
+ dozen sequential researches inside one connector execution is the silent-death failure
42
+ mode scan_link hit at enterprise scale. Bounded twice: max_fixtures_per_run (default 5)
43
+ caps cost per scan and the backlog drains across scheduled scans (verified by the next
44
+ scan's broken count), and a no-PROGRESS budget (max_heal_attempts, default 3) stops
45
+ re-dispatching when healing isn't working and escalates to Slack instead -- a draining
46
+ backlog (13->10->7) never trips it; a stuck one (13->13->13) does.
47
+
29
48
  Provisions:
30
49
  connector context-verify-tools scan_edges + scan_odds + scan_link
31
50
  prompt context-verify-eval edge-agnostic assessment (analysis, odds)
@@ -37,10 +56,18 @@ Provisions:
37
56
  Usage:
38
57
  CLIENT_API_URL="https://<org>-<project>.org.machina.gg" \\
39
58
  API_TOKEN="<project X-Api-Token>" [MODEL="gemini-3.1-flash-lite"] \\
59
+ [FIXTURE_DOC_NAME="sportradar-fixture"] [MARKETS_DOC_NAME="entain-markets-tier3"] \\
60
+ [ANALYSIS_HEAL_WORKFLOW="<per-fixture research workflow, e.g. sportingbot-coverage-fut-enrich-fixtures>"] \\
40
61
  python3 context-verify.py # provision
41
62
  python3 context-verify.py --run # provision, run all audits, print graph health
42
63
  python3 context-verify.py --teardown # remove
43
64
 
65
+ If this pod stores the same fixture/markets schema under a brand-prefixed doc name
66
+ (check with a document/search sample first — same field names, different `name`),
67
+ override FIXTURE_DOC_NAME / MARKETS_DOC_NAME instead of assuming the entain default.
68
+ Before setting ANALYSIS_HEAL_WORKFLOW, confirm the named workflow accepts a
69
+ `fixture_id` input (= metadata.sport_event_id) and re-researches just that fixture.
70
+
44
71
  Runs entirely server-side in the pod — unaffected by the MCP agent-by-name
45
72
  limitation (machina-client-api#287).
46
73
  """
@@ -55,6 +82,21 @@ import urllib.error
55
82
  BASE = os.environ.get("CLIENT_API_URL", "").rstrip("/")
56
83
  TOKEN = os.environ.get("API_TOKEN", "")
57
84
  MODEL = os.environ.get("MODEL", "gemini-3.1-flash-lite")
85
+ # Document names are per-tenant: some pods write the same schema (bwin_fixture_id,
86
+ # markets_tier3, pre_match_research, ...) under a brand-prefixed doc name instead of
87
+ # the entain/sportradar default (e.g. SBOT's own pods use sportingbot-fixture /
88
+ # sportingbot-markets-tier3). Verified field-identical before relying on this -- override
89
+ # per pod at provision time; the default is unchanged so existing deployments are unaffected.
90
+ FIXTURE_DOC_NAME = os.environ.get("FIXTURE_DOC_NAME", "sportradar-fixture")
91
+ MARKETS_DOC_NAME = os.environ.get("MARKETS_DOC_NAME", "entain-markets-tier3")
92
+ # Auto-heal for the analysis<->fixture edge: name of THIS POD's per-fixture research
93
+ # workflow (e.g. sportingbot-coverage-fut-enrich-fixtures on SBOT Prd -- it accepts a
94
+ # `fixture_id` = metadata.sport_event_id input and re-researches just that fixture).
95
+ # Default EMPTY = heal disabled, detect-only: each tenant's enrich pipeline differs, so
96
+ # healing is strictly opt-in at provision time. When set, a `context-heal-runner` agent
97
+ # is provisioned and the analysis audit gains a heal step (async dispatch, budgeted).
98
+ ANALYSIS_HEAL_WORKFLOW = os.environ.get("ANALYSIS_HEAL_WORKFLOW", "").strip()
99
+ HEAL_AGENT_NAME = "context-heal-runner"
58
100
  GENAI = {"command": "invoke_prompt", "location": "global", "model": MODEL,
59
101
  "name": "google-genai", "provider": "vertex_ai"}
60
102
  CTX_VARS = {"debugger": {"enabled": True}, "google-genai": {
@@ -93,7 +135,7 @@ def _create(kind, body):
93
135
 
94
136
  # --- connector source: deterministic edge gates (pyscript, exec'd from the DB) ---
95
137
  SCAN_SRC = r'''"""Context Graph edge scanners (analysis, odds, linkability)."""
96
- import re, unicodedata
138
+ import json, os, re, unicodedata, urllib.request, urllib.error
97
139
  from collections import defaultdict
98
140
 
99
141
  def _docs(name, extra, limit):
@@ -102,8 +144,13 @@ def _docs(name, extra, limit):
102
144
  flt = {"name": name}; flt.update(extra or {})
103
145
  # page cap follows the requested limit (was a hard `page <= 8` = max 400 docs, which
104
146
  # silently capped the fixture pull at 300 while 2k+ fixtures existed -> false orphans).
105
- while len(out) < limit and page <= (limit // 50 + 2):
106
- r = document_search(filters=flt, page=page, page_size=50, sorters=["_id", -1])
147
+ # page_size=500 (was 50): an enterprise-scale pod's full-universe pull (~4k fixtures +
148
+ # ~1.8k markets) took ~115 sequential 50-doc round-trips -- long enough to silently die
149
+ # mid-execution (no health doc, no error) rather than return an honest error. 500/page
150
+ # cuts that to ~12 round-trips; confirmed 1000/page pulls the same data in ~30s total.
151
+ page_size = 500
152
+ while len(out) < limit and page <= (limit // page_size + 2):
153
+ r = document_search(filters=flt, page=page, page_size=page_size, sorters=["_id", -1])
107
154
  dd = r.get("data") if isinstance(r, dict) else None
108
155
  batch = dd.get("data") if isinstance(dd, dict) else (dd if isinstance(dd, list) else [])
109
156
  if not batch: break
@@ -200,23 +247,29 @@ def scan_edges(request_data: dict) -> dict:
200
247
  p = request_data.get("params", {}) or request_data
201
248
  try: docs = _docs("sportradar-fixture", {"value.has_pre_match_research": True}, _limit(p))
202
249
  except Exception as ex:
203
- return {"status": True, "data": {"health": {"edge": "analysis<->fixture", "error": str(ex)}, "flagged": []}}
250
+ return {"status": True, "data": {"health": {"edge": "analysis<->fixture", "error": str(ex)}, "flagged": [], "heal_needed": False}}
204
251
  enriched = []
205
252
  for d in docs:
206
253
  v = d.get("value", {}) or {}
207
254
  tf = (v.get("pre_match_research") or {}).get("team_form") or {}
208
255
  ha = ((tf.get("home") or {}).get("analysis") or "").strip()
209
256
  title = re.sub(r"\s*\(\d+\)\s*$", "", str(v.get("title") or "")).strip()
210
- if ha and title: enriched.append((title, re.sub(r"\s+", " ", ha.lower())[:160]))
211
- groups = defaultdict(set)
212
- for title, key in enriched: groups[key].add(title)
257
+ if ha and title: enriched.append((title, v.get("sport_event_id"), re.sub(r"\s+", " ", ha.lower())[:160]))
258
+ groups = defaultdict(set); group_ids = defaultdict(set)
259
+ for title, sid, key in enriched:
260
+ groups[key].add(title)
261
+ if sid: group_ids[key].add(sid)
213
262
  collapsed = {k: sorted(v) for k, v in groups.items() if len(v) > 1}
214
263
  broken = sum(len(v) - 1 for v in collapsed.values())
215
- flagged = [{"fixtures": v, "analysis": k[:120]} for k, v in list(collapsed.items())[:10]]
264
+ # fixture_ids feed the auto-heal: EVERY fixture in a collapsed group gets re-researched
265
+ # (we can't tell which one rightfully owns the analysis; re-researching the owner too is
266
+ # harmless -- it just gets a fresh, correct analysis of its own).
267
+ flagged = [{"fixtures": v, "fixture_ids": sorted(group_ids.get(k, set())), "analysis": k[:120]}
268
+ for k, v in list(collapsed.items())[:10]]
216
269
  n = len(enriched)
217
270
  health = {"edge": "analysis<->fixture", "sampled": n, "collapsed_groups": len(collapsed),
218
271
  "broken_edges": broken, "broken_rate_pct": round(100 * broken / n) if n else 0}
219
- return {"status": True, "data": {"health": health, "flagged": flagged}}
272
+ return {"status": True, "data": {"health": health, "flagged": flagged, "heal_needed": broken > 0}}
220
273
 
221
274
  def scan_odds(request_data: dict) -> dict:
222
275
  """odd <-> market <-> fixture: a market's options must reference the fixture it declares."""
@@ -255,9 +308,13 @@ def scan_link(request_data: dict) -> dict:
255
308
  lim = _limit(p)
256
309
  try:
257
310
  # Pull the FULL fixture set (not a 300-doc slice): markets must be linkable against
258
- # every fixture, not the first page. Markets are few; fixtures are the haystack.
311
+ # every fixture, not the first page. The 500 cap on markets was sized for the
312
+ # original small datasets ("markets are few") -- an enterprise-scale pod can have
313
+ # 1000s (SBOT Prd: ~1.8k), and unlike the universe/unresolved caps below, this one
314
+ # wasn't reported when it silently dropped markets before they were ever counted.
315
+ # Match the fixture side: pull the full set, no silent pre-count truncation.
259
316
  fdocs = _docs("sportradar-fixture", {}, max(lim, 5000))
260
- mdocs = _docs("entain-markets-tier3", {}, max(lim, 500))
317
+ mdocs = _docs("entain-markets-tier3", {}, max(lim, 5000))
261
318
  except Exception as ex:
262
319
  return {"status": True, "data": {"health": {"edge": "market->fixture(link)", "error": str(ex)}, "unresolved_sample": [], "fixture_universe": []}}
263
320
  fixture_keys = set(); universe = []; fidx_full = {}; canon_idx = {}
@@ -328,6 +385,196 @@ def resolve_link_ids(request_data: dict) -> dict:
328
385
  "market": mk, "fixture": fx, "source": "semantic-heal"})
329
386
  return {"status": True, "data": {"links": links, "resolved": len(links),
330
387
  "deterministic": det_n, "semantic": len(links) - det_n, "rejected": rejected}}
388
+
389
+ def _stuck_heal_attempts(current_broken):
390
+ """How many CONSECUTIVE prior analysis<->fixture scans attempted a heal WITHOUT the
391
+ broken count improving, walking back from now. Progress resets the chain: a backlog
392
+ draining 13 -> 10 -> 7 across scans never trips the budget (each attempt helped);
393
+ 13 -> 13 -> 13 does (healing isn't working -- stop dispatching and call a human).
394
+ Read from the persisted health-doc history: each scan is a fresh process, so the
395
+ doc trail is the loop's only memory -- same pattern the transition detection uses."""
396
+ try:
397
+ from core.document.controller import document_search
398
+ r = document_search(filters={"name": "context_graph_health"}, page=1, page_size=30,
399
+ sorters=["created", -1])
400
+ dd = r.get("data") if isinstance(r, dict) else None
401
+ rows = dd.get("data") if isinstance(dd, dict) else (dd if isinstance(dd, list) else [])
402
+ except Exception:
403
+ return 0
404
+ n, cur = 0, current_broken
405
+ for row in rows or []:
406
+ v = row.get("value") or {}
407
+ h = v.get("health") or {}
408
+ if h.get("edge") != "analysis<->fixture":
409
+ continue
410
+ broken = h.get("broken_edges") or 0
411
+ attempted = ((v.get("healed") or {}).get("heal_count") or 0) > 0
412
+ if broken > 0 and attempted and cur >= broken:
413
+ n += 1; cur = broken
414
+ else:
415
+ break
416
+ return n
417
+
418
+
419
+ def trigger_analysis_heal(request_data: dict) -> dict:
420
+ """Re-research the fixtures in collapsed analysis groups, via async agent dispatches.
421
+
422
+ Each affected fixture gets one `context-heal-runner` dispatch (delay=True), which runs
423
+ this pod's per-fixture research workflow (fresh web search + LLM extract + doc update)
424
+ server-side on its own -- the connector only fires the dispatches and returns in ms.
425
+ Deliberately NOT synchronous: each research takes ~a minute, and a dozen sequential
426
+ ones inside one connector execution is exactly the silent-death-mid-run failure mode
427
+ scan_link hit at enterprise scale.
428
+
429
+ Bounded twice: max_fixtures_per_run caps cost per scan (the backlog drains across
430
+ scheduled scans, verified by the next scan's broken count), and _stuck_heal_attempts
431
+ stops re-dispatching after max_heal_attempts consecutive no-progress rounds and lets
432
+ notify_slack escalate to a human instead."""
433
+ p = request_data.get("params", {}) or request_data
434
+ if not p.get("heal_needed"):
435
+ return {"status": True, "data": {"healed": [], "heal_count": 0, "skipped": "edge is clean"}}
436
+ heal_agent = (p.get("heal_agent") or "").strip()
437
+ if not heal_agent or heal_agent.startswith("$"):
438
+ return {"status": True, "data": {"healed": [], "heal_count": 0, "skipped": "heal not configured"}}
439
+
440
+ health = p.get("health") or {}
441
+ current_broken = health.get("broken_edges") or 0
442
+ max_attempts = int(p.get("max_heal_attempts", 3) or 3)
443
+ stuck = _stuck_heal_attempts(current_broken)
444
+ if stuck >= max_attempts:
445
+ return {"status": True, "data": {"healed": [], "heal_count": 0, "budget_exceeded": True,
446
+ "prior_attempts": stuck, "max_attempts": max_attempts,
447
+ "skipped": "no progress after %d heal rounds" % stuck}}
448
+
449
+ # unique fixture ids across flagged groups, order-preserving
450
+ ids, seen = [], set()
451
+ for g in (p.get("flagged") or []):
452
+ for fid in (g.get("fixture_ids") or []) if isinstance(g, dict) else []:
453
+ if fid and fid not in seen:
454
+ seen.add(fid); ids.append(fid)
455
+ cap = int(p.get("max_fixtures_per_run", 5) or 5)
456
+ batch, backlog = ids[:cap], max(0, len(ids) - cap)
457
+
458
+ token = os.environ.get("MACHINA_PROJECT_KEY", "")
459
+ out = []
460
+ for fid in batch:
461
+ try:
462
+ req = urllib.request.Request("http://localhost:5003/agent/executor/" + heal_agent,
463
+ data=json.dumps({"context-agent": {"fixture_id": fid},
464
+ "agent-config": {"delay": True}}).encode(), method="POST",
465
+ headers={"X-Api-Token": token, "Content-Type": "application/json"})
466
+ with urllib.request.urlopen(req, timeout=15) as r:
467
+ r.read()
468
+ out.append({"fixture_id": fid, "status": "dispatched"})
469
+ except Exception as e:
470
+ out.append({"fixture_id": fid, "error": str(e)[:120]})
471
+ return {"status": True, "data": {"healed": out, "heal_count": len([o for o in out if not o.get("error")]),
472
+ "backlog": backlog}}
473
+
474
+
475
+ # Raw broken-COUNT field per edge, not the rounded broken_rate_pct: round(100*1/500) is
476
+ # 0, so a genuine single broken record can silently round down to a "clean" 0% and never
477
+ # alert. The count is exact; the percentage is just for display.
478
+ BROKEN_COUNT_FIELD = {"analysis<->fixture": "broken_edges", "odd<->market<->fixture": "misattributed"}
479
+
480
+ def notify_slack(request_data: dict) -> dict:
481
+ """Post to Slack on a broken TRANSITION for one edge -- entering a broken state (0
482
+ broken -> some) or recovering (some -> 0). Silent while unchanged, so an
483
+ already-flagged, still-open issue doesn't re-page every scan. Only covers edges in
484
+ BROKEN_COUNT_FIELD (analysis<->fixture, odd<->market<->fixture) -- the linkability
485
+ edge's link-rate isn't inherently good/bad the same way (many markets are
486
+ structurally unlinkable outrights), so it has no verdict to alert on here; this
487
+ no-ops cleanly if wired to it anyway. Reuses the assessment the eval prompt already
488
+ wrote -- it's already a specific, human-written summary, better than anything a
489
+ template string could produce. Best-effort: never raises (a notify failure must
490
+ never fail the audit)."""
491
+ p = request_data.get("params", {}) or request_data
492
+ health = p.get("health") or {}
493
+ edge = health.get("edge", "unknown")
494
+ count_field = BROKEN_COUNT_FIELD.get(edge)
495
+ if count_field is None:
496
+ return {"status": True, "data": {"notified": False, "skipped": "edge has no broken-count signal"}}
497
+ count = health.get(count_field)
498
+ rate = health.get("broken_rate_pct")
499
+ if count is None:
500
+ return {"status": True, "data": {"notified": False, "skipped": "no %s on this edge" % count_field}}
501
+
502
+ webhook = (p.get("webhook_url") or "").strip()
503
+ if not webhook or webhook.startswith("$"):
504
+ try:
505
+ from core.document.controller import document_search
506
+ r = document_search(filters={"name": "slack-notify-config"}, page=1, page_size=1)
507
+ dd = r.get("data") if isinstance(r, dict) else None
508
+ rows = dd.get("data") if isinstance(dd, dict) else (dd if isinstance(dd, list) else [])
509
+ if rows:
510
+ webhook = ((rows[0].get("value") or {}).get("webhook_url") or "").strip()
511
+ except Exception:
512
+ pass
513
+ if not webhook:
514
+ return {"status": True, "data": {"notified": False, "skipped": "no webhook configured"}}
515
+
516
+ # context_graph_health holds every edge under the same document name, so filter by
517
+ # name then walk client-side to the first (most recent) match for THIS edge. This
518
+ # task runs before save-health persists the current run, so the first match found
519
+ # here is genuinely the prior reading -- same trick surface-verify uses.
520
+ prev_count, prev_budget_exceeded = None, False
521
+ try:
522
+ from core.document.controller import document_search
523
+ r = document_search(filters={"name": "context_graph_health"}, page=1, page_size=20,
524
+ sorters=["created", -1])
525
+ dd = r.get("data") if isinstance(r, dict) else None
526
+ rows = dd.get("data") if isinstance(dd, dict) else (dd if isinstance(dd, list) else [])
527
+ for row in rows or []:
528
+ rv = row.get("value") or {}
529
+ if (rv.get("health") or {}).get("edge") == edge:
530
+ prev_count = (rv.get("health") or {}).get(count_field)
531
+ prev_budget_exceeded = bool((rv.get("healed") or {}).get("budget_exceeded"))
532
+ break
533
+ except Exception:
534
+ pass
535
+
536
+ healed = p.get("healed") or {}
537
+ heal_count = healed.get("heal_count") or 0
538
+ budget_exceeded = bool(healed.get("budget_exceeded"))
539
+
540
+ was_broken = bool(prev_count and prev_count > 0)
541
+ is_broken = count > 0
542
+ # Hitting the heal budget is news even when the broken count itself didn't move --
543
+ # auto-heal just gave up, which is exactly when a human must take over.
544
+ newly_exhausted = is_broken and budget_exceeded and not prev_budget_exceeded
545
+ if is_broken == was_broken and not newly_exhausted:
546
+ return {"status": True, "data": {"notified": False, "skipped": "unchanged"}}
547
+
548
+ assessment = (p.get("assessment") or "").strip()
549
+ if is_broken and budget_exceeded:
550
+ headline = ":rotating_light: *Context Graph -- could NOT self-heal* (`%s`)" % edge
551
+ body = ("Still %s broken after %s heal rounds with no progress -- auto-heal is pausing. "
552
+ "*Needs a human.*" % (count, healed.get("prior_attempts", "?")))
553
+ if assessment: body += "\n>%s" % assessment
554
+ elif is_broken and heal_count > 0:
555
+ backlog = healed.get("backlog") or 0
556
+ tail = " (%d more queued for the next scans)" % backlog if backlog else ""
557
+ headline = ":adhesive_bandage: *Context Graph -- data issue found, self-healing* (`%s`)" % edge
558
+ body = ((assessment + "\n>") if assessment else "") + \
559
+ ("Auto-heal dispatched fresh research for %d fixture(s)%s -- the next scans verify the fix." % (heal_count, tail))
560
+ elif is_broken:
561
+ headline = ":rotating_light: *Context Graph -- data issue found* (`%s`)" % edge
562
+ body = assessment or ("%s broken (%s%% of sample). *Needs a human* -- "
563
+ "auto-heal is not configured for this edge here." % (count, rate))
564
+ else:
565
+ headline = ":white_check_mark: *Context Graph -- recovered* (`%s`)" % edge
566
+ body = "Back to 0 broken (was %s)." % prev_count
567
+
568
+ text = "%s\n>%s" % (headline, body)
569
+ body_bytes = json.dumps({"text": text}).encode()
570
+ req = urllib.request.Request(webhook, data=body_bytes, method="POST",
571
+ headers={"Content-Type": "application/json"})
572
+ try:
573
+ with urllib.request.urlopen(req, timeout=15) as r:
574
+ r.read()
575
+ return {"status": True, "data": {"notified": True, "edge": edge, "rate": rate}}
576
+ except Exception as e:
577
+ return {"status": True, "data": {"notified": False, "error": str(e)[:150]}}
331
578
  '''
332
579
 
333
580
  EVAL_SCHEMA = {"title": "ContextGraphAssessment", "type": "object", "properties": {
@@ -364,6 +611,9 @@ LINK_INSTR = (
364
611
  # --- workflow fragments ---
365
612
  HVAL = ("{'edge':$.get('cg_health', {}).get('edge','?'),'health':$.get('cg_health', {}),"
366
613
  "'flagged':$.get('cg_flagged', []),'assessment':$.get('cg_summary', {}).get('assessment',''),"
614
+ # heal attempts ride the history doc: the stuck-heal budget and the timeline both
615
+ # reconstruct from this trail (each scan is a fresh process with no other memory).
616
+ "'healed':$.get('cg_healed', {}),"
367
617
  "'generator':'context-verify v0'}")
368
618
  LINKVAL = ("{'edge':'market->fixture(link)','health':$.get('cg_health', {}),"
369
619
  "'recovered_by_semantic':len($.get('cg_link', {}).get('matches', [])),"
@@ -381,22 +631,50 @@ HEALVAL = ("{'edge':'market->fixture','links':$.get('cg_links', []),"
381
631
  "'source':'deterministic+semantic','generator':'context-heal v2 (country-map + full universe)'}")
382
632
 
383
633
 
384
- def _audit_workflow(name, title, desc, scan_command):
634
+ def _audit_workflow(name, title, desc, scan_command, with_heal=False):
635
+ tasks = [
636
+ {"name": "scan", "type": "connector", "connector": {"command": scan_command, "name": "context-verify-tools"},
637
+ "inputs": {"limit": "$.get('limit', 200)"},
638
+ "outputs": {"cg_health": "$.get('health')", "cg_flagged": "$.get('flagged')",
639
+ "cg_heal": "$.get('heal_needed', False)"}},
640
+ {"name": "context-verify-eval", "type": "prompt", "connector": GENAI,
641
+ "inputs": {"_1-health": "$.get('cg_health', {})", "_2-flagged": "$.get('cg_flagged', [])"},
642
+ "outputs": {"cg_summary": "$"}},
643
+ ]
644
+ if with_heal:
645
+ # async re-research dispatches for the collapsed fixtures; the workflow name it
646
+ # runs is tenant-specific, baked in at provision time via ANALYSIS_HEAL_WORKFLOW.
647
+ tasks.append(
648
+ {"name": "heal", "type": "connector",
649
+ "condition": "$.get('cg_heal', False) == True",
650
+ "connector": {"command": "trigger_analysis_heal", "name": "context-verify-tools"},
651
+ "inputs": {"heal_needed": "$.get('cg_heal', False)",
652
+ "health": "$.get('cg_health', {})",
653
+ "flagged": "$.get('cg_flagged', [])",
654
+ "heal_agent": "'%s'" % HEAL_AGENT_NAME,
655
+ "max_heal_attempts": "$.get('max_heal_attempts', 3)",
656
+ "max_fixtures_per_run": "$.get('max_fixtures_per_run', 5)"},
657
+ "outputs": {"cg_healed": "$"}})
658
+ tasks += [
659
+ # runs before save-health so it still reads the PREVIOUS reading for this
660
+ # edge (transition detection) -- see notify_slack's docstring. Always runs
661
+ # (no condition): it also fires the "recovered" message.
662
+ {"name": "notify", "type": "connector",
663
+ "connector": {"command": "notify_slack", "name": "context-verify-tools"},
664
+ "inputs": {"health": "$.get('cg_health', {})",
665
+ "assessment": "$.get('cg_summary', {}).get('assessment','')",
666
+ "healed": "$.get('cg_healed', {})",
667
+ "webhook_url": "$TEMP_CONTEXT_VARIABLE_SLACK_WEBHOOK_URL"},
668
+ "outputs": {"cg_notified": "$"}},
669
+ {"name": "save-health", "type": "document",
670
+ "config": {"action": "save", "embed-vector": False, "force-update": True},
671
+ "documents": {"context_graph_health": HVAL}},
672
+ ]
385
673
  return {"name": name, "title": title, "status": "active", "description": desc,
386
674
  "context-variables": CTX_VARS, "inputs": {"limit": "$.get('limit', 200)"},
387
675
  "outputs": {"health": "$.get('cg_health', {})",
388
676
  "assessment": "$.get('cg_summary', {}).get('assessment','')", "workflow-status": "'executed'"},
389
- "tasks": [
390
- {"name": "scan", "type": "connector", "connector": {"command": scan_command, "name": "context-verify-tools"},
391
- "inputs": {"limit": "$.get('limit', 200)"},
392
- "outputs": {"cg_health": "$.get('health')", "cg_flagged": "$.get('flagged')"}},
393
- {"name": "context-verify-eval", "type": "prompt", "connector": GENAI,
394
- "inputs": {"_1-health": "$.get('cg_health', {})", "_2-flagged": "$.get('cg_flagged', [])"},
395
- "outputs": {"cg_summary": "$"}},
396
- {"name": "save-health", "type": "document",
397
- "config": {"action": "save", "embed-vector": False, "force-update": True},
398
- "documents": {"context_graph_health": HVAL}},
399
- ]}
677
+ "tasks": tasks}
400
678
 
401
679
 
402
680
  def _link_workflow():
@@ -432,19 +710,32 @@ def _link_workflow():
432
710
  ]}
433
711
 
434
712
 
713
+ def _scan_src_for_tenant():
714
+ """SCAN_SRC with the two entain-specific doc names swapped for this pod's config.
715
+ Plain string substitution (not .format()/f-string) because SCAN_SRC is full of
716
+ literal { } from dict literals/comprehensions that would collide with either.
717
+ json.dumps() re-quotes safely; with the defaults, this is a no-op (identical output)."""
718
+ src = SCAN_SRC.replace('"sportradar-fixture"', json.dumps(FIXTURE_DOC_NAME))
719
+ src = src.replace('"entain-markets-tier3"', json.dumps(MARKETS_DOC_NAME))
720
+ return src
721
+
722
+
435
723
  def definitions():
436
724
  tools = {"name": "context-verify-tools", "title": "Context Verify Tools", "status": "active",
437
725
  "description": "deterministic edge scanners (analysis + odds + linkability)",
438
- "filename": "context_verify.py", "filetype": "pyscript", "filecontent": SCAN_SRC,
726
+ "filename": "context_verify.py", "filetype": "pyscript", "filecontent": _scan_src_for_tenant(),
439
727
  "commands": [{"name": "Scan", "value": "scan_edges"}, {"name": "ScanOdds", "value": "scan_odds"},
440
- {"name": "ScanLink", "value": "scan_link"}, {"name": "ResolveIds", "value": "resolve_link_ids"}]}
728
+ {"name": "ScanLink", "value": "scan_link"}, {"name": "ResolveIds", "value": "resolve_link_ids"},
729
+ {"name": "NotifySlack", "value": "notify_slack"},
730
+ {"name": "TriggerAnalysisHeal", "value": "trigger_analysis_heal"}]}
441
731
  evaluate = {"name": "context-verify-eval", "title": "Context Verify Eval", "type": "prompt", "status": "active",
442
732
  "description": "edge-agnostic semantic lens over graph-health findings",
443
733
  "instruction": EVAL_INSTR, "schema": EVAL_SCHEMA}
444
734
  link_eval = {"name": "context-link-eval", "title": "Context Link Eval", "type": "prompt", "status": "active",
445
735
  "description": "semantic resolver for the market->fixture linkability edge",
446
736
  "instruction": LINK_INSTR, "schema": LINK_SCHEMA}
447
- wf_a = _audit_workflow("context-verify", "Context Verify", "audit the analysis<->fixture edge", "scan_edges")
737
+ wf_a = _audit_workflow("context-verify", "Context Verify", "audit the analysis<->fixture edge", "scan_edges",
738
+ with_heal=bool(ANALYSIS_HEAL_WORKFLOW))
448
739
  wf_o = _audit_workflow("context-verify-odds", "Context Verify Odds", "audit the odd<->market<->fixture edge", "scan_odds")
449
740
  wf_l = _link_workflow()
450
741
  edge_workflows = [
@@ -461,8 +752,23 @@ def definitions():
461
752
  "description": "continuous self-healing sweep of the context graph (set status:active to enable)",
462
753
  "context": {"config-frequency": 60}, "context-agent": {"limit": "$.get('limit', 200)"},
463
754
  "workflows": edge_workflows}
464
- return [("connector", tools), ("prompt", evaluate), ("prompt", link_eval),
755
+ defs = [("connector", tools), ("prompt", evaluate), ("prompt", link_eval),
465
756
  ("workflow", wf_a), ("workflow", wf_o), ("workflow", wf_l), ("agent", runner), ("agent", beat)]
757
+ if ANALYSIS_HEAL_WORKFLOW:
758
+ # One async dispatch per fixture to heal: trigger_analysis_heal fires
759
+ # agent/executor/<this> with {"fixture_id": ...} and the pod's own per-fixture
760
+ # research workflow does the actual work server-side (fresh search + LLM +
761
+ # doc update). Inactive/unscheduled -- executor-dispatched only.
762
+ heal_runner = {"name": HEAL_AGENT_NAME, "title": "Context Heal Runner", "status": "inactive",
763
+ "scheduled": False,
764
+ "description": "re-researches one fixture (dispatched by the analysis<->fixture heal)",
765
+ "context-agent": {"fixture_id": "$.get('fixture_id')"},
766
+ "workflows": [{"name": ANALYSIS_HEAL_WORKFLOW,
767
+ "description": "per-fixture research regeneration",
768
+ "inputs": {"fixture_id": "$.get('fixture_id')"},
769
+ "outputs": {"workflow-status": "$.get('workflow-status', 'executed')"}}]}
770
+ defs.append(("agent", heal_runner))
771
+ return defs
466
772
 
467
773
 
468
774
  def _run_once():