first commit

This commit is contained in:
2026-07-22 13:48:46 +08:00
commit c87751c3dc
2820 changed files with 726976 additions and 0 deletions
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_BIN="${PYTHON_BIN:-python3}"
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
PYTHON_BIN="python"
fi
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
echo "Error: python interpreter not found." >&2
exit 1
fi
PYTHON_BIN="$(command -v "${PYTHON_BIN}")"
export PYTHON_BIN
if [[ $# -lt 1 ]]; then
echo "Usage: scripts/add_new_case.sh <path-to-python-file> [--function <name>] [--target <path>]" >&2
exit 1
fi
exec "${SCRIPT_DIR}/with_skill.sh" -- "${PYTHON_BIN}" "${SCRIPT_DIR}/evolve_case.py" "$@"
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""Extract and append a new case function into skill-local evolve module."""
from __future__ import annotations
import argparse
import ast
from pathlib import Path
CASES_MODULE = "simplecad_self_evolve_cases"
SKILL_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_TARGET = SKILL_ROOT / "cases" / CASES_MODULE / "evolve.py"
def _read_text(path: Path) -> str:
return path.read_text(encoding="utf-8")
def _node_source(lines: list[str], node: ast.AST) -> str:
start = getattr(node, "lineno", 1)
end = getattr(node, "end_lineno", start)
return "\n".join(lines[start - 1 : end])
def _extract_header_imports(tree: ast.Module, lines: list[str]) -> list[str]:
imports: list[str] = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
imports.append(_node_source(lines, node).strip())
continue
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
break
return [item for item in imports if item]
def _find_import_insert_index(lines: list[str]) -> int:
if len(lines) <= 1:
return len(lines)
index = 1
while index < len(lines) and not lines[index].strip():
index += 1
if index >= len(lines):
return 1
triple_double = '"' * 3
triple_single = "'" * 3
stripped = lines[index].strip()
if not (stripped.startswith(triple_double) or stripped.startswith(triple_single)):
return 1
quote = triple_double if stripped.startswith(triple_double) else triple_single
if stripped.count(quote) >= 2 and len(stripped) > len(quote) * 2:
return index + 1
index += 1
while index < len(lines):
if quote in lines[index]:
return index + 1
index += 1
return 1
def _combine_imports(imports: list[str], function_source: str) -> str:
if not imports:
return function_source
lines = function_source.splitlines()
if not lines:
return function_source
insert_at = _find_import_insert_index(lines)
import_lines = [f" {item}" for item in imports]
merged = lines[:insert_at] + [""] + import_lines + [""] + lines[insert_at:]
return "\n".join(merged)
def _ensure_target(path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
return
path.write_text(
"\n".join(
[
'"""Skill-local evolved case functions."""',
"",
"__all__: list[str] = []",
"",
]
),
encoding="utf-8",
)
def _select_function(tree: ast.Module, name: str | None) -> ast.FunctionDef:
functions = [node for node in tree.body if isinstance(node, ast.FunctionDef)]
if not functions:
raise ValueError("No top-level function found in source file")
if name is None:
return functions[0]
for node in functions:
if node.name == name:
return node
raise ValueError(f"Function '{name}' not found in source file")
def _append_case(target: Path, function_source: str, function_name: str, allow_duplicate: bool) -> None:
content = _read_text(target)
if not allow_duplicate and f"def {function_name}(" in content:
raise ValueError(f"Function '{function_name}' already exists in {target}")
with target.open("a", encoding="utf-8") as stream:
stream.write("\n\n" + function_source.strip() + "\n")
if f'__all__.append("{function_name}")' not in content:
stream.write(f'\n__all__.append("{function_name}")\n')
ast.parse(_read_text(target), filename=str(target))
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Add a new evolved case function into this skill package"
)
parser.add_argument("source_file", type=Path, help="Python file containing new function")
parser.add_argument(
"--function",
default=None,
help="Specific function name to extract (default: first top-level function)",
)
parser.add_argument(
"--target",
type=Path,
default=DEFAULT_TARGET,
help="Target evolve module path",
)
parser.add_argument(
"--allow-duplicate",
action="store_true",
help="Allow appending function even if same name already exists",
)
return parser.parse_args()
def main() -> None:
args = _parse_args()
if not args.source_file.exists():
raise SystemExit(f"Source file not found: {args.source_file}")
source_text = _read_text(args.source_file)
if not source_text.strip():
raise SystemExit(f"Source file is empty: {args.source_file}")
try:
tree = ast.parse(source_text)
except SyntaxError as exc:
raise SystemExit(f"Cannot parse source file: {exc}") from exc
function_node = _select_function(tree, args.function)
lines = source_text.splitlines()
function_source = _node_source(lines, function_node)
imports = _extract_header_imports(tree, lines)
merged_source = _combine_imports(imports, function_source)
_ensure_target(args.target)
try:
_append_case(
target=args.target,
function_source=merged_source,
function_name=function_node.name,
allow_duplicate=args.allow_duplicate,
)
except ValueError as exc:
raise SystemExit(str(exc)) from exc
print(f"Added function '{function_node.name}' to {args.target}")
print("Import with:")
print(f" from {CASES_MODULE}.evolve import {function_node.name}")
if __name__ == "__main__":
main()
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
PYTHON_BIN="${PYTHON_BIN:-python3}"
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
PYTHON_BIN="python"
fi
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
echo "Error: python interpreter not found." >&2
exit 1
fi
PYTHON_BIN="$(command -v "${PYTHON_BIN}")"
export PYTHON_BIN
if ! "${PYTHON_BIN}" - <<'PY' >/dev/null 2>&1
import sys
raise SystemExit(0 if sys.prefix != sys.base_prefix else 1)
PY
then
echo "Error: target interpreter is not inside a virtual environment." >&2
echo "Hint: activate a venv first, or run with PYTHON_BIN=/path/to/venv/bin/python." >&2
exit 1
fi
export SIMPLECAD_SKILL_ROOT="${SKILL_ROOT}"
export SIMPLECAD_RUNTIME_PACKAGE="simplecadapi"
export SIMPLECAD_CASES_ROOT="${SKILL_ROOT}/cases"
export SIMPLECAD_CASES_MODULE="simplecad_self_evolve_cases"
PACKAGE_SPEC="simplecadapi==2.0.8"
JUPYTER_DEPS=("jupyterlab>=4.5.5" "ipykernel>=6.29.5")
INSTALL_JUPYTER=0
INSTALL_ARGS=()
while [[ $# -gt 0 ]]; do
case "$1" in
--with-jupyter)
INSTALL_JUPYTER=1
shift
;;
--)
shift
INSTALL_ARGS+=("$@")
break
;;
*)
INSTALL_ARGS+=("$1")
shift
;;
esac
done
if command -v uv >/dev/null 2>&1; then
INSTALL_CMD=(uv pip install --python "${PYTHON_BIN}")
else
INSTALL_CMD=("${PYTHON_BIN}" -m pip install)
fi
run_install() {
local targets=("$@")
if [[ ${#INSTALL_ARGS[@]} -gt 0 ]]; then
"${INSTALL_CMD[@]}" "${INSTALL_ARGS[@]}" "${targets[@]}"
else
"${INSTALL_CMD[@]}" "${targets[@]}"
fi
}
echo "Installing runtime package: ${PACKAGE_SPEC}"
run_install "${PACKAGE_SPEC}"
if [[ "${INSTALL_JUPYTER}" == "1" ]]; then
echo "Installing Jupyter dependencies..."
run_install "${JUPYTER_DEPS[@]}"
fi
"${PYTHON_BIN}" - <<'PY'
import simplecadapi as scad
print("simplecadapi import OK")
print(getattr(scad, "__description__", ""))
PY
echo "Runtime install completed for simplecadapi 2.0.8."
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_BIN="${PYTHON_BIN:-python3}"
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
PYTHON_BIN="python"
fi
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
echo "Error: python interpreter not found." >&2
exit 1
fi
PYTHON_BIN="$(command -v "${PYTHON_BIN}")"
export PYTHON_BIN
if [[ $# -lt 1 ]]; then
echo "Usage: scripts/jupyter_with_skill.sh <lab|notebook> [-- <extra args>]" >&2
exit 1
fi
JUPYTER_APP="$1"
shift
case "${JUPYTER_APP}" in
lab|notebook) ;;
*)
echo "Error: first argument must be 'lab' or 'notebook'." >&2
exit 1
;;
esac
if [[ "${1:-}" == "--" ]]; then
shift
fi
exec "${SCRIPT_DIR}/with_skill.sh" --ensure-jupyter -- "${PYTHON_BIN}" -m jupyter "${JUPYTER_APP}" "$@"
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Bootstrap runtime package in a persistent Python REPL/kernel."""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from pathlib import Path
PACKAGE_SPEC = "simplecadapi==2.0.8"
CASES_MODULE = "simplecad_self_evolve_cases"
def _script_dir() -> Path:
return Path(__file__).resolve().parent
def _cases_root() -> Path:
return _script_dir().parent / "cases"
def _activate_cases_path() -> None:
cases_root = str(_cases_root())
os.environ["SIMPLECAD_CASES_ROOT"] = cases_root
os.environ["SIMPLECAD_CASES_MODULE"] = CASES_MODULE
current_pythonpath = os.environ.get("PYTHONPATH", "")
parts = [item for item in current_pythonpath.split(os.pathsep) if item]
if cases_root not in parts:
parts.insert(0, cases_root)
os.environ["PYTHONPATH"] = os.pathsep.join(parts)
if cases_root not in sys.path:
sys.path.insert(0, cases_root)
def _install(with_jupyter: bool = False) -> None:
cmd = [str(_script_dir() / "install.sh")]
if with_jupyter:
cmd.append("--with-jupyter")
env = os.environ.copy()
env.setdefault("PYTHON_BIN", sys.executable)
subprocess.run(cmd, check=True, env=env)
def _has_simplecadapi() -> bool:
try:
import simplecadapi # noqa: F401
except Exception:
return False
return True
def _has_jupyter_deps() -> bool:
try:
import jupyterlab # noqa: F401
import ipykernel # noqa: F401
except Exception:
return False
return True
def activate(check: bool = False, with_jupyter: bool = False) -> int:
skill_root = _script_dir().parent
os.environ["SIMPLECAD_SKILL_ROOT"] = str(skill_root)
_activate_cases_path()
if not _has_simplecadapi():
print(f"Installing runtime package {PACKAGE_SPEC} ...")
_install(with_jupyter=with_jupyter)
if with_jupyter and not _has_jupyter_deps():
print("Installing Jupyter dependencies ...")
_install(with_jupyter=True)
if check and not _has_simplecadapi():
print("Runtime install failed: cannot import simplecadapi", file=sys.stderr)
return 1
print(f"Skill runtime activated from site-packages: {PACKAGE_SPEC}")
print(f"Skill cases module ready: {CASES_MODULE}.evolve")
print("You can now run: import simplecadapi as scad")
return 0
def main() -> None:
parser = argparse.ArgumentParser(
description="Bootstrap SimpleCAD runtime in persistent Python process"
)
parser.add_argument(
"--check",
action="store_true",
help="Validate that import simplecadapi succeeds after bootstrap",
)
parser.add_argument(
"--with-jupyter",
action="store_true",
help="Also ensure jupyterlab and ipykernel are installed",
)
args = parser.parse_args()
raise SystemExit(activate(check=args.check, with_jupyter=args.with_jupyter))
if __name__ == "__main__":
main()
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
missing=0
required=(
"SKILL.md"
"scripts/install.sh"
"scripts/with_skill.sh"
"scripts/jupyter_with_skill.sh"
"scripts/repl_bootstrap.py"
"scripts/add_new_case.sh"
"scripts/evolve_case.py"
"scripts/validate_skill.sh"
"references/PROJECT_OVERVIEW.md"
"references/RUNTIME_INSTALL.md"
"references/EVOLVE_WORKFLOW.md"
"references/PROJECT_README.md"
"references/LICENSE.txt"
"references/docs/api/README.md"
"references/docs/core/README.md"
"cases/simplecad_self_evolve_cases/__init__.py"
"cases/simplecad_self_evolve_cases/evolve.py"
)
for relative in "${required[@]}"; do
if [[ ! -e "${SKILL_ROOT}/${relative}" ]]; then
echo "Missing required path: ${relative}" >&2
missing=1
fi
done
if [[ -d "${SKILL_ROOT}/assets/project_snapshot/src" || -d "${SKILL_ROOT}/src" ]]; then
echo "Unexpected bundled source code found in thin skill package." >&2
missing=1
fi
if [[ "${missing}" -ne 0 ]]; then
exit 1
fi
if command -v skills-ref >/dev/null 2>&1; then
skills-ref validate "${SKILL_ROOT}"
else
echo "skills-ref not found, skipped external spec validation."
fi
echo "Skill validation succeeded: ${SKILL_ROOT}"
@@ -0,0 +1,113 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
CASES_ROOT="${SKILL_ROOT}/cases"
CASES_MODULE="simplecad_self_evolve_cases"
PYTHON_BIN="${PYTHON_BIN:-python3}"
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
PYTHON_BIN="python"
fi
if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
echo "Error: python interpreter not found." >&2
exit 1
fi
PYTHON_BIN="$(command -v "${PYTHON_BIN}")"
export PYTHON_BIN
export SIMPLECAD_SKILL_ROOT="${SKILL_ROOT}"
export SIMPLECAD_CASES_ROOT="${CASES_ROOT}"
export SIMPLECAD_CASES_MODULE="${CASES_MODULE}"
case ":${PYTHONPATH:-}:" in
*":${CASES_ROOT}:"*) ;;
*) export PYTHONPATH="${CASES_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" ;;
esac
MODE="run"
ENSURE_JUPYTER=0
while [[ $# -gt 0 ]]; do
case "$1" in
--print-env)
MODE="print-env"
shift
;;
--check)
MODE="check"
shift
;;
--ensure-jupyter)
ENSURE_JUPYTER=1
shift
;;
--)
shift
break
;;
*)
break
;;
esac
done
ensure_runtime() {
if ! "${PYTHON_BIN}" - <<'PY' >/dev/null 2>&1
import simplecadapi # noqa: F401
PY
then
echo "Runtime package missing, running scripts/install.sh ..."
"${SCRIPT_DIR}/install.sh"
fi
}
ensure_jupyter() {
if ! "${PYTHON_BIN}" - <<'PY' >/dev/null 2>&1
import jupyterlab # noqa: F401
import ipykernel # noqa: F401
PY
then
echo "Jupyter dependencies missing, running scripts/install.sh --with-jupyter ..."
"${SCRIPT_DIR}/install.sh" --with-jupyter
fi
}
if [[ "${MODE}" == "print-env" ]]; then
printf 'export SIMPLECAD_SKILL_ROOT="%s"\n' "${SIMPLECAD_SKILL_ROOT}"
printf 'export SIMPLECAD_CASES_ROOT="%s"\n' "${SIMPLECAD_CASES_ROOT}"
printf 'export SIMPLECAD_CASES_MODULE="%s"\n' "${SIMPLECAD_CASES_MODULE}"
printf 'export PYTHONPATH="%s"\n' "${PYTHONPATH}"
exit 0
fi
ensure_runtime
if [[ "${ENSURE_JUPYTER}" == "1" ]]; then
ensure_jupyter
fi
if [[ "${MODE}" == "check" ]]; then
"${PYTHON_BIN}" - <<'PY'
import os
import simplecadapi as scad
print("Runtime check passed.")
print(getattr(scad, "__description__", ""))
print(f"Skill cases module: {os.environ.get('SIMPLECAD_CASES_MODULE', '')}")
PY
exit 0
fi
if [[ $# -eq 0 ]]; then
echo "Skill runtime is ready in current environment."
echo "Run command via wrapper: scripts/with_skill.sh -- ${PYTHON_BIN} your_script.py"
echo 'Add skill env vars: eval "$(scripts/with_skill.sh --print-env)"'
echo "Or check runtime: scripts/with_skill.sh --check"
exit 0
fi
exec "$@"