async def _add(a, b): return a + b
assert arun(_add(1, 2)) == L(3)
print('arun: sync context ok')arun: sync context ok
Utility functions for finding the repo root, copying the SKILL.md file, running async code from sync contexts, and getting installed package versions.
Parse source, tag parents, return (tree, imp, top_fns, all_fns, imp2mod). Cached — called freely.
Copy bundled SKILL.md to skill directories.
Find the root of the current git repository, or None if not in a repo.
Run an async coroutine from sync code, even if already inside an event loop
arun: sync context ok
arun: nested-loop context ok
BFS over importlib.metadata requires: return seeds + all transitive deps up to depth levels (installed only, no optional extras).
Get a dict of installed package versions using importlib.metadata. passing depth traverse multiple layers of dependencies
['fastprogress', 'litesearch', 'pyan3', 'pyskills', 'watchfiles']
['chonkie', 'fastlite', 'notebook', 'litesearch', 'yake', 'model2vec', 'onnx', 'codesigs', 'liteparse', 'pillow', 'usearch', 'flashrank', 'pdf-oxide', 'onnxruntime', 'pandas', 'tokenizers']
# httpx depends on httpcore; depth=1 should include both httpx + httpcore
d1 = pkg_trans_deps(['httpx'], depth=1)
assert 'httpx' in d1, "seeds must be in result"
assert 'httpcore' in d1, f"depth=1 should include httpcore (direct dep of httpx): {d1}"
# depth=0 returns only seeds
assert list(pkg_trans_deps(['httpx'], depth=0)) == ['httpx'], "depth=0 should return only seeds"
# pyproject seeds → depth=2 expansion
pyp = installed_packages(pyproject=True)
if pyp:
deep = pkg_trans_deps(list(pyp), depth=2)
assert set(pyp).issubset(set(deep)), "seeds must be a subset of result"
assert len(deep) >= len(pyp), "depth=2 should expand beyond pyproject direct deps"
print(f"pkg_trans_deps ok: {len(pyp)} pyproject seeds → {len(deep)} packages at depth=2")
else:
print("pkg_trans_deps ok (no pyproject deps to test)")pkg_trans_deps ok: 5 pyproject seeds → 65 packages at depth=2
{'chonkie': '1.7.0',
'fastlite': '0.2.4',
'notebook': '7.6.1',
'pyskills': '0.0.24',
'anyio': '4.14.2',
'fastprogress': '1.1.6',
'fastcore': '2.1.5',
'watchfiles': '1.2.0',
'litesearch': '0.0.36',
'yake': '0.7.3',
'onnx': '1.22.0',
'codesigs': '0.0.3',
'liteparse': '2.8.1',
'fastaudit': '0.2.6',
'python-fasthtml': '0.14.9',
'pillow': '12.3.0',
'usearch': '2.26.0',
'pyan3': '2.6.2',
'FlashRank': '0.2.10',
'Jinja2': '3.1.6',
'onnxruntime': '1.27.0',
'pdf_oxide': '0.3.75',
'model2vec': '0.8.2',
'pandas': '3.0.5',
'tokenizers': '0.23.1'}
{'chonkie': '1.7.0',
'jupyterlab_server': '2.28.0',
'fastlite': '0.2.4',
'build': '1.5.0',
'fastprogress': '1.1.6',
'watchfiles': '1.2.0',
'litesearch': '0.0.36',
'fastgit': '0.1.0',
'mcp': '1.28.1',
'onnx': '1.22.0',
'tornado': '6.5.7',
'codesigs': '0.0.3',
'PyYAML': '6.0.3',
'liteparse': '2.8.1',
'fastaudit': '0.2.6',
'python-fasthtml': '0.14.9',
'yt-dlp': '2026.7.4',
'nbdev': '3.3.1',
'jupyterlab': '4.6.2',
'execnb': '0.2.9',
'pillow': '12.3.0',
'usearch': '2.26.0',
'notebook_shim': '0.2.4',
'pyan3': '2.6.2',
'pdf_oxide': '0.3.75',
'model2vec': '0.8.2',
'pandas': '3.0.5',
'tokenizers': '0.23.1',
'notebook': '7.6.1',
'diskcache': '5.6.3',
'watchdog': '6.0.0',
'pyskills': '0.0.24',
'setuptools': '83.0.0',
'anyio': '4.14.2',
'fastcore': '2.1.5',
'yake': '0.7.3',
'fossick': '0.0.15',
'asttokens': '3.0.2',
'html2text': '2025.4.15',
'readability-lxml': '0.8.4.1',
'jupyter_server': '2.20.0',
'ghapi': '2.0.3',
'ddgs': '9.14.4',
'astunparse': '1.6.3',
'curl_cffi': '0.15.0',
'FlashRank': '0.2.10',
'Jinja2': '3.1.6',
'scrapling': '0.4.11',
'fastcdp': '0.0.7',
'jupyter_builder': '1.1.1',
'onnxruntime': '1.27.0'}
The main class for managing the code and environment databases, updating package metadata, embedding code snippets, and performing context-aware searches.
Kosha allows you to build a context for code generation based on your repo and environment.
/Users/71293/code/personal/orgs/kosha/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
array([[ 1.0394e-01, 4.9438e-03, -1.2079e-01, 6.4026e-02, 6.0699e-02,
-1.9971e-01, 7.8125e-02, -2.9053e-02, 1.3100e-02, 3.9398e-02,
1.1307e-02, -8.7830e-02, 1.8845e-02, 4.8309e-02, -8.6670e-02,
8.5083e-02, -1.0788e-02, 4.5197e-02, -1.8661e-02, 4.2084e-02,
2.5284e-02, -1.0582e-02, -2.4757e-03, -2.8519e-02, 3.7109e-02,
-2.4109e-02, -5.1514e-02, -3.3875e-02, -3.2867e-02, 1.3110e-01,
-7.6342e-04, -5.1331e-02, -2.2522e-02, -8.9233e-02, -1.1131e-02,
-1.0872e-02, -5.7861e-02, -8.6975e-02, -3.4790e-02, -1.3191e-02,
7.6965e-02, -3.4210e-02, -3.2532e-02, 3.8605e-02, 4.3304e-02,
-9.4360e-02, -4.0497e-02, -5.2490e-02, 2.0142e-02, -1.2463e-01,
-1.7975e-02, 4.4464e-02, 5.1788e-02, 1.8530e-01, 9.9976e-02,
7.2571e-02, 7.6233e-02, 1.0156e-01, 6.5727e-03, 1.8646e-02,
3.8109e-03, 6.3232e-02, 4.9774e-02, 4.4373e-02, 8.8196e-03,
1.0364e-01, 2.7695e-02, -1.1450e-01, 4.9866e-02, -4.1779e-02,
-6.3904e-02, 1.0948e-02, -1.0107e-01, 2.2339e-02, 1.6312e-02,
2.0538e-02, 3.3691e-02, 4.0192e-02, 4.7882e-02, 9.2590e-02,
2.7359e-02, 2.4353e-02, 8.8196e-02, -5.7312e-02, 1.2067e-01,
-1.1833e-02, -7.1533e-02, -1.3000e-01, -2.2934e-02, 2.9678e-02,
1.0124e-02, -5.9174e-02, -8.7891e-02, -1.3328e-04, 7.9468e-02,
7.2815e-02, 8.6853e-02, -2.7161e-02, 4.9713e-02, 6.1798e-02,
7.4829e-02, -2.1210e-02, -6.4087e-02, 3.5706e-02, -1.1444e-01,
-1.5778e-02, -7.2021e-02, -5.9937e-02, -4.8523e-02, -1.0864e-01,
9.4238e-02, 9.2239e-03, -7.1533e-02, -4.8828e-02, -5.2216e-02,
-8.4717e-02, -8.4290e-02, 2.0569e-02, -5.8502e-02, 2.7908e-02,
1.5350e-02, 7.9529e-02, -8.6594e-03, -2.2354e-02, 2.4918e-02,
3.7323e-02, 1.5961e-02, -6.4453e-02, 9.7168e-02, 6.5552e-02,
-1.1163e-01, -1.6711e-01, 1.5190e-02, -3.5400e-02, 1.2323e-01,
7.2693e-02, -3.7964e-02, -3.4821e-02, 1.9360e-01, -4.2725e-02,
-8.1848e-02, 4.2145e-02, -3.4302e-02, 8.3466e-03, 1.8509e-02,
-1.5808e-02, 5.4970e-03, 6.9885e-02, 5.5817e-02, 6.7749e-02,
-2.2705e-02, -3.4332e-02, -6.4758e-02, -1.4481e-02, 8.5327e-02,
8.7738e-04, -4.2328e-02, 7.2327e-02, 4.8309e-02, 9.3018e-02,
-2.1210e-02, -5.6763e-02, 8.1726e-02, 3.0060e-02, 5.3070e-02,
-1.6449e-02, -1.5579e-02, -7.2327e-03, 5.1636e-02, 1.1925e-02,
-8.4167e-02, -3.1921e-02, -7.5745e-02, 1.5356e-01, 1.4246e-01,
-9.9792e-03, 2.1652e-02, 1.0718e-01, 6.3416e-02, 6.4850e-03,
-1.2825e-02, -5.4077e-02, 7.2708e-03, -2.0111e-02, 9.6558e-02,
-4.5868e-02, 9.1187e-02, 4.5441e-02, 2.5040e-02, -1.2030e-01,
-1.0168e-01, -3.1281e-02, -2.1194e-02, -1.2444e-02, -1.3023e-02,
-1.5839e-02, 2.8793e-02, 7.4463e-03, -5.8502e-02, 5.7030e-03,
-1.7670e-02, 6.3171e-02, -6.8787e-02, 2.2537e-02, -7.9727e-03,
-7.9224e-02, 3.8269e-02, -4.7638e-02, -4.1168e-02, -3.0106e-02,
-2.2339e-02, 2.7359e-02, -1.0269e-02, -2.3163e-02, 1.7654e-02,
5.1147e-02, -5.9998e-02, 5.3497e-02, 1.8448e-02, -7.0923e-02,
2.4246e-02, 4.7760e-02, -5.9509e-02, 1.4519e-02, -3.8422e-02,
-9.5139e-03, -5.0201e-03, 8.6899e-03, -7.0801e-02, 3.2135e-02,
-1.4062e-01, -1.4954e-01, 1.9623e-02, -9.6130e-02, -1.3374e-02,
5.7922e-02, 5.0171e-02, 3.8940e-02, 5.6488e-02, 9.1629e-03,
1.3130e-02, -5.2246e-02, -6.3416e-02, 3.0396e-02, 1.9089e-02,
8.6487e-02, -3.2715e-02, -5.2734e-02, 5.3802e-02, 9.0408e-03,
-1.0633e-03, 4.0405e-02, -1.7990e-02, 5.1056e-02, 4.7089e-02,
-8.9905e-02]], dtype=float16)
Return best web URL for pkg from importlib.metadata: Source Code > Repository > Home-page > first Project-URL.
Build pkg_store content dict: content=summary+readme, metadata=json.
{'content': 'The next generation HTTP client.\n<p align="center">\n <a href="https://www.python-httpx.org/"><img width="350" height="208" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/butterfly.png" alt=\'HTTPX\'></a>\n</p>\n\n<p align="center"><strong>HTTPX</strong> <em>- A next-generation HTTP client for Python.</em></p>\n\n<p align="center">\n<a href="https://github.com/encode/httpx/actions">\n <img src="https://github.com/encode/httpx/workflows/Test%20Suite/badge.svg" alt="Test Suite">\n</a>\n<a href="https://pypi.org/project/httpx/">\n <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">\n</a>\n</p>\n\nHTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**.\n\n---\n\nInstall HTTPX using pip:\n\n```shell\n$ pip install httpx\n```\n\nNow, let\'s get started:\n\n```pycon\n>>> import httpx\n>>> r = httpx.get(\'https://www.example.org/\')\n>>> r\n<Response [200 OK]>\n>>> r.status_code\n200\n>>> r.headers[\'content-type\']\n\'text/html; charset=UTF-8\'\n>>> r.text\n\'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...\'\n```\n\nOr, using the command-line client.\n\n```shell\n$ pip install \'httpx[cli]\' # The command line client is an optional dependency.\n```\n\nWhich now allows us to use HTTPX directly from the command-line...\n\n<p align="center">\n <img width="700" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/httpx-help.png" alt=\'httpx --help\'>\n</p>\n\nSending a request...\n\n<p align="center">\n <img width="700" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/httpx-request.png" alt=\'httpx http://httpbin.org/json\'>\n</p>\n\n## Features\n\nHTTPX builds on the well-established usability of `requests`, and gives you:\n\n* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/).\n* An integrated command-line client.\n* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/).\n* Standard synchronous interface,',
'metadata': {'name': 'httpx',
'version': '0.28.1',
'keywords': '',
'requires': 'certifi h2 brotli anyio rich httpcore click brotlicffi socksio zstandard idna pygments',
'summary': 'The next generation HTTP client.',
'url': 'https://github.com/encode/httpx'}}
pkg_url httpx: https://github.com/encode/httpx
pkg_url fastcore: https://github.com/AnswerDotAI/fastcore/
Import root of p: the nearest ancestor directory without init.py.
True if dir is a Python package root: has init.py or a C-extension init.so.*
Set public_api+docstring flags on non-assign chunks and explode ClassDefs into method sub-chunks.
*External top-level imports from a source-string iterable. Reuses cached _parse.*
Embed all documents in the env store, or only those without embeddings if reembed=False.
Reset the databases by dropping all tables.
def update_pkgs(
pkgs:str | list=None, # packages to sync; None syncs all installed env packages
embed:bool=True, # embed chunks after indexing
exts:str='.py,.js,.ts,.jsx,.tsx,.java,.go,.cs,.ruby,.php,.swift,.kt,.kts,.rs,.scala,.lua', # file extensions to include
verbose:bool=True, # print progress
force:bool=False, # reindex even if package version already loaded
**kwargs
):Sync installed packages into the env store; if pkgs is None, syncs all env packages.
Remove a package and its code snippets from the database.
Update package metadata in the packages table.
def update_repo(
dir:Path=None, # directory to index; defaults to repo root
embed:bool=True, # embed chunks after parsing
exts:str='.py,.js,.ts,.jsx,.tsx,.java,.go,.cs,.ruby,.php,.swift,.kt,.kts,.rs,.scala,.lua',
verbose:bool=True, # verbose
force:bool=False, # reindex all files regardless of mtime
skip_file_re:str='^[.]|^(?:setup\\.py|conftest\\.py)$',
skip_folder_re:str='^[.]|^(?:tests?|examples?|docs?|build|dist)$', func:type=Path, path:pathlib.Path | str='.',
recursive:bool=True, maxdepth:int=None, symlinks:bool=True, file_glob:str=None, file_re:str=None,
folder_re:str=None, skip_file_glob:str=None, ret_folders:bool=False, sort:bool=True, types:str | list=None
):Index or update repo code chunks. Pass files= for incremental update (e.g. from watcher).
Embed all documents in the code store, or only those without embeddings if reembed=False.
Intersection of the packages table with packages installed in the environment.
Keep only the latest version of each package in the database.
Keep only the latest version of a package in the database.
mod_name anchor fix: ok — kosha.core
[Path('/Users/71293/code/personal/orgs/kosha/kosha/__init__.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/_modidx.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/cli.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/core.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/graph.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/mcp.py')]
[Path('/Users/71293/code/personal/orgs/kosha/kosha/cli.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/core.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/graph.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/mcp.py')]
[{'content': 'def request(\n method: str,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n trust_env: bool = True,\n) -> Response:\n """\n Sends an HTTP request.\n\n **Parameters:**\n\n * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,\n `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.\n * **url** - URL for the new `Request` object.\n * **params** - *(optional)* Query parameters to include in the URL, as a\n string, dictionary, or sequence of two-tuples.\n * **content** - *(optional)* Binary content to include in the body of the\n request, as bytes or a byte iterator.\n * **data** - *(optional)* Form data to include in the body of the request,\n as a dictionary.\n * **files** - *(optional)* A dictionary of upload files to include in the\n body of the request.\n * **json** - *(optional)* A JSON serializable object to include in the body\n of the request.\n * **headers** - *(optional)* Dictionary of HTTP headers to include in the\n request.\n * **cookies** - *(optional)* Dictionary of Cookie items to include in the\n request.\n * **auth** - *(optional)* An authentication class to use when sending the\n request.\n * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.\n * **timeout** - *(optional)* The timeout configuration to use when sending\n the request.\n * **follow_redirects** - *(optional)* Enables or disables HTTP redirects.\n * **verify** - *(optional)* Either `True` to use an SSL context with the\n default CA bundle, `False` to disable verification, or an instance of\n `ssl.SSLContext` to use a custom context.\n * **trust_env** - *(optional)* Enables or disables usage of environment\n variables for configuration.\n\n **Returns:** `Response`\n\n Usage:\n\n ```\n >>> import httpx\n >>> response = httpx.request(\'GET\', \'https://httpbin.org/get\')\n >>> response\n <Response [200 OK]>\n ```\n """\n with Client(\n cookies=cookies,\n proxy=proxy,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n ) as client:\n return client.request(\n method=method,\n url=url,\n content=content,\n data=data,\n files=files,\n json=json,\n params=params,\n headers=headers,\n auth=auth,\n follow_redirects=follow_redirects,\n )',
'embedding': b'\xf1\xb1i-3*\x17\x9b\x14(\xa7.\xac\xa1\x14\xad\xee\xa8r\xa5Y0\x98\xab\xd8+\x80,q%\x86\xabJ,&+\xdb.\xb7\xa9:(O\xac\x9d\xa3\xba\xa6\xca\xa6\xcb\xb2B+[\xae\xb3(\x01\xac\xb7\xac\x07,i\xae:\xad\xab\xa8/\'\xb4\x9e\xa1,\xb9\xa8,\x1ah\xad*-\xfe+\xc6\xb0T\xaf\x88,#\x1b\x17\xaf\xe3&Q\xa9\xa6\x94\x1b\xac\xe2\xab[)Y\xa1\x03\x149\xad_-\x8a1\xe2\xab\xa5,\xb5+\xdd(\xa2.j\xaa\x07)\x19\xaeT.}\xaaq(\xa7+\x1e(\x82\xa4\x0e2\xb0& \x8dy.\xb5/\r\xb0\x84+\xaf*\x18\xad\xf3 6\xadJ-\xfe\xabH(\xd4,\x05&@)\xa4\x1e\xb5\xa2\x84\x13\x13+\x17\xad\x9b)Y)u+A\x9cQ\xa1\x98\x1e\x94/G\xael,q,\x17\xa3~\xa6\xee\x95G\xa2%\xac\xfd\x9cp\xa6\\\xaf*(\xb5\xa9\x18\xa4\x8a,\n#\x8f\x9e\x83+\x9b\xa3\x0c)o-\x980,\xa7<\xaa\xa9+a\xa9\xb8,S0, \x83(\xc8\xaf\x19\x15\xa3\xa9\x92\x9c\x8a\x9dZ \x00\xab\x83)\x8f\xa4\x7f\xab\x92\xacI\xa3]"\xb9\x17A*I\xa7\x9e\xa5\x11/\x0b\xa8O)\\ R\xac\xf1 \x99\x19\xe8\xa0\xfe&\xb5\'\xf1,@\xac\xa6"}&\xdb%R\xa8\xe2\xa4m\xa2\x93\xa0\x86+\xc3\x9d4+:\xadW+\x0c\xabw*[\xa7i\xach-\x980O\xa9\xea*G\xa3F\xabA\xa5\xbf$k![\'\x91\xb0\x80%\t\xac^\xab[\xac\xf0\x9fU!#\xa1\x1a%\x9b\'\x9e\xac\xfd%h\xa5\xf0%\n\xaf(\'\x91*o\xa8T\x92\x05/|%\xed-\xee\xa5\xb5\xa7}%C\xad]\xa9\xc7\x1c\xf3&\xda\xac9\xa5:*\xf6 \xfa,\x1e\xa0t,\x8a\xa9\xb5\xa43%}\xad\x1f(\x15,\x1d\xacv\xa8\x98\xa8\x81\xa3v\xa1\xa5\x97\xf0$\xd4/#-\xb3\x17\x05,\xa8*\xc0\xa8\xff%\xa9\xa7\x8a&\xa7\xa9S\xac\xb5+\x07\'\xcb)!+l/\xc7*9\xa4\xe8\xa6\x89\x9c',
'pa': '["httpx._api.request","Sends an HTTP request.\\n\\n**Parameters:**\\n\\n* **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,\\n`HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.\\n* **url** - URL for the new `Request` object.\\n* **params** - *(optional)* Query parameters to include in the URL, as a\\nstring, dictionary, or sequence of two-tuples.\\n* **content** - *(optional)* Binary content to include in the body of the\\nrequest, as bytes or a byte iterator.\\n* **data** - *(optional)* Form data to include in the body of the request,\\nas a dictionary.\\n* **files** - *(optional)* A dictionary of upload files to include in the\\nbody of the request.\\n* **json** - *(optional)* A JSON serializable object to include in the body\\nof the request.\\n* **headers** - *(optional)* Dictionary of HTTP headers to include in the\\nrequest.\\n* **cookies** - *(optional)* Dictionary of Cookie items to include in the\\nrequest.\\n* **auth** - *(optional)* An authentication class to use when sending the\\nrequest.\\n* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.\\n* **timeout** - *(optional)* The timeout configuration to use when sending\\nthe request.\\n* **follow_redirects** - *(optional)* Enables or disables HTTP redirects.\\n* **verify** - *(optional)* Either `True` to use an SSL context with the\\ndefault CA bundle, `False` to disable verification, or an instance of\\n`ssl.SSLContext` to use a custom context.\\n* **trust_env** - *(optional)* Enables or disables usage of environment\\nvariables for configuration.\\n\\n**Returns:** `Response`\\n\\nUsage:\\n\\n```\\n>>> import httpx\\n>>> response = httpx.request(\'GET\', \'https://httpbin.org/get\')\\n>>> response\\n<Response [200 OK]>\\n```",true]'}]
[{'name': 'FlashRank',
'version': '0.2.10',
'summary': 'Ultra lite & Super fast SoTA cross-encoder based re-ranking for your search & retrieval pipelines.',
'uploaded_at': '2026-07-23 06:31:37'}]
updating pkg: protobuf ...
package {'name': 'protobuf', 'version': '7.35.1'} already loaded.
updating pkg: fastlite ...
package {'name': 'fastlite', 'version': '0.2.4'} already loaded.
forcing an update to pkg {'name': 'fastlite', 'version': '0.2.4'}
parse files from fastlite: 100%|██████████| 4/4 [00:00<00:00, 252.18it/s]
{'changed': 64, 'same': 0, 'removed': 0}
{}
syncing files [Path('/Users/71293/code/personal/orgs/kosha/kosha/cli.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/core.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/graph.py'), Path('/Users/71293/code/personal/orgs/kosha/kosha/mcp.py')] .....
parse files from /Users/71293/code/personal/orgs/kosha: 100%|██████████| 4/4 [00:00<00:00, 40.30it/s]
{'changed': 154, 'same': 0, 'removed': 0}
synced repo
[{'pa': '["kosha.cli.context","Fan-out semantic search over repo and env, optionally graph-enriched.",true]'},
{'pa': '["kosha.cli.repo_context","Semantic + keyword search over indexed repo code only.",true]'},
{'pa': '["kosha.cli.env_context","Semantic search over indexed env packages only.",true]'},
{'pa': '["kosha.cli.ni","Node info: callers, callees, co_dispatched, pagerank for a single graph node.",true]'},
{'pa': '["kosha.cli.watch","Live incremental re-index on file changes. Blocking — Ctrl-C to stop.",true]'},
{'pa': '["kosha.cli.public_api","List public API entries for a package (respects __all__ + @patch methods).",true]'},
{'pa': '["kosha.cli.api_paths","Shortest call-graph paths from from_pkg public API to to_pkg public API.",true]'},
{'pa': '["kosha.cli.dep_stack","BFS dependency layers from seed packages, ordered by coupling strength.",true]'},
{'pa': '["kosha.cli.top_nodes","Top-k public API nodes for a package ranked by PageRank in the call graph.",true]'},
{'pa': '["kosha.cli.status","Show index freshness: file/pkg/node counts, stale files, and stale packages.",true]'},
{'pa': '["kosha.cli.where_to_add","Find likely insertion points for new code matching description.",true]'},
{'pa': '["kosha.cli.daemon","Persistent kosha kernel. Reads newline-delimited JSON from stdin, writes results to stdout.",true]'},
{'pa': '["kosha.cli.install","Install kosha SKILL.md to .agents/skills/kosha/ and .claude/skills/kosha/.",true]'},
{'pa': '["kosha.cli.main","Entry point for the `kosha` CLI command.",true]'},
{'pa': '["kosha.core.parse","Parse source, tag parents, return (tree, imp, top_fns, all_fns, imp2mod). Cached — called freely.",true]'},
{'pa': '["kosha.core.repo_root","Find the root of the current git repository, or None if not in a repo.",true]'},
{'pa': '["kosha.core.mv_skill_md","Copy bundled SKILL.md to skill directories.",true]'},
{'pa': '["kosha.core.arun","Run an async coroutine from sync code, even if already inside an event loop",true]'},
{'pa': '["kosha.core.pkg_trans_deps","BFS over importlib.metadata requires: return seeds + all transitive deps up to depth levels (installed only, no optional extras).",true]'},
{'pa': '["kosha.core.env_pkg_versions","Get a dict of installed package versions using importlib.metadata.\\npassing depth traverse multiple layers of dependencies",true]'},
{'pa': '["kosha.core.pkg_url","Return best web URL for pkg from importlib.metadata: Source Code > Repository > Home-page > first Project-URL.",true]'},
{'pa': '["kosha.core.pkg_doc","Build pkg_store content dict: content=summary+readme, metadata=json.",true]'},
{'pa': '["kosha.core.has_init","True if dir is a Python package root: has __init__.py or a C-extension __init__*.so.",true]'},
{'pa': '["kosha.core.imp_root","Import root of p: the nearest ancestor directory without __init__.py.",true]'},
{'pa': '["kosha.core.enrich_chunks","Set public_api+docstring flags on non-assign chunks and explode ClassDefs into method sub-chunks.",true]'},
{'pa': '["kosha.core.count_imp","External top-level imports from a source-string iterable. Reuses cached _parse.",true]'},
{'pa': '["kosha.graph.dyn_edges","All dynamic dispatch edges: decorator, connect_body, registration, co_dispatch.",true]'},
{'pa': '["kosha.graph.static_edges","Static call edges via pyan3. Provide either filenames+root or sources dict.",true]'},
{'pa': '["kosha.graph.is_sys_pkg","Return True if pkg is a system-wide package (e.g. in site-packages), False if likely user code.",true]'},
{'pa': '["kosha.graph.CodeGraph.nuke",null,true]'},
{'pa': '["kosha.graph.CodeGraph","Call graph builder and query engine. Uses pyan3 for static analysis and custom AST parsing for dynamic edges.\\nStores everything in a SQLite database.",true]'},
{'pa': '["kosha.graph.CodeGraph.__init__",null,true]'},
{'pa': '["kosha.cli.sync","Sync repo + env packages + call graph into .kosha/ databases.",true]'},
{'pa': '["kosha.cli.nuke","Delete all kosha data and caches.",true]'},
{'pa': '["kosha.core.parseq","Parse key:value filter tokens from a query. A trailing `!` marks a strict/hard filter (e.g. `package!:x`), stored under the `key!` key. Returns (bare_query, filters).",true]'},
{'pa': '["kosha.core.filt2wh","Convert a filter dict (from parse_query) to a SQL WHERE clause for the given store (code or env).",true]'},
{'pa': '["kosha.graph.is_symbol_query","True if the query looks like a bare symbol or namespace-qualified identifier.",true]'},
{'pa': '["kosha.graph.rank_results","Rerank result dicts: query boosts + soft-package boost + semble-style path penalties.",true]'},
{'pa': '["kosha.core.Kosha","Kosha allows you to build a context for code generation based on your repo and environment.",true]'},
{'pa': '["kosha.core.Kosha.__init__",null,true]'},
{'pa': '["kosha.mcp.status","Index freshness: {files, packages, graph_nodes, stale_files, stale_pkgs}. Call this first; if anything is stale, sync before querying (stale looks like missing).",true]'},
{'pa': '["kosha.mcp.sync","Sync repo + env packages + call graph into the .kosha/ index. Incremental — only changed files and new package versions re-index. Returns post-sync status.",true]'},
{'pa': '["kosha.mcp.context","Fan-out semantic + keyword search over repo and installed packages, graph-enriched (callers/callees/pagerank). The right default once a task touches more than one module. compact=True returns slim dicts (mod_name, signature, docstring, lineno) for triage.",true]'},
{'pa': '["kosha.mcp.repo_context","Semantic + keyword search over indexed repo code only.",true]'},
{'pa': '["kosha.mcp.env_context","Semantic search over installed packages only — check whether a dependency already does something before implementing it. Bare package names in the query auto-detect as soft filters.",true]'},
{'pa': '["kosha.mcp.where_to_add","Likely file:line insertion points for new code matching a description, with co_dispatched peers to pattern-match.",true]'},
{'pa': '["kosha.mcp.node_info","Callers, callees, co_dispatched peers, and pagerank for a fully-qualified node, e.g. fastcore.basics.merge. pagerank = blast radius: high means load-bearing, touch carefully.",true]'},
{'pa': '["kosha.mcp.neighbors","Callers + callees of a fully-qualified node up to depth hops.",true]'},
{'pa': '["kosha.mcp.short_path","Shortest call-graph path between two fully-qualified nodes (how do these connect?).",true]'},
{'pa': '["kosha.mcp.public_api","A package\'s real public API — __all__ entries plus @patch-derived methods — with docstrings. Works for a package (\'fastcore\') or submodule (\'fastcore.basics\').",true]'},
{'pa': '["kosha.mcp.top_nodes","Top-k public API nodes for a package ranked by PageRank in the call graph.",true]'},
{'pa': '["kosha.mcp.api_paths","Shortest call-graph paths from one package\'s public API to another\'s — how two packages actually connect.",true]'},
{'pa': '["kosha.mcp.dep_stack","BFS dependency layers from seed packages (default: pyproject deps), ordered by coupling strength.",true]'},
{'pa': '["kosha.mcp.pkg_url","Best repo/docs URL for an installed package — feed it to a web-fetch tool for docs, changelogs, or migration guides.",true]'},
{'pa': '["kosha.mcp.main","Entry point for the `kosha-mcp` console script. stdio by default; pass --http for Streamable HTTP.",true]'}]
[{'content': "def __init__(self, dir: Path = None, install_skill: bool = False, xdg_dir: Path = None, efn=static_code_embedder):\n\t\tself.root, self.xdg, self.efn = Path(dir or repo_root() or '.'), xdg_dir or xdg_data_home(), efn()\n\t\tself.emb_doc, self.emb_query = doc_encoder(self.efn), query_encoder(self.efn)\n\t\tif install_skill: mv_skill_md(dir=self.root, dry_run=False)\n\t\tself.cp, self.ce = self.root.joinpath('.kosha','code.db'), self.xdg.joinpath('kosha','env.db')\n\t\tfor p in (self.cp, self.ce): p.parent.mkdir(parents=True, exist_ok=True)\n\t\tself.codedb, self.envdb, kw = database(self.cp), database(self.ce), dict(hash=True,ann=True)\n\t\tself.code_st,self.env_st = self.codedb.get_store(path=str,**kw),self.envdb.get_store(package=str,**kw)\n\t\tself.pkg_st, self.pkgs = self.envdb.get_store('pkg_store', **kw), self.envdb.t.packages\n\t\tself.env_pd, self.code_rd = self.envdb.t.pkg_deps, self.codedb.t.repo_deps\n\t\tself.pkgs.create(name=str, version=str, summary=str, uploaded_at=float, pk=['name','version'],\n\t\t\t defaults=dict(uploaded_at='CURRENT_TIMESTAMP'), if_not_exists=True)\n\t\tself.env_pd.create(from_pkg=str, to_pkg=str, n_modules=int, if_not_exists=True, pk=['from_pkg','to_pkg'])\n\t\tself.code_rd.create(from_module=str, to_pkg=str, n_files=int, if_not_exists=True, pk=['from_module','to_pkg'])"}]
loading pkgs {'chonkie', 'fastlite', 'build', 'fastprogress', 'watchfiles', 'litesearch', 'fastgit', 'mcp', 'onnx', 'tornado', 'codesigs', 'liteparse', 'fastaudit', 'python-fasthtml', 'yt-dlp', 'nbdev', 'jupyterlab_server', 'jupyterlab', 'execnb', 'pillow', 'usearch', 'pyan3', 'pdf_oxide', 'onnxruntime', 'model2vec', 'pandas', 'tokenizers', 'notebook', 'diskcache', 'watchdog', 'pyskills', 'setuptools', 'anyio', 'fastcore', 'FlashRank', 'jupyter_builder', 'yake', 'fossick', 'asttokens', 'PyYAML', 'html2text', 'jupyter_server', 'ghapi', 'ddgs', 'astunparse', 'curl_cffi', 'scrapling', 'fastcdp', 'notebook_shim', 'readability-lxml', 'Jinja2'} ...
Updating packages: 0%| | 0/51 [00:00<?, ?pkg/s]
updating pkg: chonkie ...
Updating packages: 2%|▏ | 1/51 [00:00<00:12, 4.03pkg/s]
package {'name': 'chonkie', 'version': '1.7.0'} already loaded.
updating pkg: fastlite ...
package {'name': 'fastlite', 'version': '0.2.4'} already loaded.
updating pkg: build ...
parse files from build: 100%|██████████| 13/13 [00:00<00:00, 491.96it/s]
Updating packages: 10%|▉ | 5/51 [00:00<00:05, 8.83pkg/s]
{'changed': 89, 'same': 0, 'removed': 0}
updating pkg: fastprogress ...
package {'name': 'fastprogress', 'version': '1.1.6'} already loaded.
updating pkg: watchfiles ...
package {'name': 'watchfiles', 'version': '1.2.0'} already loaded.
updating pkg: litesearch ...
package {'name': 'litesearch', 'version': '0.0.36'} already loaded.
updating pkg: fastgit ...
parse files from fastgit: 100%|██████████| 3/3 [00:00<00:00, 1039.91it/s]
Updating packages: 14%|█▎ | 7/51 [00:00<00:04, 9.58pkg/s]
{'changed': 12, 'same': 0, 'removed': 0}
updating pkg: mcp ...
parse files from mcp: 0%| | 0/110 [00:00<?, ?it/s]
parse files from mcp: 100%|██████████| 110/110 [00:00<00:00, 350.45it/s][A
Updating packages: 22%|██▏ | 11/51 [00:02<00:12, 3.26pkg/s]
{'changed': 945, 'same': 0, 'removed': 0}
updating pkg: onnx ...
package {'name': 'onnx', 'version': '1.22.0'} already loaded.
updating pkg: tornado ...
package {'name': 'tornado', 'version': '6.5.7'} already loaded.
updating pkg: codesigs ...
package {'name': 'codesigs', 'version': '0.0.3'} already loaded.
updating pkg: liteparse ...
Updating packages: 29%|██▉ | 15/51 [00:03<00:06, 5.73pkg/s]
package {'name': 'liteparse', 'version': '2.8.1'} already loaded.
updating pkg: fastaudit ...
package {'name': 'fastaudit', 'version': '0.2.6'} already loaded.
updating pkg: python-fasthtml ...
package {'name': 'python-fasthtml', 'version': '0.14.9'} already loaded.
updating pkg: yt-dlp ...
package {'name': 'yt-dlp', 'version': '2026.7.4'} already loaded.
updating pkg: nbdev ...
parse files from nbdev: 100%|██████████| 26/26 [00:00<00:00, 263.39it/s]
Updating packages: 33%|███▎ | 17/51 [00:03<00:08, 4.11pkg/s]
{'changed': 348, 'same': 0, 'removed': 0}
updating pkg: jupyterlab_server ...
package {'name': 'jupyterlab_server', 'version': '2.28.0'} already loaded.
updating pkg: jupyterlab ...
parse files from jupyterlab: 0%| | 0/292 [00:00<?, ?it/s]
parse files from jupyterlab: 5%|▌ | 15/292 [00:00<00:02, 105.17it/s]
parse files from jupyterlab: 16%|█▌ | 46/292 [00:00<00:01, 158.41it/s]
parse files from jupyterlab: 21%|██ | 62/292 [00:00<00:01, 153.26it/s]
parse files from jupyterlab: 27%|██▋ | 78/292 [00:00<00:02, 89.87it/s]
parse files from jupyterlab: 31%|███ | 90/292 [00:00<00:02, 91.97it/s]
parse files from jupyterlab: 35%|███▍ | 101/292 [00:01<00:02, 81.93it/s]
parse files from jupyterlab: 38%|███▊ | 111/292 [00:01<00:02, 76.90it/s]
parse files from jupyterlab: 43%|████▎ | 127/292 [00:01<00:04, 37.66it/s]
parse files from jupyterlab: 46%|████▌ | 134/292 [00:02<00:04, 35.51it/s]
parse files from jupyterlab: 52%|█████▏ | 152/292 [00:02<00:02, 52.40it/s]
parse files from jupyterlab: 55%|█████▌ | 161/292 [00:02<00:02, 51.19it/s]
parse files from jupyterlab: 58%|█████▊ | 169/292 [00:02<00:02, 53.86it/s]
parse files from jupyterlab: 61%|██████ | 177/292 [00:02<00:02, 55.17it/s]
parse files from jupyterlab: 63%|██████▎ | 184/292 [00:02<00:01, 55.47it/s]
parse files from jupyterlab: 70%|██████▉ | 204/292 [00:03<00:01, 67.34it/s]
parse files from jupyterlab: 75%|███████▌ | 219/292 [00:03<00:00, 81.55it/s]
parse files from jupyterlab: 78%|███████▊ | 229/292 [00:03<00:00, 72.08it/s]
parse files from jupyterlab: 82%|████████▏ | 238/292 [00:03<00:00, 74.18it/s]
parse files from jupyterlab: 85%|████████▍ | 248/292 [00:03<00:00, 76.30it/s]
parse files from jupyterlab: 89%|████████▊ | 259/292 [00:03<00:00, 83.16it/s]
parse files from jupyterlab: 92%|█████████▏| 270/292 [00:03<00:00, 87.94it/s]
parse files from jupyterlab: 100%|██████████| 292/292 [00:04<00:00, 62.98it/s]
Updating packages: 35%|███▌ | 18/51 [00:23<02:06, 3.82s/pkg]
{'changed': 14773, 'same': 2213, 'removed': 10}
updating pkg: execnb ...
parse files from execnb: 100%|██████████| 3/3 [00:00<00:00, 205.63it/s]
Updating packages: 37%|███▋ | 19/51 [00:23<01:37, 3.06s/pkg]
{'changed': 46, 'same': 0, 'removed': 0}
updating pkg: pillow ...
Updating packages: 41%|████ | 21/51 [00:23<00:58, 1.94s/pkg]
package {'name': 'pillow', 'version': '12.3.0'} already loaded.
updating pkg: usearch ...
package {'name': 'usearch', 'version': '2.26.0'} already loaded.
updating pkg: pyan3 ...
package {'name': 'pyan3', 'version': '2.6.2'} already loaded.
updating pkg: pdf_oxide ...
Updating packages: 45%|████▌ | 23/51 [00:24<00:35, 1.29s/pkg]
package {'name': 'pdf_oxide', 'version': '0.3.75'} already loaded.
updating pkg: onnxruntime ...
Updating packages: 49%|████▉ | 25/51 [00:24<00:22, 1.13pkg/s]
package {'name': 'onnxruntime', 'version': '1.27.0'} already loaded.
updating pkg: model2vec ...
package {'name': 'model2vec', 'version': '0.8.2'} already loaded.
updating pkg: pandas ...
Updating packages: 53%|█████▎ | 27/51 [00:24<00:14, 1.61pkg/s]
package {'name': 'pandas', 'version': '3.0.5'} already loaded.
updating pkg: tokenizers ...
package {'name': 'tokenizers', 'version': '0.23.1'} already loaded.
updating pkg: notebook ...
Updating packages: 57%|█████▋ | 29/51 [00:24<00:09, 2.26pkg/s]
package {'name': 'notebook', 'version': '7.6.1'} already loaded.
updating pkg: diskcache ...
package {'name': 'diskcache', 'version': '5.6.3'} already loaded.
updating pkg: watchdog ...
parse files from watchdog: 100%|██████████| 25/25 [00:00<00:00, 260.91it/s]
Updating packages: 61%|██████ | 31/51 [00:25<00:08, 2.30pkg/s]
{'changed': 372, 'same': 0, 'removed': 0}
updating pkg: pyskills ...
package {'name': 'pyskills', 'version': '0.0.24'} already loaded.
updating pkg: setuptools ...
parse files from setuptools: 0%| | 0/215 [00:00<?, ?it/s]
parse files from setuptools: 19%|█▉ | 41/215 [00:00<00:00, 408.22it/s]
parse files from setuptools: 38%|███▊ | 82/215 [00:00<00:00, 238.27it/s]
parse files from setuptools: 51%|█████ | 110/215 [00:00<00:00, 156.10it/s]
parse files from setuptools: 60%|██████ | 130/215 [00:00<00:00, 165.27it/s]
parse files from setuptools: 79%|███████▊ | 169/215 [00:00<00:00, 219.29it/s]
parse files from setuptools: 100%|██████████| 215/215 [00:01<00:00, 200.46it/s]
Updating packages: 69%|██████▊ | 35/51 [00:30<00:12, 1.27pkg/s]
{'changed': 2993, 'same': 0, 'removed': 0}
updating pkg: anyio ...
package {'name': 'anyio', 'version': '4.14.2'} already loaded.
updating pkg: fastcore ...
package {'name': 'fastcore', 'version': '2.1.5'} already loaded.
updating pkg: FlashRank ...
package {'name': 'FlashRank', 'version': '0.2.10'} already loaded.
updating pkg: jupyter_builder ...
parse files from jupyter_builder: 0%| | 0/17 [00:00<?, ?it/s]
parse files from jupyter_builder: 100%|██████████| 17/17 [00:00<00:00, 28.33it/s]
Updating packages: 73%|███████▎ | 37/51 [00:32<00:11, 1.17pkg/s]
{'changed': 291, 'same': 2882, 'removed': 1}
updating pkg: yake ...
package {'name': 'yake', 'version': '0.7.3'} already loaded.
updating pkg: fossick ...
parse files from fossick: 100%|██████████| 7/7 [00:00<00:00, 103.57it/s]
Updating packages: 75%|███████▍ | 38/51 [00:32<00:09, 1.32pkg/s]
{'changed': 65, 'same': 67, 'removed': 18}
updating pkg: asttokens ...
parse files from asttokens: 100%|██████████| 7/7 [00:00<00:00, 273.86it/s]
Updating packages: 76%|███████▋ | 39/51 [00:33<00:07, 1.53pkg/s]
{'changed': 100, 'same': 0, 'removed': 0}
updating pkg: PyYAML ...
parse files from PyYAML: 100%|██████████| 1/1 [00:00<00:00, 1014.34it/s]
Updating packages: 82%|████████▏ | 42/51 [00:33<00:03, 2.69pkg/s]
{'changed': 0, 'same': 0, 'removed': 0}
updating pkg: html2text ...
package {'name': 'html2text', 'version': '2025.4.15'} already loaded.
updating pkg: jupyter_server ...
package {'name': 'jupyter_server', 'version': '2.20.0'} already loaded.
updating pkg: ghapi ...
package {'name': 'ghapi', 'version': '2.0.3'} already loaded.
updating pkg: ddgs ...
Updating packages: 86%|████████▋ | 44/51 [00:33<00:01, 3.65pkg/s]
package {'name': 'ddgs', 'version': '9.14.4'} already loaded.
updating pkg: astunparse ...
parse files from astunparse: 100%|██████████| 4/4 [00:00<00:00, 257.83it/s]
Updating packages: 94%|█████████▍| 48/51 [00:33<00:00, 5.63pkg/s]
{'changed': 102, 'same': 0, 'removed': 0}
updating pkg: curl_cffi ...
package {'name': 'curl_cffi', 'version': '0.15.0'} already loaded.
updating pkg: scrapling ...
package {'name': 'scrapling', 'version': '0.4.11'} already loaded.
updating pkg: fastcdp ...
package {'name': 'fastcdp', 'version': '0.0.7'} already loaded.
updating pkg: notebook_shim ...
Updating packages: 100%|██████████| 51/51 [00:34<00:00, 1.50pkg/s]
package {'name': 'notebook_shim', 'version': '0.2.4'} already loaded.
updating pkg: readability-lxml ...
package {'name': 'readability-lxml', 'version': '0.8.4.1'} already loaded.
updating pkg: Jinja2 ...
package {'name': 'Jinja2', 'version': '3.1.6'} already loaded.
loading pkgs ['fastcore', 'litesearch', 'fastlite', 'apsw', 'ghapi', 'httpx'] ...
Updating packages: 17%|█▋ | 1/6 [00:00<00:00, 9.54pkg/s]
updating pkg: fastlite ...
package {'name': 'fastlite', 'version': '0.2.4'} already loaded.
updating pkg: apsw ...
package {'name': 'apsw', 'version': '3.53.3.1'} already loaded.
updating pkg: fastcore ...
Updating packages: 100%|██████████| 6/6 [00:00<00:00, 16.00pkg/s]
package {'name': 'fastcore', 'version': '2.1.5'} already loaded.
updating pkg: litesearch ...
package {'name': 'litesearch', 'version': '0.0.36'} already loaded.
updating pkg: httpx ...
package {'name': 'httpx', 'version': '0.28.1'} already loaded.
updating pkg: ghapi ...
package {'name': 'ghapi', 'version': '2.0.3'} already loaded.
parseqstripskey:valuefilter tokens from a query string.filt2whmaps them to SQL WHERE clauses.Kosha.contextfans out searches across detected packages and merges results with chained RRF.
Parse key:value filter tokens from a query. A trailing ! marks a strict/hard filter (e.g. package!:x), stored under the key! key. Returns (bare_query, filters).
('how do I merge dicts',
defaultdict(list, {'package': ['fastcore'], 'path': ['data*']}))
assert parseq('stripe payments package:fasthtml file:routes*') == ('stripe payments', {'package': ['fasthtml'], 'file': ['routes*']})
assert parseq('package:monsterui package:fasthtml create a table') == ('create a table', {'package': ['monsterui', 'fasthtml']})
assert parseq('no filters here') == ('no filters here', {})
assert parseq('type:FunctionDef lang:py') == ('type:FunctionDef lang:py', {'type': ['FunctionDef'], 'lang': ['py']})
assert parseq('package:only')[0] == 'package:only'
# plural forms + comma-separated values
assert parseq('merge dicts packages:fastcore,litesearch') == ('merge dicts', {'package': ['fastcore', 'litesearch']})
assert parseq('search paths:basics,core,data') == ('search', {'path': ['basics', 'core', 'data']})
assert parseq('query packages:fastcore,litesearch paths:basics,core') == ('query', {'package': ['fastcore', 'litesearch'], 'path': ['basics', 'core']})
assert parseq('langs:py,js files:routes*,api*') == ('langs:py,js files:routes*,api*', {'lang': ['py', 'js'], 'file': ['routes*', 'api*']})
print('parse_query: all assertions pass')parse_query: all assertions pass
# Regression: underscore in bare query must not survive into FTS token
assert clean('with_uv') == 'with uv', f'clean() did not strip underscore: {clean("with_uv")!r}'
result = pre('with_uv', wc=False, wide=False, extract_kw=False)
assert result is not None, 'pre() returned None for non-empty query'
assert '_' not in result, f'underscore survived pre(): {result!r}'
print('pre() underscore sanitisation: pass')pre() underscore sanitisation: pass
Convert a filter dict (from parse_query) to a SQL WHERE clause for the given store (code or env).
"(json_extract(metadata, '$.path') like '%data%') AND (package='fastcore')"
assert filt2wh({'file': ['routes*']}, 'code') == "(path LIKE '%routes%')"
assert filt2wh({'path': ['api/*']}, 'code') == "(path LIKE '%api/%')"
assert filt2wh({'lang': ['py']}, 'code') == "(json_extract(metadata, '$.lang') = '.py')"
assert filt2wh({'lang': ['python']}, 'code') == "(json_extract(metadata, '$.lang') = '.py')"
assert filt2wh({'package': ['fasthtml']}, 'env') == "(package='fasthtml')"
assert filt2wh({'type': ['FunctionDef']}, 'code') == "(json_extract(metadata, '$.type') = 'FunctionDef')"
assert filt2wh({}, 'code') is None
assert filt2wh({}, 'env') is None
assert filt2wh({'package': ['fasthtml']}, 'code') is None
print('filters_to_where: all assertions pass')filters_to_where: all assertions pass
Determine which packages to consider for search intersecting packages table and the environment.
def env_context(
q:str, # query to search (supports key:value filters)
emb_q:str=None, # query to embed; defaults to bare query after filter parsing
wide:bool=False, # whether to use wide search
columns:str='content,metadata,package', # comma separated columns string to return from search
where:str=None, # additional where clause to filter search results
ann:bool=True, # HNSW Approximate Nearest Neighbors (ann) search; defaults to True
**kw
)->L: # additional args to pass to db.searchCode search over the env store, with optional key:value filters (e.g. package:fasthtml).
Block and watch repo for changes, re-indexing incrementally. Ctrl-C to stop.
Async watcher: re-indexes changed files on every watchfiles event.
def repo_context(
q:str, # query to search (supports key:value filters)
emb_q:str=None, # query to embed; defaults to bare query after filter parsing
wide:bool=False, # use wide (OR) FTS search
columns:str='content,path,metadata', # columns to return
where:str=None, # extra SQL filter
ann:bool=True, # HNSW Approximate Nearest Neighbors (ann) search; defaults to True
**kw
)->L: # additional args to pass to db.searchSemantic + keyword search through indexed repo code.
FTS5+vector search over package descriptions in pkg_store.
'def parse(code=None, p=None):\n "Parse source, tag parents, return (tree, imp, top_fns, all_fns, imp2mod). Cached — called freely."\n if not code and not p: return None, {}, set(), set(), {}\n try: tree = ast.parse(Path(p).read_text(errors=\'replace\') if not code else code)\n except SyntaxError: return None, {}, set(), set(), {}\n [setattr(c,\'parent\',n) for n in ast.walk(tree) for c in ast.iter_child_nodes(n)]\n is_top = lambda n: isinstance(getattr(n,\'parent\',None), ast.Module)\n is_fn = lambda n: isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef))\n is_nm = lambda n: isinstance(n, ast.Name)\n imp, imp2mod, top = {}, {}, set()\n # Single pass: imports + top-level fn names\n for n in ast.walk(tree):\n if is_fn(n) and is_top(n): top.add(n.name)\n elif isinstance(n, ast.Import):\n for a in n.names: imp[a.asname or a.name.split(\'.\')[0]] = a.name.split(\'.\')[0]\n elif isinstance(n, ast.ImportFrom):\n pkg = (n.module or \'\').split(\'.\')[0]\n for a in n.names:\n if a.name != \'*\':\n\t imp[a.asname or a.name] = pkg\n\t if n.module: imp2mod[a.asname or a.name] = f\'{n.module}.{a.name}\'\n else: imp.setdefault(f\'*{pkg}\', pkg)\n ca = {nm for n in tree.body if isinstance(n,ast.Assign) and isinstance(n.value,ast.Call)\n for t in n.targets\n for nm in ([t.id] if is_nm(t) else [e.id for e in t.elts if is_nm(e)] if isinstance(t,ast.Tuple) else [])}\n return tree, imp, top, top | ca, imp2mod'
{'content': 'def create_mcp_http_client(\n headers: dict[str, str] | None = None,\n timeout: httpx.Timeout | None = None,\n auth: httpx.Auth | None = None,\n) -> httpx.AsyncClient:\n """Create a standardized httpx AsyncClient with MCP defaults.\n\n This function provides common defaults used throughout the MCP codebase:\n - follow_redirects=True (always enabled)\n - Default timeout of 30 seconds if not specified\n\n Args:\n headers: Optional headers to include with all requests.\n timeout: Request timeout as httpx.Timeout object.\n Defaults to 30 seconds if not specified.\n auth: Optional authentication handler.\n\n Returns:\n Configured httpx.AsyncClient instance with MCP defaults.\n\n Note:\n The returned AsyncClient must be used as a context manager to ensure\n proper cleanup of connections.\n\n Examples:\n # Basic usage with MCP defaults\n async with create_mcp_http_client() as client:\n response = await client.get("https://api.example.com")\n\n # With custom headers\n headers = {"Authorization": "Bearer token"}\n async with create_mcp_http_client(headers) as client:\n response = await client.get("/endpoint")\n\n # With both custom headers and timeout\n timeout = httpx.Timeout(60.0, read=300.0)\n async with create_mcp_http_client(headers, timeout) as client:\n response = await client.get("/long-request")\n\n # With authentication\n from httpx import BasicAuth\n auth = BasicAuth(username="user", password="pass")\n async with create_mcp_http_client(headers, timeout, auth) as client:\n response = await client.get("/protected-endpoint")\n """\n # Set MCP defaults\n kwargs: dict[str, Any] = {\n "follow_redirects": True,\n }\n\n # Handle timeout\n if timeout is None:\n kwargs["timeout"] = httpx.Timeout(MCP_DEFAULT_TIMEOUT, read=MCP_DEFAULT_SSE_READ_TIMEOUT)\n else:\n kwargs["timeout"] = timeout\n\n # Handle headers\n if headers is not None:\n kwargs["headers"] = headers\n\n # Handle authentication\n if auth is not None: # pragma: no cover\n kwargs["auth"] = auth\n\n return httpx.AsyncClient(**kwargs)',
'metadata': {'path': '/Users/71293/code/personal/orgs/kosha/.venv/lib/python3.13/site-packages/mcp/shared/_httpx_utils.py',
'uploaded_at': 1782721849.5891402,
'name': 'create_mcp_http_client',
'lang': '.py',
'type': 'FunctionDef',
'lineno': 23,
'end_lineno': 87,
'mod_name': 'mcp.shared._httpx_utils.create_mcp_http_client',
'package': 'mcp',
'version': '1.28.1',
'docstring': 'Create a standardized httpx AsyncClient with MCP defaults.\n\nThis function provides common defaults used throughout the MCP codebase:\n- follow_redirects=True (always enabled)\n- Default timeout of 30 seconds if not specified\n\nArgs:\n headers: Optional headers to include with all requests.\n timeout: Request timeout as httpx.Timeout object.\n Defaults to 30 seconds if not specified.\n auth: Optional authentication handler.\n\nReturns:\n Configured httpx.AsyncClient instance with MCP defaults.\n\nNote:\n The returned AsyncClient must be used as a context manager to ensure\n proper cleanup of connections.\n\nExamples:\n # Basic usage with MCP defaults\n async with create_mcp_http_client() as client:\n response = await client.get("https://api.example.com")\n\n # With custom headers\n headers = {"Authorization": "Bearer token"}\n async with create_mcp_http_client(headers) as client:\n response = await client.get("/endpoint")\n\n # With both custom headers and timeout\n timeout = httpx.Timeout(60.0, read=300.0)\n async with create_mcp_http_client(headers, timeout) as client:\n response = await client.get("/long-request")\n\n # With authentication\n from httpx import BasicAuth\n auth = BasicAuth(username="user", password="pass")\n async with create_mcp_http_client(headers, timeout, auth) as client:\n response = await client.get("/protected-endpoint")',
'public_api': True},
'package': 'mcp',
'rowid': 95730,
'_dist': np.float32(0.5820982),
'_rrf_score': 0.016666666666666666}