Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/apps-module-migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,10 @@
"consumers": [
"src/inferrsi/apps/cli/__init__.py",
"src/inferrsi/apps/integrations/cannbot/round_knowledge.py",
"src/inferrsi/apps/integrations/external_channels.py",
"tests/check_installed.py",
"tests/test_apps_module_migrations.py"
"tests/test_apps_module_migrations.py",
"tests/test_knowledge_channels.py"
],
"package": true,
"module_exports": {
Expand Down Expand Up @@ -385,6 +387,7 @@
"src/inferrsi/apps/cli/arguments.py",
"src/inferrsi/apps/integrations/cannbot/__init__.py",
"src/inferrsi/apps/integrations/cannbot/round_knowledge.py",
"src/inferrsi/apps/integrations/external_channels.py",
"tests/check_installed.py",
"tests/test_apps_module_migrations.py",
"tests/test_cannbot_boundaries.py",
Expand Down
14 changes: 14 additions & 0 deletions docs/external-channels.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ Revoke it with `inferrsi cannbot disable`. The grant lives at
project's `.git` identity, so copying it to another clone does not carry the
approval along.

## Using the shared registry

Find and managed round retrieval use the same Apps registry for external
sources. Packaged knowledge is searched independently. Find uses the current
Git project and calls sources eligible for the task backend. An explicit
`--backend` takes precedence over a grant default. If available sources declare
different defaults, Find requires an explicit backend before calling any source.
`--no-external` runs Find without using the registry.

CANNBot serves Ascend and uses its native indexed query and exact-page read
through the approved checkout's worker. Managed rounds select that source from
the registry for the Git project frozen at session start, and check the grant
again for both search and read. See [managed round retrieval](optimization-benchmarks.md#include-cannbot-in-the-round).

## Using it

Once approved, the default path searches automatically because the grant declares
Expand Down
15 changes: 12 additions & 3 deletions docs/optimization-benchmarks.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,21 @@ and access to material outside this session require their own observation.

### Include CANNBot in the round

Run from the project with an [approved CANNBot grant](external-channels.md).
Add `--cannbot-platform <platform>` at `benchmarks session start` or AB/BA
`campaign start` to freeze the external source and an explicit Ascend
platform. Omit the option for a local-only session. The paired
`campaign start` to freeze the external source and an explicit Ascend platform.
Start a benchmark session from the Git project with the
[CANNBot grant](external-channels.md). An AB/BA campaign uses the Git project of
its `--repo` target. The session records the checkout identity, including the
Git administration directory of linked worktrees. Each search and read checks
that identity and the current grant, even when invoked from a different
working directory. Omit the option for a local-only session. The paired
`benchmarks compare` conditions keep their existing behavior.

A session without a verifiable project binding returns `not_enabled` for
CANNBot and still delivers local knowledge. Start a new benchmark session from
the approved Git project if your session has no binding. Use the original
frozen InferRSI release to resume sessions created with an earlier runtime.

`knowledge` queries both sources for the next round. It returns the local
context and a separate `external` result, with its own ranking, channel state
and `reference.path`. A CANNBot timeout still returns the local result. The
Expand Down
47 changes: 22 additions & 25 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,29 @@ def _print(value: object) -> None:
print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False))


def _round_provider(plan):
from ..integrations.external_channels import round_provider

return round_provider(plan)


def _optimization_session(args, *, task_source=None, report_metadata=None):
from ...harness.optimization_session import session_command

settings = None
provider = None
external_project = None
if getattr(args, "cannbot_platform", None):
settings = {"channel": "cannbot-knowledge", "backend": "ascend",
"platform": args.cannbot_platform}
if args.session_action in ("knowledge", "knowledge-read"):
from ..integrations.cannbot.round_knowledge import CannbotRoundKnowledge
from ..integrations.cannbot import CHANNEL_NAME
from ..integrations.external_channels import freeze_project

provider = CannbotRoundKnowledge()
settings = {"channel": CHANNEL_NAME, "backend": "ascend",
"platform": args.cannbot_platform}
external_project = freeze_project(args.repo if args.project_task else None)
return session_command(
args, task_source=task_source, retain_context=capture_context,
knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None,
external_knowledge=settings, external_provider=provider,
external_knowledge=settings, external_project=external_project,
external_provider_for=_round_provider,
report_metadata=report_metadata,
)

Expand Down Expand Up @@ -158,24 +165,9 @@ def _clip(value: str, limit: int = 160) -> str:


def _channels():
"""Build the external channel registry from whatever this checkout approved.

The grant is the second source of a declared backend, after an explicit
`--backend`. Reading it here is what makes `cannbot enable --backend ascend`
mean something: without it, an approved Ascend source would only ever run
when the caller repeated the flag, and the approval would silently do
nothing on the default path.

Constructing a channel reads its grant, which is a cheap local file read.
An unreadable or absent grant is not fatal: the channel still exists and
reports `not_enabled` with a fix when asked, which is more useful than
dropping it from the list.
"""
from ...knowledge.channels import ChannelRegistry
from ..integrations.cannbot import CannbotChannel
from ..integrations.external_channels import external_channels

channel = CannbotChannel()
return ChannelRegistry([channel], declared_backend=channel.declared_backend)
return external_channels()


def _print_external(result: dict) -> None:
Expand Down Expand Up @@ -443,7 +435,12 @@ def main(argv: list[str] | None = None) -> int:
args.query, platform=args.platform, limit=args.limit,
)
else:
result = cannbot.project.read(
channel = _channels().named(cannbot.CHANNEL_NAME)
if channel is None:
raise cannbot.project.ChannelFailure(
"The CANNBot knowledge channel is unavailable", state="not_enabled",
)
result = channel.read_page(
args.locator, page=args.page, expected_sha256=args.sha256,
expected_revision=args.revision,
)
Expand Down
27 changes: 20 additions & 7 deletions src/inferrsi/apps/integrations/cannbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,22 @@
__all__ = ["CannbotChannel", "project"]

SCORE_SCALE = "cannbot/knowledge-search.v5"
CHANNEL_NAME = "cannbot-knowledge"


class CannbotChannel:
"""Approved cannbot-knowledge checkout, queried through its own interpreter."""

def __init__(self, *, root: Path | None = None, timeout: float = 8.0):
def __init__(self, *, root: Path | None = None, timeout: float = 8.0,
expected_checkout: dict | None = None):
from . import project

self._project = project
self.root = root
self.timeout = timeout
self._binding = (
{"expected_checkout": expected_checkout} if expected_checkout is not None else {}
)
# `hint` records why this channel cannot answer before any search runs.
# Keeping it lets `find` report "not enabled" instead of telling the
# caller to declare a backend for a source that is not approved yet.
Expand All @@ -41,11 +46,13 @@ def __init__(self, *, root: Path | None = None, timeout: float = 8.0):
self.hint = ChannelStatus("rejected", detail=str(exc))
self.backend = "ascend"
self.declared_backend = grant.get("backend")
self.name = "cannbot-knowledge"
self.name = CHANNEL_NAME

def describe(self, *, request: ChannelRequest) -> ChannelStatus:
try:
info = self._project.describe(self.root, timeout=request.remaining(), request=request)
info = self._project.describe(
self.root, timeout=request.remaining(), request=request, **self._binding,
)
except self._project.ChannelFailure as exc:
return ChannelStatus(exc.state, detail=str(exc), fix=exc.fix)
state = info.get("state", "rejected")
Expand All @@ -63,7 +70,7 @@ def search(
try:
payload = self._project.search(
query, platform=platform, limit=limit, root=self.root,
timeout=request.remaining(), request=request,
timeout=request.remaining(), request=request, **self._binding,
)
except self._project.ChannelFailure as exc:
return ChannelResult(
Expand Down Expand Up @@ -99,9 +106,15 @@ def search(

def read(self, locator: str, *, expected_sha256: str | None = None,
expected_revision: str | None = None) -> str:
payload = self._project.read(
locator, expected_sha256=expected_sha256, root=self.root,
expected_revision=expected_revision,
payload = self.read_page(
locator, expected_sha256=expected_sha256, expected_revision=expected_revision,
timeout=max(self.timeout, 15.0),
)
return str(payload.get("text") or "")

def read_page(self, locator: str, *, page: int = 1, expected_sha256: str | None = None,
expected_revision: str | None = None, timeout: float = 15.0) -> dict:
return self._project.read(
locator, page=page, expected_sha256=expected_sha256,
expected_revision=expected_revision, root=self.root, timeout=timeout, **self._binding,
)
35 changes: 24 additions & 11 deletions src/inferrsi/apps/integrations/cannbot/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import tempfile
from pathlib import Path

from ..project_binding import matches_checkout
from .read_worker import OutputLimitError, _finite, capture

_SCHEMA = "inferrsi-cannbot-project/1"
Expand All @@ -37,9 +38,9 @@ def __init__(self, message, *, state="rejected", fix="", exit_code=None):
self.exit_code = exit_code


def project_root() -> Path:
cwd = Path.cwd().resolve()
for folder in (cwd, *cwd.parents):
def project_root(start: Path | None = None) -> Path:
directory = (Path.cwd() if start is None else start).resolve()
for folder in (directory, *directory.parents):
if (folder / ".git").exists():
return folder
raise ChannelFailure(
Expand All @@ -53,7 +54,7 @@ def _grant_path(root: Path) -> Path:
return Path.home() / ".config" / "inferrsi" / "cannbot-projects" / (project_id + ".json")


def _checkout_identity(root: Path) -> dict:
def checkout_identity(root: Path) -> dict:
marker = root / ".git"
info = marker.stat()
identity = {"device": info.st_dev, "inode": info.st_ino}
Expand Down Expand Up @@ -101,7 +102,7 @@ def load_grant(root: Path | None = None) -> dict:
if len(raw) > MAX_BYTES:
raise ValueError("The cannbot project grant exceeds 2 MiB")
grant = _parse(raw)
checkout = _checkout_identity(root)
checkout = checkout_identity(root)
except FileNotFoundError:
raise ChannelFailure(
"cannbot knowledge is not enabled for this project", state="not_enabled",
Expand All @@ -125,6 +126,15 @@ def load_grant(root: Path | None = None) -> dict:
return grant


def _checked_grant(root: Path | None, expected_checkout: dict | None) -> dict:
grant = load_grant(root)
if expected_checkout is not None and (
root is None or not matches_checkout(root, expected_checkout)
):
raise ChannelFailure("The checkout no longer matches the external knowledge session")
return grant


def _run(grant: dict, action: str, arguments: dict, *, timeout: float, request=None) -> dict:
environment = os.environ.copy()
for key in ("CANNBOT_MCP_TOKENS", "CANNBOT_KNOWLEDGE_PLATFORM"):
Expand Down Expand Up @@ -165,9 +175,10 @@ def _run(grant: dict, action: str, arguments: dict, *, timeout: float, request=N
return payload


def describe(root: Path | None = None, *, timeout: float = 15.0, request=None) -> dict:
def describe(root: Path | None = None, *, timeout: float = 15.0, request=None,
expected_checkout: dict | None = None) -> dict:
try:
grant = load_grant(root)
grant = _checked_grant(root, expected_checkout)
except ChannelFailure as exc:
return {"state": exc.state, "detail": str(exc), "fix": exc.fix}
try:
Expand All @@ -186,12 +197,13 @@ def describe(root: Path | None = None, *, timeout: float = 15.0, request=None) -
def search(
query: str, *, platform: str | None = None, limit: int = 100,
root: Path | None = None, timeout: float = 8.0, request=None,
expected_checkout: dict | None = None,
) -> dict:
if not isinstance(query, str) or not query.strip():
raise ChannelFailure("cannbot search needs a non-empty query")
if type(limit) is not int or not 1 <= limit <= 200:
raise ChannelFailure("cannbot limit must be an integer from 1 through 200")
grant = load_grant(root)
grant = _checked_grant(root, expected_checkout)
platforms = list(grant.get("platforms", []))
if platform is None:
if not platforms:
Expand All @@ -209,7 +221,8 @@ def search(

def read(locator: str, *, page: int = 1, expected_sha256: str | None = None,
expected_revision: str | None = None,
root: Path | None = None, timeout: float = 15.0) -> dict:
root: Path | None = None, timeout: float = 15.0,
expected_checkout: dict | None = None) -> dict:
if not isinstance(locator, str) or not locator.strip():
raise ChannelFailure("cannbot read needs a locator from a search result")
if type(page) is not int or page < 1:
Expand All @@ -228,7 +241,7 @@ def read(locator: str, *, page: int = 1, expected_sha256: str | None = None,
arguments["expected_sha256"] = expected_sha256
if expected_revision:
arguments["expected_revision"] = expected_revision
return _run(load_grant(root), "read", arguments, timeout=timeout)
return _run(_checked_grant(root, expected_checkout), "read", arguments, timeout=timeout)


def enable(*, upstream: Path, python: Path, backend: str = "ascend",
Expand Down Expand Up @@ -256,7 +269,7 @@ def enable(*, upstream: Path, python: Path, backend: str = "ascend",
raise ValueError("--platform takes one of " + ", ".join(PLATFORMS))
grant = {
"schema": _SCHEMA, "project_root": str(root),
"checkout_identity": _checkout_identity(root),
"checkout_identity": checkout_identity(root),
"upstream": str(upstream.resolve()),
# Record the interpreter path as given. Resolving the symlink in a venv
# bin/ lands on the base interpreter, which loses every installed
Expand Down
26 changes: 19 additions & 7 deletions src/inferrsi/apps/integrations/cannbot/round_knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@
import re

from ....harness.records.evidence import relative_location
from ....knowledge.channels import CHANNEL_STATES, TIMEOUT, ChannelRegistry, search_channels
from . import SCORE_SCALE, CannbotChannel, project
from ....knowledge.channels import (
CHANNEL_STATES,
NOT_ENABLED,
TIMEOUT,
ChannelRegistry,
search_channels,
)
from . import CHANNEL_NAME, SCORE_SCALE, project
from .read_worker import _WORKER_CLEANUP_SECONDS

SCORE_SCALES = (SCORE_SCALE, "knowledge-search.v5")
Expand All @@ -30,7 +36,7 @@ def _card_identity(record):
def search_metadata(record):
"""Validate the scalar metadata published from a retained search."""
if (
not isinstance(record, dict) or record.get("channel") != "cannbot-knowledge"
not isinstance(record, dict) or record.get("channel") != CHANNEL_NAME
or record.get("backend") != "ascend" or record.get("platform") not in project.PLATFORMS
or record.get("state") not in CHANNEL_STATES or not isinstance(record.get("items"), list)
):
Expand Down Expand Up @@ -60,22 +66,26 @@ def search_metadata(record):
def read_metadata(record):
"""Validate the identity and page of a retained read receipt."""
card = _card_identity(record)
if (card is None or record.get("channel") != "cannbot-knowledge"
if (card is None or record.get("channel") != CHANNEL_NAME
or not _hex(record.get("revision"), 40)
or type(record.get("page")) is not int or record["page"] < 1):
return None
return {**card, **{key: record[key] for key in ("channel", "revision", "page")}}


class CannbotRoundKnowledge:
def __init__(self, channel):
self.channel = channel

def search(self, query, *, settings, limit, timeout):
# Process cleanup runs after a timeout and must fit in the search budget too.
timeout = min(8.0, timeout - _WORKER_CLEANUP_SECONDS)
if timeout <= 0:
return {"state": TIMEOUT, "items": [], "count": 0}
channel = CannbotChannel()
if self.channel is None:
return {"state": NOT_ENABLED, "items": [], "count": 0}
results = search_channels(
ChannelRegistry([channel]), query, backend=settings["backend"],
ChannelRegistry([self.channel]), query, backend=settings["backend"],
platform=settings["platform"], limit=limit, timeout=timeout,
)
result, = results
Expand All @@ -93,8 +103,10 @@ def read(self, locator, *, revision, card_sha256, page, timeout):
timeout = min(15.0, timeout - _WORKER_CLEANUP_SECONDS)
if timeout <= 0:
raise ValueError("CANNBot read has insufficient time before the final reserve")
if self.channel is None:
raise ValueError("CANNBot read failed (not_enabled). Check the grant or search again")
try:
result = project.read(
result = self.channel.read_page(
locator, expected_revision=revision, expected_sha256=card_sha256, page=page,
timeout=timeout,
)
Expand Down
Loading
Loading