Skip to main content

API diagnostics and project paths

Record tool usage, resolve project inputs and bound diagnostic output.
from nbskill.fixtures import demo_path, write_demo_file, write_demo_notebook
from io import StringIO
from tempfile import TemporaryDirectory
from contextlib import redirect_stderr
from fastcore.test import test_fail

Python API contracts and diagnostics

The public functions in later notebooks are direct Python APIs. These helpers keep return values and validation errors predictable while recording completed calls and failures in a small local statistics file.

api_return preserves the Python value and its identity for direct callers.


source

api_return

def api_return(
    value:NoneType=None
):

Return a Python API value unchanged.

payload = dict(answer=42)
returned = api_return(payload)
assert returned is payload
returned

Direct API calls return Python values. api_error raises ValueError for invalid inputs; callers retain the exception rather than receiving an error-shaped success value.

api_error raises a validation error so callers retain its original message.


source

api_error

def api_error(
    msg
):

Raise a Python API validation error.

try: api_error("a notebook path is required")
except ValueError as error: validation_message = str(error)
assert validation_message == "a notebook path is required"
validation_message

source

failure_map_path

def failure_map_path():

Resolve the usage-statistics path from the environment or home directory.

failure_map_path honors NBSKILL_FAILURE_MAP for isolated runs. empty_failure_map creates a fresh versioned record with no calls or events; it does not create a file.

Each call to empty_failure_map starts an independent event history.


source

empty_failure_map

def empty_failure_map():

Return a fresh empty usage-statistics record.

first_history = empty_failure_map()
first_history["events"].append(dict(operation="context"))
assert empty_failure_map()["events"] == []

source

load_failure_map

def load_failure_map(
    path, strict:bool=False
):

Read saved usage, optionally rejecting corrupt or unreadable statistics.

load_failure_map supplies empty counts for a missing file. Writers use strict=True to reject corrupt JSON and preserve the original file for diagnosis. The default read mode still tolerates missing or unreadable statistics.

empty_usage = load_failure_map(demo_path("missing_usage.json"), strict=True)
empty_usage

Usage counters and failures are committed together. The writer replaces the statistics file atomically after the outermost tracked call; readers never need to merge partially written records.

track_call restores recording at the direct Python API boundary after the old command wrappers were removed. The eight Pyskill operations and style_report use it in their owning modules, so direct imports and Pyskill imports count the same calls. NBSKILL_FAILURE_MAP selects a different statistics file; the default remains ~/.nbskill-errors.json.

Each completed or interrupted outermost call increments counts.usage and updates last_call with its tool name, working directory and completion time. Usage and failure counts are committed together. Nested tool calls in the same process are excluded. Notebook execution children count their own calls. Ordinary exceptions and results with ok=False also increment counts.failures; the original exception or result reaches the caller unchanged. Cancellation releases the call scope. Function signatures, docments and return identities are preserved.

The existing path locks serialize threads and processes. A temporary file and atomic replacement keep readers from seeing partial JSON. Corrupt statistics are preserved for diagnosis, and persistence failures produce a logging warning while the tool continues. Failure details are capped at 1000 characters and the most recent 100 events are kept. Counts remain cumulative until an explicit reset. Resetting also discards the current call’s pending record.


source

track_call

def track_call(
    func
):

Record an outermost synchronous tool call without changing its Python contract.

A tracked calculation returns its value while writing one usage count. The temporary destination keeps lesson calls out of the global statistics.

with tempfile.TemporaryDirectory() as usage_dir, patch_env.dict(os.environ, NBSKILL_FAILURE_MAP=str(Path(usage_dir)/"usage.json")):
    tracked_add = track_call(lambda left, right: left + right)
    added_cells = tracked_add(2, 3)
    example_usage = load_failure_map(failure_map_path())
added_cells, example_usage["counts"]

reset_usage clears the file under the writer lock and discards the active call’s pending record. This preserves style_check(delete_after_output=True) without recreating the file after printing.


source

reset_usage

def reset_usage(
    path:NoneType=None
):

Clear selected statistics and discard the current call’s pending record.

with tempfile.TemporaryDirectory() as usage_dir, patch_env.dict(os.environ, NBSKILL_FAILURE_MAP=str(Path(usage_dir)/"usage.json")):
    failure_map_path().write_text(json.dumps(empty_failure_map()))
    reset_usage()
    cleared_usage = not failure_map_path().exists()
cleared_usage

Git discovery is optional. git_run returns empty text for a failed command, and git_root returns None when no candidate belongs to a repository. Source inspection can still work outside Git.

Repository discovery only reads .git markers, including the files used by worktrees and submodules. Launching git rev-parse here made ordinary notebook reads require subprocess permission in the sandbox.

git_run returns command output for repository inspection.


source

git_run

def git_run(
    root, *args
):

Run a git command from root and return stdout, or empty text on failure.

inside_repository = git_run(Path.cwd(), "rev-parse", "--is-inside-work-tree").strip()
assert inside_repository == "true"
inside_repository

git_root resolves the repository containing the current working directory.


source

git_root

def git_root(
    path:str='.'
):

Return the containing git repository root, if one exists.

repository = git_root(Path.cwd())
assert repository is not None and (repository/".git").exists()
repository.name

load_nbskill_config reads trusted project Python from .nbskill.py and overlays its public names on the defaults. This configuration file executes with the agent process permissions.

load_nbskill_config merges project settings over the default notebook exclusions.


source

load_nbskill_config

def load_nbskill_config(
    path:str='.'
):

Load .nbskill.py config from project root, merged over defaults.

configuration = load_nbskill_config(".")
assert ".ipynb_checkpoints" in configuration.exclude_dirs
configuration.exclude_dirs

Metadata migration removes obsolete stored analysis fields because source properties are recomputed from current code.


source

notebook_paths

def notebook_paths(
    path:str='nbs'
):

Return visible notebook paths for a file, directory, glob, or nbdev project path.

notebook_paths keeps an explicitly selected notebook reachable inside a hidden workspace folder such as .codex. It checks the filename in this case; directory discovery still filters hidden paths. A temporary hidden folder demonstrates the explicit-file contract.

visible_notebooks = notebook_paths("nbs/00_foundation.ipynb")
visible_notebooks

Python analysis uses source_without_directives to remove notebook control lines.


source

source_without_directives

def source_without_directives(
    source
):

Return source with nbdev cell directives removed.

plain_source = source_without_directives("#| export\nanswer = 42")
assert plain_source == "answer = 42"
plain_source

source_without_directives removes notebook control lines before Python analysis. source_hash fingerprints the supplied text exactly; directive removal is an explicit caller decision.

source_hash compares source content without storing another editable copy.


source

source_hash

def source_hash(
    source, length:int=12
):

Return a SHA-256 source hash, shortened unless length is None.

assert source_hash("answer = 42") == source_hash("answer = 42")
assert source_hash("answer = 42") != source_hash("answer = 43")

file_line_count counts physical lines in an existing source file.


source

file_line_count

def file_line_count(
    path
):

Return the number of text lines in path, or zero when it cannot be read.

with write_demo_file("two_lines.py", "first = 1\nsecond = 2\n") as two_lines: assert file_line_count(two_lines) == 2

file_line_count treats an unreadable file as unavailable size evidence. cap_text bounds display text and, when requested, reports omitted characters without discarding the underlying structured result.

cap_text bounds the rendered text while recording whether content was omitted.


source

cap_text

def cap_text(
    text, limit:int=2000, max_output_chars:ellipsis=Ellipsis
):

Bound the complete text; an explicit max_output_chars returns metadata, with None meaning unlimited.

bounded_example = cap_text("a long result", max_output_chars=8)
assert len(bounded_example["text"]) <= 8 and bounded_example["truncated"]
bounded_example

NotebookResult retains dictionary access while limiting what an interpreter displays. The complete result remains available for subsequent operations.


source

NotebookResult

def NotebookResult(
    *args, **kwargs
):

Dictionary result with one compact interpreter display.


source

notebook_result

def notebook_result(
    data, max_display_chars:int=6000
):

Bound the interpreter display while retaining the complete structured text.

notebook_result bounds the interpreter display while retaining the complete structured result for callers.

result_example = notebook_result(dict(text="complete evidence " * 50), max_display_chars=80)
assert len(repr(result_example)) <= 80
assert len(result_example["text"]) > 80
repr(result_example)

Display limits include the truncation marker itself. Structured results retain the full text, and an explicit None budget keeps it unabridged.