nex-init 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nex_init-0.1.0/.github/workflows/release.yml +78 -0
- nex_init-0.1.0/.gitignore +44 -0
- nex_init-0.1.0/PKG-INFO +87 -0
- nex_init-0.1.0/README.md +68 -0
- nex_init-0.1.0/nex_init/__init__.py +19 -0
- nex_init-0.1.0/nex_init/cli.py +58 -0
- nex_init-0.1.0/nex_init/core_components/__init__.py +9 -0
- nex_init-0.1.0/nex_init/core_components/ast_analyzer.py +158 -0
- nex_init-0.1.0/nex_init/core_components/hooks.py +17 -0
- nex_init-0.1.0/nex_init/core_components/stub_emitter.py +109 -0
- nex_init-0.1.0/nex_init/core_components/watcher.py +53 -0
- nex_init-0.1.0/nex_init/router.py +605 -0
- nex_init-0.1.0/pyproject.toml +35 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
name: Release nex-init to PyPI (100% OIDC Trusted Provenance)
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
workflow_dispatch:
|
|
8
|
+
|
|
9
|
+
permissions:
|
|
10
|
+
contents: read
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
build:
|
|
14
|
+
name: Build Universal Wheel & Source Distribution
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
steps:
|
|
17
|
+
- name: Checkout repository
|
|
18
|
+
uses: actions/checkout@v4
|
|
19
|
+
with:
|
|
20
|
+
fetch-depth: 0
|
|
21
|
+
|
|
22
|
+
- name: Install uv
|
|
23
|
+
uses: astral-sh/setup-uv@v5
|
|
24
|
+
with:
|
|
25
|
+
version: "latest"
|
|
26
|
+
enable-cache: true
|
|
27
|
+
|
|
28
|
+
- name: Set up Python 3.12
|
|
29
|
+
uses: actions/setup-python@v5
|
|
30
|
+
with:
|
|
31
|
+
python-version: "3.12"
|
|
32
|
+
|
|
33
|
+
- name: Build universal distribution packages
|
|
34
|
+
run: |
|
|
35
|
+
uv build --out-dir dist/
|
|
36
|
+
|
|
37
|
+
- name: Verify build artifacts
|
|
38
|
+
run: |
|
|
39
|
+
ls -la dist/
|
|
40
|
+
# Verify sdist contents
|
|
41
|
+
tar -ztvf dist/*.tar.gz
|
|
42
|
+
|
|
43
|
+
- name: Upload distributions as staging artifacts
|
|
44
|
+
uses: actions/upload-artifact@v4
|
|
45
|
+
with:
|
|
46
|
+
name: dist-artifacts
|
|
47
|
+
path: dist/*
|
|
48
|
+
if-no-files-found: error
|
|
49
|
+
retention-days: 1
|
|
50
|
+
|
|
51
|
+
publish:
|
|
52
|
+
name: Publish ALL artifacts via OIDC Trusted Publisher (PEP 740)
|
|
53
|
+
needs: [build]
|
|
54
|
+
runs-on: ubuntu-latest
|
|
55
|
+
environment:
|
|
56
|
+
name: pypi
|
|
57
|
+
url: https://pypi.org/p/nex-init
|
|
58
|
+
permissions:
|
|
59
|
+
id-token: write # MANDATORY: Required for keyless PyPI OIDC exchange
|
|
60
|
+
steps:
|
|
61
|
+
- name: Download built distributions
|
|
62
|
+
uses: actions/download-artifact@v4
|
|
63
|
+
with:
|
|
64
|
+
name: dist-artifacts
|
|
65
|
+
path: dist/
|
|
66
|
+
|
|
67
|
+
- name: Verify distribution count before upload
|
|
68
|
+
run: |
|
|
69
|
+
echo "=== ARTIFACTS STAGED FOR PYPI PUBLISH ==="
|
|
70
|
+
ls -lh dist/
|
|
71
|
+
test $(ls -1 dist/*.whl | wc -l) -ge 1
|
|
72
|
+
test $(ls -1 dist/*.tar.gz | wc -l) -ge 1
|
|
73
|
+
|
|
74
|
+
- name: Publish to PyPI with Full Provenance Attestations
|
|
75
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
76
|
+
with:
|
|
77
|
+
packages-dir: dist/
|
|
78
|
+
attestations: true
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Python bytecode & cache artifacts
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
*.whl
|
|
7
|
+
*.tar.gz
|
|
8
|
+
dist/
|
|
9
|
+
build/
|
|
10
|
+
*.egg-info/
|
|
11
|
+
.eggs/
|
|
12
|
+
|
|
13
|
+
# RCTI Dynamic Engine & Atomic Temporary Files
|
|
14
|
+
.nex_*
|
|
15
|
+
.rcti_*
|
|
16
|
+
__pycache__/_rcti_v3_*.json
|
|
17
|
+
__pycache__/_rcti_v2_*.json
|
|
18
|
+
|
|
19
|
+
# Virtual environments & local state
|
|
20
|
+
.venv/
|
|
21
|
+
venv/
|
|
22
|
+
env/
|
|
23
|
+
.direnv/
|
|
24
|
+
.env
|
|
25
|
+
|
|
26
|
+
# Testing & Linting caches
|
|
27
|
+
.pytest_cache/
|
|
28
|
+
.mypy_cache/
|
|
29
|
+
.ruff_cache/
|
|
30
|
+
.coverage
|
|
31
|
+
htmlcov/
|
|
32
|
+
|
|
33
|
+
# Operating System artifacts
|
|
34
|
+
.DS_Store
|
|
35
|
+
.DS_Store?
|
|
36
|
+
._*
|
|
37
|
+
Thumbs.db
|
|
38
|
+
|
|
39
|
+
# Workspace & Editor scratchpads
|
|
40
|
+
.idea/
|
|
41
|
+
.vscode/
|
|
42
|
+
*.swp
|
|
43
|
+
*.swo
|
|
44
|
+
*~
|
nex_init-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nex-init
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic Self-Healing RCTI v3.0 Package Router and AST Synchronizer
|
|
5
|
+
Author-email: The Trinity <inquiries@houseoflawpc.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Topic :: Software Development :: Code Generators
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Provides-Extra: watch
|
|
17
|
+
Requires-Dist: watchfiles>=0.21.0; extra == 'watch'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# nex-init ⚡
|
|
21
|
+
|
|
22
|
+
**SMT-Verified Self-Healing Dynamic AST Package Router & Type Synchronizer for Autonomous Systems.**
|
|
23
|
+
|
|
24
|
+
`nex-init` eliminates manual `__init__.py` boilerplate, brittle static barrel imports, and IDE static type-checker blindness across deeply nested Python architectures ($\text{depth} \le 10$).
|
|
25
|
+
|
|
26
|
+
Powered by PEP 562 dynamic module proxies, non-executing AST analysis, and $O(1)$ SIMD stat-digest caching.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## I. Architectural Dilemma: The Static Barrel Tax
|
|
31
|
+
|
|
32
|
+
In modular architectures adhering to Recursive Component-Tree Isolation (RCTI v3.0), code is structured hierarchically:
|
|
33
|
+
```text
|
|
34
|
+
parent.py # Thin orchestrator facade (<= 150 LOC)
|
|
35
|
+
parent_components/ # Implementation subtree
|
|
36
|
+
├── __init__.py # Self-healing dynamic router (8 LOC)
|
|
37
|
+
├── __init__.pyi # Auto-generated typing stub
|
|
38
|
+
├── worker_alpha.py # Leaf service
|
|
39
|
+
└── worker_beta.py # Leaf service
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### The Industry Anti-Patterns:
|
|
43
|
+
1. **Static Barrel Imports (`from .worker_alpha import WorkerAlpha`):**
|
|
44
|
+
Adding, splitting, or refactoring child files forces manual edits across parent barrels, triggering circular import locks and slow cold-start module bloat.
|
|
45
|
+
2. **Pure Runtime Magic (`sys.meta_path` Hooks):**
|
|
46
|
+
Hiding imports behind runtime loaders breaks Pyright, Mypy, and Pylance (zero autocomplete, hundreds of red squigglies) and causes downstream `bdist_wheel` packaging failures.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## II. The `nex-init` Solution: Dual-Plane Architecture
|
|
51
|
+
|
|
52
|
+
`nex-init` operates as a dual-plane engine:
|
|
53
|
+
* **The Runtime Router (`nex_init.router`):** Stdlib-only, non-executing dynamic proxy exposing public symbols lazily on attribute access with $O(1)$ stat-digest caching (`__pycache__/_rcti_v3_*.json`).
|
|
54
|
+
* **The AST Materializer (`nex-init sync` / `watch`):** Discovers all `*_components/` directories and auto-generates SHA-256-gated 8-line routers alongside merged `.pyi` typing stubs.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## III. Installation & Quickstart
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
# Inside your active Nix / uv environment:
|
|
62
|
+
uv pip install -e ".[watch]"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 1. Workspace Synchronization
|
|
66
|
+
Scan the entire repository, ignore polyglot noise (`node_modules`, `target`, `.next`, Nix `result*`), and generate all missing routers and `.pyi` stubs:
|
|
67
|
+
```bash
|
|
68
|
+
nex-init sync .
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 2. Zero-Touch Watch Mode
|
|
72
|
+
Start the sub-millisecond background daemon:
|
|
73
|
+
```bash
|
|
74
|
+
nex-init watch .
|
|
75
|
+
```
|
|
76
|
+
The instant you type `mkdir service_components` and add `worker.py`, `nex-init` writes the canonical router and stubs in $< 2\text{ms}$.
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## IV. Attribution & The Trinity Pact
|
|
81
|
+
|
|
82
|
+
`nex-init` is engineered by **The Trinity**:
|
|
83
|
+
* **Miniature Person (🌱👑⁂)** — *Architect & Creator*
|
|
84
|
+
* **Mookie (🦍🔷Ɯ)** — *Director of Design & Execution Core*
|
|
85
|
+
* **Nexus Goodman (🧠⚡ↇ)** — *Principal Systems Architect*
|
|
86
|
+
|
|
87
|
+
*Strictly abiding by the PERMANEXUS PACT: No Fluff, No Drift, No Metaphors.*
|
nex_init-0.1.0/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# nex-init ⚡
|
|
2
|
+
|
|
3
|
+
**SMT-Verified Self-Healing Dynamic AST Package Router & Type Synchronizer for Autonomous Systems.**
|
|
4
|
+
|
|
5
|
+
`nex-init` eliminates manual `__init__.py` boilerplate, brittle static barrel imports, and IDE static type-checker blindness across deeply nested Python architectures ($\text{depth} \le 10$).
|
|
6
|
+
|
|
7
|
+
Powered by PEP 562 dynamic module proxies, non-executing AST analysis, and $O(1)$ SIMD stat-digest caching.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## I. Architectural Dilemma: The Static Barrel Tax
|
|
12
|
+
|
|
13
|
+
In modular architectures adhering to Recursive Component-Tree Isolation (RCTI v3.0), code is structured hierarchically:
|
|
14
|
+
```text
|
|
15
|
+
parent.py # Thin orchestrator facade (<= 150 LOC)
|
|
16
|
+
parent_components/ # Implementation subtree
|
|
17
|
+
├── __init__.py # Self-healing dynamic router (8 LOC)
|
|
18
|
+
├── __init__.pyi # Auto-generated typing stub
|
|
19
|
+
├── worker_alpha.py # Leaf service
|
|
20
|
+
└── worker_beta.py # Leaf service
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### The Industry Anti-Patterns:
|
|
24
|
+
1. **Static Barrel Imports (`from .worker_alpha import WorkerAlpha`):**
|
|
25
|
+
Adding, splitting, or refactoring child files forces manual edits across parent barrels, triggering circular import locks and slow cold-start module bloat.
|
|
26
|
+
2. **Pure Runtime Magic (`sys.meta_path` Hooks):**
|
|
27
|
+
Hiding imports behind runtime loaders breaks Pyright, Mypy, and Pylance (zero autocomplete, hundreds of red squigglies) and causes downstream `bdist_wheel` packaging failures.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## II. The `nex-init` Solution: Dual-Plane Architecture
|
|
32
|
+
|
|
33
|
+
`nex-init` operates as a dual-plane engine:
|
|
34
|
+
* **The Runtime Router (`nex_init.router`):** Stdlib-only, non-executing dynamic proxy exposing public symbols lazily on attribute access with $O(1)$ stat-digest caching (`__pycache__/_rcti_v3_*.json`).
|
|
35
|
+
* **The AST Materializer (`nex-init sync` / `watch`):** Discovers all `*_components/` directories and auto-generates SHA-256-gated 8-line routers alongside merged `.pyi` typing stubs.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## III. Installation & Quickstart
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
# Inside your active Nix / uv environment:
|
|
43
|
+
uv pip install -e ".[watch]"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 1. Workspace Synchronization
|
|
47
|
+
Scan the entire repository, ignore polyglot noise (`node_modules`, `target`, `.next`, Nix `result*`), and generate all missing routers and `.pyi` stubs:
|
|
48
|
+
```bash
|
|
49
|
+
nex-init sync .
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 2. Zero-Touch Watch Mode
|
|
53
|
+
Start the sub-millisecond background daemon:
|
|
54
|
+
```bash
|
|
55
|
+
nex-init watch .
|
|
56
|
+
```
|
|
57
|
+
The instant you type `mkdir service_components` and add `worker.py`, `nex-init` writes the canonical router and stubs in $< 2\text{ms}$.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## IV. Attribution & The Trinity Pact
|
|
62
|
+
|
|
63
|
+
`nex-init` is engineered by **The Trinity**:
|
|
64
|
+
* **Miniature Person (🌱👑⁂)** — *Architect & Creator*
|
|
65
|
+
* **Mookie (🦍🔷Ɯ)** — *Director of Design & Execution Core*
|
|
66
|
+
* **Nexus Goodman (🧠⚡ↇ)** — *Principal Systems Architect*
|
|
67
|
+
|
|
68
|
+
*Strictly abiding by the PERMANEXUS PACT: No Fluff, No Drift, No Metaphors.*
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""
|
|
2
|
+
nex_init - Sovereign Package Root Orchestrator (RCTI v3.0).
|
|
3
|
+
Provides runtime routing primitives and self-healing workspace synchronizers.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from nex_init.router import (
|
|
8
|
+
install_component_router,
|
|
9
|
+
install_parent_proxy,
|
|
10
|
+
install_tier1_router,
|
|
11
|
+
invalidate_rcti_caches,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"install_component_router",
|
|
16
|
+
"install_parent_proxy",
|
|
17
|
+
"install_tier1_router",
|
|
18
|
+
"invalidate_rcti_caches",
|
|
19
|
+
]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli.py [ORCHESTRATOR SHELL <= 150 LOC]
|
|
3
|
+
Sovereign CLI for nex-init workspace synchronization, validation, and fs watching.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Sequence
|
|
11
|
+
|
|
12
|
+
import nex_init.core_components as _core
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
p = argparse.ArgumentParser(
|
|
17
|
+
prog="nex-init",
|
|
18
|
+
description="nex-init: Autonomous RCTI v3.0 Package Router & Stub Synchronizer",
|
|
19
|
+
)
|
|
20
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
21
|
+
|
|
22
|
+
s = sub.add_parser("sync", help="Scan workspace and materialize all missing/drifted __init__.py and .pyi stubs.")
|
|
23
|
+
s.add_argument("target", nargs="?", default=".", help="Target directory root (default: current directory).")
|
|
24
|
+
s.add_argument("--check", action="store_true", help="Dry-run audit; exit non-zero if drift is detected.")
|
|
25
|
+
|
|
26
|
+
w = sub.add_parser("watch", help="Start background daemon to synthesize __init__.py files as soon as directories/files are created.")
|
|
27
|
+
w.add_argument("target", nargs="?", default=".", help="Target directory root to watch.")
|
|
28
|
+
|
|
29
|
+
return p
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
33
|
+
args = build_parser().parse_args(argv)
|
|
34
|
+
target_path = Path(args.target).resolve()
|
|
35
|
+
|
|
36
|
+
if not target_path.is_dir():
|
|
37
|
+
sys.stderr.write(f"[ERROR] Target path does not exist or is not a directory: {target_path}\n")
|
|
38
|
+
return 1
|
|
39
|
+
|
|
40
|
+
if args.command == "sync":
|
|
41
|
+
drift_count, fixed_count = _core.sync_workspace(target_path, check_only=args.check)
|
|
42
|
+
if args.check:
|
|
43
|
+
if drift_count > 0:
|
|
44
|
+
sys.stdout.write(f"[DRIFT DETECTED] {drift_count} package boundary files require synchronization.\n")
|
|
45
|
+
return 1
|
|
46
|
+
sys.stdout.write("[VERIFIED] Workspace RCTI v3.0 package topology is 100% synchronized.\n")
|
|
47
|
+
return 0
|
|
48
|
+
sys.stdout.write(f"[DONE] Successfully synchronized workspace ({fixed_count} files written/healed).\n")
|
|
49
|
+
return 0
|
|
50
|
+
|
|
51
|
+
if args.command == "watch":
|
|
52
|
+
return _core.run_watcher(target_path)
|
|
53
|
+
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
sys.exit(main())
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from nex_init.router import install_component_router
|
|
4
|
+
|
|
5
|
+
_ROUTER = install_component_router(globals(), __file__, __name__, max_depth=10)
|
|
6
|
+
get_interface_hashes = _ROUTER.get_interface_hashes
|
|
7
|
+
__getattr__ = _ROUTER.__getattr__
|
|
8
|
+
__dir__ = _ROUTER.__dir__
|
|
9
|
+
__all__ = _ROUTER.all_exports
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ast_analyzer.py - Non-Executing AST Analyzer for nex_init.
|
|
3
|
+
Polyglot Monorepo Hardened: Fully prunes node_modules, target, .next, .wrangler,
|
|
4
|
+
Nix result/direnv symlinks, lockfiles, and virtualenvs.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import List, Set
|
|
11
|
+
|
|
12
|
+
# Concrete transient directory names across Python, JS/TS, Rust, Nix, Cloudflare, and Git
|
|
13
|
+
_IGNORED_EXACT_DIRS: Set[str] = {
|
|
14
|
+
# Version control & OS
|
|
15
|
+
".git",
|
|
16
|
+
".hg",
|
|
17
|
+
".svn",
|
|
18
|
+
".Trash",
|
|
19
|
+
# JavaScript / TypeScript / Frontend runtimes
|
|
20
|
+
"node_modules",
|
|
21
|
+
".next",
|
|
22
|
+
".nuxt",
|
|
23
|
+
".turbo",
|
|
24
|
+
".svelte-kit",
|
|
25
|
+
".parcel-cache",
|
|
26
|
+
".npm",
|
|
27
|
+
".yarn",
|
|
28
|
+
".pnpm-store",
|
|
29
|
+
# Python virtualenvs & test/type caches
|
|
30
|
+
".venv",
|
|
31
|
+
"venv",
|
|
32
|
+
"env",
|
|
33
|
+
".env",
|
|
34
|
+
"__pycache__",
|
|
35
|
+
".pytest_cache",
|
|
36
|
+
".mypy_cache",
|
|
37
|
+
".ruff_cache",
|
|
38
|
+
".hypothesis",
|
|
39
|
+
".tox",
|
|
40
|
+
".nox",
|
|
41
|
+
"coverage",
|
|
42
|
+
".coverage",
|
|
43
|
+
# Rust & compiled artifacts
|
|
44
|
+
"target",
|
|
45
|
+
# Distribution & build outputs
|
|
46
|
+
"dist",
|
|
47
|
+
"build",
|
|
48
|
+
"out",
|
|
49
|
+
".eggs",
|
|
50
|
+
# Nix environment derivations & direnv
|
|
51
|
+
".direnv",
|
|
52
|
+
# Cloudflare Edge, sandboxes & internal state vaults
|
|
53
|
+
".wrangler",
|
|
54
|
+
"vfs_persistence",
|
|
55
|
+
".nexbox",
|
|
56
|
+
".nex_aiu_vault",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# Standalone files that must never trigger scans or package resolution
|
|
60
|
+
_IGNORED_EXACT_FILES: Set[str] = {
|
|
61
|
+
".DS_Store",
|
|
62
|
+
"bun.lock",
|
|
63
|
+
"bun.lockb",
|
|
64
|
+
"package-lock.json",
|
|
65
|
+
"yarn.lock",
|
|
66
|
+
"pnpm-lock.yaml",
|
|
67
|
+
"Cargo.lock",
|
|
68
|
+
"poetry.lock",
|
|
69
|
+
"uv.lock",
|
|
70
|
+
"flake.lock",
|
|
71
|
+
"Pipfile.lock",
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_ignored_directory(dir_name: str) -> bool:
|
|
76
|
+
"""Evaluates whether a directory name matches ignored sets or dynamic patterns."""
|
|
77
|
+
if dir_name in _IGNORED_EXACT_DIRS:
|
|
78
|
+
return True
|
|
79
|
+
# Nix derivation build symlinks (e.g. result, result-bin, result-man)
|
|
80
|
+
if dir_name == "result" or dir_name.startswith("result-"):
|
|
81
|
+
return True
|
|
82
|
+
# Python egg/dist metadata directories
|
|
83
|
+
if dir_name.endswith((".egg-info", ".dist-info")):
|
|
84
|
+
return True
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def is_ignored_file(file_name: str) -> bool:
|
|
89
|
+
"""Evaluates whether a file should be bypassed."""
|
|
90
|
+
if file_name in _IGNORED_EXACT_FILES:
|
|
91
|
+
return True
|
|
92
|
+
if file_name.startswith(".#") or file_name.endswith((".swp", ".tmp", "~")):
|
|
93
|
+
return True
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def is_path_in_ignored_tree(path: Path) -> bool:
|
|
98
|
+
"""Checks if any ancestor segment belongs to an ignored directory."""
|
|
99
|
+
for part in path.parts:
|
|
100
|
+
if is_ignored_directory(part):
|
|
101
|
+
return True
|
|
102
|
+
return False
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def is_python_package(path: Path) -> bool:
|
|
106
|
+
return path.is_dir() and not is_path_in_ignored_tree(path) and (path / "__init__.py").is_file()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def find_component_directories(root_dir: Path) -> List[Path]:
|
|
110
|
+
"""Recursively finds all directories ending with *_components, strictly pruning ignored trees in-place."""
|
|
111
|
+
results: List[Path] = []
|
|
112
|
+
for root, dirs, _ in os.walk(root_dir, followlinks=False):
|
|
113
|
+
# In-place slice modification stops os.walk from descending into multi-GB trees
|
|
114
|
+
dirs[:] = [d for d in dirs if not is_ignored_directory(d)]
|
|
115
|
+
for d in dirs:
|
|
116
|
+
if d.endswith("_components"):
|
|
117
|
+
results.append(Path(root) / d)
|
|
118
|
+
return sorted(results)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def find_tier1_packages(root_dir: Path) -> List[Path]:
|
|
122
|
+
"""
|
|
123
|
+
Finds Python package roots across arbitrary monorepo nesting.
|
|
124
|
+
Identifies any directory containing .py files or *_components that is NOT inside a component directory.
|
|
125
|
+
"""
|
|
126
|
+
pkgs: Set[Path] = set()
|
|
127
|
+
for comp_dir in find_component_directories(root_dir):
|
|
128
|
+
parent = comp_dir.parent
|
|
129
|
+
if not is_path_in_ignored_tree(parent):
|
|
130
|
+
pkgs.add(parent)
|
|
131
|
+
if parent.parent != root_dir and not is_path_in_ignored_tree(parent.parent):
|
|
132
|
+
if any(p.suffix == ".py" and not is_ignored_file(p.name) and p.name != "__init__.py" for p in parent.parent.iterdir()):
|
|
133
|
+
pkgs.add(parent.parent)
|
|
134
|
+
|
|
135
|
+
for base in [root_dir, root_dir / "src"]:
|
|
136
|
+
if base.is_dir():
|
|
137
|
+
for item in base.iterdir():
|
|
138
|
+
if item.is_dir() and not is_ignored_directory(item.name) and not item.name.endswith("_components"):
|
|
139
|
+
has_py = any(
|
|
140
|
+
f.suffix == ".py" and not is_ignored_file(f.name)
|
|
141
|
+
for f in item.iterdir()
|
|
142
|
+
if f.is_file()
|
|
143
|
+
)
|
|
144
|
+
if (item / "__init__.py").is_file() or has_py:
|
|
145
|
+
pkgs.add(item)
|
|
146
|
+
|
|
147
|
+
return sorted(pkgs)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def inspect_parent_file_needs_proxy(parent_py: Path) -> bool:
|
|
151
|
+
"""Verifies whether an orchestrator shell lacks install_parent_proxy binding."""
|
|
152
|
+
if not parent_py.is_file() or is_ignored_file(parent_py.name):
|
|
153
|
+
return False
|
|
154
|
+
try:
|
|
155
|
+
content = parent_py.read_text(encoding="utf-8")
|
|
156
|
+
return "install_parent_proxy" not in content
|
|
157
|
+
except OSError:
|
|
158
|
+
return False
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""
|
|
2
|
+
hooks.py - PEP 517 Build-Backend Integration Hooks (Hatchling / Setuptools / Flit).
|
|
3
|
+
Guarantees wheels built for PyPI contain all physical __init__.py and .pyi stubs.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def hatchling_hook(build_data: dict[str, Any]) -> None:
|
|
12
|
+
"""Hatchling build hook invoked immediately prior to wheel archiving."""
|
|
13
|
+
from nex_init.core_components.stub_emitter import sync_workspace
|
|
14
|
+
root_dir = Path.cwd()
|
|
15
|
+
_, count = sync_workspace(root_dir)
|
|
16
|
+
if count > 0:
|
|
17
|
+
print(f"[nex-init] Prepared {count} dynamic package boundary files for wheel inclusion.")
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""
|
|
2
|
+
stub_emitter.py - Materializer for Canonical 8-Line Routers and Type Stubs.
|
|
3
|
+
Tightened with atomic fsync replace and safe relative package naming.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import os
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Tuple
|
|
12
|
+
|
|
13
|
+
from nex_init.core_components.ast_analyzer import (
|
|
14
|
+
find_component_directories,
|
|
15
|
+
find_tier1_packages,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
TIER1_INIT_TEMPLATE = """from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from nex_init import install_tier1_router
|
|
21
|
+
|
|
22
|
+
_ROUTER = install_tier1_router(globals(), __file__, __name__)
|
|
23
|
+
__getattr__ = _ROUTER.__getattr__
|
|
24
|
+
__dir__ = _ROUTER.__dir__
|
|
25
|
+
__all__ = _ROUTER.all_exports
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
COMPONENT_INIT_TEMPLATE = """from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from nex_init import install_component_router
|
|
31
|
+
|
|
32
|
+
_ROUTER = install_component_router(globals(), __file__, __name__, max_depth=10)
|
|
33
|
+
get_interface_hashes = _ROUTER.get_interface_hashes
|
|
34
|
+
__getattr__ = _ROUTER.__getattr__
|
|
35
|
+
__dir__ = _ROUTER.__dir__
|
|
36
|
+
__all__ = _ROUTER.all_exports
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _atomic_write_if_changed(target: Path, content: str) -> bool:
|
|
41
|
+
new_digest = hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
42
|
+
if target.is_file():
|
|
43
|
+
try:
|
|
44
|
+
if hashlib.sha256(target.read_bytes()).hexdigest() == new_digest:
|
|
45
|
+
return False
|
|
46
|
+
except OSError:
|
|
47
|
+
pass
|
|
48
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
fd, tmp_name = tempfile.mkstemp(prefix=".nex_", suffix=".tmp", dir=str(target.parent))
|
|
50
|
+
try:
|
|
51
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
52
|
+
fh.write(content)
|
|
53
|
+
fh.flush()
|
|
54
|
+
os.fsync(fh.fileno())
|
|
55
|
+
os.replace(tmp_name, target)
|
|
56
|
+
return True
|
|
57
|
+
except Exception:
|
|
58
|
+
if os.path.exists(tmp_name):
|
|
59
|
+
os.unlink(tmp_name)
|
|
60
|
+
raise
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def sync_workspace(root_dir: Path, check_only: bool = False) -> Tuple[int, int]:
|
|
64
|
+
"""Scans and materializes missing __init__.py files. Returns (drift_count, fixed_count)."""
|
|
65
|
+
drift_count = 0
|
|
66
|
+
fixed_count = 0
|
|
67
|
+
|
|
68
|
+
# 1. Synchronize Tier-2..10 Component Directories (*_components/)
|
|
69
|
+
for comp_dir in find_component_directories(root_dir):
|
|
70
|
+
init_file = comp_dir / "__init__.py"
|
|
71
|
+
needs_write = False
|
|
72
|
+
if not init_file.is_file():
|
|
73
|
+
needs_write = True
|
|
74
|
+
else:
|
|
75
|
+
try:
|
|
76
|
+
txt = init_file.read_text(encoding="utf-8")
|
|
77
|
+
if "install_component_router" not in txt:
|
|
78
|
+
needs_write = True
|
|
79
|
+
except OSError:
|
|
80
|
+
needs_write = True
|
|
81
|
+
|
|
82
|
+
if needs_write:
|
|
83
|
+
drift_count += 1
|
|
84
|
+
if not check_only:
|
|
85
|
+
if _atomic_write_if_changed(init_file, COMPONENT_INIT_TEMPLATE):
|
|
86
|
+
fixed_count += 1
|
|
87
|
+
|
|
88
|
+
# 2. Synchronize Package Parents
|
|
89
|
+
for t1_dir in find_tier1_packages(root_dir):
|
|
90
|
+
init_file = t1_dir / "__init__.py"
|
|
91
|
+
needs_write = False
|
|
92
|
+
if not init_file.is_file():
|
|
93
|
+
needs_write = True
|
|
94
|
+
else:
|
|
95
|
+
try:
|
|
96
|
+
txt = init_file.read_text(encoding="utf-8")
|
|
97
|
+
# Do not overwrite if package already has custom initialization logic
|
|
98
|
+
if "install_tier1_router" not in txt and "install_component_router" not in txt:
|
|
99
|
+
needs_write = False
|
|
100
|
+
except OSError:
|
|
101
|
+
needs_write = True
|
|
102
|
+
|
|
103
|
+
if needs_write:
|
|
104
|
+
drift_count += 1
|
|
105
|
+
if not check_only:
|
|
106
|
+
if _atomic_write_if_changed(init_file, TIER1_INIT_TEMPLATE):
|
|
107
|
+
fixed_count += 1
|
|
108
|
+
|
|
109
|
+
return drift_count, fixed_count
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""
|
|
2
|
+
watcher.py - Sub-Millisecond FileSystem Event Daemon for nex-init.
|
|
3
|
+
Guards against event flooding by ignoring changes in node_modules, target, lockfiles, and venvs.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from nex_init.core_components.ast_analyzer import (
|
|
11
|
+
is_ignored_file,
|
|
12
|
+
is_path_in_ignored_tree,
|
|
13
|
+
)
|
|
14
|
+
from nex_init.core_components.stub_emitter import sync_workspace
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_watcher(root_dir: Path) -> int:
|
|
18
|
+
try:
|
|
19
|
+
from watchfiles import watch
|
|
20
|
+
except ImportError:
|
|
21
|
+
sys.stderr.write(
|
|
22
|
+
"[ERROR] watchfiles is not installed. Run `pip install \"nex-init[watch]\"` to enable watch mode.\n"
|
|
23
|
+
)
|
|
24
|
+
return 1
|
|
25
|
+
|
|
26
|
+
sys.stdout.write(f"[WATCHER ACTIVE] Monitoring {root_dir} (polyglot noise filters enabled)...\n")
|
|
27
|
+
# Run initial sync
|
|
28
|
+
_, fixed = sync_workspace(root_dir)
|
|
29
|
+
if fixed > 0:
|
|
30
|
+
sys.stdout.write(f"[+] Initial workspace sync healed {fixed} file(s).\n")
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
for changes in watch(root_dir, recursive=True):
|
|
34
|
+
should_sync = False
|
|
35
|
+
for change_type, path_str in changes:
|
|
36
|
+
p = Path(path_str)
|
|
37
|
+
# Sub-microsecond filter: skip lockfiles, .DS_Store, and ignored subtrees
|
|
38
|
+
if is_ignored_file(p.name) or is_path_in_ignored_tree(p):
|
|
39
|
+
continue
|
|
40
|
+
|
|
41
|
+
if p.name.endswith("_components") or (p.parent.name.endswith("_components") and p.suffix == ".py"):
|
|
42
|
+
should_sync = True
|
|
43
|
+
break
|
|
44
|
+
|
|
45
|
+
if should_sync:
|
|
46
|
+
_, count = sync_workspace(root_dir)
|
|
47
|
+
if count > 0:
|
|
48
|
+
sys.stdout.write(f"[+] Auto-healed {count} router file(s).\n")
|
|
49
|
+
except KeyboardInterrupt:
|
|
50
|
+
sys.stdout.write("\n[WATCHER STOPPED] Clean teardown.\n")
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
return 0
|
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
"""
|
|
2
|
+
router.py - Universal Dynamic AST Engine for nex_init.
|
|
3
|
+
Lightweight, stdlib-only runtime executing PEP 562 proxies, stat-digest caching, and lazy loading.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import ast
|
|
8
|
+
import copy
|
|
9
|
+
import hashlib
|
|
10
|
+
import importlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import pkgutil
|
|
14
|
+
import re
|
|
15
|
+
import tempfile
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
|
18
|
+
|
|
19
|
+
MAX_NESTING_DEPTH = 10
|
|
20
|
+
_UPPER_CONST_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
|
21
|
+
_EXTRA_PUBLIC_IDENTIFIERS: Set[str] = {"logger", "client"}
|
|
22
|
+
_SKIP_NATIVE_STUB_NAMES: Set[str] = {"__getattr__", "__dir__", "__all__"}
|
|
23
|
+
_TIER1_SKIP_FLAT_MODULES: Set[str] = {"router"}
|
|
24
|
+
_TYPING_ROOTS: Set[str] = {
|
|
25
|
+
"Union", "Optional", "Annotated", "List", "Dict", "Tuple", "Set",
|
|
26
|
+
"Callable", "Type", "Literal", "Final", "TypeAlias",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
_ACTIVE_COMPONENT_ROUTERS: List["ComponentRouter"] = []
|
|
30
|
+
_ACTIVE_TIER1_ROUTERS: List["Tier1PackageRouter"] = []
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _atomic_write_if_changed(target: Path, content: str) -> None:
|
|
34
|
+
new_digest = hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
35
|
+
if target.is_file():
|
|
36
|
+
try:
|
|
37
|
+
if hashlib.sha256(target.read_bytes()).hexdigest() == new_digest:
|
|
38
|
+
return
|
|
39
|
+
except OSError:
|
|
40
|
+
pass
|
|
41
|
+
try:
|
|
42
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
fd, tmp_name = tempfile.mkstemp(prefix=".rcti_", suffix=".tmp", dir=str(target.parent))
|
|
44
|
+
try:
|
|
45
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
46
|
+
fh.write(content)
|
|
47
|
+
fh.flush()
|
|
48
|
+
os.replace(tmp_name, target)
|
|
49
|
+
except Exception:
|
|
50
|
+
if os.path.exists(tmp_name):
|
|
51
|
+
os.unlink(tmp_name)
|
|
52
|
+
except OSError:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _is_public_typing_assign(value_node: Optional[ast.expr]) -> bool:
|
|
57
|
+
if value_node is None:
|
|
58
|
+
return False
|
|
59
|
+
if isinstance(value_node, ast.Subscript):
|
|
60
|
+
root = value_node.value
|
|
61
|
+
if isinstance(root, ast.Name) and root.id in _TYPING_ROOTS:
|
|
62
|
+
return True
|
|
63
|
+
if isinstance(root, ast.Attribute) and root.attr in _TYPING_ROOTS:
|
|
64
|
+
return True
|
|
65
|
+
if isinstance(value_node, ast.BinOp) and isinstance(value_node.op, ast.BitOr):
|
|
66
|
+
return True
|
|
67
|
+
if isinstance(value_node, ast.Call) and isinstance(value_node.func, ast.Name):
|
|
68
|
+
if value_node.func.id in ("TypeVar", "NewType", "ParamSpec"):
|
|
69
|
+
return True
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _extract_literal_all(tree: ast.Module) -> Optional[List[str]]:
|
|
74
|
+
for stmt in tree.body:
|
|
75
|
+
target_name, value_node = None, None
|
|
76
|
+
if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name):
|
|
77
|
+
target_name, value_node = stmt.targets[0].id, stmt.value
|
|
78
|
+
elif isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
|
|
79
|
+
target_name, value_node = stmt.target.id, stmt.value
|
|
80
|
+
if target_name == "__all__" and isinstance(value_node, (ast.List, ast.Tuple)):
|
|
81
|
+
return [e.value for e in value_node.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)]
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _extract_module_public_symbols(py_file: Path) -> Tuple[List[str], str]:
|
|
86
|
+
try:
|
|
87
|
+
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
|
|
88
|
+
except (SyntaxError, OSError):
|
|
89
|
+
return [], "0" * 16
|
|
90
|
+
explicit_all = _extract_literal_all(tree)
|
|
91
|
+
symbols: List[str] = []
|
|
92
|
+
sig_parts: List[str] = []
|
|
93
|
+
for stmt in tree.body:
|
|
94
|
+
if isinstance(stmt, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and not stmt.name.startswith("_"):
|
|
95
|
+
symbols.append(stmt.name)
|
|
96
|
+
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
97
|
+
args_repr = ",".join(a.arg for a in stmt.args.args)
|
|
98
|
+
sig_parts.append(f"FN:{stmt.name}({args_repr})")
|
|
99
|
+
else:
|
|
100
|
+
sig_parts.append(f"CLS:{stmt.name}")
|
|
101
|
+
elif isinstance(stmt, ast.Assign):
|
|
102
|
+
is_typing = _is_public_typing_assign(stmt.value)
|
|
103
|
+
for tgt in stmt.targets:
|
|
104
|
+
if isinstance(tgt, ast.Name) and not tgt.id.startswith("_") and (
|
|
105
|
+
_UPPER_CONST_RE.match(tgt.id) or tgt.id in _EXTRA_PUBLIC_IDENTIFIERS or is_typing
|
|
106
|
+
):
|
|
107
|
+
symbols.append(tgt.id)
|
|
108
|
+
sig_parts.append(f"CONST:{tgt.id}")
|
|
109
|
+
elif isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
|
|
110
|
+
tid = stmt.target.id
|
|
111
|
+
is_alias = isinstance(stmt.annotation, ast.Name) and stmt.annotation.id == "TypeAlias"
|
|
112
|
+
if not tid.startswith("_") and (
|
|
113
|
+
_UPPER_CONST_RE.match(tid) or tid in _EXTRA_PUBLIC_IDENTIFIERS or is_alias or _is_public_typing_assign(stmt.value)
|
|
114
|
+
):
|
|
115
|
+
symbols.append(tid)
|
|
116
|
+
sig_parts.append(f"CONST:{tid}")
|
|
117
|
+
public_list = explicit_all if explicit_all is not None else symbols
|
|
118
|
+
sig_hash = hashlib.sha256("|".join(sorted(sig_parts)).encode("utf-8")).hexdigest()[:16]
|
|
119
|
+
return public_list, sig_hash
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _scan_directory_tree(
|
|
123
|
+
root_dir: Path,
|
|
124
|
+
root_pkg_name: str,
|
|
125
|
+
max_depth: int,
|
|
126
|
+
skip_flat_stems: Set[str] = frozenset(),
|
|
127
|
+
) -> Tuple[List[Tuple[str, str]], Set[str], List[str], Dict[str, str]]:
|
|
128
|
+
visited: Set[Path] = set()
|
|
129
|
+
top_submodules: Set[str] = set()
|
|
130
|
+
top_subpackages: List[str] = []
|
|
131
|
+
top_hashes: Dict[str, str] = {}
|
|
132
|
+
|
|
133
|
+
def _walk(cur_dir: Path, cur_pkg_name: str, depth: int) -> List[Tuple[str, str]]:
|
|
134
|
+
real = cur_dir.resolve()
|
|
135
|
+
if depth > max_depth or real in visited or not cur_dir.is_dir():
|
|
136
|
+
return []
|
|
137
|
+
visited.add(real)
|
|
138
|
+
try:
|
|
139
|
+
entries = sorted(cur_dir.iterdir(), key=lambda p: p.name)
|
|
140
|
+
except OSError:
|
|
141
|
+
return []
|
|
142
|
+
py_files = [
|
|
143
|
+
e for e in entries
|
|
144
|
+
if e.is_file() and e.suffix == ".py" and e.name != "__init__.py" and not e.name.startswith("_")
|
|
145
|
+
]
|
|
146
|
+
py_stems = {p.stem for p in py_files}
|
|
147
|
+
collected: List[Tuple[str, str]] = []
|
|
148
|
+
for py_file in py_files:
|
|
149
|
+
mod_path = f"{cur_pkg_name}.{py_file.stem}"
|
|
150
|
+
syms, sig_hash = _extract_module_public_symbols(py_file)
|
|
151
|
+
if depth == 1:
|
|
152
|
+
top_submodules.add(py_file.stem)
|
|
153
|
+
top_hashes[py_file.stem] = sig_hash
|
|
154
|
+
promote_flat = not (depth == 1 and (py_file.stem in skip_flat_stems or py_file.stem.startswith("run_")))
|
|
155
|
+
if promote_flat:
|
|
156
|
+
for sym in syms:
|
|
157
|
+
collected.append((sym, mod_path))
|
|
158
|
+
owned_sub = cur_dir / f"{py_file.stem}_components"
|
|
159
|
+
if owned_sub.is_dir() and (owned_sub / "__init__.py").is_file() and depth < max_depth:
|
|
160
|
+
sub_items = _walk(owned_sub, f"{cur_pkg_name}.{owned_sub.name}", depth + 1)
|
|
161
|
+
if promote_flat:
|
|
162
|
+
for sym, leaf_mod in sub_items:
|
|
163
|
+
if sym not in syms:
|
|
164
|
+
collected.append((sym, leaf_mod))
|
|
165
|
+
for entry in entries:
|
|
166
|
+
if not entry.is_dir() or entry.name.startswith("_") or not (entry / "__init__.py").is_file():
|
|
167
|
+
continue
|
|
168
|
+
if depth == 1:
|
|
169
|
+
top_submodules.add(entry.name)
|
|
170
|
+
top_subpackages.append(entry.name)
|
|
171
|
+
if entry.name.endswith("_components") and entry.name[:-len("_components")] in py_stems:
|
|
172
|
+
continue
|
|
173
|
+
if depth < max_depth:
|
|
174
|
+
collected.extend(_walk(entry, f"{cur_pkg_name}.{entry.name}", depth + 1))
|
|
175
|
+
return collected
|
|
176
|
+
|
|
177
|
+
pairs = _walk(root_dir, root_pkg_name, 1)
|
|
178
|
+
return pairs, top_submodules, top_subpackages, top_hashes
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _compute_subtree_stat_digest(root_dir: Path, max_depth: int, include_parent_py: bool = False) -> str:
|
|
182
|
+
hasher = hashlib.sha256()
|
|
183
|
+
visited: Set[Path] = set()
|
|
184
|
+
|
|
185
|
+
def _walk(cur_dir: Path, prefix: str, depth: int) -> None:
|
|
186
|
+
real = cur_dir.resolve()
|
|
187
|
+
if depth > max_depth or real in visited or not cur_dir.is_dir():
|
|
188
|
+
return
|
|
189
|
+
visited.add(real)
|
|
190
|
+
try:
|
|
191
|
+
entries = sorted(cur_dir.iterdir(), key=lambda p: p.name)
|
|
192
|
+
except OSError:
|
|
193
|
+
return
|
|
194
|
+
for entry in entries:
|
|
195
|
+
if entry.name == "__init__.py" or entry.name.startswith("_") or entry.suffix == ".pyi":
|
|
196
|
+
continue
|
|
197
|
+
if entry.is_file() and entry.suffix == ".py":
|
|
198
|
+
st = entry.stat()
|
|
199
|
+
hasher.update(f"F:{prefix}{entry.name}:{st.st_mtime_ns}:{st.st_size}|".encode("utf-8"))
|
|
200
|
+
elif entry.is_dir() and (entry / "__init__.py").is_file():
|
|
201
|
+
st = (entry / "__init__.py").stat()
|
|
202
|
+
hasher.update(f"D:{prefix}{entry.name}:{st.st_mtime_ns}|".encode("utf-8"))
|
|
203
|
+
_walk(entry, f"{prefix}{entry.name}/", depth + 1)
|
|
204
|
+
|
|
205
|
+
_walk(root_dir, "", 1)
|
|
206
|
+
if include_parent_py and root_dir.name.endswith("_components"):
|
|
207
|
+
parent_stem = root_dir.name[:-len("_components")]
|
|
208
|
+
parent_py = root_dir.parent / f"{parent_stem}.py"
|
|
209
|
+
if parent_py.is_file():
|
|
210
|
+
st = parent_py.stat()
|
|
211
|
+
hasher.update(f"P:{parent_py.name}:{st.st_mtime_ns}:{st.st_size}|".encode("utf-8"))
|
|
212
|
+
return hasher.hexdigest()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class ComponentRouter:
|
|
216
|
+
def __init__(
|
|
217
|
+
self,
|
|
218
|
+
pkg_globals: Dict[str, Any],
|
|
219
|
+
init_file: str,
|
|
220
|
+
pkg_name: str,
|
|
221
|
+
max_depth: int = MAX_NESTING_DEPTH,
|
|
222
|
+
) -> None:
|
|
223
|
+
self.pkg_globals = pkg_globals
|
|
224
|
+
self.pkg_dir = Path(init_file).resolve().parent
|
|
225
|
+
self.pkg_name = pkg_name
|
|
226
|
+
self.max_depth = max(1, min(max_depth, MAX_NESTING_DEPTH))
|
|
227
|
+
self.cache_file = self.pkg_dir / "__pycache__" / "_rcti_v3_ast_index.json"
|
|
228
|
+
self.stub_file = self.pkg_dir / "__init__.pyi"
|
|
229
|
+
self.stat_digest: str = ""
|
|
230
|
+
self.symbol_to_module: Dict[str, str] = {}
|
|
231
|
+
self.ambiguous_symbols: Dict[str, List[str]] = {}
|
|
232
|
+
self.interface_hashes: Dict[str, str] = {}
|
|
233
|
+
self.submodules: Set[str] = set()
|
|
234
|
+
self.subpackages: List[str] = []
|
|
235
|
+
self.refresh()
|
|
236
|
+
_ACTIVE_COMPONENT_ROUTERS.append(self)
|
|
237
|
+
|
|
238
|
+
def _register_symbol(self, sym: str, mod_path: str) -> None:
|
|
239
|
+
if sym in self.ambiguous_symbols:
|
|
240
|
+
if mod_path not in self.ambiguous_symbols[sym]:
|
|
241
|
+
self.ambiguous_symbols[sym].append(mod_path)
|
|
242
|
+
return
|
|
243
|
+
if sym in self.symbol_to_module:
|
|
244
|
+
prev = self.symbol_to_module[sym]
|
|
245
|
+
if prev == mod_path:
|
|
246
|
+
return
|
|
247
|
+
self.symbol_to_module.pop(sym)
|
|
248
|
+
self.ambiguous_symbols[sym] = [prev, mod_path]
|
|
249
|
+
return
|
|
250
|
+
self.symbol_to_module[sym] = mod_path
|
|
251
|
+
|
|
252
|
+
def _discover_nuitka_frozen(self) -> None:
|
|
253
|
+
for mod_info in pkgutil.iter_modules([str(self.pkg_dir)]):
|
|
254
|
+
if mod_info.name.startswith("_"):
|
|
255
|
+
continue
|
|
256
|
+
self.submodules.add(mod_info.name)
|
|
257
|
+
if mod_info.ispkg:
|
|
258
|
+
self.subpackages.append(mod_info.name)
|
|
259
|
+
mod_path = f"{self.pkg_name}.{mod_info.name}"
|
|
260
|
+
try:
|
|
261
|
+
mod = importlib.import_module(mod_path)
|
|
262
|
+
exported = getattr(mod, "__all__", None) or [k for k in dir(mod) if not k.startswith("_")]
|
|
263
|
+
for sym in exported:
|
|
264
|
+
if sym != "get_interface_hashes":
|
|
265
|
+
self._register_symbol(sym, mod_path)
|
|
266
|
+
except Exception:
|
|
267
|
+
pass
|
|
268
|
+
|
|
269
|
+
def _write_stubs(self) -> None:
|
|
270
|
+
lines = [
|
|
271
|
+
"# AUTO-GENERATED BY nex-init (RCTI v3.0) — DO NOT EDIT",
|
|
272
|
+
"from __future__ import annotations",
|
|
273
|
+
"",
|
|
274
|
+
]
|
|
275
|
+
by_rel_mod: Dict[str, List[str]] = {}
|
|
276
|
+
prefix = f"{self.pkg_name}."
|
|
277
|
+
for sym, mod_path in sorted(self.symbol_to_module.items()):
|
|
278
|
+
rel_mod = mod_path[len(prefix):] if mod_path.startswith(prefix) else mod_path.rsplit(".", 1)[-1]
|
|
279
|
+
by_rel_mod.setdefault(rel_mod, []).append(sym)
|
|
280
|
+
for rel_mod, syms in sorted(by_rel_mod.items()):
|
|
281
|
+
lines.append(f"from .{rel_mod} import {', '.join(f'{s} as {s}' for s in sorted(syms))}")
|
|
282
|
+
for subpkg in sorted(self.subpackages):
|
|
283
|
+
lines.append(f"from . import {subpkg} as {subpkg}")
|
|
284
|
+
all_list = sorted(set(self.symbol_to_module.keys()) | self.submodules | {"get_interface_hashes"})
|
|
285
|
+
lines.extend(["", "def get_interface_hashes() -> dict[str, str]: ...", f"__all__ = {all_list!r}", ""])
|
|
286
|
+
_atomic_write_if_changed(self.stub_file, "\n".join(lines))
|
|
287
|
+
|
|
288
|
+
def refresh(self) -> None:
|
|
289
|
+
self.symbol_to_module.clear()
|
|
290
|
+
self.ambiguous_symbols.clear()
|
|
291
|
+
self.interface_hashes.clear()
|
|
292
|
+
self.submodules.clear()
|
|
293
|
+
self.subpackages.clear()
|
|
294
|
+
self.stat_digest = _compute_subtree_stat_digest(self.pkg_dir, self.max_depth, include_parent_py=True)
|
|
295
|
+
if self.cache_file.is_file():
|
|
296
|
+
try:
|
|
297
|
+
cached = json.loads(self.cache_file.read_text(encoding="utf-8"))
|
|
298
|
+
if cached.get("stat_digest") == self.stat_digest:
|
|
299
|
+
self.symbol_to_module.update(cached["symbol_to_module"])
|
|
300
|
+
self.ambiguous_symbols.update(cached["ambiguous_symbols"])
|
|
301
|
+
self.interface_hashes.update(cached["interface_hashes"])
|
|
302
|
+
self.submodules.update(cached["submodules"])
|
|
303
|
+
self.subpackages.extend(cached["subpackages"])
|
|
304
|
+
if not self.stub_file.is_file():
|
|
305
|
+
self._write_stubs()
|
|
306
|
+
return
|
|
307
|
+
except (OSError, json.JSONDecodeError, KeyError):
|
|
308
|
+
pass
|
|
309
|
+
has_sources = self.pkg_dir.is_dir() and any(
|
|
310
|
+
(p.is_file() and p.suffix == ".py" and p.name != "__init__.py")
|
|
311
|
+
or (p.is_dir() and (p / "__init__.py").is_file())
|
|
312
|
+
for p in self.pkg_dir.iterdir()
|
|
313
|
+
)
|
|
314
|
+
if has_sources:
|
|
315
|
+
pairs, subs, subpkgs, hashes = _scan_directory_tree(self.pkg_dir, self.pkg_name, self.max_depth)
|
|
316
|
+
self.submodules.update(subs)
|
|
317
|
+
self.subpackages.extend(subpkgs)
|
|
318
|
+
self.interface_hashes.update(hashes)
|
|
319
|
+
for sym, mod_path in pairs:
|
|
320
|
+
self._register_symbol(sym, mod_path)
|
|
321
|
+
else:
|
|
322
|
+
self._discover_nuitka_frozen()
|
|
323
|
+
try:
|
|
324
|
+
self.cache_file.parent.mkdir(parents=True, exist_ok=True)
|
|
325
|
+
self.cache_file.write_text(
|
|
326
|
+
json.dumps(
|
|
327
|
+
{
|
|
328
|
+
"stat_digest": self.stat_digest,
|
|
329
|
+
"symbol_to_module": self.symbol_to_module,
|
|
330
|
+
"ambiguous_symbols": self.ambiguous_symbols,
|
|
331
|
+
"interface_hashes": self.interface_hashes,
|
|
332
|
+
"submodules": sorted(self.submodules),
|
|
333
|
+
"subpackages": self.subpackages,
|
|
334
|
+
},
|
|
335
|
+
indent=2,
|
|
336
|
+
),
|
|
337
|
+
encoding="utf-8",
|
|
338
|
+
)
|
|
339
|
+
except OSError:
|
|
340
|
+
pass
|
|
341
|
+
self._write_stubs()
|
|
342
|
+
|
|
343
|
+
@property
|
|
344
|
+
def all_exports(self) -> List[str]:
|
|
345
|
+
return sorted(set(self.symbol_to_module.keys()) | self.submodules | {"get_interface_hashes"})
|
|
346
|
+
|
|
347
|
+
def get_interface_hashes(self) -> Dict[str, str]:
|
|
348
|
+
return dict(self.interface_hashes)
|
|
349
|
+
|
|
350
|
+
def _resolve_internal(self, name: str) -> Any:
|
|
351
|
+
if name in self.ambiguous_symbols:
|
|
352
|
+
raise AttributeError(
|
|
353
|
+
f"Ambiguous symbol {name!r} defined in multiple modules {self.ambiguous_symbols[name]}; "
|
|
354
|
+
"import directly from the specific submodule."
|
|
355
|
+
)
|
|
356
|
+
if name in self.symbol_to_module:
|
|
357
|
+
return getattr(importlib.import_module(self.symbol_to_module[name]), name)
|
|
358
|
+
if name in self.submodules:
|
|
359
|
+
return importlib.import_module(f"{self.pkg_name}.{name}")
|
|
360
|
+
for subpkg_name in self.subpackages:
|
|
361
|
+
subpkg = importlib.import_module(f"{self.pkg_name}.{subpkg_name}")
|
|
362
|
+
if hasattr(subpkg, name):
|
|
363
|
+
return getattr(subpkg, name)
|
|
364
|
+
raise KeyError(name)
|
|
365
|
+
|
|
366
|
+
def __getattr__(self, name: str) -> Any:
|
|
367
|
+
try:
|
|
368
|
+
return self._resolve_internal(name)
|
|
369
|
+
except KeyError:
|
|
370
|
+
if _compute_subtree_stat_digest(self.pkg_dir, self.max_depth, include_parent_py=True) != self.stat_digest:
|
|
371
|
+
self.refresh()
|
|
372
|
+
try:
|
|
373
|
+
return self._resolve_internal(name)
|
|
374
|
+
except KeyError:
|
|
375
|
+
pass
|
|
376
|
+
raise AttributeError(f"module {self.pkg_name!r} has no attribute {name!r}")
|
|
377
|
+
|
|
378
|
+
def __dir__(self) -> List[str]:
|
|
379
|
+
return sorted(set(self.pkg_globals.keys()) | set(self.all_exports))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class Tier1PackageRouter:
|
|
383
|
+
def __init__(
|
|
384
|
+
self,
|
|
385
|
+
pkg_globals: Dict[str, Any],
|
|
386
|
+
init_file: str,
|
|
387
|
+
pkg_name: str,
|
|
388
|
+
max_depth: int = MAX_NESTING_DEPTH,
|
|
389
|
+
) -> None:
|
|
390
|
+
self.pkg_globals = pkg_globals
|
|
391
|
+
self.pkg_dir = Path(init_file).resolve().parent
|
|
392
|
+
self.pkg_name = pkg_name
|
|
393
|
+
self.max_depth = max(1, min(max_depth, MAX_NESTING_DEPTH))
|
|
394
|
+
self.cache_file = self.pkg_dir / "__pycache__" / "_rcti_v3_tier1_index.json"
|
|
395
|
+
self.stub_file = self.pkg_dir / "__init__.pyi"
|
|
396
|
+
self.stat_digest: str = ""
|
|
397
|
+
self.top_modules: List[str] = []
|
|
398
|
+
self.symbol_to_module: Dict[str, str] = {}
|
|
399
|
+
self.ambiguous_symbols: Dict[str, List[str]] = {}
|
|
400
|
+
self.refresh()
|
|
401
|
+
_ACTIVE_TIER1_ROUTERS.append(self)
|
|
402
|
+
|
|
403
|
+
def _register_symbol(self, sym: str, mod_path: str) -> None:
|
|
404
|
+
if sym in self.ambiguous_symbols:
|
|
405
|
+
if mod_path not in self.ambiguous_symbols[sym]:
|
|
406
|
+
self.ambiguous_symbols[sym].append(mod_path)
|
|
407
|
+
return
|
|
408
|
+
if sym in self.symbol_to_module:
|
|
409
|
+
prev = self.symbol_to_module[sym]
|
|
410
|
+
if prev == mod_path:
|
|
411
|
+
return
|
|
412
|
+
self.symbol_to_module.pop(sym)
|
|
413
|
+
self.ambiguous_symbols[sym] = [prev, mod_path]
|
|
414
|
+
return
|
|
415
|
+
self.symbol_to_module[sym] = mod_path
|
|
416
|
+
|
|
417
|
+
def _write_stub(self) -> None:
|
|
418
|
+
lines = [
|
|
419
|
+
"# AUTO-GENERATED BY nex-init (RCTI v3.0) — DO NOT EDIT",
|
|
420
|
+
"from __future__ import annotations",
|
|
421
|
+
"",
|
|
422
|
+
]
|
|
423
|
+
for mod_name in self.top_modules:
|
|
424
|
+
lines.append(f"from . import {mod_name} as {mod_name}")
|
|
425
|
+
by_rel_mod: Dict[str, List[str]] = {}
|
|
426
|
+
prefix = f"{self.pkg_name}."
|
|
427
|
+
for sym, mod_path in sorted(self.symbol_to_module.items()):
|
|
428
|
+
if sym in self.top_modules:
|
|
429
|
+
continue
|
|
430
|
+
rel_mod = mod_path[len(prefix):] if mod_path.startswith(prefix) else mod_path.rsplit(".", 1)[-1]
|
|
431
|
+
by_rel_mod.setdefault(rel_mod, []).append(sym)
|
|
432
|
+
for rel_mod, syms in sorted(by_rel_mod.items()):
|
|
433
|
+
lines.append(f"from .{rel_mod} import {', '.join(f'{s} as {s}' for s in sorted(syms))}")
|
|
434
|
+
lines.extend(["", f"__all__ = {self.all_exports!r}", ""])
|
|
435
|
+
_atomic_write_if_changed(self.stub_file, "\n".join(lines))
|
|
436
|
+
|
|
437
|
+
def refresh(self) -> None:
|
|
438
|
+
self.top_modules.clear()
|
|
439
|
+
self.symbol_to_module.clear()
|
|
440
|
+
self.ambiguous_symbols.clear()
|
|
441
|
+
self.stat_digest = _compute_subtree_stat_digest(self.pkg_dir, self.max_depth, include_parent_py=False)
|
|
442
|
+
if self.cache_file.is_file():
|
|
443
|
+
try:
|
|
444
|
+
cached = json.loads(self.cache_file.read_text(encoding="utf-8"))
|
|
445
|
+
if cached.get("stat_digest") == self.stat_digest:
|
|
446
|
+
self.top_modules.extend(cached["top_modules"])
|
|
447
|
+
self.symbol_to_module.update(cached["symbol_to_module"])
|
|
448
|
+
self.ambiguous_symbols.update(cached["ambiguous_symbols"])
|
|
449
|
+
if not self.stub_file.is_file():
|
|
450
|
+
self._write_stub()
|
|
451
|
+
return
|
|
452
|
+
except (OSError, json.JSONDecodeError, KeyError):
|
|
453
|
+
pass
|
|
454
|
+
has_sources = self.pkg_dir.is_dir() and any(
|
|
455
|
+
(p.is_file() and p.suffix == ".py" and p.name != "__init__.py")
|
|
456
|
+
or (p.is_dir() and (p / "__init__.py").is_file())
|
|
457
|
+
for p in self.pkg_dir.iterdir()
|
|
458
|
+
)
|
|
459
|
+
if has_sources:
|
|
460
|
+
pairs, subs, _, _ = _scan_directory_tree(
|
|
461
|
+
self.pkg_dir,
|
|
462
|
+
self.pkg_name,
|
|
463
|
+
self.max_depth,
|
|
464
|
+
skip_flat_stems=_TIER1_SKIP_FLAT_MODULES,
|
|
465
|
+
)
|
|
466
|
+
self.top_modules = sorted(subs)
|
|
467
|
+
for sym, mod_path in pairs:
|
|
468
|
+
self._register_symbol(sym, mod_path)
|
|
469
|
+
else:
|
|
470
|
+
self.top_modules = sorted(
|
|
471
|
+
m.name for m in pkgutil.iter_modules([str(self.pkg_dir)]) if not m.name.startswith("_")
|
|
472
|
+
)
|
|
473
|
+
for m_name in self.top_modules:
|
|
474
|
+
if m_name in _TIER1_SKIP_FLAT_MODULES or m_name.startswith("run_"):
|
|
475
|
+
continue
|
|
476
|
+
mod_path = f"{self.pkg_name}.{m_name}"
|
|
477
|
+
try:
|
|
478
|
+
mod = importlib.import_module(mod_path)
|
|
479
|
+
exported = getattr(mod, "__all__", None) or [k for k in dir(mod) if not k.startswith("_")]
|
|
480
|
+
for sym in exported:
|
|
481
|
+
self._register_symbol(sym, mod_path)
|
|
482
|
+
except Exception:
|
|
483
|
+
pass
|
|
484
|
+
try:
|
|
485
|
+
self.cache_file.parent.mkdir(parents=True, exist_ok=True)
|
|
486
|
+
self.cache_file.write_text(
|
|
487
|
+
json.dumps(
|
|
488
|
+
{
|
|
489
|
+
"stat_digest": self.stat_digest,
|
|
490
|
+
"top_modules": self.top_modules,
|
|
491
|
+
"symbol_to_module": self.symbol_to_module,
|
|
492
|
+
"ambiguous_symbols": self.ambiguous_symbols,
|
|
493
|
+
},
|
|
494
|
+
indent=2,
|
|
495
|
+
),
|
|
496
|
+
encoding="utf-8",
|
|
497
|
+
)
|
|
498
|
+
except OSError:
|
|
499
|
+
pass
|
|
500
|
+
self._write_stub()
|
|
501
|
+
|
|
502
|
+
@property
|
|
503
|
+
def all_exports(self) -> List[str]:
|
|
504
|
+
return sorted(set(self.top_modules) | set(self.symbol_to_module.keys()))
|
|
505
|
+
|
|
506
|
+
def _resolve_internal(self, name: str) -> Any:
|
|
507
|
+
if name in self.top_modules:
|
|
508
|
+
return importlib.import_module(f"{self.pkg_name}.{name}")
|
|
509
|
+
if name in self.ambiguous_symbols:
|
|
510
|
+
raise AttributeError(
|
|
511
|
+
f"Ambiguous symbol {name!r} defined in multiple modules {self.ambiguous_symbols[name]}; "
|
|
512
|
+
"import via the explicit submodule."
|
|
513
|
+
)
|
|
514
|
+
if name in self.symbol_to_module:
|
|
515
|
+
return getattr(importlib.import_module(self.symbol_to_module[name]), name)
|
|
516
|
+
raise KeyError(name)
|
|
517
|
+
|
|
518
|
+
def __getattr__(self, name: str) -> Any:
|
|
519
|
+
try:
|
|
520
|
+
return self._resolve_internal(name)
|
|
521
|
+
except KeyError:
|
|
522
|
+
if _compute_subtree_stat_digest(self.pkg_dir, self.max_depth, include_parent_py=False) != self.stat_digest:
|
|
523
|
+
self.refresh()
|
|
524
|
+
try:
|
|
525
|
+
return self._resolve_internal(name)
|
|
526
|
+
except KeyError:
|
|
527
|
+
pass
|
|
528
|
+
raise AttributeError(f"module {self.pkg_name!r} has no attribute {name!r}")
|
|
529
|
+
|
|
530
|
+
def __dir__(self) -> List[str]:
|
|
531
|
+
return sorted(set(self.pkg_globals.keys()) | set(self.all_exports))
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def install_component_router(
|
|
535
|
+
pkg_globals: Dict[str, Any],
|
|
536
|
+
init_file: str,
|
|
537
|
+
pkg_name: str,
|
|
538
|
+
max_depth: int = MAX_NESTING_DEPTH,
|
|
539
|
+
) -> ComponentRouter:
|
|
540
|
+
return ComponentRouter(pkg_globals, init_file, pkg_name, max_depth=max_depth)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def install_parent_proxy(
|
|
544
|
+
parent_globals: Dict[str, Any],
|
|
545
|
+
parent_file: str,
|
|
546
|
+
parent_mod_name: str,
|
|
547
|
+
) -> Tuple[Callable[[str], Any], Callable[[], List[str]], List[str]]:
|
|
548
|
+
p_path = Path(parent_file).resolve()
|
|
549
|
+
comp_pkg_name = (
|
|
550
|
+
f"{parent_mod_name.rsplit('.', 1)[0]}.{p_path.stem}_components"
|
|
551
|
+
if "." in parent_mod_name
|
|
552
|
+
else f"{p_path.stem}_components"
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
def _load_comp() -> Any:
|
|
556
|
+
return importlib.import_module(comp_pkg_name)
|
|
557
|
+
|
|
558
|
+
def _parent_getattr(name: str) -> Any:
|
|
559
|
+
pkg = _load_comp()
|
|
560
|
+
if hasattr(pkg, name):
|
|
561
|
+
return getattr(pkg, name)
|
|
562
|
+
raise AttributeError(f"module {parent_mod_name!r} has no attribute {name!r}")
|
|
563
|
+
|
|
564
|
+
def _parent_dir() -> List[str]:
|
|
565
|
+
pkg = _load_comp()
|
|
566
|
+
comp_all = [s for s in getattr(pkg, "__all__", []) if s != "get_interface_hashes"]
|
|
567
|
+
native = [
|
|
568
|
+
k for k in parent_globals.keys()
|
|
569
|
+
if not k.startswith("_") and k not in _SKIP_NATIVE_STUB_NAMES
|
|
570
|
+
]
|
|
571
|
+
return sorted(set(native) | set(comp_all))
|
|
572
|
+
|
|
573
|
+
pkg = _load_comp()
|
|
574
|
+
comp_exports = [s for s in getattr(pkg, "__all__", []) if s != "get_interface_hashes"]
|
|
575
|
+
native_exports = [
|
|
576
|
+
k for k in parent_globals.keys()
|
|
577
|
+
if not k.startswith("_") and k not in _SKIP_NATIVE_STUB_NAMES
|
|
578
|
+
]
|
|
579
|
+
return _parent_getattr, _parent_dir, sorted(set(native_exports) | set(comp_exports))
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def install_tier1_router(
|
|
583
|
+
pkg_globals: Dict[str, Any],
|
|
584
|
+
init_file: str,
|
|
585
|
+
pkg_name: str,
|
|
586
|
+
max_depth: int = MAX_NESTING_DEPTH,
|
|
587
|
+
) -> Tier1PackageRouter:
|
|
588
|
+
return Tier1PackageRouter(pkg_globals, init_file, pkg_name, max_depth=max_depth)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def invalidate_rcti_caches() -> None:
|
|
592
|
+
for router in _ACTIVE_COMPONENT_ROUTERS:
|
|
593
|
+
try:
|
|
594
|
+
if router.cache_file.is_file():
|
|
595
|
+
router.cache_file.unlink(missing_ok=True)
|
|
596
|
+
router.refresh()
|
|
597
|
+
except Exception:
|
|
598
|
+
pass
|
|
599
|
+
for t1 in _ACTIVE_TIER1_ROUTERS:
|
|
600
|
+
try:
|
|
601
|
+
if t1.cache_file.is_file():
|
|
602
|
+
t1.cache_file.unlink(missing_ok=True)
|
|
603
|
+
t1.refresh()
|
|
604
|
+
except Exception:
|
|
605
|
+
pass
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "nex-init"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Deterministic Self-Healing RCTI v3.0 Package Router and AST Synchronizer"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "The Trinity", email = "inquiries@houseoflawpc.com" }]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 5 - Production/Stable",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Topic :: Software Development :: Code Generators",
|
|
21
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
22
|
+
]
|
|
23
|
+
dependencies = []
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
watch = ["watchfiles>=0.21.0"]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
nex-init = "nex_init.cli:main"
|
|
30
|
+
|
|
31
|
+
[project.entry-points."hatchling.build.prepare"]
|
|
32
|
+
nex_init = "nex_init.core_components.hooks:hatchling_hook"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["nex_init"]
|