Skip to content

feat(context): compact the session bootstrap, bundle a routed skill's context into one call, and audit context budgets in CI - #812

Merged
sumithr merged 11 commits into
mainfrom
feat/issue-512-compact-bootstrap-bundled-context
Oct 3, 2026
Merged

sumithr merged 11 commits into
mainfrom
feat/issue-512-compact-bootstrap-bundled-context

Conversation

@sumithr

@sumithr sumithr commented Oct 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

Three context-cost changes from #512: a compact session bootstrap, a one-call bundle mode for a routed skill's working context (wired into sumo-qa-reviewing-before-merge only), and a deterministic context-budget audit that runs in CI. A build-time pass also serves every tool description through inspect.cleandoc, so tools/list is identical on every supported Python.

Measured honestly: the bundle does NOT reduce turns or total tokens on a real review. It makes the review load its modules in one call where the per-loader path skipped them. Details under "How it was verified".

Related issue

Refs #512. Child of epic #508. This PR does not close #512: its turn/token acceptance criterion is not met (see below), and wiring the bundle into the other routed skills is split to #802, which first re-checks the premise per skill family. Bringing every root skill under its token budget is #798.

Changes

  • Compact bootstrap. hooks/session-start injects hooks/compact-bootstrap.md (the QA-trigger rule, the canonical first hop, and a fallback naming the absolute router path) instead of the full router body. It falls back to the full body when uvx is missing; SUMO_QA_BOOTSTRAP=auto|compact|full overrides, and an unrecognised value adds a one-line notice. On Git Bash the path is converted with cygpath -m. Claude, Cursor and Codex/Copilot envelopes are unchanged and schema-valid.
  • Bundle mode. sumo_qa_load_skill_context(mode="bundle", classification=..., modules=..., include_body=...) returns the skill body, the named modules, the catalogue entries, and the rules and standards in one call.
    • Rules and standards parts are sumo_qa_load_rules / sumo_qa_load_standards called once each with the same argument, so they equal the single loaders by construction.
    • Catalogue entries are looked up by exact id. Classification ids are matched exactly (case-sensitive), in request order. Any id that matches nothing returns an error envelope listing the catalogue ids plus the rules keys. A loader exception returns an "unreadable" envelope; the tool never raises.
    • Module ids are split on commas and looked up exactly as mode="module" does.
    • known_hash / content_hash and the oversize cap work on the served form.
    • src/sumo_qa/knowledge_loaders.py is unchanged from main.
  • Review skill. Step 3 makes one bundle call: test-only-diff when every changed file is a test, otherwise runtime-scope, discovery-probes, coverage-ledger plus any conditional module the file list calls for. The root stays within its 3,000-token ceiling. The deciding-approach routing line names the bundle call and stays within its own budget.
  • Tool descriptions. MCPServer serves a tool's docstring unchanged. Python 3.13+ strips docstring indentation at compile time and 3.10 to 3.12 keep it, so tools/list used to be larger on the older interpreters. A build-time pass now normalises every served description with inspect.cleandoc, and a test pins that no served description carries docstring indentation.
  • Conformance. Scenario S02 requires rules to be loaded: sumo_qa_load_rules, or a bundle call with a classification (argument-aware required_one_of). A module-only call fails it.
  • Audit. scripts/audit_context_budget.py reads [tool.sumo-qa.context-budget] in pyproject.toml, measures the real hook and the real server, and fails configured budgets. CI runs it as the context-budget job, and the suite enforces it on every pytest matrix leg. The root-skill budget is report-only.
  • Docs. ARCHITECTURE (session bootstrap), TOOLS, SKILLS, DEVELOPMENT, README.

Rebased onto main after the tool registry with core and full profiles (#811) and the executable-ness routing change (#818) landed.

How it was verified

  • Audit (context budget: OK, identical on Python 3.12 and 3.14): compact bootstrap 359 estimated tokens (budget 1,000; the full router body is 4,185); tools/list 11,681 of 11,900; bundles 5,547 of 5,800 (business logic), 6,719 of 7,000 (security), 2,218 of 2,250 (test-only). Modelled per workflow, the bundle cuts loader calls from 11/12/9 to 6. Before the description fix, Python 3.12 measured tools/list at 12,525 and failed the budget, which is why the 3.10 to 3.12 pytest legs were red.

  • Real session measurement (compare-mcp-versions --review-mode, haiku, one run each, a real review of the fix(repo-map): resolve src-layout Python imports and add Python/Java import-edge fixtures #790 diff, tests run, full ledger and verdict on both sides):

    main this branch (ab4cf33)
    Total tokens 1,405,091 1,485,677 (+5.7%)
    API calls 17 17
    Cost $0.361 $0.383
    Review modules loaded none runtime-scope, discovery-probes, coverage-ledger (one call)
    Verdict SAFE TO MERGE SAFE TO MERGE

    The [Task]: Make session bootstrap conditional, collapse skill-loading turns, and enforce context token budgets #512 criterion "reaches its ledger in measurably fewer turns than the 16-call baseline" is not met: that baseline came from a Gemini CLI run, and on haiku both versions take 17 calls. Main is cheaper partly because it never loads the review modules. The compact bootstrap saving is not in this measurement, because the harness launches the server without the plugin's SessionStart hook. Full write-up on [Task]: Make session bootstrap conditional, collapse skill-loading turns, and enforce context token budgets #512.

  • Behaviour on a clean wheel build, driven by headless haiku through the MCP tools: in a real Claude Code session the SessionStart hook injected 390 estimated tokens with no router body, and a non-QA prompt made no sumo-qa call. A development-framed QA prompt took the first hop (using_sumo_qa, sumo_qa_deciding_approach, one routed skill). A review prompt loaded its context in one bundle call. The bundle's rules, standards and module text were byte-identical to the separate loader calls. using_sumo_qa and sumo_qa_load_classifications returned identical output on this branch and on main. The hook was also run with uvx absent, with SUMO_QA_BOOTSTRAP=full, compact and an unknown value, and in the Codex shape.

  • Evals (Claude pair, on the final skill text): skill-reviewing-before-merge.yaml 1/1; skill-deciding-approach.yaml 5/5.

  • Byte-identity: load_rules(), load_standards(), load_rules("api_contract_change"), load_rules("Business_Logic_Change") and load_standards("api_contract_change") return the same text as main.

  • Suite: full local suite 5,411 passed, 7 skipped, 1 xfailed, 100% coverage.

  • Review: sumo-qa per-file review of every changed file plus /code-review high on the full diff and on every fix delta. Rounds 2 to 4 of the original review kept finding mismatches between a case-insensitive bundle and the case-sensitive loaders, so the bundle was simplified to pass ids through to the unchanged loaders. The post-rebase fixes (the budget trim, the description normalisation and a test docstring correction) were reviewed in two rounds, which found no high or medium defect.

Not changed, deliberately: the bundle's error lists rules keys but not standards-only ids (the message says those are accepted too); rules-file keys containing separators are listed but cannot be requested; the bundle is not wired into the other routed skills (#802).

Checklist

  • PR title follows Conventional Commits
  • Tests pass locally (pytest) and lint/type checks are green (pre-commit run --all-files, python -m mypy)
  • Added or updated tests covering the change
  • Updated the relevant docs in this same PR
  • No breaking changes (or they are called out above)

sumithr added 11 commits October 3, 2026 13:38
… context into one call, and audit context budgets in CI

The SessionStart hook now injects a compact bootstrap (hooks/compact-bootstrap.md,
about 320 estimated tokens: what makes a request QA-shaped, the canonical
first-hop rule and a pointer to the using_sumo_qa router) instead of the full
~4.1k-token router body, so a non-QA session never carries it. When uvx is
missing the MCP server cannot start, so the hook falls back to the full body;
SUMO_QA_BOOTSTRAP=full|compact overrides the detection. Host envelopes are
unchanged.

sumo_qa_load_skill_context gains mode="bundle" (classification, modules,
include_body): one call returns a routed skill's body, the named modules, the
classification entries and the filtered standards and rules, each part
identical to its single loader. Unknown classifications or modules return an
error envelope; an over-cap bundle returns per-part sizes. The review skill
loads its working context through one bundle call in step 3 instead of the
classifications, standards, rules and per-module chain, and the S02
conformance contract follows.

scripts/audit_context_budget.py measures the bootstrap, tools/list, every root
skill and the bundled review workflows (per-loader vs bundled call counts and
a re-sent estimate) against [tool.sumo-qa.context-budget] in pyproject.toml and
fails on an exceeded budget; CI runs it in lint.yml. The root-skill budget is
report-only until #798.

Refs #512
…me-scope, and keep context docs current-state (Refs #512)

Bundle mode accepts any classification id the rules or standards loaders
accept, resolved case-insensitively, reuses the shared classification-term
parser, reads the catalogue only when a classification is requested, returns
an error envelope when the rules or standards source is unreadable, and
hashes and sizes the served JSON so known_hash round-trips. The audit script
uses the canonical estimator. The SessionStart hook probes uvx once, reports
an unrecognised SUMO_QA_BOOTSTRAP value and treats it as auto, and the compact
bootstrap names the Skill and file fallbacks. The review skill's step-3 bundle
carries the modules every runtime review needs, and the S02 conformance
scenario requires the change rules to be loaded.

Refs #512
…review modules to the diff shape (Refs #512)

Classification ids are lowercased once in the shared term parser, so the
rules and standards loaders and the context bundle select the same entries
for any casing. The bundle reads the rules file and standards packs once,
accepts an id by membership in their parsed ids (a malformed rules file
accepts none), and lists every accepted id when one is unknown. Catalogue
lookup shares load_catalogue_entry's id-or-heading matcher.

The review skill's step-3 bundle loads test-only-diff for an all-test diff
and the runtime modules otherwise. The compact bootstrap names the router by
absolute path. Conformance `required_one_of` rejects malformed entries and a
"*" argument holding no id.

Refs #512
…undle ids to their canonical spelling (Refs #512)

The shared classification-term parser preserves case again, so
sumo_qa_load_rules and sumo_qa_load_standards match ids exactly as on main
and return the raw files unparsed when unfiltered. A mapping-valued
classifications entry declares no ids.

Bundle mode maps each requested id, case-insensitively, to the spellings the
single loaders select by (rules keys, rules aliases resolved against the keys,
standards-declared ids, catalogue ids) and calls those loaders with them, so
each bundle part equals the loader called with the canonical id. A rules or
standards source PyYAML cannot construct returns the unreadable envelope.
Module ids are matched exactly, as in mode="module".

The SessionStart hook injects the cygpath -m form of the plugin root under
Git Bash / MSYS, and the context audit measures the bootstrap with a fixed
stand-in root so the count does not depend on the clone path.

Refs #512
…anged loaders (Refs #512)

The bundle now calls sumo_qa_load_rules and sumo_qa_load_standards once
each with the classification value as given and reads catalogue entries
by exact id, so every part equals its single loader for the same argument.
Ids with no catalogue entry are listed in unmatched_classifications; ids
matching nothing return the unknown-classification envelope, and any
loader exception returns the unreadable envelope. Module ids split on
commas and match exactly. knowledge_loaders.py is identical to main.

Refs #512
…request order (Refs #512)

Each requested id must match a catalogue entry by exact id, or select
rules or standards through the unchanged loaders; any unmatched id returns
the unknown-classification envelope with no partial payload. Ids keep
their request order, and the rules and standards parts stay one call each
to the single loaders with the value as given.

Refs #512
The reviewing-before-merge routing line names the one bundle call without
restating the bundle's parts, which docs/SKILLS.md already lists.

Refs #512
MCPServer serves a tool's docstring as its description unchanged. Python
3.13+ strips docstring indentation at compile time and 3.10-3.12 keep it, so
tools/list was larger on the older interpreters and failed the context
budget there. A build-time pass now runs every description through
inspect.cleandoc, and a test pins that no served description carries
docstring indentation.

Refs #512
@sumithr
sumithr force-pushed the feat/issue-512-compact-bootstrap-bundled-context branch from 88895f1 to af02d65 Compare October 3, 2026 12:17
@sumithr
sumithr merged commit 99bf3ad into main Oct 3, 2026
29 checks passed
@sumithr
sumithr deleted the feat/issue-512-compact-bootstrap-bundled-context branch October 3, 2026 13:50
sumithr added a commit that referenced this pull request Oct 3, 2026
…ty discovery (#826)

## Summary

Capability discovery now reports which MCP tool profile is active, which
capability groups it serves, and how to turn on the groups it leaves
out. A workflow that needs a group the profile leaves out answers with
one activation path. It never sends the host to tools that are not
there.

## Related issue

Closes #807
Refs #515 (slice 2 of the epic; #515 stays open)

## Changes

- `sumo_qa_capabilities` adds `active_profile`, `enabled_groups`, and
`unavailable_groups` as `{group, open_world, activate}`. All three are
derived from the tool registry, so they match the `tools/list` the
server serves for each profile. It returns compact JSON, so the
500-token bound is measured on the text the host receives. Under `core`
the response is about 440 estimated tokens and under `full` about 445,
both under the bound. `workflows` leaves out any workflow the active
profile cannot run.
- `ToolMeta.requires` names the capability group a core workflow cannot
run without. `sumo_qa_suggesting_external_skill` requires `external`.
Under `core`, its skill tool, `sumo_qa_load_skill_context` and the
`sumoqa://skills/...` resources return this instead of the skill body:
  ```text
  capability unavailable in core profile
  required group: external
  activate: SUMO_QA_MCP_PROFILE=full
  ```
The response then tells the host to report this to the user, not to
substitute another tool or answer from memory. `load_skill_context`
keeps its never-raises contract: an invalid profile value comes back as
an error envelope.
- The Iron Law in `skills/sumo-qa-suggesting-external-skill/SKILL.md`
covers the host-local copy that the installer links into
`~/.claude/skills`, which has no server gate in front of it. When an
external tool cannot be found or called, the host calls
`sumo_qa_capabilities`. If that lists `external` as unavailable, the
host gives the user the activation setting and stops. If it lists
`external` as enabled, the host searches the exact tool name once, and
if the tool is still missing it reports it unavailable and stops.
- Tests: the old external-skill exemption in
`tests/test_tool_registry.py` is now derived from `requires`. There are
new tests for discovery parity against the served `tools/list` per
profile, the activation path on every route, the bound on the served
text, and the omitted workflow.
- Docs: `docs/CONFIGURATION.md` (Tool profiles), `docs/TOOLS.md` and
`docs/ARCHITECTURE.md`.

## Boundary with related work

- **#519 (external-skill annotations and opt-in exposure):** this PR
adds no annotation work. External tools stay in `full`, and the only
activation is `SUMO_QA_MCP_PROFILE=full`, a single `ACTIVATION` constant
in `tool_registry.py`. If #519 moves the external group behind its own
opt-in, each `unavailable_groups[].activate` takes that group's setting.
Only that constant and its use in `capabilities.py` and
`unavailable_capability` change.
- **#512 / PR #812 (context budget audit):** this branch is rebased onto
`main` at `99bf3add`, which includes #812. The `tools/list` change is
the longer `sumo_qa_capabilities` description. The output schema is
dropped from `tools/list`, so the new response fields cost nothing
there. On the rebased tree, `scripts/audit_context_budget.py` measures
`tools/list` at 11708 estimated tokens against its 11900 budget and
reports `context budget: OK`.
`tests/fixtures/mcp_tools_list_snapshot.json` regenerates with no diff.
- **#808, #809, #810:** they own the core `tools/list` budget,
launch-path parity, and the core routing guard and default flip.

## How it was verified

- Rebase onto `main` at `99bf3add` (#812): one `docs/ARCHITECTURE.md`
conflict, resolved by keeping #812's `bundle` wording and this PR's
capabilities sentence. No code change was needed after the rebase.
- On the rebased head `29129b0e`:
- Touched and contract modules: `test_capabilities`,
`test_server_schemas`, `test_skill_manifest`, `test_skill_prompts`,
`test_skill_tool_crossref`, `test_tool_registry`,
`test_tool_schema_titles`, `test_tools_list_contract`,
`test_audit_context_budget`. Result: 187 passed.
- `scripts/audit_context_budget.py`: `context budget: OK`, with
`tools/list` at 11708 of 11900.
- `python -m mypy`: no issues in 76 source files. `ruff check` and `ruff
format --check` are clean.
- Pre-push hook on the rebased head `29129b0e`: full suite `5418 passed,
17 skipped, 1 xfailed`, `Required test coverage of 100% reached`; scoped
mutmut passed.
- Mutation warm-up (`scripts/check_mutation_gate.py --run-mutmut
--max-children 1`): every module had 0 survivors, with kill counts at or
above baseline.
- Behaviour on a clean wheel of `29129b0e`, driven by headless `claude
-p --model haiku` through the MCP tools with `--strict-mcp-config`:
- `core`: discovery reports `core`, the four enabled groups, and
`specialist` and `external` as unavailable, each with `open_world` and
`activate: SUMO_QA_MCP_PROFILE=full`. The groups match the 40 tools the
host received. The response is 1752 characters, about 438 estimated
tokens.
- `full`: discovery reports all six groups enabled and none unavailable.
The groups match the 48 tools the host received. The response is 1780
characters, about 445 estimated tokens.
- Under `core`, the external-skill tool and `sumo_qa_load_skill_context`
(`bundle` and `manifest`) return the activation path. A PDF-conversion
ask routed through `using_sumo_qa` ends at that path, and the agent
tells the user to set `SUMO_QA_MCP_PROFILE=full`.
- Under `full`, the skill body is served and the same ask reaches
`sumo_qa_search_external_skills`.
- With an invalid value the server fails at launch with
`SUMO_QA_MCP_PROFILE='bogus' is not a valid MCP tool profile; expected
one of: core, full`.
- `using_sumo_qa` and `sumo_qa_load_classifications` return the same
output from this build and from a `99bf3add` build.
- Evals, Claude backend, on the rebased head:
  - `skill-suggesting-external-skill.yaml`: 1/1 passed.
- `skill-suggesting-external-skill-conversion.yaml`: 7/8 passed. One
case aborted on a judge-reply parse error even though the judge's own
text said pass (open #796). Re-running that case gave 1/1 passed.

## Review passes

- sumo-qa-reviewing-before-merge, `origin/main...27b5e07`: found a
never-raises contract break in `load_skill_context` on an invalid
profile. Fixed in `49338df5` with a regression test.
- /code-review high, fresh context, `origin/main...49338df`: 2 medium
and 2 low.
- Fixed in `f8c8a55c`: the served text was over the bound because it was
indented, the host-local skill route bypassed the gate, and core listed
the external workflow as runnable.
- Declined: the gate re-reads the env per call while discovery uses the
build-time profile. A stdio server's env does not change and launch
rejects a bad value. The fix would mean threading the profile into the
skill loaders.
- /code-review high, `49338df5..f8c8a55`: 2 medium and 1 low. The
SKILL.md trigger over-fired in the no-tools eval and on hosts that defer
tools, and there was docs drift. Fixed in `f6400129`.
- /code-review high, `f8c8a55c..f640012`: 1 medium and 2 low. The
trigger under-fired on the core host-local route, there was no branch
for an enabled group, and the docs spelled a tool name wrong. Fixed in
`bfa02efc`.
- /code-review high, `f6400129..bfa02ef`: no blocking defects. Evals
were re-run on that SKILL.md and passed, which settles the unverified
eval risk. 2 low (a false stop on a deferred-tool search miss) fixed in
`c8726af5`.
- /code-review high, `bfa02efc..c8726af`: no correctness defects.
Wording nits only, so the loop stopped.
- /code-review high, `c8726af5..e05109c` (the mypy fix that widens
`active_profile` to `str`): no correctness defects. Every caller
validates the profile before the model is built. Declined: a `Profile`
Literal alias threaded through four files, and a direct
`build_capabilities("bogus")` test, because `profile_tool_names` already
rejects unknown values under test.
- sumo-qa-reviewing-before-merge, per file, `origin/main...29129b0`
(the rebased head): all 13 files are SAFE, with low notes only.

## Checklist

- [x] PR title follows [Conventional
Commits](https://www.conventionalcommits.org/)
- [x] Tests pass locally (`pytest`) and lint/type checks are green
(`pre-commit run --all-files`, `python -m mypy`)
- [x] Added or updated tests covering the change
- [x] Updated the relevant docs in this same PR
- [x] No breaking changes. The response fields are additive, the server
tool's text output is compact JSON with the same shape, and the default
`full` profile serves every workflow as before.
sumithr added a commit that referenced this pull request Oct 3, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.72.0](v0.71.1...v0.72.0)
(2026-10-03)


### Features

* **context:** compact the session bootstrap, bundle a routed skill's
context into one call, and audit context budgets in CI
([#812](#812))
([99bf3ad](99bf3ad))
* **server:** report the active profile and opt-in groups in capability
discovery ([#826](#826))
([db73841](db73841))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

---------

Co-authored-by: release-please[bot] <release-please[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Task]: Make session bootstrap conditional, collapse skill-loading turns, and enforce context token budgets

1 participant