# API diagnostics and project paths


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

``` python
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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#api_return)
preserves the Python value and its identity for direct callers.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L25"
target="_blank" style="float:right; font-size:smaller">source</a>

### api_return

``` python
def api_return(
    value:NoneType=None
):
```

*Return a Python API value unchanged.*

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

Direct API calls return Python values.
[`api_error`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#api_error)
raises `ValueError` for invalid inputs; callers retain the exception
rather than receiving an error-shaped success value.

[`api_error`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#api_error)
raises a validation error so callers retain its original message.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L30"
target="_blank" style="float:right; font-size:smaller">source</a>

### api_error

``` python
def api_error(
    msg
):
```

*Raise a Python API validation error.*

``` python
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
```

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L35"
target="_blank" style="float:right; font-size:smaller">source</a>

### failure_map_path

``` python
def failure_map_path():
```

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

[`failure_map_path`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#failure_map_path)
honors `NBSKILL_FAILURE_MAP` for isolated runs.
[`empty_failure_map`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#empty_failure_map)
starts an independent event history.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L41"
target="_blank" style="float:right; font-size:smaller">source</a>

### empty_failure_map

``` python
def empty_failure_map():
```

*Return a fresh empty usage-statistics record.*

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

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L46"
target="_blank" style="float:right; font-size:smaller">source</a>

### load_failure_map

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

*Read saved usage, optionally rejecting corrupt or unreadable
statistics.*

[`load_failure_map`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#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.

``` python
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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#track_call)
restores recording at the direct Python API boundary after the old
command wrappers were removed. The eight Pyskill operations and
[`style_report`](https://MorsCerta-crypto.github.io/nbskill/review.html#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.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L105"
target="_blank" style="float:right; font-size:smaller">source</a>

### track_call

``` python
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.

``` python
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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#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.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L125"
target="_blank" style="float:right; font-size:smaller">source</a>

### reset_usage

``` python
def reset_usage(
    path:NoneType=None
):
```

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

``` python
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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#git_run)
returns empty text for a failed command, and
[`git_root`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#git_run)
returns command output for repository inspection.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L133"
target="_blank" style="float:right; font-size:smaller">source</a>

### git_run

``` python
def git_run(
    root, *args
):
```

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

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

[`git_root`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#git_root)
resolves the repository containing the current working directory.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L139"
target="_blank" style="float:right; font-size:smaller">source</a>

### git_root

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

*Return the containing git repository root, if one exists.*

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

[`load_nbskill_config`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#load_nbskill_config)
merges project settings over the default notebook exclusions.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L162"
target="_blank" style="float:right; font-size:smaller">source</a>

### load_nbskill_config

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

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

``` python
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.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L194"
target="_blank" style="float:right; font-size:smaller">source</a>

### notebook_paths

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

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

[`notebook_paths`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#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.

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

Python analysis uses
[`source_without_directives`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#source_without_directives)
to remove notebook control lines.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L217"
target="_blank" style="float:right; font-size:smaller">source</a>

### source_without_directives

``` python
def source_without_directives(
    source
):
```

*Return source with nbdev cell directives removed.*

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

[`source_without_directives`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#source_without_directives)
removes notebook control lines before Python analysis.
[`source_hash`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#source_hash)
fingerprints the supplied text exactly; directive removal is an explicit
caller decision.

[`source_hash`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#source_hash)
compares source content without storing another editable copy.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L222"
target="_blank" style="float:right; font-size:smaller">source</a>

### source_hash

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

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

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

[`file_line_count`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#file_line_count)
counts physical lines in an existing source file.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L228"
target="_blank" style="float:right; font-size:smaller">source</a>

### file_line_count

``` python
def file_line_count(
    path
):
```

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

``` python
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`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#file_line_count)
treats an unreadable file as unavailable size evidence.
[`cap_text`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#cap_text)
bounds display text and, when requested, reports omitted characters
without discarding the underlying structured result.

[`cap_text`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#cap_text)
bounds the rendered text while recording whether content was omitted.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L234"
target="_blank" style="float:right; font-size:smaller">source</a>

### cap_text

``` python
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.*

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

[`NotebookResult`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#notebookresult)
retains dictionary access while limiting what an interpreter displays.
The complete result remains available for subsequent operations.

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L251"
target="_blank" style="float:right; font-size:smaller">source</a>

### NotebookResult

``` python
def NotebookResult(
    *args, **kwargs
):
```

*Dictionary result with one compact interpreter display.*

------------------------------------------------------------------------

<a
href="https://github.com/MorsCerta-crypto/nbskill/blob/main/nbskill/diagnostics.py#L256"
target="_blank" style="float:right; font-size:smaller">source</a>

### notebook_result

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

*Bound the interpreter display while retaining the complete structured
text.*

[`notebook_result`](https://MorsCerta-crypto.github.io/nbskill/diagnostics.html#notebook_result)
bounds the interpreter display while retaining the complete structured
result for callers.

``` python
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.
